package main import ( "archive/zip" "encoding/json" "fmt" "io" "log/slog" "net/http" "os" "os/exec" "path/filepath" "strings" "time" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" "unified-dashboard/internal/common" mymiddleware "unified-dashboard/internal/middleware" ) func writeJSON(w http.ResponseWriter, status int, data any) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(status) json.NewEncoder(w).Encode(data) } func getWebFilePath(filename string) string { candidates := []string{ filepath.Join("web", "image-hoster", filename), filepath.Join("cmd", "image-hoster", filename), } for _, p := range candidates { if _, err := os.Stat(p); err == nil { return p } } return filepath.Join("web", "image-hoster", filename) } func main() { common.InitLogger("image-hoster") port := common.EnvOr("PORT", "5008") scriptName := os.Getenv("SCRIPT_NAME") initGovernance() r := chi.NewRouter() r.Use(middleware.RealIP) r.Use(middleware.RequestID) r.Use(mymiddleware.RequestLogger) r.Use(middleware.Recoverer) if scriptName != "" { r.Use(common.PrefixMiddleware(scriptName)) } // ───────────────────────────────────────────────────────────── // STATIC ASSETS // ───────────────────────────────────────────────────────────── r.Get("/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") http.ServeFile(w, r, getWebFilePath("index.html")) }) r.Get("/styles.css", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/css; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") http.ServeFile(w, r, getWebFilePath("styles.css")) }) r.Get("/app.js", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/javascript; charset=utf-8") w.Header().Set("Cache-Control", "no-cache, no-store, must-revalidate") http.ServeFile(w, r, getWebFilePath("app.js")) }) r.Get("/radheradhe", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") http.ServeFile(w, r, getWebFilePath("admin.html")) }) r.Get("/radheradhe/", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/html; charset=utf-8") http.ServeFile(w, r, getWebFilePath("admin.html")) }) r.Get("/admin.css", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "text/css; charset=utf-8") http.ServeFile(w, r, getWebFilePath("admin.css")) }) r.Get("/admin.js", func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/javascript; charset=utf-8") http.ServeFile(w, r, getWebFilePath("admin.js")) }) // ───────────────────────────────────────────────────────────── // SESSION MANAGEMENT & GOVERNANCE // ───────────────────────────────────────────────────────────── r.Post("/create_session", func(w http.ResponseWriter, r *http.Request) { var req struct { Name string `json:"name"` Mode string `json:"mode"` TimeLimitSec int `json:"time_limit_sec"` } json.NewDecoder(r.Body).Decode(&req) sessionID := fmt.Sprintf("%d", time.Now().UnixNano()) mode := SessionMode(req.Mode) if mode == "" { mode = ModeServerBg } now := time.Now() var expiresAt time.Time if req.TimeLimitSec > 0 { expiresAt = now.Add(time.Duration(req.TimeLimitSec) * time.Second) } name := req.Name if name == "" { name = "Session " + sessionID[len(sessionID)-6:] } sessionDir := filepath.Join(sessionsDir, sessionID) if mode == ModeServerBg { os.MkdirAll(sessionDir, 0755) } meta := &SessionMeta{ ID: sessionID, Name: name, Mode: mode, Path: sessionDir, CreatedAt: now, ExpiresAt: expiresAt, TimeLimitSec: req.TimeLimitSec, LastActive: now, TunnelURL: fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", sessionID), } globalState.mu.Lock() globalState.sessions[sessionID] = meta if mode == ModeRelay { globalState.relaySessions[sessionID] = make(chan map[string]interface{}, 100) } globalState.mu.Unlock() saveSessionsMetadata() writeJSON(w, 200, map[string]any{ "success": true, "session_id": sessionID, "session": meta, }) }) r.Get("/get_sessions_list", func(w http.ResponseWriter, r *http.Request) { globalState.mu.RLock() defer globalState.mu.RUnlock() now := time.Now() var list []map[string]any for _, s := range globalState.sessions { remSec := 0 if !s.ExpiresAt.IsZero() { if s.ExpiresAt.After(now) { remSec = int(s.ExpiresAt.Sub(now).Seconds()) } } list = append(list, map[string]any{ "id": s.ID, "name": s.Name, "mode": s.Mode, "path": s.Path, "created_at": s.CreatedAt, "expires_at": s.ExpiresAt, "time_limit_sec": s.TimeLimitSec, "remaining_sec": remSec, "file_count": s.FileCount, "total_bytes": s.TotalBytes, "requests": s.Requests, "bytes_served": s.BytesServed, "tunnel_url": s.TunnelURL, "tunnel_active": s.TunnelActive, }) } writeJSON(w, 200, map[string]any{ "success": true, "sessions": list, }) }) r.Post("/update_session_governance", func(w http.ResponseWriter, r *http.Request) { var req struct { SessionID string `json:"session_id"` Name string `json:"name"` TimeLimitSec int `json:"time_limit_sec"` } if err := json.NewDecoder(r.Body).Decode(&req); err != nil { writeJSON(w, 400, map[string]string{"error": "Invalid payload"}) return } globalState.mu.Lock() s, exists := globalState.sessions[req.SessionID] if !exists { globalState.mu.Unlock() writeJSON(w, 404, map[string]string{"error": "Session not found"}) return } if req.Name != "" { s.Name = req.Name } s.TimeLimitSec = req.TimeLimitSec if req.TimeLimitSec > 0 { s.ExpiresAt = time.Now().Add(time.Duration(req.TimeLimitSec) * time.Second) } else { s.ExpiresAt = time.Time{} // Unlimited } globalState.mu.Unlock() saveSessionsMetadata() writeJSON(w, 200, map[string]any{"success": true, "session": s}) }) r.Post("/delete_session", func(w http.ResponseWriter, r *http.Request) { var req struct { SessionID string `json:"session_id"` } json.NewDecoder(r.Body).Decode(&req) if req.SessionID != "" { deleteSessionInternal(req.SessionID) saveSessionsMetadata() } writeJSON(w, 200, map[string]bool{"success": true}) }) // ───────────────────────────────────────────────────────────── // SERVER-SIDE BACKGROUND FILE UPLOADS // ───────────────────────────────────────────────────────────── r.Post("/upload_files", func(w http.ResponseWriter, r *http.Request) { // Limit max upload to 500MB r.Body = http.MaxBytesReader(w, r.Body, 500*1024*1024) if err := r.ParseMultipartForm(50 * 1024 * 1024); err != nil { writeJSON(w, 400, map[string]string{"error": "Failed to parse upload: " + err.Error()}) return } sessionID := r.FormValue("session_id") if sessionID == "" { writeJSON(w, 400, map[string]string{"error": "session_id required"}) return } targetDir := filepath.Join(sessionsDir, sessionID) if err := os.MkdirAll(targetDir, 0755); err != nil { writeJSON(w, 500, map[string]string{"error": "Failed to create session dir"}) return } files := r.MultipartForm.File["files"] relPaths := r.MultipartForm.Value["relative_paths"] var totalUploadedBytes int64 uploadedCount := 0 for i, fHeader := range files { relPath := fHeader.Filename if i < len(relPaths) && relPaths[i] != "" { relPath = relPaths[i] } relPath = filepath.Clean(relPath) if strings.HasPrefix(relPath, "..") { continue } destPath := filepath.Join(targetDir, relPath) os.MkdirAll(filepath.Dir(destPath), 0755) srcFile, err := fHeader.Open() if err != nil { continue } dstFile, err := os.Create(destPath) if err != nil { srcFile.Close() continue } n, err := io.Copy(dstFile, srcFile) srcFile.Close() dstFile.Close() if err == nil { totalUploadedBytes += n uploadedCount++ } } // Update session metadata globalState.mu.Lock() s, exists := globalState.sessions[sessionID] if !exists { now := time.Now() s = &SessionMeta{ ID: sessionID, Name: "Session " + sessionID[len(sessionID)-6:], CreatedAt: now, LastActive: now, TunnelURL: fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", sessionID), } globalState.sessions[sessionID] = s } s.Mode = ModeServerBg s.Path = targetDir s.FileCount += uploadedCount s.TotalBytes += totalUploadedBytes s.LastActive = time.Now() globalState.mu.Unlock() saveSessionsMetadata() writeJSON(w, 200, map[string]any{ "success": true, "uploaded_count": uploadedCount, "total_bytes": totalUploadedBytes, }) }) r.Post("/upload_zip", func(w http.ResponseWriter, r *http.Request) { r.Body = http.MaxBytesReader(w, r.Body, 500*1024*1024) if err := r.ParseMultipartForm(50 * 1024 * 1024); err != nil { writeJSON(w, 400, map[string]string{"error": "Failed to parse upload"}) return } sessionID := r.FormValue("session_id") if sessionID == "" { writeJSON(w, 400, map[string]string{"error": "session_id required"}) return } file, fileHeader, err := r.FormFile("zip_file") if err != nil { writeJSON(w, 400, map[string]string{"error": "zip_file required"}) return } defer file.Close() targetDir := filepath.Join(sessionsDir, sessionID) os.MkdirAll(targetDir, 0755) zr, err := zip.NewReader(file, fileHeader.Size) if err != nil { writeJSON(w, 400, map[string]string{"error": "Invalid zip format"}) return } var count int var totalBytes int64 for _, zf := range zr.File { cleaned := filepath.Clean(zf.Name) if strings.HasPrefix(cleaned, "..") { continue } dest := filepath.Join(targetDir, cleaned) if zf.FileInfo().IsDir() { os.MkdirAll(dest, 0755) continue } os.MkdirAll(filepath.Dir(dest), 0755) rc, err := zf.Open() if err != nil { continue } out, err := os.Create(dest) if err != nil { rc.Close() continue } n, err := io.Copy(out, rc) rc.Close() out.Close() if err == nil { count++ totalBytes += n } } globalState.mu.Lock() s, exists := globalState.sessions[sessionID] if exists { s.Mode = ModeServerBg s.Path = targetDir s.FileCount += count s.TotalBytes += totalBytes s.LastActive = time.Now() } globalState.mu.Unlock() saveSessionsMetadata() writeJSON(w, 200, map[string]any{ "success": true, "count": count, "total_bytes": totalBytes, }) }) r.Post("/set_session_path", func(w http.ResponseWriter, r *http.Request) { var req struct { SessionID string `json:"session_id"` Path string `json:"path"` } json.NewDecoder(r.Body).Decode(&req) globalState.mu.Lock() s, exists := globalState.sessions[req.SessionID] if !exists { s = &SessionMeta{ ID: req.SessionID, Name: "Session " + req.SessionID[len(req.SessionID)-6:], CreatedAt: time.Now(), TunnelURL: fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", req.SessionID), } globalState.sessions[req.SessionID] = s } if req.Path == "(Relay Mode)" { s.Mode = ModeRelay s.Path = "" if _, chExists := globalState.relaySessions[req.SessionID]; !chExists { globalState.relaySessions[req.SessionID] = make(chan map[string]interface{}, 100) } globalState.mu.Unlock() saveSessionsMetadata() writeJSON(w, 200, map[string]any{"success": true, "mode": "relay"}) return } if req.Path == "" { globalState.mu.Unlock() writeJSON(w, 400, map[string]string{"error": "Path required"}) return } s.Mode = ModeLocalPath s.Path = req.Path delete(globalState.relaySessions, req.SessionID) globalState.mu.Unlock() saveSessionsMetadata() writeJSON(w, 200, map[string]bool{"success": true}) }) r.Get("/get_session_files/{session_id}", func(w http.ResponseWriter, r *http.Request) { sid := chi.URLParam(r, "session_id") globalState.mu.RLock() s, exists := globalState.sessions[sid] globalState.mu.RUnlock() if !exists { writeJSON(w, 200, map[string]any{"success": true, "files": []any{}, "path_set": false}) return } if s.Mode == ModeRelay { writeJSON(w, 200, map[string]any{ "success": true, "mode": "relay", "path_set": true, "current_path": "(Hosted from Browser P2P)", "session": s, }) return } basePath := s.Path if s.Mode == ModeServerBg { basePath = filepath.Join(sessionsDir, sid) } if basePath == "" { writeJSON(w, 200, map[string]any{"success": true, "files": []any{}, "path_set": false}) return } var filesList []map[string]any var totalBytes int64 filepath.Walk(basePath, func(path string, info os.FileInfo, err error) error { if err != nil || info.IsDir() { return nil } relPath, err := filepath.Rel(basePath, path) if err != nil { return nil } relPath = filepath.ToSlash(relPath) folder := filepath.Dir(relPath) if folder == "." { folder = "(Root)" } ext := strings.ToLower(filepath.Ext(path)) isCode := ext == ".json" || ext == ".html" || ext == ".htm" || ext == ".css" || ext == ".js" || ext == ".ts" || ext == ".xml" || ext == ".yaml" || ext == ".yml" isImage := ext == ".jpg" || ext == ".jpeg" || ext == ".png" || ext == ".webp" || ext == ".gif" || ext == ".svg" || ext == ".bmp" || ext == ".ico" totalBytes += info.Size() filesList = append(filesList, map[string]any{ "path": relPath, "folder": folder, "name": info.Name(), "size": info.Size(), "url": fmt.Sprintf("/files/%s/%s", sid, relPath), "is_code": isCode, "is_image": isImage, "modified": info.ModTime().Unix(), }) return nil }) // Update counts globalState.mu.Lock() s.FileCount = len(filesList) s.TotalBytes = totalBytes globalState.mu.Unlock() writeJSON(w, 200, map[string]any{ "success": true, "files": filesList, "path_set": true, "current_path": basePath, "session": s, }) }) r.Get("/download_session_zip/{session_id}", func(w http.ResponseWriter, r *http.Request) { sid := chi.URLParam(r, "session_id") if err := createSessionZip(sid, w); err != nil { http.Error(w, "Failed to create zip: "+err.Error(), http.StatusInternalServerError) } }) // ───────────────────────────────────────────────────────────── // TELEMETRY & ACCESS LOGS // ───────────────────────────────────────────────────────────── r.Get("/api/session_telemetry/{session_id}", func(w http.ResponseWriter, r *http.Request) { sid := chi.URLParam(r, "session_id") globalState.mu.RLock() s, exists := globalState.sessions[sid] logs := globalState.accessLogs[sid] globalState.mu.RUnlock() if !exists { writeJSON(w, 404, map[string]string{"error": "Session not found"}) return } writeJSON(w, 200, map[string]any{ "success": true, "session_id": sid, "requests": s.Requests, "bytes_served": s.BytesServed, "last_active": s.LastActive, "logs": logs, }) }) // ───────────────────────────────────────────────────────────── // SERVER DIRECTORY NAVIGATION API // ───────────────────────────────────────────────────────────── r.Post("/api/list_server_directories", func(w http.ResponseWriter, r *http.Request) { var req struct { Path string `json:"path"` } json.NewDecoder(r.Body).Decode(&req) p := req.Path if p == "" { p, _ = os.UserHomeDir() } p = filepath.Clean(p) entries, err := os.ReadDir(p) if err != nil { writeJSON(w, 400, map[string]string{"error": err.Error()}) return } var dirs []string for _, e := range entries { if e.IsDir() && !strings.HasPrefix(e.Name(), ".") { dirs = append(dirs, e.Name()) } } writeJSON(w, 200, map[string]any{ "success": true, "current_path": p, "parent_path": filepath.Dir(p), "directories": dirs, }) }) r.Post("/browse_folder", func(w http.ResponseWriter, r *http.Request) { cmd := exec.Command("zenity", "--file-selection", "--directory", "--title=Select Folder to Host") out, err := cmd.Output() path := strings.TrimSpace(string(out)) if err == nil && path != "" { writeJSON(w, 200, map[string]any{"success": true, "path": path}) return } pyCode := `import tkinter as tk; from tkinter import filedialog; root = tk.Tk(); root.withdraw(); root.attributes("-topmost", True); print(filedialog.askdirectory()); root.destroy()` cmd = exec.Command("python3", "-c", pyCode) out, err = cmd.Output() path = strings.TrimSpace(string(out)) if err == nil && path != "" { writeJSON(w, 200, map[string]any{"success": true, "path": path}) return } writeJSON(w, 200, map[string]any{"success": false, "error": "No folder selected"}) }) // ───────────────────────────────────────────────────────────── // BROWSER RELAY SSE STREAMING // ───────────────────────────────────────────────────────────── r.Get("/stream_events/{session_id}", func(w http.ResponseWriter, r *http.Request) { sid := chi.URLParam(r, "session_id") w.Header().Set("Content-Type", "text/event-stream") w.Header().Set("Cache-Control", "no-cache") w.Header().Set("Connection", "keep-alive") flusher, ok := w.(http.Flusher) if !ok { return } globalState.mu.Lock() ch, exists := globalState.relaySessions[sid] if !exists { ch = make(chan map[string]interface{}, 100) globalState.relaySessions[sid] = ch } globalState.mu.Unlock() for msg := range ch { b, _ := json.Marshal(msg) fmt.Fprintf(w, "data: %s\n\n", b) flusher.Flush() } }) r.Post("/fulfill_request", func(w http.ResponseWriter, r *http.Request) { reqID := r.FormValue("req_id") globalState.mu.Lock() ch, exists := globalState.requestEvents[reqID] globalState.mu.Unlock() if !exists { writeJSON(w, 404, map[string]string{"error": "Invalid request ID"}) return } file, _, err := r.FormFile("file") if err == nil { data, _ := io.ReadAll(file) ch <- data file.Close() } else { ch <- nil } writeJSON(w, 200, map[string]bool{"success": true}) }) // ───────────────────────────────────────────────────────────── // PUBLIC FILE SERVING (/files/{session_id}/*) // ───────────────────────────────────────────────────────────── r.Get("/files/{session_id}/*", func(w http.ResponseWriter, r *http.Request) { sid := chi.URLParam(r, "session_id") filename := chi.URLParam(r, "*") globalState.mu.RLock() s, exists := globalState.sessions[sid] ch, relayExists := globalState.relaySessions[sid] globalState.mu.RUnlock() clientIP := r.RemoteAddr userAgent := r.UserAgent() var basePath string if exists { if s.Mode == ModeServerBg { basePath = filepath.Join(sessionsDir, sid) } else if s.Mode == ModeLocalPath { basePath = s.Path } } if basePath != "" { fullPath := filepath.Join(basePath, filename) stat, err := os.Stat(fullPath) if err == nil { if stat.IsDir() { // Obsidian Liquid Glass HTML Directory Listing w.Header().Set("Content-Type", "text/html; charset=utf-8") entries, _ := os.ReadDir(fullPath) w.Write([]byte(renderObsidianDirectoryHTML(sid, filename, entries))) recordAccessEvent(sid, clientIP, r.Method, r.URL.Path, 200, 1024, userAgent) return } recordAccessEvent(sid, clientIP, r.Method, r.URL.Path, 200, stat.Size(), userAgent) http.ServeFile(w, r, fullPath) return } } else if relayExists { reqID := fmt.Sprintf("%d", time.Now().UnixNano()) resCh := make(chan []byte, 1) globalState.mu.Lock() globalState.requestEvents[reqID] = resCh globalState.mu.Unlock() ch <- map[string]interface{}{ "type": "request_file", "req_id": reqID, "filename": filename, } select { case data := <-resCh: globalState.mu.Lock() delete(globalState.requestEvents, reqID) globalState.mu.Unlock() if data != nil { recordAccessEvent(sid, clientIP, r.Method, r.URL.Path, 200, int64(len(data)), userAgent) w.Write(data) return } case <-time.After(30 * time.Second): globalState.mu.Lock() delete(globalState.requestEvents, reqID) globalState.mu.Unlock() } } recordAccessEvent(sid, clientIP, r.Method, r.URL.Path, 404, 0, userAgent) http.Error(w, "File not found or session expired", 404) }) // ───────────────────────────────────────────────────────────── // TUNNELING ENDPOINTS // ───────────────────────────────────────────────────────────── r.Post("/get_tunnel", func(w http.ResponseWriter, r *http.Request) { var req struct { SessionID string `json:"session_id"` } json.NewDecoder(r.Body).Decode(&req) if req.SessionID == "" { writeJSON(w, 400, map[string]string{"error": "Session ID required"}) return } tunnelURL := fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", req.SessionID) globalState.mu.Lock() if s, ok := globalState.sessions[req.SessionID]; ok { s.TunnelActive = true s.TunnelURL = tunnelURL } globalState.mu.Unlock() writeJSON(w, 200, map[string]any{"success": true, "url": tunnelURL}) }) r.Post("/stop_tunnel", func(w http.ResponseWriter, r *http.Request) { var req struct { SessionID string `json:"session_id"` } json.NewDecoder(r.Body).Decode(&req) globalState.mu.Lock() if s, ok := globalState.sessions[req.SessionID]; ok { s.TunnelActive = false } globalState.mu.Unlock() writeJSON(w, 200, map[string]bool{"success": true}) }) r.Post("/regenerate_tunnel", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]bool{"success": true}) }) r.Post("/get_tunnel_status", func(w http.ResponseWriter, r *http.Request) { var req struct { SessionID string `json:"session_id"` } json.NewDecoder(r.Body).Decode(&req) tunnelURL := fmt.Sprintf("https://nexus.linuxguy.space/hoster/%s", req.SessionID) writeJSON(w, 200, map[string]any{"active": true, "url": tunnelURL}) }) r.Post("/admin_login", func(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, map[string]bool{"success": true}) }) slog.Info("starting image-hoster", "port", port, "pid", os.Getpid()) if err := http.ListenAndServe(":"+port, r); err != nil { slog.Error("server failed", "error", err) } } // Render Obsidian Liquid Glass Directory Listing func renderObsidianDirectoryHTML(sid, relDir string, entries []os.DirEntry) string { var sb strings.Builder title := "Index of /" + relDir if relDir == "" { title = "Hosted Files Directory" } sb.WriteString(`