package main import ( "bytes" "context" "crypto/rand" "crypto/subtle" "encoding/base64" "encoding/hex" "encoding/json" "flag" "fmt" "io" "log" "net/http" "net/url" "os" "strconv" "strings" "sync" "time" "github.com/gorilla/websocket" "github.com/klipperanywhere/klipperanywhere/internal/protocol" ) var serverVersion = "dev" type tunnel struct { printerID string remoteAddr string connectedAt time.Time conn *websocket.Conn writeMu sync.Mutex pending map[string]chan protocol.Message pendingMu sync.Mutex health *protocol.Health healthMu sync.RWMutex done chan struct{} } type server struct { agentToken string cookieSecure bool controlMode string upgrader websocket.Upgrader tunnels map[string]*tunnel tunnelsMu sync.RWMutex users *userStore auditLog *auditStore printerSettings *printerSettingsStore notificationSettings *notificationSettingsStore notifier *telegramNotifier installJobs map[string]*installJob installJobsMu sync.RWMutex sessions map[string]sessionRecord sessionsMu sync.RWMutex loginLimiter *loginLimiter } type sessionRecord struct { UserID string CSRFToken string ExpiresAt time.Time } type authenticatedSession struct { UserID string Username string Role string PrinterGrants []printerGrant CSRFToken string ExpiresAt time.Time } type loginAttempt struct { Count int WindowEnds time.Time } type loginLimiter struct { mu sync.Mutex attempts map[string]loginAttempt limit int window time.Duration } func main() { var listen string var token string var adminUser string var adminPass string var usersFile string var auditFile string var settingsFile string var notificationSettingsFile string var cookieSecure bool var controlMode string flag.StringVar(&listen, "listen", ":8080", "address to listen on") flag.StringVar(&token, "agent-token", envOrDefault("KA_AGENT_TOKEN", "dev-token"), "shared agent token for local development") flag.StringVar(&adminUser, "admin-user", envOrDefault("KA_ADMIN_USER", "admin"), "admin username") flag.StringVar(&adminPass, "admin-password", envOrDefault("KA_ADMIN_PASSWORD", "admin"), "admin password") flag.StringVar(&usersFile, "users-file", envOrDefault("KA_USERS_FILE", "data/users.json"), "path to the persistent users file") flag.StringVar(&auditFile, "audit-file", envOrDefault("KA_AUDIT_FILE", "data/audit.log"), "path to the append-only audit log") flag.StringVar(&settingsFile, "settings-file", envOrDefault("KA_PRINTER_SETTINGS_FILE", "data/printer-settings.json"), "path to synced printer settings") flag.StringVar(¬ificationSettingsFile, "notification-settings-file", envOrDefault("KA_NOTIFICATION_SETTINGS_FILE", "data/notification-settings.json"), "path to global notification settings") flag.BoolVar(&cookieSecure, "cookie-secure", false, "set Secure on session cookies") flag.StringVar(&controlMode, "control-mode", envOrDefault("KA_CONTROL_MODE", "readonly"), "printer control mode: readonly or full") flag.Parse() if envBool("KA_COOKIE_SECURE") { cookieSecure = true } warnIfDevelopmentSecrets(token, adminUser, adminPass, cookieSecure) rawControlMode := controlMode controlMode = normalizeControlMode(controlMode) if controlMode == "" { log.Printf("WARNING: invalid control mode %q; falling back to readonly", rawControlMode) controlMode = "readonly" } users, err := newUserStore(usersFile, adminUser, adminPass) if err != nil { log.Fatal(err) } audit, err := newAuditStore(auditFile) if err != nil { log.Fatal(err) } printerSettings, err := newPrinterSettingsStore(settingsFile) if err != nil { log.Fatal(err) } notificationSettings, err := newNotificationSettingsStore(notificationSettingsFile) if err != nil { log.Fatal(err) } s := &server{ agentToken: token, cookieSecure: cookieSecure, controlMode: controlMode, upgrader: websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, }, tunnels: make(map[string]*tunnel), users: users, auditLog: audit, printerSettings: printerSettings, notificationSettings: notificationSettings, notifier: &telegramNotifier{client: &http.Client{Timeout: 15 * time.Second}, settings: notificationSettings}, installJobs: make(map[string]*installJob), sessions: make(map[string]sessionRecord), loginLimiter: newLoginLimiter(5, 5*time.Minute), } go (&telegramBot{ client: &http.Client{Timeout: 30 * time.Second}, settings: notificationSettings, server: s, }).run(context.Background()) mux := http.NewServeMux() mux.HandleFunc("/agent/tunnel", s.handleAgentTunnel) mux.HandleFunc("/p/", s.requireAuth(s.handlePrinterProxy)) mux.HandleFunc("/webcam/", s.requireAuth(s.handleLegacyWebcamProxy)) mux.HandleFunc("/api/session", s.handleSessionAPI) mux.HandleFunc("/api/printers", s.requireAuth(s.handlePrintersAPI)) mux.HandleFunc("/api/printers/", s.requireAuth(s.handlePrinterAPI)) mux.HandleFunc("/dashboard", s.requireAuth(s.handleDashboard)) mux.HandleFunc("/account", s.requireAuth(s.handleAccountPage)) mux.HandleFunc("/api/account", s.requireAuth(s.handleAccountAPI)) mux.HandleFunc("/admin", s.requireAdmin(s.handleAdminPage)) mux.HandleFunc("/api/notifications", s.requireAdmin(s.handleNotificationsAPI)) mux.HandleFunc("/api/notifications/test", s.requireAdmin(s.handleNotificationsTestAPI)) mux.HandleFunc("/install", s.requireAdmin(s.handleInstallPage)) mux.HandleFunc("/api/install/ssh", s.requireAdmin(s.handleInstallSSHAPI)) mux.HandleFunc("/api/install/ssh/jobs/", s.requireAdmin(s.handleInstallSSHJobAPI)) mux.HandleFunc("/audit", s.requireAdmin(s.handleAuditPage)) mux.HandleFunc("/api/audit", s.requireAdmin(s.handleAuditAPI)) mux.HandleFunc("/users", s.requireAdmin(s.handleUsersPage)) mux.HandleFunc("/api/users", s.requireAdmin(s.handleUsersAPI)) mux.HandleFunc("/api/users/", s.requireAdmin(s.handleUserAPI)) mux.HandleFunc("/printers/", s.requireAuth(s.handlePrinterPage)) mux.HandleFunc("/login", s.handleLogin) mux.HandleFunc("/logout", s.handleLogout) mux.HandleFunc("/favicon.ico", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "web/static/assets/favicon.png") }) mux.HandleFunc("/apple-touch-icon.png", func(w http.ResponseWriter, r *http.Request) { http.ServeFile(w, r, "web/static/assets/favicon.png") }) mux.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("web/static")))) mux.HandleFunc("/", s.handleLandingPage) mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte("ok\n")) }) log.Printf("server listening on %s", listen) if err := http.ListenAndServe(listen, mux); err != nil { log.Fatal(err) } } func (s *server) requireAuth(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { if isPublicPrinterUIAsset(r.URL.Path) { next(w, r) return } if s.isAuthenticated(r) { next(w, r) return } if strings.HasPrefix(r.URL.Path, "/api/") { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } http.Redirect(w, r, "/login", http.StatusSeeOther) } } func isPublicPrinterUIAsset(path string) bool { return strings.HasSuffix(path, "/manifest.webmanifest") || strings.HasSuffix(path, "/sw.js") } func (s *server) isAuthenticated(r *http.Request) bool { _, ok := s.currentSession(r) return ok } func (s *server) currentSession(r *http.Request) (authenticatedSession, bool) { cookie, err := r.Cookie("ka_session") if err != nil || cookie.Value == "" { return authenticatedSession{}, false } s.sessionsMu.RLock() sess, ok := s.sessions[cookie.Value] s.sessionsMu.RUnlock() if !ok || time.Now().After(sess.ExpiresAt) { if ok { s.sessionsMu.Lock() delete(s.sessions, cookie.Value) s.sessionsMu.Unlock() } return authenticatedSession{}, false } user, ok := s.users.getByID(sess.UserID) if !ok { s.sessionsMu.Lock() delete(s.sessions, cookie.Value) s.sessionsMu.Unlock() return authenticatedSession{}, false } return authenticatedSession{ UserID: user.ID, Username: user.Username, Role: user.Role, PrinterGrants: append([]printerGrant(nil), user.PrinterGrants...), CSRFToken: sess.CSRFToken, ExpiresAt: sess.ExpiresAt, }, true } func (s *server) handleLandingPage(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/" { http.NotFound(w, r) return } http.ServeFile(w, r, "web/static/index.html") } func (s *server) handleDashboard(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/dashboard" { http.NotFound(w, r) return } sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return } page, err := os.ReadFile("web/static/dashboard.html") if err != nil { http.Error(w, "dashboard unavailable", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") _, _ = w.Write([]byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken))) } func (s *server) handleAccountPage(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/account" { http.NotFound(w, r) return } sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return } page, err := os.ReadFile("web/static/account.html") if err != nil { http.Error(w, "account page unavailable", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) page = []byte(strings.ReplaceAll(string(page), "{{USERNAME}}", sess.Username)) page = []byte(strings.ReplaceAll(string(page), "{{ROLE}}", sess.Role)) _, _ = w.Write(page) } func (s *server) handleAdminPage(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/admin" { http.NotFound(w, r) return } sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return } page, err := os.ReadFile("web/static/admin.html") if err != nil { http.Error(w, "admin page unavailable", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) _, _ = w.Write(page) } func (s *server) handleAccountAPI(w http.ResponseWriter, r *http.Request) { sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } switch r.Method { case http.MethodGet: user, ok := s.users.getByID(sess.UserID) if !ok { writeJSON(w, http.StatusNotFound, map[string]any{"error": "user not found"}) return } writeJSON(w, http.StatusOK, map[string]any{"user": user}) case http.MethodPatch: if !s.verifyCSRF(w, r, sess) { return } var body struct { CurrentPassword string `json:"current_password"` NewPassword string `json:"new_password"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } if strings.TrimSpace(body.CurrentPassword) == "" || strings.TrimSpace(body.NewPassword) == "" { http.Error(w, "current password and new password are required", http.StatusBadRequest) return } if err := s.users.changePassword(sess.UserID, body.CurrentPassword, body.NewPassword); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("account_password_change"), Detail: "changed own password", }) writeJSON(w, http.StatusOK, map[string]any{"ok": true}) default: w.Header().Set("Allow", "GET, PATCH") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func (s *server) handleNotificationsAPI(w http.ResponseWriter, r *http.Request) { sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } if sess.Role != "admin" { http.Error(w, "admin access required", http.StatusForbidden) return } switch r.Method { case http.MethodGet: if s.notificationSettings == nil { writeJSON(w, http.StatusOK, map[string]any{"notifications": publicNotificationSettings(notificationSettingsRecord{})}) return } writeJSON(w, http.StatusOK, map[string]any{"notifications": publicNotificationSettings(s.notificationSettings.snapshot())}) case http.MethodPatch: if !s.verifyCSRF(w, r, sess) { return } if s.notificationSettings == nil { http.Error(w, "notification settings are unavailable", http.StatusInternalServerError) return } before := s.notificationSettings.snapshot() var body struct { TelegramEnabled *bool `json:"telegram_enabled"` TelegramCommandsEnabled *bool `json:"telegram_commands_enabled"` TelegramBotToken *string `json:"telegram_bot_token"` TelegramChatID *string `json:"telegram_chat_id"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } updated, err := s.notificationSettings.update(body.TelegramEnabled, body.TelegramCommandsEnabled, body.TelegramBotToken, body.TelegramChatID) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("notification_settings_update"), Detail: describeNotificationSettingsChange(before, updated), }) writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "notifications": publicNotificationSettings(updated), }) default: w.Header().Set("Allow", "GET, PATCH") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func (s *server) handleNotificationsTestAPI(w http.ResponseWriter, r *http.Request) { sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } if sess.Role != "admin" { http.Error(w, "admin access required", http.StatusForbidden) return } if r.Method != http.MethodPost { w.Header().Set("Allow", "POST") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } if !s.verifyCSRF(w, r, sess) { return } if s.notificationSettings == nil || s.notifier == nil { http.Error(w, "notification settings are unavailable", http.StatusInternalServerError) return } var body struct { TelegramEnabled *bool `json:"telegram_enabled"` TelegramBotToken *string `json:"telegram_bot_token"` TelegramChatID *string `json:"telegram_chat_id"` Message *string `json:"message"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil && err != io.EOF { http.Error(w, "invalid json", http.StatusBadRequest) return } record := s.notificationSettings.snapshot() if body.TelegramEnabled != nil { record.TelegramEnabled = *body.TelegramEnabled } if body.TelegramBotToken != nil { record.TelegramBotToken = strings.TrimSpace(*body.TelegramBotToken) } if body.TelegramChatID != nil { record.TelegramChatID = strings.TrimSpace(*body.TelegramChatID) } token := strings.TrimSpace(record.TelegramBotToken) chatID := strings.TrimSpace(record.TelegramChatID) if token == "" || chatID == "" { http.Error(w, "telegram bot token and chat ID are required", http.StatusBadRequest) return } message := "" if body.Message != nil { message = strings.TrimSpace(*body.Message) } if message == "" { message = "KlipperAnywhere test notification\nIf you received this, Telegram delivery is working." } if err := s.notifier.sendTelegramMessage(r.Context(), token, chatID, message); err != nil { s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("notification_settings_test"), Detail: fmt.Sprintf("failed telegram test notification: %v", err), }) http.Error(w, err.Error(), http.StatusBadGateway) return } detail := "sent telegram test notification" if !record.TelegramEnabled { detail += " while delivery is disabled" } if body.TelegramEnabled != nil || body.TelegramBotToken != nil || body.TelegramChatID != nil { detail += " using submitted values" } else { detail += " using saved settings" } s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("notification_settings_test"), Detail: detail, }) responseMessage := "Test notification sent." if !record.TelegramEnabled { responseMessage = "Test notification sent while Telegram delivery is disabled." } writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "message": responseMessage, }) } func (s *server) requireAdmin(next http.HandlerFunc) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return } if sess.Role != "admin" { http.Error(w, "admin access required", http.StatusForbidden) return } next(w, r) } } func (s *server) authorizePrinter(w http.ResponseWriter, r *http.Request, printerID string, control bool) (authenticatedSession, bool) { sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return authenticatedSession{}, false } if sess.Role != "admin" && !s.users.canAccessPrinter(sess.UserID, printerID, control) { http.Error(w, "printer access denied", http.StatusForbidden) return authenticatedSession{}, false } return sess, true } func (s *server) filteredConnectedPrinters(userID string) []string { s.tunnelsMu.RLock() printerIDs := make([]string, 0, len(s.tunnels)) for printerID := range s.tunnels { printerIDs = append(printerIDs, printerID) } s.tunnelsMu.RUnlock() return s.users.visiblePrinters(userID, printerIDs) } func (s *server) handlePrinterPage(w http.ResponseWriter, r *http.Request) { if strings.TrimPrefix(r.URL.Path, "/printers/") == "" { http.NotFound(w, r) return } if printerID, ok := parsePrinterAgentPath(r.URL.Path); ok { if _, ok := s.authorizePrinter(w, r, printerID, false); !ok { return } http.ServeFile(w, r, "web/static/printer-agent.html") return } if printerID, ok := parsePrinterSettingsPath(r.URL.Path); ok { if _, ok := s.authorizePrinter(w, r, printerID, false); !ok { return } http.ServeFile(w, r, "web/static/printer-settings.html") return } if printerID, uiPath, ok := parsePrinterUIPath(r.URL.Path); ok { if uiPath == "/manifest.webmanifest" || uiPath == "/sw.js" { s.handleUIProxy(w, r, printerID, uiPath, "") return } sess, ok := s.authorizePrinter(w, r, printerID, false) if !ok { return } s.handleUIProxy(w, r, printerID, uiPath, sess.Username) return } if printerID, ok := parsePrinterRootPath(r.URL.Path); ok { if _, ok := s.authorizePrinter(w, r, printerID, false); !ok { return } } http.ServeFile(w, r, "web/static/printer.html") } func (s *server) handleLogin(w http.ResponseWriter, r *http.Request) { switch r.Method { case http.MethodGet: if s.isAuthenticated(r) { http.Redirect(w, r, "/dashboard", http.StatusSeeOther) return } http.ServeFile(w, r, "web/static/login.html") case http.MethodPost: clientIP := requestIP(r) if !s.loginLimiter.allow(clientIP) { http.Error(w, "too many login attempts", http.StatusTooManyRequests) return } if err := r.ParseForm(); err != nil { http.Error(w, "invalid form", http.StatusBadRequest) return } username := r.FormValue("username") password := r.FormValue("password") user, ok, err := s.users.authenticate(username, password) if err != nil { http.Error(w, "authentication unavailable", http.StatusInternalServerError) return } if !ok { http.Redirect(w, r, "/login?error=1", http.StatusSeeOther) return } s.loginLimiter.reset(clientIP) sessionID, err := newID() if err != nil { http.Error(w, "failed to create session", http.StatusInternalServerError) return } csrfToken, err := newID() if err != nil { http.Error(w, "failed to create session", http.StatusInternalServerError) return } expiresAt := time.Now().Add(12 * time.Hour) s.sessionsMu.Lock() s.sessions[sessionID] = sessionRecord{ UserID: user.ID, CSRFToken: csrfToken, ExpiresAt: expiresAt, } s.sessionsMu.Unlock() http.SetCookie(w, &http.Cookie{ Name: "ka_session", Value: sessionID, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.cookieSecure, Expires: expiresAt, }) s.logAudit(auditEvent{ Actor: user.Username, Action: actionLabel("login"), Detail: "successful login", }) http.Redirect(w, r, "/dashboard", http.StatusSeeOther) default: w.Header().Set("Allow", "GET, POST") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func (s *server) handleLogout(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodPost { w.Header().Set("Allow", "POST") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/", http.StatusSeeOther) return } if err := r.ParseForm(); err != nil { http.Error(w, "invalid form", http.StatusBadRequest) return } if !constantTimeEqual(r.FormValue("csrf_token"), sess.CSRFToken) { http.Error(w, "invalid csrf token", http.StatusForbidden) return } if cookie, err := r.Cookie("ka_session"); err == nil { s.sessionsMu.Lock() delete(s.sessions, cookie.Value) s.sessionsMu.Unlock() } s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("logout"), Detail: "signed out", }) http.SetCookie(w, &http.Cookie{ Name: "ka_session", Value: "", Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.cookieSecure, MaxAge: -1, }) http.Redirect(w, r, "/", http.StatusSeeOther) } func (s *server) handleSessionAPI(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { w.Header().Set("Allow", "GET") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusOK, map[string]any{ "authenticated": false, }) return } writeJSON(w, http.StatusOK, map[string]any{ "authenticated": true, "user_id": sess.UserID, "username": sess.Username, "role": sess.Role, "is_admin": sess.Role == "admin", "printer_grants": sess.PrinterGrants, "csrf_token": sess.CSRFToken, "server_version": serverVersion, }) } func (s *server) handleUsersPage(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/users" { http.NotFound(w, r) return } page, err := os.ReadFile("web/static/users.html") if err != nil { http.Error(w, "users page unavailable", http.StatusInternalServerError) return } sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) page = []byte(strings.ReplaceAll(string(page), "{{CURRENT_ROLE}}", sess.Role)) _, _ = w.Write(page) } func (s *server) handleAuditPage(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/audit" { http.NotFound(w, r) return } sess, ok := s.currentSession(r) if !ok { http.Redirect(w, r, "/login", http.StatusSeeOther) return } page, err := os.ReadFile("web/static/audit.html") if err != nil { http.Error(w, "audit page unavailable", http.StatusInternalServerError) return } w.Header().Set("Content-Type", "text/html; charset=utf-8") page = []byte(strings.ReplaceAll(string(page), "{{CSRF_TOKEN}}", sess.CSRFToken)) _, _ = w.Write(page) } func (s *server) handleAuditAPI(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { w.Header().Set("Allow", "GET") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } limit := 100 if raw := strings.TrimSpace(r.URL.Query().Get("limit")); raw != "" { if parsed, err := strconv.Atoi(raw); err == nil && parsed > 0 && parsed <= 500 { limit = parsed } } events, err := s.auditLog.recent(limit) if err != nil { http.Error(w, "unable to load audit events", http.StatusInternalServerError) return } writeJSON(w, http.StatusOK, map[string]any{ "events": events, "user": sess.Username, }) } func (s *server) handleUsersAPI(w http.ResponseWriter, r *http.Request) { sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } if sess.Role != "admin" { http.Error(w, "admin access required", http.StatusForbidden) return } switch r.Method { case http.MethodGet: users := s.users.listPublic() writeJSON(w, http.StatusOK, map[string]any{"users": users}) case http.MethodPost: if !s.verifyCSRF(w, r, sess) { return } var body struct { Username string `json:"username"` Password string `json:"password"` Role string `json:"role"` PrinterGrants []printerGrant `json:"printer_grants"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } user, err := s.users.create(body.Username, body.Password, body.Role, body.PrinterGrants) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("user_create"), TargetID: user.ID, Detail: "created user " + user.Username, }) writeJSON(w, http.StatusCreated, map[string]any{"user": user}) default: w.Header().Set("Allow", "GET, POST") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func (s *server) handleUserAPI(w http.ResponseWriter, r *http.Request) { sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } if sess.Role != "admin" { http.Error(w, "admin access required", http.StatusForbidden) return } userID := strings.TrimPrefix(r.URL.Path, "/api/users/") if userID == "" || strings.Contains(userID, "/") { http.NotFound(w, r) return } switch r.Method { case http.MethodPatch: if !s.verifyCSRF(w, r, sess) { return } var body struct { Password string `json:"password"` Role string `json:"role"` PrinterGrants []printerGrant `json:"printer_grants"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } updated, err := s.users.update(userID, body.Password, body.Role, body.PrinterGrants) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("user_update"), TargetID: userID, Detail: "updated user " + updated.Username, }) writeJSON(w, http.StatusOK, map[string]any{"user": updated}) case http.MethodDelete: if !s.verifyCSRF(w, r, sess) { return } if err := s.users.delete(userID, sess.UserID); err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("user_delete"), TargetID: userID, Detail: "deleted user", }) w.WriteHeader(http.StatusNoContent) default: w.Header().Set("Allow", "PATCH, DELETE") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func (s *server) verifyCSRF(w http.ResponseWriter, r *http.Request, sess authenticatedSession) bool { if constantTimeEqual(r.Header.Get("X-CSRF-Token"), sess.CSRFToken) { return true } if err := r.ParseForm(); err == nil && constantTimeEqual(r.FormValue("csrf_token"), sess.CSRFToken) { return true } http.Error(w, "invalid csrf token", http.StatusForbidden) return false } func (s *server) handleAgentTunnel(w http.ResponseWriter, r *http.Request) { printerID := r.URL.Query().Get("printer_id") token := r.URL.Query().Get("token") if printerID == "" || token == "" { http.Error(w, "printer_id and token are required", http.StatusBadRequest) return } if token != s.agentToken { http.Error(w, "invalid token", http.StatusUnauthorized) return } s.tunnelsMu.RLock() old := s.tunnels[printerID] if old != nil && old.acceptsDuplicateBlock(time.Now()) { log.Printf("rejecting duplicate agent tunnel printer_id=%s existing_remote=%s new_remote=%s", printerID, old.remoteAddr, r.RemoteAddr) s.tunnelsMu.RUnlock() http.Error(w, "printer agent is already connected", http.StatusConflict) return } s.tunnelsMu.RUnlock() conn, err := s.upgrader.Upgrade(w, r, nil) if err != nil { log.Printf("upgrade failed: %v", err) return } t := &tunnel{ printerID: printerID, remoteAddr: r.RemoteAddr, connectedAt: time.Now().UTC(), conn: conn, pending: make(map[string]chan protocol.Message), done: make(chan struct{}), } s.tunnelsMu.Lock() if old := s.tunnels[printerID]; old != nil { log.Printf("replacing existing agent tunnel printer_id=%s old_remote=%s new_remote=%s", printerID, old.remoteAddr, r.RemoteAddr) old.close() } s.tunnels[printerID] = t s.tunnelsMu.Unlock() log.Printf("agent connected printer_id=%s remote=%s", printerID, r.RemoteAddr) go t.readLoop(s) if err := s.syncPrinterSettings(printerID); err != nil { log.Printf("failed to sync printer settings printer_id=%s: %v", printerID, err) } <-t.done s.tunnelsMu.Lock() if s.tunnels[printerID] == t { delete(s.tunnels, printerID) } s.tunnelsMu.Unlock() t.close() log.Printf("agent disconnected printer_id=%s", printerID) } func (s *server) handlePrintersAPI(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/api/printers" { http.NotFound(w, r) return } sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } s.tunnelsMu.RLock() printers := make([]map[string]any, 0, len(s.tunnels)) for printerID, t := range s.tunnels { if sess.Role != "admin" && !s.users.canAccessPrinter(sess.UserID, printerID, false) { continue } t.healthMu.RLock() health := t.health t.healthMu.RUnlock() settings := s.printerSettings.current(printerID, health, s.controlMode) printers = append(printers, map[string]any{ "printer_id": printerID, "connected": true, "health": health, "settings": settings, }) } s.tunnelsMu.RUnlock() writeJSON(w, http.StatusOK, map[string]any{"printers": printers}) } func (s *server) handlePrinterAPI(w http.ResponseWriter, r *http.Request) { if strings.HasSuffix(r.URL.Path, "/agent/update") { printerID := strings.TrimSuffix(strings.TrimPrefix(r.URL.Path, "/api/printers/"), "/agent/update") printerID = strings.Trim(printerID, "/") if printerID == "" || strings.Contains(printerID, "/") { http.NotFound(w, r) return } s.handlePrinterAgentUpdateAPI(w, r, printerID) return } printerID, action, ok := parsePrinterAPIPath(r.URL.Path) if !ok { http.NotFound(w, r) return } if action == "" { s.handlePrinterDetailAPI(w, r, printerID) return } switch action { case "health": sess, ok := s.authorizePrinter(w, r, printerID, false) if !ok { return } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { writeJSON(w, http.StatusOK, map[string]any{ "printer_id": printerID, "connected": false, }) return } t.healthMu.RLock() health := t.health t.healthMu.RUnlock() writeJSON(w, http.StatusOK, map[string]any{ "printer_id": printerID, "connected": true, "health": health, "user": sess.Username, }) case "settings": s.handlePrinterSettingsAPI(w, r, printerID) case "agent": http.NotFound(w, r) default: http.NotFound(w, r) return } } func (s *server) handlePrinterDetailAPI(w http.ResponseWriter, r *http.Request, printerID string) { if r.Method != http.MethodGet { w.Header().Set("Allow", "GET") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } sess, ok := s.authorizePrinter(w, r, printerID, false) if !ok { return } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { synced, state, detail := s.printerSettingsSyncStatus(printerID, nil) record := s.printerSettings.current(printerID, nil, s.controlMode) writeJSON(w, http.StatusOK, map[string]any{ "printer_id": printerID, "connected": false, "health": nil, "info": nil, "print_status": nil, "recent_jobs": nil, "control_mode": s.controlModeForPrinter(printerID, nil), "settings": s.publicPrinterSettings(record), "settings_synced": synced, "settings_sync_state": state, "settings_sync_detail": detail, }) return } t.healthMu.RLock() health := t.health t.healthMu.RUnlock() synced, state, detail := s.printerSettingsSyncStatus(printerID, health) info, infoErr := s.fetchPrinterInfo(r.Context(), t) printStatus, printStatusErr := s.fetchPrinterPrintStatus(r.Context(), t) recentJobs, recentJobsErr := s.fetchPrinterJobHistory(r.Context(), t) if printStatus == nil && health != nil { printStatus = printStatusFromHealth(health) } response := map[string]any{ "printer_id": printerID, "connected": true, "health": health, "info": info, "print_status": printStatus, "recent_jobs": recentJobs, "control_mode": s.controlModeForPrinter(printerID, health), "access": s.users.printerAccessLevel(sess.UserID, printerID), "settings": s.publicPrinterSettings(s.printerSettings.current(printerID, health, s.controlMode)), "settings_synced": synced, "settings_sync_state": state, "settings_sync_detail": detail, } if infoErr != nil { response["info_error"] = infoErr.Error() } if printStatusErr != nil { response["print_status_error"] = printStatusErr.Error() } if recentJobsErr != nil { response["recent_jobs_error"] = recentJobsErr.Error() } writeJSON(w, http.StatusOK, response) } func (s *server) fetchPrinterInfo(ctx context.Context, t *tunnel) (map[string]any, error) { id, err := newID() if err != nil { return nil, err } requestCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() resp, err := t.request(requestCtx, protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Method: http.MethodGet, Path: "/printer/info", }) if err != nil { return nil, err } if resp.Type == protocol.MessageError { return nil, fmt.Errorf("%s", resp.Error) } body, err := base64.StdEncoding.DecodeString(resp.Body) if err != nil { return nil, err } var parsed struct { Result map[string]any `json:"result"` } if err := json.Unmarshal(body, &parsed); err != nil { return nil, err } return parsed.Result, nil } func (s *server) fetchPrinterPrintStatus(ctx context.Context, t *tunnel) (map[string]any, error) { return s.fetchPrinterObjectStatus(ctx, t, []string{"print_stats", "display_status"}) } func (s *server) fetchPrinterObjectStatus(ctx context.Context, t *tunnel, objects []string) (map[string]any, error) { if t == nil { return nil, fmt.Errorf("printer is not connected") } id, err := newID() if err != nil { return nil, err } requestCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() escaped := make([]string, 0, len(objects)) for _, object := range objects { object = strings.TrimSpace(object) if object == "" { continue } escaped = append(escaped, url.QueryEscape(object)) } path := "/printer/objects/query" if len(escaped) > 0 { path += "?" + strings.Join(escaped, "&") } resp, err := t.request(requestCtx, protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Method: http.MethodGet, Path: path, }) if err != nil { return nil, err } if resp.Type == protocol.MessageError { return nil, fmt.Errorf("%s", resp.Error) } body, err := base64.StdEncoding.DecodeString(resp.Body) if err != nil { return nil, err } status, err := parseMoonrakerObjectStatus(body) if err != nil { return nil, err } if status == nil { return nil, fmt.Errorf("missing status data") } return status, nil } func (s *server) fetchPrinterJobHistory(ctx context.Context, t *tunnel) ([]map[string]any, error) { id, err := newID() if err != nil { return nil, err } requestCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() resp, err := t.request(requestCtx, protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Method: http.MethodGet, Path: "/server/history/list?limit=5&order=desc", }) if err != nil { return nil, err } if resp.Type == protocol.MessageError { return nil, fmt.Errorf("%s", resp.Error) } body, err := base64.StdEncoding.DecodeString(resp.Body) if err != nil { return nil, err } jobs, err := parseMoonrakerJobHistory(body) if err != nil { return nil, err } return jobs, nil } func (s *server) fetchPrinterFileList(ctx context.Context, t *tunnel) ([]moonrakerFileInfo, error) { id, err := newID() if err != nil { return nil, err } requestCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() resp, err := t.request(requestCtx, protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Method: http.MethodGet, Path: "/server/files/list?root=gcodes", }) if err != nil { return nil, err } if resp.Type == protocol.MessageError { return nil, fmt.Errorf("%s", resp.Error) } body, err := base64.StdEncoding.DecodeString(resp.Body) if err != nil { return nil, err } files, err := parseMoonrakerFileList(body) if err != nil { return nil, err } return files, nil } func (s *server) tunnelForPrinter(printerID string) *tunnel { s.tunnelsMu.RLock() defer s.tunnelsMu.RUnlock() return s.tunnels[printerID] } func (s *server) lastPrintableJobFilename(ctx context.Context, t *tunnel) (string, string, error) { jobs, err := s.fetchPrinterJobHistory(ctx, t) if err != nil { return "", "", err } filename, status := selectLastPrintableJob(jobs) if filename != "" { return filename, status, nil } return "", "", fmt.Errorf("no completed print job was found in recent history") } func (s *server) startPrinterJob(ctx context.Context, t *tunnel, filename string) error { filename = strings.TrimSpace(filename) if filename == "" { return fmt.Errorf("filename is required") } id, err := newID() if err != nil { return err } requestCtx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() resp, err := t.request(requestCtx, protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Method: http.MethodPost, Path: "/printer/print/start?filename=" + url.QueryEscape(filename), }) if err != nil { return err } if resp.Type == protocol.MessageError { return fmt.Errorf("%s", resp.Error) } if resp.Status < 200 || resp.Status >= 300 { return fmt.Errorf("printer rejected print start with status %d", resp.Status) } return nil } func (s *server) setPrinterHeaterTarget(ctx context.Context, t *tunnel, heater string, target float64) error { heater = strings.TrimSpace(heater) if heater == "" { return fmt.Errorf("heater is required") } id, err := newID() if err != nil { return err } requestCtx, cancel := context.WithTimeout(ctx, 15*time.Second) defer cancel() script := fmt.Sprintf("SET_HEATER_TEMPERATURE HEATER=%s TARGET=%s", heater, strconv.FormatFloat(target, 'f', -1, 64)) resp, err := t.request(requestCtx, protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Method: http.MethodPost, Path: "/printer/gcode/script?script=" + url.QueryEscape(script), }) if err != nil { return err } if resp.Type == protocol.MessageError { return fmt.Errorf("%s", resp.Error) } if resp.Status < 200 || resp.Status >= 300 { return fmt.Errorf("printer rejected heater target change with status %d", resp.Status) } return nil } func isTerminalJobHistoryStatus(status string) bool { switch strings.ToLower(strings.TrimSpace(status)) { case "complete", "completed", "cancelled", "canceled", "failed", "error", "aborted": return true default: return false } } func selectLastPrintableJob(jobs []map[string]any) (string, string) { for _, job := range jobs { filename := strings.TrimSpace(stringFromAny(job["filename"])) if filename == "" { continue } status := strings.ToLower(strings.TrimSpace(stringFromAny(job["status"]))) if status == "" || isTerminalJobHistoryStatus(status) { return filename, status } } return "", "" } type moonrakerFileInfo struct { Path string `json:"path"` Modified float64 `json:"modified"` Size int64 `json:"size"` Permissions string `json:"permissions"` } func parseMoonrakerFileList(body []byte) ([]moonrakerFileInfo, error) { trimmed := bytes.TrimSpace(body) if len(trimmed) > 0 && trimmed[0] == '[' { var arrayResult []moonrakerFileInfo if err := json.Unmarshal(trimmed, &arrayResult); err != nil { return nil, err } return arrayResult, nil } var parsed struct { Result []moonrakerFileInfo `json:"result"` Files []moonrakerFileInfo `json:"files"` } if err := json.Unmarshal(trimmed, &parsed); err != nil { return nil, err } if len(parsed.Result) > 0 { return parsed.Result, nil } return parsed.Files, nil } func stringFromAny(value any) string { switch v := value.(type) { case string: return v case fmt.Stringer: return v.String() default: return "" } } func parseMoonrakerPrintStatus(body []byte) (map[string]any, error) { status, err := parseMoonrakerObjectStatus(body) if err != nil { return nil, err } return status, nil } func parseMoonrakerObjectStatus(body []byte) (map[string]any, error) { var parsed struct { Result struct { Status map[string]any `json:"status"` } `json:"result"` } if err := json.Unmarshal(body, &parsed); err != nil { return nil, err } return parsed.Result.Status, nil } func parseMoonrakerJobHistory(body []byte) ([]map[string]any, error) { var parsed struct { Result struct { Jobs []map[string]any `json:"jobs"` } `json:"result"` Jobs []map[string]any `json:"jobs"` } if err := json.Unmarshal(body, &parsed); err != nil { return nil, err } if len(parsed.Result.Jobs) > 0 { return parsed.Result.Jobs, nil } return parsed.Jobs, nil } func printStatusFromHealth(health *protocol.Health) map[string]any { if health == nil || health.PrintStatus == nil { return nil } return map[string]any{ "print_stats": map[string]any{ "state": health.PrintStatus.State, "filename": health.PrintStatus.Filename, "message": health.PrintStatus.Message, "print_duration": health.PrintStatus.PrintDuration, "total_duration": health.PrintStatus.TotalDuration, "filament_used": health.PrintStatus.FilamentUsed, "estimated_time_remaining": health.PrintStatus.EstimatedTimeRemaining, }, "display_status": map[string]any{ "progress": health.PrintStatus.Progress, }, "moonraker_status": health.PrintStatus.MoonrakerStatus, "moonraker_metadata": health.PrintStatus.MoonrakerMetadata, "layer_source": health.PrintStatus.LayerSource, } } func (s *server) handlePrinterProxy(w http.ResponseWriter, r *http.Request) { if printerID, cameraName, cameraKind, ok := parseCameraPath(r.URL.Path); ok { sess, ok := s.authorizePrinter(w, r, printerID, false) if !ok { return } if cameraKind == "stream" { s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("camera_view"), PrinterID: printerID, Detail: "opened camera stream", }) } s.handleCameraProxy(w, r, printerID, cameraName, cameraKind) return } printerID, moonrakerPath, ok := parseProxyPath(r.URL.Path) if !ok { http.NotFound(w, r) return } if r.URL.RawQuery != "" { moonrakerPath += "?" + r.URL.RawQuery } controlRequest := !isReadOnlyMoonrakerRequest(r.Method, moonrakerPath) sess, ok := s.authorizePrinter(w, r, printerID, controlRequest) if !ok { return } if s.controlModeForPrinter(printerID, nil) == "readonly" && !isReadOnlyMoonrakerRequest(r.Method, moonrakerPath) { log.Printf("blocked read-only printer_id=%s method=%s path=%s", printerID, r.Method, moonrakerPath) http.Error(w, "blocked by read-only printer control policy", http.StatusForbidden) return } if isWebSocketUpgrade(r) { enforceReadOnlyFrames := s.controlModeForPrinter(printerID, nil) == "readonly" if controlRequest { s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("printer_ws_control"), PrinterID: printerID, Method: r.Method, Path: moonrakerPath, Detail: "opened Moonraker websocket", }) } s.handleTunneledWebSocket(w, r, printerID, moonrakerPath, "moonraker_ws", enforceReadOnlyFrames, sess.Username) return } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { http.Error(w, "printer agent is not connected", http.StatusBadGateway) return } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 32<<20)) if err != nil { http.Error(w, "failed to read request body", http.StatusBadRequest) return } id, err := newID() if err != nil { http.Error(w, "failed to create request id", http.StatusInternalServerError) return } msg := protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Method: r.Method, Path: moonrakerPath, Headers: moonrakerRequestHeaders(r.Header), Body: base64.StdEncoding.EncodeToString(body), } ctx, cancel := context.WithTimeout(r.Context(), 30*time.Second) defer cancel() resp, err := t.request(ctx, msg) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } if resp.Type == protocol.MessageError { http.Error(w, resp.Error, http.StatusBadGateway) return } respBody, err := base64.StdEncoding.DecodeString(resp.Body) if err != nil { http.Error(w, "agent returned invalid response body", http.StatusBadGateway) return } if strings.Contains(moonrakerPath, "/server/webcams/") { respBody = rewriteMoonrakerWebcams(respBody, printerID) } writeResponseHeaders(w, resp) w.Header().Set("Cache-Control", "no-store, max-age=0") if resp.Status == 0 { resp.Status = http.StatusBadGateway } w.WriteHeader(resp.Status) _, _ = w.Write(respBody) if controlRequest { s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("printer_http_control"), PrinterID: printerID, Method: r.Method, Path: moonrakerPath, Status: resp.Status, Detail: "proxied Moonraker control request", }) } log.Printf("proxied printer_id=%s method=%s path=%s status=%d", printerID, r.Method, moonrakerPath, resp.Status) } func (s *server) handlePrinterSettingsAPI(w http.ResponseWriter, r *http.Request, printerID string) { sess, ok := s.currentSession(r) if !ok { writeJSON(w, http.StatusUnauthorized, map[string]any{"error": "authentication required"}) return } if sess.Role != "admin" { http.Error(w, "admin access required", http.StatusForbidden) return } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() var health *protocol.Health if t != nil { t.healthMu.RLock() health = t.health t.healthMu.RUnlock() } switch r.Method { case http.MethodGet: synced, state, detail := s.printerSettingsSyncStatus(printerID, health) record := s.printerSettings.current(printerID, health, s.controlMode) writeJSON(w, http.StatusOK, map[string]any{ "printer_id": printerID, "settings": s.publicPrinterSettings(record), "control_mode": s.controlModeForPrinter(printerID, health), "settings_synced": synced, "settings_sync_state": state, "settings_sync_detail": detail, }) case http.MethodPatch: if !s.verifyCSRF(w, r, sess) { return } before := s.printerSettings.current(printerID, health, s.controlMode) var body struct { DisplayName *string `json:"display_name"` ControlMode *string `json:"control_mode"` UIURL *string `json:"ui_url"` UIAutoDetect *bool `json:"ui_auto_detect"` NotificationSnapshotCamera *string `json:"notification_snapshot_camera"` PrintNotificationsEnabled *bool `json:"print_notifications_enabled"` NotifyPrintStarted *bool `json:"notify_print_started"` NotifyPrintPaused *bool `json:"notify_print_paused"` NotifyPrintResumed *bool `json:"notify_print_resumed"` NotifyPrintCompleted *bool `json:"notify_print_completed"` NotifyPrintCanceled *bool `json:"notify_print_canceled"` NotifyPrintFailed *bool `json:"notify_print_failed"` NotifyFirstLayer *bool `json:"notify_print_first_layer"` NotifyThirdLayer *bool `json:"notify_print_third_layer"` } if err := json.NewDecoder(r.Body).Decode(&body); err != nil { http.Error(w, "invalid json", http.StatusBadRequest) return } if body.NotificationSnapshotCamera != nil && health != nil && !notificationSnapshotCameraAllowed(health, *body.NotificationSnapshotCamera) { http.Error(w, "notification snapshot camera must be blank or a snapshot-capable camera from the latest heartbeat", http.StatusBadRequest) return } updated, err := s.printerSettings.update(printerID, body.DisplayName, body.ControlMode, body.UIURL, body.UIAutoDetect, body.NotificationSnapshotCamera, s.controlMode) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } updated, err = s.printerSettings.updateNotifications(printerID, body.PrintNotificationsEnabled, body.NotifyPrintStarted, body.NotifyPrintPaused, body.NotifyPrintResumed, body.NotifyPrintCompleted, body.NotifyPrintCanceled, body.NotifyPrintFailed, body.NotifyFirstLayer, body.NotifyThirdLayer) if err != nil { http.Error(w, err.Error(), http.StatusBadRequest) return } if err := s.syncPrinterSettings(printerID); err != nil { log.Printf("failed to sync printer settings printer_id=%s: %v", printerID, err) } synced, state, detail := s.printerSettingsSyncStatus(printerID, health) s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("printer_settings_update"), PrinterID: printerID, Detail: describePrinterSettingsChange(before, updated), }) writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "printer_id": printerID, "settings": s.publicPrinterSettings(updated), "settings_synced": synced, "settings_sync_state": state, "settings_sync_detail": detail, }) default: w.Header().Set("Allow", "GET, PATCH") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) } } func (s *server) syncPrinterSettings(printerID string) error { s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { return nil } record, ok := s.printerSettings.snapshot(printerID) if !ok { return nil } id, err := newID() if err != nil { return err } requestCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) defer cancel() resp, err := t.request(requestCtx, protocol.Message{ ID: id, Type: protocol.MessageConfigSync, Settings: &protocol.Settings{ ControlMode: record.ControlMode, UIURL: record.UIURL, UIAutoDetect: record.UIAutoDetect, }, }) if err != nil { return err } if resp.Type == protocol.MessageError { return fmt.Errorf("%s", resp.Error) } if err := s.printerSettings.markSynced(printerID); err != nil { return err } return nil } func (s *server) controlModeForPrinter(printerID string, health *protocol.Health) string { if record, ok := s.printerSettings.snapshot(printerID); ok { if record.ControlMode != "" { return record.ControlMode } } return s.controlMode } func (s *server) printerSettingsSyncStatus(printerID string, health *protocol.Health) (bool, string, string) { record := s.printerSettings.current(printerID, health, s.controlMode) if record.UpdatedAt.IsZero() { return false, "Pending", "No printer settings have been saved yet." } if record.LastSyncedAt.IsZero() || record.LastSyncedAt.Before(record.UpdatedAt) { if health == nil { return false, "Pending", "Waiting for the agent to confirm the latest settings." } detail := "Waiting for the agent to confirm the latest settings." if applied := strings.TrimSpace(health.ControlMode); applied != "" { detail = fmt.Sprintf("%s Last heartbeat just now; applied mode %s.", detail, applied) } else { detail = fmt.Sprintf("%s Last heartbeat just now.", detail) } return false, "Pending", detail } return true, "Synced", "Agent acknowledged the latest saved settings." } func describePrinterSettingsChange(before, after printerSettingsRecord) string { var changes []string if strings.TrimSpace(before.DisplayName) != strings.TrimSpace(after.DisplayName) { changes = append(changes, fmt.Sprintf("display_name %q -> %q", strings.TrimSpace(before.DisplayName), strings.TrimSpace(after.DisplayName))) } if normalizeControlMode(before.ControlMode) != normalizeControlMode(after.ControlMode) { changes = append(changes, fmt.Sprintf("control_mode %q -> %q", normalizeControlMode(before.ControlMode), normalizeControlMode(after.ControlMode))) } if strings.TrimSpace(before.UIURL) != strings.TrimSpace(after.UIURL) { changes = append(changes, fmt.Sprintf("ui_url %q -> %q", strings.TrimSpace(before.UIURL), strings.TrimSpace(after.UIURL))) } if before.UIAutoDetect != after.UIAutoDetect { changes = append(changes, fmt.Sprintf("ui_auto_detect %t -> %t", before.UIAutoDetect, after.UIAutoDetect)) } if strings.TrimSpace(before.NotificationSnapshotCamera) != strings.TrimSpace(after.NotificationSnapshotCamera) { changes = append(changes, fmt.Sprintf("notification_snapshot_camera %q -> %q", strings.TrimSpace(before.NotificationSnapshotCamera), strings.TrimSpace(after.NotificationSnapshotCamera))) } if before.PrintNotificationsEnabled != after.PrintNotificationsEnabled { changes = append(changes, fmt.Sprintf("print_notifications_enabled %t -> %t", before.PrintNotificationsEnabled, after.PrintNotificationsEnabled)) } if before.NotifyPrintStarted != after.NotifyPrintStarted { changes = append(changes, fmt.Sprintf("notify_print_started %t -> %t", before.NotifyPrintStarted, after.NotifyPrintStarted)) } if before.NotifyPrintPaused != after.NotifyPrintPaused { changes = append(changes, fmt.Sprintf("notify_print_paused %t -> %t", before.NotifyPrintPaused, after.NotifyPrintPaused)) } if before.NotifyPrintResumed != after.NotifyPrintResumed { changes = append(changes, fmt.Sprintf("notify_print_resumed %t -> %t", before.NotifyPrintResumed, after.NotifyPrintResumed)) } if before.NotifyPrintCompleted != after.NotifyPrintCompleted { changes = append(changes, fmt.Sprintf("notify_print_completed %t -> %t", before.NotifyPrintCompleted, after.NotifyPrintCompleted)) } if before.NotifyPrintCanceled != after.NotifyPrintCanceled { changes = append(changes, fmt.Sprintf("notify_print_canceled %t -> %t", before.NotifyPrintCanceled, after.NotifyPrintCanceled)) } if before.NotifyPrintFailed != after.NotifyPrintFailed { changes = append(changes, fmt.Sprintf("notify_print_failed %t -> %t", before.NotifyPrintFailed, after.NotifyPrintFailed)) } if before.NotifyFirstLayer != after.NotifyFirstLayer { changes = append(changes, fmt.Sprintf("notify_print_first_layer %t -> %t", before.NotifyFirstLayer, after.NotifyFirstLayer)) } if before.NotifyThirdLayer != after.NotifyThirdLayer { changes = append(changes, fmt.Sprintf("notify_print_third_layer %t -> %t", before.NotifyThirdLayer, after.NotifyThirdLayer)) } if len(changes) == 0 { return "updated printer settings without field changes" } return "updated printer settings: " + strings.Join(changes, "; ") } func (s *server) publicPrinterSettings(record printerSettingsRecord) map[string]any { notificationReady, notificationSource := s.notificationDeliveryStatus() settings := map[string]any{ "printer_id": record.PrinterID, "display_name": record.DisplayName, "control_mode": record.ControlMode, "ui_url": record.UIURL, "ui_auto_detect": record.UIAutoDetect, "notification_snapshot_camera": record.NotificationSnapshotCamera, "updated_at": record.UpdatedAt, "display_name_updated_at": record.DisplayNameUpdatedAt, "last_synced_at": record.LastSyncedAt, "install": record.Install, "install_history": record.InstallHistory, "print_notifications_enabled": record.PrintNotificationsEnabled, "notify_print_started": record.NotifyPrintStarted, "notify_print_paused": record.NotifyPrintPaused, "notify_print_resumed": record.NotifyPrintResumed, "notify_print_completed": record.NotifyPrintCompleted, "notify_print_canceled": record.NotifyPrintCanceled, "notify_print_failed": record.NotifyPrintFailed, "notify_print_first_layer": record.NotifyFirstLayer, "notify_print_third_layer": record.NotifyThirdLayer, "notification_delivery_ready": notificationReady, "notification_delivery_source": notificationSource, "last_observed_print_state": record.LastObservedPrintState, "last_observed_print_file": record.LastObservedPrintFile, "last_observed_print_layer": record.LastObservedPrintLayer, "last_observed_at": record.LastObservedAt, "last_notified_print_state": record.LastNotifiedPrintState, "last_notified_print_file": record.LastNotifiedPrintFile, "last_notified_at": record.LastNotifiedAt, "last_notification_source": record.LastNotificationSource, "last_notification_error": record.LastNotificationError, "last_layer_notified_print_layer": record.LastLayerNotifiedPrintLayer, "last_layer_notified_at": record.LastLayerNotifiedAt, "last_layer_notification_source": record.LastLayerNotificationSource, "last_layer_notification_error": record.LastLayerNotificationError, } return settings } func describeNotificationSettingsChange(before notificationSettingsRecord, after notificationSettingsRecord) string { changes := make([]string, 0, 4) if before.TelegramEnabled != after.TelegramEnabled { changes = append(changes, fmt.Sprintf("telegram_enabled %t -> %t", before.TelegramEnabled, after.TelegramEnabled)) } if before.TelegramCommandsEnabled != after.TelegramCommandsEnabled { changes = append(changes, fmt.Sprintf("telegram_commands_enabled %t -> %t", before.TelegramCommandsEnabled, after.TelegramCommandsEnabled)) } if before.TelegramBotToken != "" && after.TelegramBotToken == "" { changes = append(changes, "telegram_bot_token cleared") } else if before.TelegramBotToken == "" && after.TelegramBotToken != "" { changes = append(changes, "telegram_bot_token configured") } if strings.TrimSpace(before.TelegramChatID) != strings.TrimSpace(after.TelegramChatID) { changes = append(changes, fmt.Sprintf("telegram_chat_id %q -> %q", strings.TrimSpace(before.TelegramChatID), strings.TrimSpace(after.TelegramChatID))) } if len(changes) == 0 { return "updated notification settings without field changes" } return "updated notification settings: " + strings.Join(changes, "; ") } func (s *server) notificationDeliveryStatus() (bool, string) { if s != nil && s.notificationSettings != nil { global := s.notificationSettings.snapshot() if global.TelegramEnabled && strings.TrimSpace(global.TelegramBotToken) != "" && strings.TrimSpace(global.TelegramChatID) != "" { return true, "admin" } } return false, "" } func (s *server) handlePrinterAgentUpdateAPI(w http.ResponseWriter, r *http.Request, printerID string) { if r.Method != http.MethodPost { w.Header().Set("Allow", "POST") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } sess, ok := s.authorizePrinter(w, r, printerID, true) if !ok { return } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { http.Error(w, "printer agent is not connected", http.StatusBadGateway) return } record, ok := s.printerSettings.snapshot(printerID) if !ok || record.Install == nil { http.Error(w, "saved install details are required before upgrading the agent", http.StatusBadRequest) return } releaseURL := strings.TrimSpace(record.Install.ReleaseURL) if releaseURL == "" { releaseURL = defaultReleaseBaseURL } reqID, err := newID() if err != nil { http.Error(w, "failed to create request", http.StatusInternalServerError) return } ctx, cancel := context.WithTimeout(r.Context(), 2*time.Minute) defer cancel() resp, err := t.request(ctx, protocol.Message{ ID: reqID, Type: protocol.MessageAgentUpdate, Update: &protocol.AgentUpdateRequest{ ReleaseURL: releaseURL, Version: serverVersion, }, }) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } if resp.Type == protocol.MessageError { http.Error(w, resp.Error, http.StatusBadGateway) return } connected, reconnectMessage, err := s.waitForPrinterConnection(r.Context(), printerID, 90*time.Second) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } updatedInstall := *record.Install updatedInstall.ReleaseURL = releaseURL updatedInstall.BinarySource = "agent-update" updatedInstall.Message = "sent one-click agent update request" updatedInstall.PostInstallConnected = connected updatedInstall.PostInstallMessage = reconnectMessage updatedInstall.RollbackPerformed = false updatedInstall.RollbackMessage = "" if connected { updatedInstall.Status = "upgraded" } else { updatedInstall.Status = "failed" updatedInstall.Error = "agent did not reconnect after update request" } updatedRecord, saveErr := s.printerSettings.updateInstall(printerID, updatedInstall) if saveErr != nil { log.Printf("failed to persist agent update record printer_id=%s: %v", printerID, saveErr) updatedRecord = record } s.logAudit(auditEvent{ Actor: sess.Username, Action: actionLabel("printer_agent_update"), PrinterID: printerID, Detail: fmt.Sprintf("triggered agent update; reconnect=%t", connected), }) writeJSON(w, http.StatusOK, map[string]any{ "ok": true, "printer_id": printerID, "settings": s.publicPrinterSettings(updatedRecord), "connected": connected, "reconnect_message": reconnectMessage, "agent_update_version": serverVersion, }) } func (s *server) handleLegacyWebcamProxy(w http.ResponseWriter, r *http.Request) { printerID, ok := legacyWebcamPrinterID(r) if !ok { http.Error(w, "printer context not found for webcam request", http.StatusNotFound) return } if _, ok := s.authorizePrinter(w, r, printerID, false); !ok { return } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { http.Error(w, "printer agent is not connected", http.StatusBadGateway) return } cameraName, kind := legacyWebcamTarget(t.health) if cameraName == "" { http.Error(w, "no camera is configured for this printer", http.StatusNotFound) return } s.setPrinterContextCookie(w, printerID) s.handleCameraProxy(w, r, printerID, cameraName, kind) } func (s *server) handleUIProxy(w http.ResponseWriter, r *http.Request, printerID string, uiPath string, actor string) { if uiPath == "/manifest.webmanifest" { manifest := map[string]any{ "name": "Fluidd", "short_name": "Fluidd", "description": "The Klipper web interface for managing your 3d printer", "start_url": "./", "scope": "./", "display": "standalone", "background_color": "#000000", "theme_color": "#2196F3", "lang": "en", } rewritten, err := json.Marshal(manifest) if err != nil { http.Error(w, "failed to render manifest", http.StatusInternalServerError) return } s.setPrinterContextCookie(w, printerID) w.Header().Set("Content-Type", "application/manifest+json") w.Header().Set("Cache-Control", "no-store, max-age=0") w.WriteHeader(http.StatusOK) _, _ = w.Write(rewritten) return } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { http.Error(w, "printer agent is not connected", http.StatusBadGateway) return } s.setPrinterContextCookie(w, printerID) if uiPath == "/" { s.logAudit(auditEvent{ Actor: actor, Action: actionLabel("printer_ui_open"), PrinterID: printerID, Detail: "opened printer UI", }) } if isWebSocketUpgrade(r) { s.handleTunneledWebSocketWithTunnel(w, r, t, printerID, uiPath, "ui_ws", false, actor) return } body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 32<<20)) if err != nil { http.Error(w, "failed to read request body", http.StatusBadRequest) return } uiPath = rewriteMoonrakerDatabaseNamespace(uiPath, printerID) id, err := newID() if err != nil { http.Error(w, "failed to create request id", http.StatusInternalServerError) return } resp, err := t.request(r.Context(), protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Target: "ui", Method: r.Method, Path: uiPath, Headers: uiRequestHeaders(r.Header), Body: base64.StdEncoding.EncodeToString(body), }) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } if resp.Type == protocol.MessageError { http.Error(w, resp.Error, http.StatusBadGateway) return } respBody, err := base64.StdEncoding.DecodeString(resp.Body) if err != nil { http.Error(w, "agent returned invalid ui response body", http.StatusBadGateway) return } writeResponseHeaders(w, resp) w.Header().Set("Cache-Control", "no-store, max-age=0") if uiPath == "/config.json" { respBody = rewriteFluiddConfig(respBody, requestOrigin(r), printerID) } if uiPath == "/sw.js" { w.Header().Set("Content-Type", "application/javascript") w.Header().Set("Cache-Control", "no-store, max-age=0") respBody = []byte(`self.addEventListener('install', event => { self.skipWaiting(); }); self.addEventListener('activate', event => { event.waitUntil(self.registration.unregister()); });`) } if uiPath == "/manifest.webmanifest" { w.Header().Set("Content-Type", "application/manifest+json") } respBody = rewriteUIResponse(resp.Headers, respBody, printerID) if resp.Status == 0 { resp.Status = http.StatusBadGateway } w.WriteHeader(resp.Status) _, _ = w.Write(respBody) log.Printf("proxied ui printer_id=%s method=%s path=%s status=%d", printerID, r.Method, uiPath, resp.Status) } func uiRequestHeaders(h http.Header) []protocol.Header { headers := make([]protocol.Header, 0, len(h)) for name, values := range h { if strings.EqualFold(name, "If-None-Match") || strings.EqualFold(name, "If-Modified-Since") || strings.EqualFold(name, "If-Range") { continue } if strings.EqualFold(name, "Cache-Control") { continue } headers = append(headers, protocol.Header{Name: name, Values: values}) } return headers } func sanitizeUIProxyQuery(rawQuery string) string { if rawQuery == "" { return "" } values, err := url.ParseQuery(rawQuery) if err != nil { return "" } values.Del("printer") return values.Encode() } func rewriteMoonrakerDatabaseNamespace(path string, printerID string) string { if !strings.HasPrefix(path, "/server/database/") { return path } u, err := url.Parse(path) if err != nil { return path } values := u.Query() namespace := values.Get("namespace") if namespace == "" { return path } if namespace == "fluidd" || strings.HasPrefix(namespace, "fluidd-") { values.Set("namespace", "fluidd-"+printerID) u.RawQuery = values.Encode() return u.String() } return path } func moonrakerRequestHeaders(h http.Header) []protocol.Header { headers := make([]protocol.Header, 0, len(h)) for name, values := range h { if strings.EqualFold(name, "If-None-Match") || strings.EqualFold(name, "If-Modified-Since") || strings.EqualFold(name, "If-Range") { continue } if strings.EqualFold(name, "Cache-Control") { continue } headers = append(headers, protocol.Header{Name: name, Values: values}) } return headers } func requestOrigin(r *http.Request) string { scheme := "http" if r.TLS != nil { scheme = "https" } if forwarded := strings.TrimSpace(r.Header.Get("X-Forwarded-Proto")); forwarded != "" { scheme = strings.ToLower(strings.Split(forwarded, ",")[0]) } return scheme + "://" + r.Host } func (s *server) handleCameraProxy(w http.ResponseWriter, r *http.Request, printerID string, cameraName string, cameraKind string) { if r.Method != http.MethodGet { w.Header().Set("Allow", "GET") http.Error(w, "method not allowed", http.StatusMethodNotAllowed) return } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { http.Error(w, "printer agent is not connected", http.StatusBadGateway) return } id, err := newID() if err != nil { http.Error(w, "failed to create request id", http.StatusInternalServerError) return } msg := protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Target: "camera", CameraName: cameraName, CameraKind: cameraKind, Method: http.MethodGet, } if cameraKind == "snapshot" { s.handleCameraSnapshot(w, r, t, msg, printerID, cameraName) return } s.handleCameraStream(w, r, t, msg, printerID, cameraName) } func (s *server) handleCameraSnapshot(w http.ResponseWriter, r *http.Request, t *tunnel, msg protocol.Message, printerID string, cameraName string) { ctx, cancel := context.WithTimeout(r.Context(), 20*time.Second) defer cancel() responses, cleanup, err := t.openRequest(ctx, msg) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } defer cleanup() var header protocol.Message select { case header = <-responses: case <-ctx.Done(): http.Error(w, ctx.Err().Error(), http.StatusBadGateway) return case <-t.done: http.Error(w, "agent disconnected", http.StatusBadGateway) return } if header.Type == protocol.MessageError { http.Error(w, header.Error, http.StatusBadGateway) return } writeResponseHeaders(w, header) w.Header().Set("Access-Control-Allow-Origin", "*") if header.Status == 0 { header.Status = http.StatusBadGateway } w.WriteHeader(header.Status) if flusher, ok := w.(http.Flusher); ok { flusher.Flush() } for msg := range responses { if msg.Type == protocol.MessageError { log.Printf("camera snapshot error printer_id=%s camera=%s error=%s", printerID, cameraName, msg.Error) return } if msg.Body != "" { body, err := base64.StdEncoding.DecodeString(msg.Body) if err != nil { log.Printf("invalid camera snapshot chunk printer_id=%s camera=%s: %v", printerID, cameraName, err) return } _, _ = w.Write(body) } if msg.End { break } } log.Printf("proxied camera snapshot printer_id=%s camera=%s status=%d", printerID, cameraName, header.Status) } func (s *server) handleCameraStream(w http.ResponseWriter, r *http.Request, t *tunnel, msg protocol.Message, printerID string, cameraName string) { responses, cleanup, err := t.openRequest(r.Context(), msg) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } defer cleanup() var header protocol.Message select { case header = <-responses: case <-r.Context().Done(): return case <-t.done: http.Error(w, "agent disconnected", http.StatusBadGateway) return } if header.Type == protocol.MessageError { http.Error(w, header.Error, http.StatusBadGateway) return } writeResponseHeaders(w, header) w.Header().Set("Access-Control-Allow-Origin", "*") if header.Status == 0 { header.Status = http.StatusBadGateway } w.WriteHeader(header.Status) if flusher, ok := w.(http.Flusher); ok { flusher.Flush() } flusher, _ := w.(http.Flusher) for { select { case <-r.Context().Done(): log.Printf("camera stream closed printer_id=%s camera=%s", printerID, cameraName) return case msg, ok := <-responses: if !ok { return } if msg.Type == protocol.MessageError { log.Printf("camera stream error printer_id=%s camera=%s error=%s", printerID, cameraName, msg.Error) return } if msg.Body != "" { body, err := base64.StdEncoding.DecodeString(msg.Body) if err != nil { log.Printf("invalid camera stream chunk printer_id=%s camera=%s: %v", printerID, cameraName, err) return } if _, err := w.Write(body); err != nil { return } if flusher != nil { flusher.Flush() } } if msg.End { return } } } } func isWebSocketUpgrade(r *http.Request) bool { return strings.EqualFold(r.Header.Get("Upgrade"), "websocket") } func (s *server) handleTunneledWebSocket(w http.ResponseWriter, r *http.Request, printerID string, upstreamPath string, target string, enforceReadOnlyFrames bool, actor string) { s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { http.Error(w, "printer agent is not connected", http.StatusBadGateway) return } s.handleTunneledWebSocketWithTunnel(w, r, t, printerID, upstreamPath, target, enforceReadOnlyFrames, actor) } func (s *server) handleTunneledWebSocketWithTunnel(w http.ResponseWriter, r *http.Request, t *tunnel, printerID string, upstreamPath string, target string, enforceReadOnlyFrames bool, actor string) { id, err := newID() if err != nil { http.Error(w, "failed to create request id", http.StatusInternalServerError) return } ctx, cancel := context.WithTimeout(r.Context(), 15*time.Second) defer cancel() responses, cleanup, err := t.openRequest(ctx, protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Target: target, Method: http.MethodGet, Path: upstreamPath, Headers: headersFromHTTP(r.Header), }) if err != nil { http.Error(w, err.Error(), http.StatusBadGateway) return } defer cleanup() var header protocol.Message select { case header = <-responses: case <-ctx.Done(): http.Error(w, ctx.Err().Error(), http.StatusBadGateway) return case <-t.done: http.Error(w, "agent disconnected", http.StatusBadGateway) return } if header.Type == protocol.MessageError { http.Error(w, header.Error, http.StatusBadGateway) return } if header.Status != http.StatusSwitchingProtocols { http.Error(w, "upstream websocket did not upgrade", http.StatusBadGateway) return } client, err := s.upgrader.Upgrade(w, r, nil) if err != nil { sendTunnelWebSocketEnd(t, id) return } defer client.Close() defer sendTunnelWebSocketEnd(t, id) done := make(chan struct{}, 2) var clientWriteMu sync.Mutex go func() { defer func() { done <- struct{}{} }() for { messageType, payload, err := client.ReadMessage() if err != nil { return } if enforceReadOnlyFrames && !isReadOnlyMoonrakerWebSocketPayload(payload) { log.Printf("blocked read-only websocket printer_id=%s path=%s payload=%s", printerID, upstreamPath, string(payload)) s.logAudit(auditEvent{ Actor: actor, Action: actionLabel("printer_ws_blocked"), PrinterID: printerID, Path: upstreamPath, Detail: "blocked read-only websocket control payload", }) clientWriteMu.Lock() _ = client.WriteJSON(readOnlyWebSocketError(payload)) clientWriteMu.Unlock() continue } if !isReadOnlyMoonrakerWebSocketPayload(payload) { s.logAudit(auditEvent{ Actor: actor, Action: actionLabel("printer_ws_control"), PrinterID: printerID, Path: upstreamPath, Detail: "proxied Moonraker websocket control payload", }) } if err := sendTunnelWebSocketFrame(t, id, messageType, payload); err != nil { return } } }() go func() { defer func() { done <- struct{}{} }() for { select { case msg := <-responses: if msg.Type == protocol.MessageError { log.Printf("websocket tunnel error printer_id=%s path=%s error=%s", printerID, upstreamPath, msg.Error) return } if msg.End { return } if msg.Body == "" { continue } payload, err := base64.StdEncoding.DecodeString(msg.Body) if err != nil { return } messageType := msg.WSMessageType if messageType != websocket.BinaryMessage && messageType != websocket.TextMessage { messageType = websocket.TextMessage } clientWriteMu.Lock() err = client.WriteMessage(messageType, payload) clientWriteMu.Unlock() if err != nil { return } case <-t.done: return case <-r.Context().Done(): return } } }() <-done log.Printf("proxied websocket printer_id=%s target=%s path=%s", printerID, target, upstreamPath) } func sendTunnelWebSocketFrame(t *tunnel, id string, messageType int, payload []byte) error { msg := protocol.Message{ ID: id, Target: "ws_frame", Body: base64.StdEncoding.EncodeToString(payload), WSMessageType: messageType, } t.writeMu.Lock() err := t.conn.WriteJSON(msg) t.writeMu.Unlock() return err } func sendTunnelWebSocketEnd(t *tunnel, id string) { t.writeMu.Lock() _ = t.conn.WriteJSON(protocol.Message{ID: id, Target: "ws_frame", End: true}) t.writeMu.Unlock() } func parsePrinterAPIPath(path string) (printerID string, action string, ok bool) { rest := strings.TrimPrefix(path, "/api/printers/") if rest == path { return "", "", false } parts := strings.Split(strings.Trim(rest, "/"), "/") if len(parts) == 1 && parts[0] != "" { return parts[0], "", true } if len(parts) != 2 || parts[0] == "" || parts[1] == "" { return "", "", false } return parts[0], parts[1], true } func parsePrinterUIPath(path string) (printerID string, uiPath string, ok bool) { rest := strings.TrimPrefix(path, "/printers/") if rest == path { return "", "", false } parts := strings.SplitN(rest, "/", 3) if len(parts) < 2 || parts[0] == "" || parts[1] != "ui" { return "", "", false } if len(parts) == 2 { return parts[0], "/", true } return parts[0], "/" + parts[2], true } func parsePrinterRootPath(path string) (printerID string, ok bool) { rest := strings.TrimPrefix(path, "/printers/") if rest == path { return "", false } parts := strings.Split(strings.Trim(rest, "/"), "/") if len(parts) != 1 || parts[0] == "" { return "", false } return parts[0], true } func parsePrinterSettingsPath(path string) (printerID string, ok bool) { rest := strings.TrimPrefix(path, "/printers/") if rest == path { return "", false } parts := strings.Split(strings.Trim(rest, "/"), "/") if len(parts) != 2 || parts[0] == "" || parts[1] != "settings" { return "", false } return parts[0], true } func parsePrinterAgentPath(path string) (printerID string, ok bool) { rest := strings.TrimPrefix(path, "/printers/") if rest == path { return "", false } parts := strings.Split(strings.Trim(rest, "/"), "/") if len(parts) != 2 || parts[0] == "" || parts[1] != "agent" { return "", false } return parts[0], true } func parseCameraPath(path string) (printerID string, cameraName string, cameraKind string, ok bool) { rest := strings.TrimPrefix(path, "/p/") if rest == path { return "", "", "", false } parts := strings.Split(strings.Trim(rest, "/"), "/") if len(parts) != 4 || parts[1] != "camera" || parts[0] == "" || parts[2] == "" { return "", "", "", false } if parts[3] != "snapshot" && parts[3] != "stream" { return "", "", "", false } return parts[0], parts[2], parts[3], true } func parseProxyPath(path string) (printerID string, moonrakerPath string, ok bool) { rest := strings.TrimPrefix(path, "/p/") if rest == path { return "", "", false } parts := strings.SplitN(rest, "/", 3) if len(parts) != 3 || parts[0] == "" || parts[1] != "moonraker" { return "", "", false } return parts[0], "/" + parts[2], true } func legacyWebcamPrinterID(r *http.Request) (string, bool) { if cookie, err := r.Cookie("ka_printer_context"); err == nil { if printerID := strings.TrimSpace(cookie.Value); printerID != "" { return printerID, true } } for _, candidate := range []string{r.Referer(), r.Header.Get("Origin")} { if candidate == "" { continue } u, err := url.Parse(candidate) if err != nil { continue } if printerID, _, ok := parsePrinterUIPath(u.Path); ok && printerID != "" { return printerID, true } } return "", false } func (s *server) setPrinterContextCookie(w http.ResponseWriter, printerID string) { if printerID == "" { return } http.SetCookie(w, &http.Cookie{ Name: "ka_printer_context", Value: printerID, Path: "/", HttpOnly: true, SameSite: http.SameSiteLaxMode, Secure: s.cookieSecure, }) } func legacyWebcamTarget(health *protocol.Health) (cameraName string, kind string) { if health == nil { return "", "snapshot" } for _, camera := range health.Cameras { if camera.Name == "" { continue } if camera.HasSnapshot { return camera.Name, "snapshot" } if camera.HasStream { return camera.Name, "stream" } } return "", "snapshot" } func (t *tunnel) request(ctx context.Context, msg protocol.Message) (protocol.Message, error) { ch, cleanup, err := t.openRequest(ctx, msg) if err != nil { return protocol.Message{}, err } defer cleanup() select { case resp := <-ch: return resp, nil case <-ctx.Done(): return protocol.Message{}, ctx.Err() case <-t.done: return protocol.Message{}, fmt.Errorf("agent disconnected") } } func (t *tunnel) openRequest(ctx context.Context, msg protocol.Message) (<-chan protocol.Message, func(), error) { ch := make(chan protocol.Message, 64) t.pendingMu.Lock() t.pending[msg.ID] = ch t.pendingMu.Unlock() cleanup := func() { t.pendingMu.Lock() delete(t.pending, msg.ID) t.pendingMu.Unlock() } t.writeMu.Lock() err := t.conn.WriteJSON(msg) t.writeMu.Unlock() if err != nil { cleanup() return nil, nil, err } return ch, cleanup, nil } func (s *server) handlePrinterHeartbeat(printerID string, health *protocol.Health) { if s == nil || s.printerSettings == nil || health == nil { return } _, created, err := s.printerSettings.ensureFromHealth(printerID, health, s.controlMode) if err != nil { log.Printf("failed to seed printer settings printer_id=%s: %v", printerID, err) return } if created { go func() { if err := s.syncPrinterSettings(printerID); err != nil { log.Printf("failed to sync seeded printer settings printer_id=%s: %v", printerID, err) } }() if health.PrintStatus != nil { if _, err := s.printerSettings.updatePrintObservation(printerID, health.PrintStatus, "", false, ""); err != nil { log.Printf("failed to seed print observation printer_id=%s: %v", printerID, err) } } return } if health.PrintStatus != nil { s.maybeNotifyPrinterPrintStatus(printerID, health) } } func (s *server) maybeNotifyPrinterPrintStatus(printerID string, health *protocol.Health) { if s == nil || s.printerSettings == nil || health == nil || health.PrintStatus == nil { return } record, ok := s.printerSettings.snapshot(printerID) if !ok { return } currentState := strings.TrimSpace(health.PrintStatus.State) currentFile := strings.TrimSpace(health.PrintStatus.Filename) currentLayer := health.PrintStatus.CurrentLayer previousState := strings.TrimSpace(record.LastObservedPrintState) previousLayer := record.LastObservedPrintLayer if record.LastObservedAt.IsZero() && previousState == "" { if _, err := s.printerSettings.updatePrintObservation(printerID, health.PrintStatus, "", false, ""); err != nil { log.Printf("failed to seed print observation printer_id=%s: %v", printerID, err) } if _, err := s.printerSettings.updatePrintLayerObservation(printerID, &protocol.PrintStatus{CurrentLayer: 0}, "", false, ""); err != nil { log.Printf("failed to seed print layer observation printer_id=%s: %v", printerID, err) } return } event := printerNotificationEvent(previousState, currentState) shouldNotify := record.PrintNotificationsEnabled && event != "" && isPrinterNotificationEventEnabled(record, event) layerEvents := printerLayerNotificationEventsForStatus(previousLayer, health.PrintStatus) layerShouldNotifyAny := false for _, layerEvent := range layerEvents { if record.PrintNotificationsEnabled && isPrinterLayerNotificationEventEnabled(record, layerEvent) { layerShouldNotifyAny = true break } } var snapshot []byte var snapshotName string if (shouldNotify || layerShouldNotifyAny) && s.notifier != nil { if data, name, err := s.capturePrinterNotificationSnapshot(printerID, health); err != nil { log.Printf("failed to capture notification snapshot printer_id=%s: %v", printerID, err) } else { snapshot = data snapshotName = name } } if (shouldNotify || layerShouldNotifyAny) && s.notifier != nil && len(snapshot) == 0 { log.Printf("sending notification without snapshot printer_id=%s", printerID) } notificationSource := "" notificationError := "" notified := false if shouldNotify && s.notifier != nil { notificationSource = "telegram" if err := s.notifier.NotifyPrinterPrintStatus(context.Background(), printerID, record, health, snapshot, snapshotName); err != nil { notificationError = err.Error() log.Printf("failed to send telegram notification printer_id=%s: %v", printerID, err) } else { notified = true } } if _, err := s.printerSettings.updatePrintObservation(printerID, &protocol.PrintStatus{ State: currentState, Filename: currentFile, }, notificationSource, notified, notificationError); err != nil { log.Printf("failed to persist print observation printer_id=%s: %v", printerID, err) } layerNotificationSource := "" layerNotificationError := "" layerNotified := false for _, layerEvent := range layerEvents { layerShouldNotify := record.PrintNotificationsEnabled && isPrinterLayerNotificationEventEnabled(record, layerEvent) if !layerShouldNotify || s.notifier == nil { continue } layerNotificationSource = "telegram" if err := s.notifier.NotifyPrinterLayerStatus(context.Background(), printerID, record, health, layerEvent, snapshot, snapshotName); err != nil { layerNotificationError = err.Error() log.Printf("failed to send telegram layer notification printer_id=%s event=%s: %v", printerID, layerEvent, err) } else { layerNotified = true } } if shouldPersistPrinterLayerObservation(health.PrintStatus) { if _, err := s.printerSettings.updatePrintLayerObservation(printerID, &protocol.PrintStatus{ State: currentState, Filename: currentFile, CurrentLayer: currentLayer, }, layerNotificationSource, layerNotified, layerNotificationError); err != nil { log.Printf("failed to persist print layer observation printer_id=%s: %v", printerID, err) } } } func (s *server) capturePrinterNotificationSnapshot(printerID string, health *protocol.Health) ([]byte, string, error) { return s.capturePrinterNotificationSnapshotWithCamera(printerID, health, "") } func (s *server) capturePrinterNotificationSnapshotWithCamera(printerID string, health *protocol.Health, preferredCamera string) ([]byte, string, error) { if s == nil || health == nil { return nil, "", fmt.Errorf("printer health unavailable") } record, _ := s.printerSettings.snapshot(printerID) cameraName, _ := notificationSnapshotCamera(health, record.NotificationSnapshotCamera) preferredCamera = strings.TrimSpace(preferredCamera) if preferredCamera != "" { name, camera := notificationSnapshotCamera(health, preferredCamera) if name == "" || camera == nil { return nil, "", fmt.Errorf("camera %q is not snapshot-capable", preferredCamera) } cameraName = name } if cameraName == "" { return nil, "", fmt.Errorf("no snapshot-capable camera configured") } s.tunnelsMu.RLock() t := s.tunnels[printerID] s.tunnelsMu.RUnlock() if t == nil { return nil, "", fmt.Errorf("printer agent is not connected") } id, err := newID() if err != nil { return nil, "", err } msg := protocol.Message{ ID: id, Type: protocol.MessageHTTPRequest, Target: "camera_snapshot", CameraName: cameraName, CameraKind: "snapshot", Method: http.MethodGet, } ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() responses, cleanup, err := t.openRequest(ctx, msg) if err != nil { return nil, "", err } defer cleanup() var header protocol.Message select { case header = <-responses: case <-ctx.Done(): return nil, "", ctx.Err() case <-t.done: return nil, "", fmt.Errorf("agent disconnected") } if header.Type == protocol.MessageError { return nil, "", fmt.Errorf(header.Error) } if header.End { if header.Body == "" { return nil, "", fmt.Errorf("empty camera snapshot") } data, err := base64.StdEncoding.DecodeString(header.Body) if err != nil { return nil, "", err } if len(data) == 0 { return nil, "", fmt.Errorf("empty camera snapshot") } if header.Status < 200 || header.Status >= 300 { return nil, "", fmt.Errorf("camera snapshot failed: status %d", header.Status) } return data, cameraName, nil } var snapshot bytes.Buffer for response := range responses { if response.Type == protocol.MessageError { return nil, "", fmt.Errorf(response.Error) } if response.Body != "" { chunk, err := base64.StdEncoding.DecodeString(response.Body) if err != nil { return nil, "", err } if _, err := snapshot.Write(chunk); err != nil { return nil, "", err } } if response.End { break } } if snapshot.Len() == 0 { return nil, "", fmt.Errorf("empty camera snapshot") } return snapshot.Bytes(), cameraName, nil } func notificationSnapshotCamera(health *protocol.Health, preferred string) (string, *protocol.CameraHealth) { if health == nil { return "", nil } preferred = strings.TrimSpace(preferred) if preferred != "" { for i := range health.Cameras { camera := &health.Cameras[i] if camera == nil || strings.TrimSpace(camera.Name) != preferred { continue } if camera.HasSnapshot { return camera.Name, camera } return "", nil } } for i := range health.Cameras { camera := &health.Cameras[i] if camera == nil || strings.TrimSpace(camera.Name) == "" { continue } if camera.HasSnapshot { return camera.Name, camera } } return "", nil } func notificationSnapshotCameraAllowed(health *protocol.Health, preferred string) bool { preferred = strings.TrimSpace(preferred) if preferred == "" { return true } if health == nil { return false } for i := range health.Cameras { camera := &health.Cameras[i] if camera != nil && strings.TrimSpace(camera.Name) == preferred && camera.HasSnapshot { return true } } return false } func printerNotificationEvent(previousState string, currentState string) string { previousState = strings.ToLower(strings.TrimSpace(previousState)) currentState = strings.ToLower(strings.TrimSpace(currentState)) if currentState == "" || currentState == previousState { return "" } switch currentState { case "printing": if previousState == "paused" { return "resumed" } return "started" case "paused": return "paused" case "complete", "completed": return "completed" case "cancelled", "canceled": return "canceled" case "error", "failed": return "failed" default: return "" } } func printerLayerNotificationEvents(previousLayer int, currentLayer int, currentState string) []string { if strings.ToLower(strings.TrimSpace(currentState)) != "printing" { return nil } if currentLayer <= 0 || currentLayer == previousLayer { return nil } if currentLayer < previousLayer { previousLayer = 0 } events := make([]string, 0, 2) if previousLayer < 2 && currentLayer >= 2 { events = append(events, "first_layer") } if previousLayer < 4 && currentLayer >= 4 { events = append(events, "third_layer") } return events } func printerLayerNotificationEventsForStatus(previousLayer int, status *protocol.PrintStatus) []string { if !printerLayerNotificationsTrusted(status) { return nil } return printerLayerNotificationEvents(previousLayer, status.CurrentLayer, status.State) } func printerLayerNotificationsTrusted(status *protocol.PrintStatus) bool { if status == nil { return false } state := strings.ToLower(strings.TrimSpace(status.State)) if state != "printing" { return true } if status.CurrentLayer <= 0 { return true } source := strings.ToLower(strings.TrimSpace(status.LayerSource)) if source == "" { return true } if strings.Contains(source, "print_stats") { return true } return false } func shouldPersistPrinterLayerObservation(status *protocol.PrintStatus) bool { if !printerLayerNotificationsTrusted(status) { return false } if status == nil { return false } state := strings.ToLower(strings.TrimSpace(status.State)) if state == "printing" && status.CurrentLayer <= 0 { return false } return true } func printerLayerNotificationEvent(previousLayer int, currentLayer int, currentState string) string { events := printerLayerNotificationEvents(previousLayer, currentLayer, currentState) if len(events) == 0 { return "" } return events[0] } func isPrinterNotificationEventEnabled(record printerSettingsRecord, event string) bool { if !record.PrintNotificationsEnabled { return false } switch event { case "started": return record.NotifyPrintStarted case "paused": return record.NotifyPrintPaused case "resumed": return record.NotifyPrintResumed case "completed": return record.NotifyPrintCompleted case "canceled": return record.NotifyPrintCanceled case "failed": return record.NotifyPrintFailed default: return false } } func isPrinterLayerNotificationEventEnabled(record printerSettingsRecord, event string) bool { if !record.PrintNotificationsEnabled { return false } switch event { case "first_layer": return record.NotifyFirstLayer case "third_layer": return record.NotifyThirdLayer default: return false } } func (t *tunnel) readLoop(s *server) { defer close(t.done) for { var msg protocol.Message if err := t.conn.ReadJSON(&msg); err != nil { log.Printf("agent read loop ended printer_id=%s remote=%s error=%v", t.printerID, t.remoteAddr, err) return } if msg.Type == protocol.MessageHeartbeat && msg.Health != nil { t.healthMu.Lock() t.health = msg.Health t.healthMu.Unlock() go s.handlePrinterHeartbeat(t.printerID, msg.Health) log.Printf("heartbeat printer_id=%s moonraker_reachable=%t state=%s", t.printerID, msg.Health.MoonrakerReachable, msg.Health.MoonrakerState) continue } t.pendingMu.Lock() ch := t.pending[msg.ID] t.pendingMu.Unlock() if ch == nil { log.Printf("received response for unknown request id=%s printer_id=%s", msg.ID, t.printerID) continue } ch <- msg } } func (t *tunnel) close() { _ = t.conn.Close() } func (t *tunnel) acceptsDuplicateBlock(now time.Time) bool { if t == nil { return false } select { case <-t.done: return false default: } t.healthMu.RLock() health := t.health t.healthMu.RUnlock() if health != nil && health.CheckedAtUnix > 0 { checkedAt := time.Unix(health.CheckedAtUnix, 0) return now.Sub(checkedAt) < 45*time.Second } if !t.connectedAt.IsZero() { return now.Sub(t.connectedAt) < 45*time.Second } return true } func headersFromHTTP(h http.Header) []protocol.Header { headers := make([]protocol.Header, 0, len(h)) for name, values := range h { headers = append(headers, protocol.Header{Name: name, Values: values}) } return headers } func writeJSON(w http.ResponseWriter, status int, value any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) if err := json.NewEncoder(w).Encode(value); err != nil { log.Printf("failed to write json response: %v", err) } } func writeResponseHeaders(w http.ResponseWriter, msg protocol.Message) { for _, h := range msg.Headers { if strings.EqualFold(h.Name, "Content-Length") || strings.EqualFold(h.Name, "Content-Encoding") || strings.EqualFold(h.Name, "Transfer-Encoding") || strings.EqualFold(h.Name, "Connection") || strings.EqualFold(h.Name, "Keep-Alive") || strings.EqualFold(h.Name, "Proxy-Authenticate") || strings.EqualFold(h.Name, "Proxy-Authorization") || strings.EqualFold(h.Name, "TE") || strings.EqualFold(h.Name, "Trailer") || strings.EqualFold(h.Name, "Upgrade") { continue } for _, v := range h.Values { w.Header().Add(h.Name, v) } } } func rewriteUIResponse(headers []protocol.Header, body []byte, printerID string) []byte { contentType := "" for _, h := range headers { if strings.EqualFold(h.Name, "Content-Type") && len(h.Values) > 0 { contentType = h.Values[0] break } } if !strings.Contains(contentType, "text/html") && !strings.Contains(contentType, "javascript") && !strings.Contains(contentType, "application/json") && !strings.Contains(contentType, "text/css") { return body } text := string(body) isHTML := strings.Contains(contentType, "text/html") uiPrefix := "/printers/" + printerID + "/ui" moonrakerPrefix := "/p/" + printerID + "/moonraker" replacements := []struct{ old, new string }{ {`http://127.0.0.1:7125/websocket`, moonrakerPrefix + `/websocket`}, {`https://127.0.0.1:7125/websocket`, moonrakerPrefix + `/websocket`}, {`ws://127.0.0.1:7125/websocket`, moonrakerPrefix + `/websocket`}, {`wss://127.0.0.1:7125/websocket`, moonrakerPrefix + `/websocket`}, {`http://localhost:7125/websocket`, moonrakerPrefix + `/websocket`}, {`https://localhost:7125/websocket`, moonrakerPrefix + `/websocket`}, {`ws://localhost:7125/websocket`, moonrakerPrefix + `/websocket`}, {`wss://localhost:7125/websocket`, moonrakerPrefix + `/websocket`}, {`http://127.0.0.1:7125`, moonrakerPrefix}, {`https://127.0.0.1:7125`, moonrakerPrefix}, {`ws://127.0.0.1:7125`, moonrakerPrefix + `/websocket`}, {`wss://127.0.0.1:7125`, moonrakerPrefix + `/websocket`}, {`http://localhost:7125`, moonrakerPrefix}, {`https://localhost:7125`, moonrakerPrefix}, {`ws://localhost:7125`, moonrakerPrefix + `/websocket`}, {`wss://localhost:7125`, moonrakerPrefix + `/websocket`}, {`href="/`, `href="` + uiPrefix + `/`}, {`src="/`, `src="` + uiPrefix + `/`}, {`action="/`, `action="` + uiPrefix + `/`}, {`url("/`, `url("` + uiPrefix + `/`}, {`url('/`, `url('` + uiPrefix + `/`}, {`fetch("/`, `fetch("` + moonrakerPrefix + `/`}, {`fetch('/`, `fetch('` + moonrakerPrefix + `/`}, {`"/printer/`, `"` + moonrakerPrefix + `/printer/`}, {`'/printer/`, `'` + moonrakerPrefix + `/printer/`}, {`"/server/`, `"` + moonrakerPrefix + `/server/`}, {`'/server/`, `'` + moonrakerPrefix + `/server/`}, } for _, replacement := range replacements { text = strings.ReplaceAll(text, replacement.old, replacement.new) } if isHTML { text = injectPrinterUIResetScript(text, printerID) } return []byte(text) } func injectPrinterUIResetScript(text string, printerID string) string { script := `` if strings.Contains(text, "") { return strings.Replace(text, "", ""+script, 1) } if strings.Contains(text, "") { return strings.Replace(text, "", script+"", 1) } return script + text } func rewriteFluiddConfig(body []byte, origin string, printerID string) []byte { var config map[string]any if err := json.Unmarshal(body, &config); err != nil { return body } config["endpoints"] = []string{origin + "/p/" + printerID + "/moonraker"} rewritten, err := json.MarshalIndent(config, "", " ") if err != nil { return body } return append(rewritten, '\n') } func rewriteMoonrakerWebcams(body []byte, printerID string) []byte { var payload map[string]any if err := json.Unmarshal(body, &payload); err != nil { return body } result, _ := payload["result"].(map[string]any) if result == nil { result = payload } webcams, _ := result["webcams"].([]any) if len(webcams) > 0 { for _, item := range webcams { webcam, ok := item.(map[string]any) if !ok { continue } name, _ := webcam["name"].(string) if name == "" { continue } if streamURL, _ := webcam["stream_url"].(string); streamURL != "" { webcam["stream_url"] = "/p/" + printerID + "/camera/" + url.PathEscape(name) + "/stream" } if snapshotURL, _ := webcam["snapshot_url"].(string); snapshotURL != "" { webcam["snapshot_url"] = "/p/" + printerID + "/camera/" + url.PathEscape(name) + "/snapshot" } if service, _ := webcam["service"].(string); service == "mjpegstreamer-adaptive" { webcam["service"] = "mjpegstreamer" } } } if streamURL, _ := result["stream_url"].(string); streamURL != "" { if name, _ := result["name"].(string); name != "" { result["stream_url"] = "/p/" + printerID + "/camera/" + url.PathEscape(name) + "/stream" } } if snapshotURL, _ := result["snapshot_url"].(string); snapshotURL != "" { if name, _ := result["name"].(string); name != "" { result["snapshot_url"] = "/p/" + printerID + "/camera/" + url.PathEscape(name) + "/snapshot" } } rewritten, err := json.MarshalIndent(payload, "", " ") if err != nil { return body } return append(rewritten, '\n') } func isReadOnlyMoonrakerRequest(method string, path string) bool { if method == http.MethodGet || method == http.MethodHead || method == http.MethodOptions { return true } cleanPath := path if i := strings.Index(cleanPath, "?"); i >= 0 { cleanPath = cleanPath[:i] } blockedPrefixes := []string{ "/printer/gcode/script", "/printer/print/", "/printer/emergency_stop", "/printer/firmware_restart", "/printer/restart", "/printer/objects/subscribe", "/server/files", "/server/machine", "/machine", "/printer/toolhead", "/printer/bed_mesh", } for _, prefix := range blockedPrefixes { if strings.HasPrefix(cleanPath, prefix) { return false } } return false } func isReadOnlyMoonrakerWebSocketPayload(payload []byte) bool { var message map[string]any if err := json.Unmarshal(payload, &message); err != nil { return true } method, _ := message["method"].(string) if method == "" { return true } blockedPrefixes := []string{ "printer.gcode.script", "printer.print.", "printer.emergency_stop", "printer.firmware_restart", "printer.restart", "server.files.upload", "server.files.delete", } for _, prefix := range blockedPrefixes { if strings.HasPrefix(method, prefix) { return false } } return true } func readOnlyWebSocketError(payload []byte) map[string]any { var message map[string]any _ = json.Unmarshal(payload, &message) response := map[string]any{ "jsonrpc": "2.0", "error": map[string]any{ "code": http.StatusForbidden, "message": "blocked by read-only printer control policy", }, } if id, ok := message["id"]; ok { response["id"] = id } return response } func constantTimeEqual(a string, b string) bool { if len(a) != len(b) { return false } return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 } func newLoginLimiter(limit int, window time.Duration) *loginLimiter { return &loginLimiter{ attempts: make(map[string]loginAttempt), limit: limit, window: window, } } func (l *loginLimiter) allow(key string) bool { now := time.Now() l.mu.Lock() defer l.mu.Unlock() attempt := l.attempts[key] if now.After(attempt.WindowEnds) { attempt = loginAttempt{WindowEnds: now.Add(l.window)} } attempt.Count++ l.attempts[key] = attempt return attempt.Count <= l.limit } func (l *loginLimiter) reset(key string) { l.mu.Lock() delete(l.attempts, key) l.mu.Unlock() } func requestIP(r *http.Request) string { forwarded := r.Header.Get("X-Forwarded-For") if forwarded != "" { return strings.TrimSpace(strings.Split(forwarded, ",")[0]) } host := r.RemoteAddr if i := strings.LastIndex(host, ":"); i > -1 { return host[:i] } return host } func envOrDefault(key string, fallback string) string { value := strings.TrimSpace(os.Getenv(key)) if value == "" { return fallback } return value } func envBool(key string) bool { switch strings.ToLower(strings.TrimSpace(os.Getenv(key))) { case "1", "true", "yes", "on": return true default: return false } } func warnIfDevelopmentSecrets(agentToken string, adminUser string, adminPass string, cookieSecure bool) { if agentToken == "dev-token" { log.Printf("WARNING: using default KA_AGENT_TOKEN/dev-token; replace it before exposing the server") } if adminUser == "admin" && adminPass == "admin" { log.Printf("WARNING: using default admin credentials admin/admin; replace them before exposing the server") } if !cookieSecure { log.Printf("WARNING: session cookies are not marked Secure; set KA_COOKIE_SECURE=true when serving over HTTPS") } } func newID() (string, error) { var b [16]byte if _, err := rand.Read(b[:]); err != nil { return "", err } return hex.EncodeToString(b[:]), nil } func init() { log.SetFlags(log.LstdFlags | log.Lmicroseconds) }