diff --git a/00-installer-config.yaml b/00-installer-config.yaml new file mode 100644 index 0000000..e324e28 --- /dev/null +++ b/00-installer-config.yaml @@ -0,0 +1,12 @@ +network: + version: 2 + ethernets: + enp6s18: + addresses: + - 10.0.0.6/8 + nameservers: + addresses: [1.1.1.1, 8.8.8.8] + routes: + - to: default + via: 10.0.0.1 + mtu: 1280 diff --git a/README.md b/README.md index c1a4b22..820de8b 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,10 @@

+ ### Compatibility: Currently works only with Ubuntu/Debian systems, we work hard to make compatibility to all Linux Distros + +
+ ### ⚡ Quick Deployment @@ -26,7 +30,7 @@ sudo mkdir -p /var/www && sudo git clone https://github.com/antonndev/ADPanel.gi ### ADaemon ```bash -curl -fsSL https://raw.githubusercontent.com/antonndev/ADPanel-Daemon/main/install-daemon.sh | tr -d '\r' | sudo bash -s -- --yes +curl -fsSL https://raw.githubusercontent.com/antonndev/ADaemon/main/install.sh | tr -d '\r' | sudo bash -s -- --yes ``` --- diff --git a/cmd/sshterm/main.go b/cmd/sshterm/main.go new file mode 100644 index 0000000..f39fda8 --- /dev/null +++ b/cmd/sshterm/main.go @@ -0,0 +1,2287 @@ +package main + +import ( + "context" + "crypto/hmac" + "crypto/sha256" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "html" + "io" + "log" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "strconv" + "strings" + "sync" + "time" + + "golang.org/x/crypto/ssh" + "nhooyr.io/websocket" + "nhooyr.io/websocket/wsjson" +) + +type tokenPayload struct { + Version int `json:"v"` + UserID string `json:"uid"` + IP string `json:"ip"` + ExpMS int64 `json:"exp"` +} + +type wsMessage struct { + Type string `json:"type"` + SessionID string `json:"sessionId,omitempty"` + Command string `json:"command,omitempty"` + Password string `json:"password,omitempty"` + Data string `json:"data,omitempty"` + Cols int `json:"cols,omitempty"` + Rows int `json:"rows,omitempty"` + Error string `json:"error,omitempty"` +} + +type sshTarget struct { + User string + Host string + Port int +} + +type appConfig struct { + BindAddr string + Secret []byte + PanelRoot string + ReadTimout time.Duration + UseTLS bool + TLSCert string + TLSKey string + WSFallback string + WSOrigin string +} + +const terminalResumeGrace = 15 * time.Minute +const terminalIdleTimeout = 20 * time.Minute +const terminalReplayLimit = 128 * 1024 + +type terminalSession struct { + owner string + id string + client *ssh.Client + session *ssh.Session + stdin io.WriteCloser + done chan struct{} + closeOnce sync.Once + mu sync.Mutex + subs map[chan wsMessage]struct{} + replay []byte + closed bool + waitErr error + lastInput time.Time + lastDetach time.Time +} + +var terminalSessions = struct { + sync.Mutex + items map[string]*terminalSession +}{items: make(map[string]*terminalSession)} + +func main() { + cwd, _ := os.Getwd() + panelRoot := strings.TrimSpace(os.Getenv("SSH_TERM_PANEL_ROOT")) + if panelRoot == "" { + panelRoot = cwd + } + _ = loadDotEnv(filepath.Join(panelRoot, ".env")) + + bind := strings.TrimSpace(os.Getenv("SSH_TERM_BIND")) + if bind == "" { + port := strings.TrimSpace(os.Getenv("SSH_TERM_PORT")) + if port == "" { + port = "9393" + } + bind = "0.0.0.0:" + port + } + + secretText := strings.TrimSpace(os.Getenv("SSH_TERM_TOKEN_SECRET")) + if secretText == "" { + sessionSecret := strings.TrimSpace(os.Getenv("SESSION_SECRET")) + if sessionSecret != "" { + h := hmac.New(sha256.New, []byte(sessionSecret)) + _, _ = h.Write([]byte("adpanel-ssh-term-token-key-v1")) + secretText = fmt.Sprintf("%x", h.Sum(nil)) + } + } + if len(secretText) < 16 { + log.Fatal("missing SSH_TERM_TOKEN_SECRET or SESSION_SECRET (must be >= 16 chars)") + } + + cfg := appConfig{ + BindAddr: bind, + Secret: []byte(secretText), + PanelRoot: panelRoot, + ReadTimout: 20 * time.Second, + UseTLS: parseBoolEnv("ENABLE_HTTPS"), + TLSCert: strings.TrimSpace(os.Getenv("SSL_CERT_PATH")), + TLSKey: strings.TrimSpace(os.Getenv("SSL_KEY_PATH")), + WSFallback: buildWSFallbackURL(bind, strings.TrimSpace(os.Getenv("SSH_TERM_PUBLIC_URL")), strings.TrimSpace(os.Getenv("SSH_TERM_WS_PUBLIC_URL"))), + } + cfg.WSOrigin = websocketOrigin(cfg.WSFallback) + + if cfg.UseTLS && (cfg.TLSCert == "" || cfg.TLSKey == "") { + cfg.UseTLS = false + } + + mux := http.NewServeMux() + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { + handleIndex(cfg, w, r) + }) + mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { + handleWS(cfg, w, r) + }) + mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Cache-Control", "no-store") + _, _ = w.Write([]byte("ok")) + }) + + srv := &http.Server{ + Addr: cfg.BindAddr, + Handler: mux, + ReadHeaderTimeout: 5 * time.Second, + IdleTimeout: 60 * time.Second, + WriteTimeout: 0, + } + + if cfg.UseTLS { + log.Printf("[ssh-term] listening on https://%s", cfg.BindAddr) + if err := srv.ListenAndServeTLS(cfg.TLSCert, cfg.TLSKey); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("server failed: %v", err) + } + return + } + + log.Printf("[ssh-term] listening on http://%s", cfg.BindAddr) + if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + log.Fatalf("server failed: %v", err) + } +} + +func parseBoolEnv(key string) bool { + v := strings.ToLower(strings.TrimSpace(os.Getenv(key))) + return v == "1" || v == "true" || v == "yes" || v == "on" +} + +func handleIndex(cfg appConfig, w http.ResponseWriter, r *http.Request) { + token := strings.TrimSpace(r.URL.Query().Get("token")) + payload, err := verifyToken(cfg.Secret, token, requestIP(r)) + if err != nil { + log.Printf("[ssh-term] index token reject: %v", err) + http.Error(w, "invalid or expired terminal token", http.StatusUnauthorized) + return + } + + w.Header().Set("Content-Type", "text/html; charset=utf-8") + w.Header().Set("Cache-Control", "no-store") + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("Referrer-Policy", "no-referrer") + cspConnect := "connect-src " + websocketConnectSrc(cfg.WSOrigin) + ";" + w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+cspConnect+" img-src 'self' data:;") + + page := strings.ReplaceAll(indexHTML, "__TOKEN__", html.EscapeString(token)) + page = strings.ReplaceAll(page, "__USER__", html.EscapeString(payload.UserID)) + page = strings.ReplaceAll(page, "__WS_FALLBACK__", html.EscapeString(cfg.WSFallback)) + _, _ = w.Write([]byte(page)) +} + +func buildWSFallbackURL(bindAddr string, publicURL string, wsPublicURL string) string { + if raw := strings.TrimSpace(wsPublicURL); raw != "" { + if u, ok := normalizeWSURL(raw); ok { + return u + } + } + + if raw := strings.TrimSpace(publicURL); raw != "" { + value := raw + if !strings.HasPrefix(strings.ToLower(value), "http://") && !strings.HasPrefix(strings.ToLower(value), "https://") { + value = "http://" + value + } + if u, err := url.Parse(value); err == nil { + wsProto := "ws" + if strings.EqualFold(u.Scheme, "https") { + wsProto = "wss" + } + host := u.Host + if host != "" { + return wsProto + "://" + host + "/ws" + } + } + } + _ = bindAddr + return "" +} + +func normalizeWSURL(raw string) (string, bool) { + value := strings.TrimSpace(raw) + if value == "" { + return "", false + } + if !strings.HasPrefix(strings.ToLower(value), "ws://") && !strings.HasPrefix(strings.ToLower(value), "wss://") { + value = "ws://" + value + } + u, err := url.Parse(value) + if err != nil || u == nil || u.Host == "" { + return "", false + } + pathPart := u.Path + if strings.TrimSpace(pathPart) == "" { + pathPart = "/ws" + } + u.Path = pathPart + u.RawQuery = "" + u.Fragment = "" + return u.String(), true +} + +func websocketOrigin(wsURL string) string { + u, err := url.Parse(strings.TrimSpace(wsURL)) + if err != nil || u == nil || u.Host == "" { + return "" + } + if u.Scheme != "ws" && u.Scheme != "wss" { + return "" + } + return u.Scheme + "://" + u.Host +} + +func websocketConnectSrc(wsOrigin string) string { + base := []string{"'self'"} + u, err := url.Parse(strings.TrimSpace(wsOrigin)) + if err != nil || u == nil || u.Host == "" { + return strings.Join(base, " ") + } + base = append(base, "ws://"+u.Host, "wss://"+u.Host) + seen := make(map[string]struct{}, len(base)) + uniq := make([]string, 0, len(base)) + for _, item := range base { + if _, ok := seen[item]; ok { + continue + } + seen[item] = struct{}{} + uniq = append(uniq, item) + } + return strings.Join(uniq, " ") +} + +func normalizeTerminalSessionID(raw string) string { + id := strings.TrimSpace(raw) + if len(id) < 8 || len(id) > 128 { + return "" + } + for _, r := range id { + if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' || r == ':' { + continue + } + return "" + } + return id +} + +func terminalSessionKey(owner string, id string) string { + return owner + "\x00" + id +} + +func getTerminalSession(owner string, id string) *terminalSession { + id = normalizeTerminalSessionID(id) + if owner == "" || id == "" { + return nil + } + terminalSessions.Lock() + ts := terminalSessions.items[terminalSessionKey(owner, id)] + terminalSessions.Unlock() + if ts == nil { + return nil + } + ts.mu.Lock() + closed := ts.closed + ts.mu.Unlock() + if closed { + return nil + } + return ts +} + +func registerTerminalSession(ts *terminalSession) { + if ts == nil || ts.owner == "" || ts.id == "" { + return + } + key := terminalSessionKey(ts.owner, ts.id) + terminalSessions.Lock() + if old := terminalSessions.items[key]; old != nil && old != ts { + go old.closeWithMessage("\r\n[adpanel] terminal replaced by a new connection\r\n") + } + terminalSessions.items[key] = ts + terminalSessions.Unlock() +} + +func removeTerminalSession(ts *terminalSession) { + if ts == nil || ts.owner == "" || ts.id == "" { + return + } + key := terminalSessionKey(ts.owner, ts.id) + terminalSessions.Lock() + if terminalSessions.items[key] == ts { + delete(terminalSessions.items, key) + } + terminalSessions.Unlock() +} + +func newTerminalSession(owner string, id string, client *ssh.Client, session *ssh.Session, stdin io.WriteCloser, stdout io.Reader, stderr io.Reader) *terminalSession { + ts := &terminalSession{ + owner: owner, + id: id, + client: client, + session: session, + stdin: stdin, + done: make(chan struct{}), + subs: make(map[chan wsMessage]struct{}), + lastInput: time.Now(), + } + + pump := func(reader io.Reader) { + buf := make([]byte, 4096) + for { + n, rerr := reader.Read(buf) + if n > 0 { + ts.addOutput(string(buf[:n])) + } + if rerr != nil { + if !errors.Is(rerr, io.EOF) { + ts.addOutput("\r\n[adpanel] remote stream closed\r\n") + } + return + } + } + } + + go pump(stdout) + go pump(stderr) + go func() { + err := session.Wait() + if err != nil { + ts.mu.Lock() + ts.waitErr = err + ts.mu.Unlock() + ts.closeWithMessage("\r\n[adpanel] ssh session ended: " + sanitizeReason(err) + "\r\n") + return + } + ts.closeWithMessage("\r\n[adpanel] ssh session ended\r\n") + }() + + return ts +} + +func (ts *terminalSession) addOutput(data string) { + if ts == nil || data == "" { + return + } + msg := wsMessage{Type: "output", Data: data} + ts.mu.Lock() + if ts.closed { + ts.mu.Unlock() + return + } + ts.replay = append(ts.replay, []byte(data)...) + if len(ts.replay) > terminalReplayLimit { + ts.replay = ts.replay[len(ts.replay)-terminalReplayLimit:] + } + subs := make([]chan wsMessage, 0, len(ts.subs)) + for ch := range ts.subs { + subs = append(subs, ch) + } + ts.mu.Unlock() + + for _, ch := range subs { + select { + case ch <- msg: + default: + } + } +} + +func (ts *terminalSession) subscribe() (chan wsMessage, string, bool) { + ch := make(chan wsMessage, 256) + ts.mu.Lock() + defer ts.mu.Unlock() + if ts.closed { + return nil, "", false + } + ts.subs[ch] = struct{}{} + return ch, string(ts.replay), true +} + +func (ts *terminalSession) unsubscribe(ch chan wsMessage) { + ts.mu.Lock() + if ch != nil { + delete(ts.subs, ch) + } + noSubs := len(ts.subs) == 0 + ts.lastDetach = time.Now() + ts.mu.Unlock() + if noSubs { + time.AfterFunc(terminalResumeGrace, cleanupIdleTerminalSessions) + } +} + +func cleanupIdleTerminalSessions() { + now := time.Now() + var stale []*terminalSession + terminalSessions.Lock() + for _, ts := range terminalSessions.items { + ts.mu.Lock() + idleDetached := len(ts.subs) == 0 && !ts.lastDetach.IsZero() && now.Sub(ts.lastDetach) >= terminalResumeGrace + idleInput := now.Sub(ts.lastInput) >= terminalIdleTimeout + closed := ts.closed + ts.mu.Unlock() + if !closed && (idleDetached || idleInput) { + stale = append(stale, ts) + } + } + terminalSessions.Unlock() + + for _, ts := range stale { + ts.closeWithMessage("") + } +} + +func (ts *terminalSession) closeWithMessage(message string) { + if ts == nil { + return + } + if strings.TrimSpace(message) != "" { + ts.addOutput(message) + } + ts.closeOnce.Do(func() { + ts.mu.Lock() + ts.closed = true + ts.mu.Unlock() + if ts.stdin != nil { + _ = ts.stdin.Close() + } + if ts.session != nil { + _ = ts.session.Close() + } + if ts.client != nil { + _ = ts.client.Close() + } + removeTerminalSession(ts) + close(ts.done) + }) +} + +func (ts *terminalSession) writeInput(data string) error { + if ts == nil || data == "" { + return nil + } + ts.mu.Lock() + if ts.closed { + ts.mu.Unlock() + return errors.New("terminal session closed") + } + ts.lastInput = time.Now() + stdin := ts.stdin + ts.mu.Unlock() + if stdin == nil { + return errors.New("terminal input unavailable") + } + _, err := io.WriteString(stdin, data) + return err +} + +func (ts *terminalSession) resize(cols int, rows int) { + if ts == nil || ts.session == nil { + return + } + if rows <= 0 { + rows = 24 + } + if cols <= 0 { + cols = 80 + } + _ = ts.session.WindowChange(rows, cols) +} + +func attachTerminalSession(ctx context.Context, conn *websocket.Conn, ts *terminalSession) { + outCh, replay, ok := ts.subscribe() + if !ok { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session closed"}) + return + } + defer ts.unsubscribe(outCh) + + write := func(msg wsMessage) bool { + wctx, cancel := context.WithTimeout(ctx, 10*time.Second) + err := wsjson.Write(wctx, conn, msg) + cancel() + return err == nil + } + + if !write(wsMessage{Type: "connected", SessionID: ts.id}) { + return + } + if replay != "" && !write(wsMessage{Type: "output", Data: replay}) { + return + } + + inputCh := make(chan wsMessage, 16) + errCh := make(chan error, 1) + go func() { + for { + var msg wsMessage + if err := wsjson.Read(ctx, conn, &msg); err != nil { + errCh <- err + return + } + select { + case inputCh <- msg: + case <-ctx.Done(): + return + } + } + }() + + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + return + case <-ts.done: + return + case <-ticker.C: + ts.mu.Lock() + expired := time.Since(ts.lastInput) >= terminalIdleTimeout + ts.mu.Unlock() + if expired { + ts.closeWithMessage("\r\n[adpanel] session expired after 20 minutes of inactivity\r\n") + return + } + case err := <-errCh: + if errors.Is(err, context.DeadlineExceeded) { + ts.closeWithMessage("\r\n[adpanel] session expired after 20 minutes of inactivity\r\n") + } + return + case msg := <-inputCh: + switch msg.Type { + case "input": + if err := ts.writeInput(msg.Data); err != nil { + ts.closeWithMessage("\r\n[adpanel] terminal input failed: " + sanitizeReason(err) + "\r\n") + return + } + case "resize": + ts.resize(msg.Cols, msg.Rows) + case "disconnect": + ts.closeWithMessage("") + return + } + case msg := <-outCh: + if !write(msg) { + return + } + } + } +} + +func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) { + token := strings.TrimSpace(r.URL.Query().Get("token")) + payload, err := verifyToken(cfg.Secret, token, requestIP(r)) + if err != nil { + log.Printf("[ssh-term] ws token reject: %v", err) + http.Error(w, "unauthorized", http.StatusUnauthorized) + return + } + + conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled}) + if err != nil { + return + } + defer conn.Close(websocket.StatusNormalClosure, "bye") + + ctx := r.Context() + conn.SetReadLimit(1 << 20) + + var first wsMessage + if err := wsjson.Read(ctx, conn, &first); err != nil { + return + } + + if first.Type == "attach" { + sessionID := normalizeTerminalSessionID(first.SessionID) + if sessionID == "" { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session id is missing"}) + return + } + if existing := getTerminalSession(payload.UserID, sessionID); existing != nil { + attachTerminalSession(ctx, conn, existing) + return + } + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session not found"}) + return + } + + connectMsg := first + if first.Type == "probe" { + target, err := parseSSHCommand(first.Command) + if err != nil { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: err.Error()}) + return + } + if err := probeSSHReachability(target, 6*time.Second); err != nil { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh target unreachable: " + sanitizeReason(err)}) + return + } + + if err := wsjson.Write(ctx, conn, wsMessage{Type: "probe-ok"}); err != nil { + return + } + + if err := wsjson.Read(ctx, conn, &connectMsg); err != nil { + return + } + if connectMsg.Type != "connect" { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "expected connect message"}) + return + } + if strings.TrimSpace(connectMsg.Command) == "" { + connectMsg.Command = first.Command + } + if strings.TrimSpace(connectMsg.SessionID) == "" { + connectMsg.SessionID = first.SessionID + } + } + + if connectMsg.Type != "connect" { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "expected connect message"}) + return + } + + target, err := parseSSHCommand(connectMsg.Command) + if err != nil { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: err.Error()}) + return + } + if err := probeSSHReachability(target, 6*time.Second); err != nil { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh target unreachable: " + sanitizeReason(err)}) + return + } + + if strings.TrimSpace(connectMsg.Password) == "" { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "password is required"}) + return + } + + sessionID := normalizeTerminalSessionID(connectMsg.SessionID) + if sessionID == "" { + sessionID = fmt.Sprintf("session-%d", time.Now().UnixNano()) + } + + client, session, stdin, err := openSSHSession(target, strings.TrimSpace(connectMsg.Password), knownHostsPath(cfg.PanelRoot), payload.UserID, connectMsg.Cols, connectMsg.Rows) + if err != nil { + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh connection failed: " + explainSSHConnectError(err)}) + return + } + + stdout, _ := session.StdoutPipe() + stderr, _ := session.StderrPipe() + if err := session.Shell(); err != nil { + _ = client.Close() + _ = session.Close() + _ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "failed to start remote shell: " + sanitizeReason(err)}) + return + } + + term := newTerminalSession(payload.UserID, sessionID, client, session, stdin, stdout, stderr) + registerTerminalSession(term) + attachTerminalSession(ctx, conn, term) +} + +func sanitizeReason(err error) string { + if err == nil { + return "unknown error" + } + reason := strings.TrimSpace(err.Error()) + reason = strings.ReplaceAll(reason, "\n", " ") + if len(reason) > 220 { + reason = reason[:220] + } + if reason == "" { + return "unknown error" + } + return reason +} + +func explainSSHConnectError(err error) string { + reason := sanitizeReason(err) + lower := strings.ToLower(reason) + if strings.Contains(lower, "host key mismatch") || strings.Contains(lower, "man-in-the-middle") { + return "host key changed since the last connection - refusing to connect (possible man-in-the-middle). If the server was legitimately reinstalled, an admin must remove its entry from data/ssh_known_hosts.json" + } + if strings.Contains(lower, "host key divergence") || strings.Contains(lower, "possible interception") { + return "this host presented a different key to another user - refusing to connect (possible interception). Verify the server fingerprint out-of-band before trusting it" + } + if strings.Contains(lower, "host key store unavailable") { + return "cannot verify the server's host key (key store unavailable) - refusing to connect" + } + if strings.Contains(lower, "unable to authenticate") || strings.Contains(lower, "no supported methods remain") { + return "remote server rejected password authentication (wrong password or password login is disabled)" + } + return reason +} + +func probeSSHReachability(target sshTarget, timeout time.Duration) error { + addr := net.JoinHostPort(target.Host, strconv.Itoa(target.Port)) + d := net.Dialer{Timeout: timeout} + conn, err := d.Dial("tcp", addr) + if err != nil { + return err + } + _ = conn.Close() + return nil +} + +// knownHostsMu serializes read/modify/write access to the on-disk TOFU store so +// concurrent terminal sessions cannot corrupt it or race on first-use pinning. +var knownHostsMu sync.Mutex + +// knownHostsPath returns the path of the TOFU known-hosts store, derived from the +// panel root. Kept alongside other node state so it survives restarts. +func knownHostsPath(panelRoot string) string { + root := strings.TrimSpace(panelRoot) + if root == "" { + root = "." + } + return filepath.Join(root, "data", "ssh_known_hosts.json") +} + +// hostKeyFingerprint returns a stable, comparable fingerprint for a host key. +// We use the SHA-256 of the wire-format public key (the same bytes OpenSSH +// fingerprints), base64-encoded, which is collision-resistant and unambiguous. +func hostKeyFingerprint(key ssh.PublicKey) string { + sum := sha256.Sum256(key.Marshal()) + return key.Type() + ":SHA256:" + base64.StdEncoding.EncodeToString(sum[:]) +} + +// knownHostsStore is the on-disk TOFU model. +// +// Pins are keyed PER USER ("uid\x00host:port" -> fingerprint) so one user can +// never pin a host key on behalf of another. This closes the multi-user +// pre-pinning attack: a malicious panel user pinning a trap key only affects +// their OWN store, and a victim still performs their own first-use pinning +// against the real server. +// +// Global holds the union of every fingerprint that has EVER been seen for a +// host:port across all users. It is advisory only: when a user pins a host for +// the first time and the presented key is NOT among the keys other users have +// already seen, we surface a warning (divergence => possible interception), +// but we still pin the user's own observation. This way a victim is never +// silently bound to an attacker's key and gets a visible signal on divergence. +type knownHostsStore struct { + Pins map[string]string `json:"pins"` + Global map[string][]string `json:"global"` +} + +func userHostKey(userID, hostport string) string { + return strings.TrimSpace(userID) + "\x00" + strings.ToLower(strings.TrimSpace(hostport)) +} + +func loadKnownHosts(path string) knownHostsStore { + st := knownHostsStore{Pins: map[string]string{}, Global: map[string][]string{}} + b, err := os.ReadFile(path) + if err != nil || len(b) == 0 { + return st + } + _ = json.Unmarshal(b, &st) + if st.Pins == nil { + st.Pins = map[string]string{} + } + if st.Global == nil { + st.Global = map[string][]string{} + } + return st +} + +func saveKnownHosts(path string, st knownHostsStore) error { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return err + } + b, err := json.MarshalIndent(st, "", " ") + if err != nil { + return err + } + tmp := path + ".tmp" + if err := os.WriteFile(tmp, b, 0o600); err != nil { + return err + } + return os.Rename(tmp, path) +} + +// tofuHostKeyCallback implements PER-USER Trust-On-First-Use host-key +// verification with a cross-user divergence check. +// +// - The first time a given USER connects to host:port, the presented key is +// pinned for that user and the connection is allowed. +// - Every subsequent connection by the SAME user must present the SAME key, +// otherwise the connection is rejected (classic MITM defense). +// - Pins are namespaced by user, so no panel user can pre-pin a key that +// another user will inherit (defeats the first-come pre-pinning attack). +// - On a user's first use, if other users have previously recorded a +// DIFFERENT key for the same host, that is a divergence signal (possible +// interception). We reject by default and require the connecting user to +// explicitly accept, surfacing the risk instead of silently trusting it. +// +// If the store path is empty/unwritable we fail closed (reject) rather than +// fall back to ignoring the key, so a misconfiguration can never silently +// re-disable verification. +func tofuHostKeyCallback(storePath, userID string, allowDivergentFirstUse bool) ssh.HostKeyCallback { + return func(hostport string, remote net.Addr, key ssh.PublicKey) error { + host := strings.ToLower(strings.TrimSpace(hostport)) + if host == "" { + host = strings.ToLower(strings.TrimSpace(remote.String())) + } + fp := hostKeyFingerprint(key) + uhk := userHostKey(userID, host) + + knownHostsMu.Lock() + defer knownHostsMu.Unlock() + + st := loadKnownHosts(storePath) + + if pinned, ok := st.Pins[uhk]; ok { + // This user already pinned a key for this host: must match exactly. + if hmac.Equal([]byte(pinned), []byte(fp)) { + return nil + } + return fmt.Errorf("host key mismatch for %s: possible man-in-the-middle attack (pinned %s, got %s)", host, pinned, fp) + } + + // First use for THIS user. Check divergence against what others saw. + seen := st.Global[host] + seenThis := false + for _, s := range seen { + if s == fp { + seenThis = true + break + } + } + if len(seen) > 0 && !seenThis && !allowDivergentFirstUse { + // Another user previously recorded a different key for this host and + // the current key is not among them => the connection may be + // intercepted. Refuse and force an explicit, informed decision. + return fmt.Errorf("host key divergence for %s: this host previously presented a different key to another user (got %s) - possible interception; explicit confirmation required", host, fp) + } + + // Pin for this user and record in the global advisory set. + st.Pins[uhk] = fp + if !seenThis { + st.Global[host] = append(seen, fp) + } + if err := saveKnownHosts(storePath, st); err != nil { + return fmt.Errorf("host key store unavailable: %w", err) + } + return nil + } +} + +func openSSHSession(target sshTarget, password, knownHostsStore, userID string, cols, rows int) (*ssh.Client, *ssh.Session, io.WriteCloser, error) { + if cols <= 0 { + cols = 100 + } + if rows <= 0 { + rows = 30 + } + + config := &ssh.ClientConfig{ + User: target.User, + Auth: []ssh.AuthMethod{ + ssh.Password(password), + ssh.KeyboardInteractive(func(_ string, _ string, questions []string, _ []bool) ([]string, error) { + answers := make([]string, len(questions)) + for i := range questions { + answers[i] = password + } + return answers, nil + }), + }, + // Divergent first-use is refused by default; an explicit accept flow can + // pass allowDivergentFirstUse=true after warning the user. + HostKeyCallback: tofuHostKeyCallback(knownHostsStore, userID, false), + Timeout: 15 * time.Second, + } + + addr := net.JoinHostPort(target.Host, strconv.Itoa(target.Port)) + client, err := ssh.Dial("tcp", addr, config) + if err != nil { + return nil, nil, nil, err + } + session, err := client.NewSession() + if err != nil { + client.Close() + return nil, nil, nil, err + } + stdin, err := session.StdinPipe() + if err != nil { + session.Close() + client.Close() + return nil, nil, nil, err + } + + modes := ssh.TerminalModes{ + ssh.ECHO: 1, + ssh.TTY_OP_ISPEED: 14400, + ssh.TTY_OP_OSPEED: 14400, + } + if err := session.RequestPty("xterm-256color", rows, cols, modes); err != nil { + stdin.Close() + session.Close() + client.Close() + return nil, nil, nil, err + } + return client, session, stdin, nil +} + +func parseSSHCommand(input string) (sshTarget, error) { + trimmed := strings.TrimSpace(input) + parts := strings.Fields(trimmed) + if len(parts) < 2 || !strings.EqualFold(parts[0], "ssh") { + return sshTarget{}, errors.New("only ssh user@host -p is allowed") + } + + args := parts[1:] + dest := "" + cliPort := 0 + + for i := 0; i < len(args); i++ { + arg := strings.TrimSpace(args[i]) + if arg == "" { + continue + } + + // Tolerate accidental spacing around '@', e.g. "root@ 1.2.3.4" or "root @1.2.3.4". + if dest != "" { + if strings.HasSuffix(dest, "@") && !strings.HasPrefix(arg, "-") { + dest += arg + continue + } + if strings.HasPrefix(arg, "@") && !strings.Contains(dest, "@") { + dest += arg + continue + } + } + + if strings.HasPrefix(arg, "-p") { + portText := "" + if arg == "-p" { + if i+1 >= len(args) { + return sshTarget{}, errors.New("invalid port") + } + i++ + portText = strings.TrimSpace(args[i]) + } else { + portText = strings.TrimSpace(strings.TrimPrefix(arg, "-p")) + } + + n, err := strconv.Atoi(portText) + if err != nil || n < 1 || n > 65535 { + return sshTarget{}, errors.New("invalid port") + } + cliPort = n + continue + } + + if strings.HasPrefix(arg, "-") { + return sshTarget{}, errors.New("only -p is accepted") + } + + if dest != "" { + return sshTarget{}, errors.New("only one ssh destination is allowed") + } + dest = arg + } + + if dest == "" { + return sshTarget{}, errors.New("missing ssh destination") + } + + at := strings.Index(dest, "@") + if at <= 0 || at == len(dest)-1 { + return sshTarget{}, errors.New("invalid ssh destination") + } + + user := dest[:at] + host, inlinePort, err := splitSSHHostPort(dest[at+1:]) + if err != nil { + return sshTarget{}, err + } + if !isSafeSSHUser(user) || !isSafeSSHHost(host) { + return sshTarget{}, errors.New("invalid user or host") + } + + port := 22 + if inlinePort > 0 { + port = inlinePort + } + if cliPort > 0 { + port = cliPort + } + + return sshTarget{User: user, Host: host, Port: port}, nil +} + +func splitSSHHostPort(raw string) (string, int, error) { + hostPart := strings.TrimSpace(raw) + if hostPart == "" { + return "", 0, errors.New("invalid ssh destination") + } + + if strings.HasPrefix(hostPart, "[") { + closeIdx := strings.Index(hostPart, "]") + if closeIdx <= 1 { + return "", 0, errors.New("invalid user or host") + } + + host := hostPart[1:closeIdx] + rest := strings.TrimSpace(hostPart[closeIdx+1:]) + if rest == "" { + return host, 0, nil + } + if !strings.HasPrefix(rest, ":") { + return "", 0, errors.New("invalid user or host") + } + + portText := strings.TrimSpace(rest[1:]) + n, err := strconv.Atoi(portText) + if err != nil || n < 1 || n > 65535 { + return "", 0, errors.New("invalid port") + } + return host, n, nil + } + + lastColon := strings.LastIndex(hostPart, ":") + if lastColon > 0 && lastColon < len(hostPart)-1 { + portText := hostPart[lastColon+1:] + if isDecimalDigits(portText) { + host := hostPart[:lastColon] + if strings.Count(host, ":") == 0 { + n, err := strconv.Atoi(portText) + if err != nil || n < 1 || n > 65535 { + return "", 0, errors.New("invalid port") + } + return host, n, nil + } + } + } + + return hostPart, 0, nil +} + +func isDecimalDigits(input string) bool { + if input == "" { + return false + } + for _, c := range input { + if c < '0' || c > '9' { + return false + } + } + return true +} + +func isSafeSSHUser(user string) bool { + if len(user) < 1 || len(user) > 32 { + return false + } + for _, c := range user { + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.' { + continue + } + return false + } + return true +} + +func isSafeSSHHost(host string) bool { + if len(host) < 1 || len(host) > 253 { + return false + } + for _, c := range host { + if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == ':' || c == '-' { + continue + } + return false + } + return true +} + +func verifyToken(secret []byte, token string, requestIP string) (tokenPayload, error) { + parts := strings.Split(token, ".") + if len(parts) != 2 { + return tokenPayload{}, errors.New("invalid token format") + } + payloadB64 := parts[0] + sigRaw, err := decodeB64URL(parts[1]) + if err != nil { + return tokenPayload{}, errors.New("invalid token signature") + } + mac := hmac.New(sha256.New, secret) + _, _ = mac.Write([]byte(payloadB64)) + expected := mac.Sum(nil) + if !hmac.Equal(expected, sigRaw) { + return tokenPayload{}, errors.New("token signature mismatch") + } + + payloadRaw, err := decodeB64URL(payloadB64) + if err != nil { + return tokenPayload{}, errors.New("invalid token payload") + } + var payload tokenPayload + if err := json.Unmarshal(payloadRaw, &payload); err != nil { + return tokenPayload{}, errors.New("invalid token json") + } + if payload.ExpMS < time.Now().UnixMilli() { + return tokenPayload{}, errors.New("token expired") + } + return payload, nil +} + +func sameIP(a, b string) bool { + na := normalizeIP(a) + nb := normalizeIP(b) + return na != "" && nb != "" && na == nb +} + +func normalizeIP(raw string) string { + s := strings.TrimSpace(raw) + if s == "" { + return "" + } + if strings.Contains(s, ",") { + s = strings.TrimSpace(strings.Split(s, ",")[0]) + } + host, _, err := net.SplitHostPort(s) + if err == nil { + s = host + } + s = strings.TrimPrefix(s, "::ffff:") + ip := net.ParseIP(s) + if ip == nil { + return "" + } + return ip.String() +} + +func requestIP(r *http.Request) string { + if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" { + return normalizeIP(xff) + } + if xr := strings.TrimSpace(r.Header.Get("X-Real-IP")); xr != "" { + return normalizeIP(xr) + } + return normalizeIP(r.RemoteAddr) +} + +func decodeB64URL(s string) ([]byte, error) { + s = strings.TrimSpace(s) + if s == "" { + return nil, errors.New("empty base64url") + } + if b, err := base64.RawURLEncoding.DecodeString(s); err == nil { + return b, nil + } + if m := len(s) % 4; m != 0 { + s += strings.Repeat("=", 4-m) + } + if b, err := base64.URLEncoding.DecodeString(s); err == nil { + return b, nil + } + std := strings.ReplaceAll(strings.ReplaceAll(s, "-", "+"), "_", "/") + return base64.StdEncoding.DecodeString(std) +} + +func loadDotEnv(path string) error { + b, err := os.ReadFile(path) + if err != nil { + return err + } + lines := strings.Split(strings.ReplaceAll(string(b), "\r\n", "\n"), "\n") + for _, line := range lines { + line = strings.TrimSpace(line) + if line == "" || strings.HasPrefix(line, "#") { + continue + } + eq := strings.IndexByte(line, '=') + if eq <= 0 { + continue + } + k := strings.TrimSpace(line[:eq]) + v := strings.TrimSpace(line[eq+1:]) + if len(v) >= 2 { + if (strings.HasPrefix(v, "\"") && strings.HasSuffix(v, "\"")) || (strings.HasPrefix(v, "'") && strings.HasSuffix(v, "'")) { + v = v[1 : len(v)-1] + } + } + if k != "" { + if _, exists := os.LookupEnv(k); exists { + continue + } + _ = os.Setenv(k, v) + } + } + return nil +} + +const indexHTML = ` + + + + + ADPanel SSH Terminal + + + +
+ + + +` diff --git a/cmd/sshterm/sshterm b/cmd/sshterm/sshterm new file mode 100755 index 0000000..afcb180 Binary files /dev/null and b/cmd/sshterm/sshterm differ diff --git a/cmd/sshterm/tofu_hostkey_test.go b/cmd/sshterm/tofu_hostkey_test.go new file mode 100644 index 0000000..3c3007f --- /dev/null +++ b/cmd/sshterm/tofu_hostkey_test.go @@ -0,0 +1,108 @@ +package main + +import ( + "crypto/ed25519" + "net" + "os" + "path/filepath" + "strings" + "testing" + + "golang.org/x/crypto/ssh" +) + +func mkKey(t *testing.T) ssh.PublicKey { + t.Helper() + pub, _, err := ed25519.GenerateKey(nil) + if err != nil { + t.Fatal(err) + } + k, err := ssh.NewPublicKey(pub) + if err != nil { + t.Fatal(err) + } + return k +} + +func TestTOFUPerUserPinning(t *testing.T) { + dir := t.TempDir() + store := filepath.Join(dir, "data", "ssh_known_hosts.json") + addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} + + real := mkKey(t) + trap := mkKey(t) + + userA := tofuHostKeyCallback(store, "userA", false) + + // userA first use pins real key. + if err := userA("srv.example:22", addr, real); err != nil { + t.Fatalf("userA first-use should pin, got: %v", err) + } + // userA reconnect with same key is fine. + if err := userA("srv.example:22", addr, real); err != nil { + t.Fatalf("userA same key should be allowed, got: %v", err) + } + // userA presented a DIFFERENT key on reconnect => MITM, rejected. + if err := userA("srv.example:22", addr, trap); err == nil { + t.Fatal("userA mismatched key MUST be rejected") + } +} + +// Core of the reported attack: a malicious user pre-pins a TRAP key; the victim +// must NOT inherit it. The victim either pins the real key for themselves, or +// (if the attacker also intercepts the victim) sees a divergence rejection. +func TestTOFUPrePinningDoesNotPoisonVictim(t *testing.T) { + dir := t.TempDir() + store := filepath.Join(dir, "data", "ssh_known_hosts.json") + addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} + + real := mkKey(t) + trap := mkKey(t) + + attacker := tofuHostKeyCallback(store, "attacker", false) + victim := tofuHostKeyCallback(store, "victim", false) + + // Attacker pre-pins a trap key for the host (their own store only). + if err := attacker("newsrv:22", addr, trap); err != nil { + t.Fatalf("attacker pre-pin setup failed: %v", err) + } + + // Victim connects to the REAL server (sees the real key). Because the + // attacker recorded a different key globally, the victim must be WARNED + // (divergence) rather than silently trusting anything. + if err := victim("newsrv:22", addr, real); err == nil { + t.Fatal("victim must be warned about divergence, not silently allowed") + } else if !strings.Contains(strings.ToLower(err.Error()), "divergence") { + t.Fatalf("expected divergence error, got: %v", err) + } + + // Critically: the victim is NEVER bound to the attacker's trap key. + st := loadKnownHosts(store) + if got := st.Pins[userHostKey("victim", "newsrv:22")]; got == hostKeyFingerprint(trap) { + t.Fatal("victim must NOT inherit the attacker's pinned key") + } + + // After explicit, informed acceptance, the victim pins the REAL key only. + victimAccept := tofuHostKeyCallback(store, "victim", true) + if err := victimAccept("newsrv:22", addr, real); err != nil { + t.Fatalf("victim explicit-accept of real key failed: %v", err) + } + st = loadKnownHosts(store) + if got := st.Pins[userHostKey("victim", "newsrv:22")]; got != hostKeyFingerprint(real) { + t.Fatalf("victim should be pinned to the REAL key, got %q", got) + } +} + +func TestTOFUFailsClosedOnUnwritableStore(t *testing.T) { + dir := t.TempDir() + blocker := filepath.Join(dir, "blocker") + if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + store := filepath.Join(blocker, "data", "known.json") + cb := tofuHostKeyCallback(store, "u", false) + addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22} + if err := cb("h:22", addr, mkKey(t)); err == nil { + t.Fatal("must fail closed when the key store is unavailable") + } +} diff --git a/data/console-command-history.json b/data/console-command-history.json new file mode 100644 index 0000000..d0f5a88 --- /dev/null +++ b/data/console-command-history.json @@ -0,0 +1 @@ +{"Tests":[{"line":"pl","ts":1778787350028,"source":"command","seq":0,"at":0},{"line":"pl","ts":1778865559475,"source":"command","seq":0,"at":0}],"da":[{"line":"pl","ts":1780081780409,"source":"command","seq":1513,"at":0},{"line":"pl","ts":1780081783489,"source":"command","seq":1514,"at":0},{"line":"pl","ts":1780081785809,"source":"command","seq":1515,"at":0},{"line":"help","ts":1780081787849,"source":"command","seq":1516,"at":0}],"test":[{"line":"pl","ts":1780131002803,"source":"command","seq":3213,"at":0},{"line":"pl","ts":1780132314446,"source":"command","seq":3262,"at":0}],"Testing":[{"line":"pl","ts":1780167742031,"source":"command","seq":75,"at":0},{"line":"pl","ts":1780168307468,"source":"command","seq":403,"at":0},{"line":"pl","ts":1780168307478,"source":"command","seq":404,"at":0},{"line":"help","ts":1780168309703,"source":"command","seq":406,"at":0},{"line":"pl","ts":1780168486609,"source":"command","seq":400,"at":0}],"Testingss":[{"line":"pl","ts":1780170899112,"source":"command","seq":76,"at":0}]} \ No newline at end of file diff --git a/data/console-history-reset.json b/data/console-history-reset.json new file mode 100644 index 0000000..100eb84 --- /dev/null +++ b/data/console-history-reset.json @@ -0,0 +1 @@ +{"da":1780081763302,"test":1780130983909,"Teste":1780764582187,"Testingss":1780170897236,"dsaf":1780242907441,"das":1780326849890,"Pe-Stick":1780852878638} \ No newline at end of file diff --git a/data/dashboard-background.json b/data/dashboard-background.json new file mode 100644 index 0000000..0ec7339 --- /dev/null +++ b/data/dashboard-background.json @@ -0,0 +1,5 @@ +{ + "type": "image", + "value": "/images/waves.png", + "updatedAt": "2026-06-05T19:05:09.162Z" +} \ No newline at end of file diff --git a/data/runtime-scaling.env b/data/runtime-scaling.env deleted file mode 100644 index 05c3c29..0000000 --- a/data/runtime-scaling.env +++ /dev/null @@ -1,6 +0,0 @@ -TOTAL_CORES=2 -TOTAL_RAM_MB=7941 -SAFE_RAM_MB=6352 -INSTANCES=1 -WORKER_RAM_MB=6352 -MAX_OLD_SPACE_MB=5399 diff --git a/docker_attach_smoke_test.go b/docker_attach_smoke_test.go new file mode 100644 index 0000000..a79a306 --- /dev/null +++ b/docker_attach_smoke_test.go @@ -0,0 +1,338 @@ +package main + +import ( + "bufio" + "context" + "fmt" + "io" + "os" + "os/exec" + "strings" + "testing" + "time" +) + +func TestDockerAttachAPIStdinTTYSmoke(t *testing.T) { + if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" { + t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test") + } + + name := fmt.Sprintf("adpanel-attach-smoke-%d", time.Now().UnixNano()) + _ = exec.Command("docker", "rm", "-f", name).Run() + t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() }) + + if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh").CombinedOutput(); err != nil { + t.Fatalf("docker run failed: %v: %s", err, string(out)) + } + + d := Docker{} + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + stream, err := d.attachContainerAPI(ctx, name, dockerAttachOptions{Stdout: true, Stderr: true}) + if err != nil { + t.Fatalf("attach stdout failed: %v", err) + } + defer stream.Close() + + lines := make(chan string, 32) + go func() { + sc := bufio.NewScanner(stream) + for sc.Scan() { + lines <- sc.Text() + } + close(lines) + }() + + stdin, err := d.attachContainerAPI(ctx, name, dockerAttachOptions{Stdin: true}) + if err != nil { + t.Fatalf("attach stdin failed: %v", err) + } + defer stdin.Close() + + if _, err := io.WriteString(stdin, "echo READY\n"); err != nil { + t.Fatalf("stdin write failed: %v", err) + } + + deadline := time.After(5 * time.Second) + for { + select { + case line := <-lines: + if strings.Contains(line, "READY") { + return + } + case <-deadline: + t.Fatal("did not receive command output from attach stream") + } + } +} + +func TestDockerSendCommandPrefersAttachBeforeTargetFallback(t *testing.T) { + if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" { + t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test") + } + + name := fmt.Sprintf("adpanel-attach-target-smoke-%d", time.Now().UnixNano()) + _ = exec.Command("docker", "rm", "-f", name).Run() + t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() }) + + startScript := `tail -f /dev/null < /dev/null & while read line; do echo "CONSOLE:$line"; done` + if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil { + t.Fatalf("docker run failed: %v: %s", err, string(out)) + } + + d := Docker{} + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + stream, err := d.attachContainerAPI(ctx, name, dockerAttachOptions{Stdout: true, Stderr: true}) + if err != nil { + t.Fatalf("attach stdout failed: %v", err) + } + defer stream.Close() + + lines := make(chan string, 32) + go func() { + sc := bufio.NewScanner(stream) + for sc.Scan() { + lines <- sc.Text() + } + close(lines) + }() + + stdinMgr := newStdinManager(&d, false) + defer stdinMgr.stop() + + if err := d.sendCommand(ctx, stdinMgr, name, "hello-from-attach", []string{"tail"}); err != nil { + t.Fatalf("sendCommand failed: %v", err) + } + + deadline := time.After(5 * time.Second) + for { + select { + case line := <-lines: + if strings.Contains(line, "CONSOLE:hello-from-attach") { + return + } + case <-deadline: + t.Fatal("did not receive command output from attached console") + } + } +} + +func TestLogManagerLiveAttachWritesTTYStdin(t *testing.T) { + if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" { + t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test") + } + t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "api") + + name := fmt.Sprintf("adpanel-live-attach-stdin-smoke-%d", time.Now().UnixNano()) + _ = exec.Command("docker", "rm", "-f", name).Run() + t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() }) + + startScript := `while read line; do echo "CONSOLE:$line"; done` + if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil { + t.Fatalf("docker run failed: %v: %s", err, string(out)) + } + + d := Docker{} + lm := newLogManager(d, false) + ch := make(chan string, 16) + tail := lm.getOrCreate(name) + tail.mu.Lock() + tail.clients[ch] = struct{}{} + tail.mu.Unlock() + + deadline := time.Now().Add(8 * time.Second) + for time.Now().Before(deadline) { + if err := lm.writeCommand(name, "hello-from-live-attach"); err == nil { + break + } + time.Sleep(100 * time.Millisecond) + } + + timeout := time.After(time.Until(deadline)) + for { + select { + case line := <-ch: + if strings.Contains(line, "CONSOLE:hello-from-live-attach") { + lm.killTail(name) + return + } + case <-timeout: + lm.killTail(name) + t.Fatal("did not receive command output from live attach stream") + } + } +} + +func TestDockerSendCommandForcedCLITransportKeepsTTYStdin(t *testing.T) { + if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" { + t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test") + } + t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "cli") + + name := fmt.Sprintf("adpanel-cli-tty-stdin-smoke-%d", time.Now().UnixNano()) + _ = exec.Command("docker", "rm", "-f", name).Run() + t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() }) + + startScript := `while read line; do echo "CONSOLE:$line"; done` + if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil { + t.Fatalf("docker run failed: %v: %s", err, string(out)) + } + + d := Docker{} + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + stdinMgr := newStdinManager(&d, false) + defer stdinMgr.stop() + + if err := d.sendCommand(ctx, stdinMgr, name, "hello-from-tty-attach", []string{"sh"}); err != nil { + t.Fatalf("sendCommand failed: %v", err) + } + + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + out, err := exec.Command("docker", "logs", name).CombinedOutput() + if err == nil && strings.Contains(string(out), "CONSOLE:hello-from-tty-attach") { + return + } + time.Sleep(100 * time.Millisecond) + } + out, _ := exec.Command("docker", "logs", name).CombinedOutput() + t.Fatalf("did not receive command output from TTY stdin attach; logs=%s", string(out)) +} + +func TestDockerSendCommandCLIPTYTransportWritesTTYStdin(t *testing.T) { + if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" { + t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test") + } + t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "pty") + + name := fmt.Sprintf("adpanel-cli-pty-stdin-smoke-%d", time.Now().UnixNano()) + _ = exec.Command("docker", "rm", "-f", name).Run() + t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() }) + + startScript := `while read line; do echo "CONSOLE:$line"; done` + if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil { + t.Fatalf("docker run failed: %v: %s", err, string(out)) + } + + d := Docker{} + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + stdinMgr := newStdinManager(&d, false) + defer stdinMgr.stop() + + if err := d.sendCommand(ctx, stdinMgr, name, "hello-from-cli-pty", []string{"sh"}); err != nil { + t.Fatalf("sendCommand failed: %v", err) + } + + deadline := time.Now().Add(5 * time.Second) + for time.Now().Before(deadline) { + out, err := exec.Command("docker", "logs", name).CombinedOutput() + if err == nil && strings.Contains(string(out), "CONSOLE:hello-from-cli-pty") { + return + } + time.Sleep(100 * time.Millisecond) + } + out, _ := exec.Command("docker", "logs", name).CombinedOutput() + t.Fatalf("did not receive command output from Docker CLI PTY stdin attach; logs=%s", string(out)) +} + +func TestDockerLogsCLITransportCapturesTTYOutput(t *testing.T) { + if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" { + t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test") + } + t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "cli") + + name := fmt.Sprintf("adpanel-cli-tty-logs-smoke-%d", time.Now().UnixNano()) + _ = exec.Command("docker", "rm", "-f", name).Run() + t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() }) + + startScript := `sleep 1; echo "CONSOLE:hello-from-docker-logs"; sleep 30` + if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil { + t.Fatalf("docker run failed: %v: %s", err, string(out)) + } + + d := Docker{} + lm := newLogManager(d, false) + ch := make(chan string, 16) + tail := &logTail{ + name: name, + clients: map[chan string]struct{}{ch: {}}, + recentN: logTailRecentMaxLines, + stopCh: make(chan struct{}), + } + + done := make(chan error, 1) + go func() { + done <- lm.followDockerLogsCLI(tail) + }() + + stopTail := func() { + tail.mu.Lock() + cmd := tail.cmd + tail.mu.Unlock() + select { + case <-tail.stopCh: + default: + close(tail.stopCh) + } + if cmd != nil && cmd.Process != nil { + _ = cmd.Process.Kill() + } + } + defer stopTail() + + deadline := time.After(6 * time.Second) + for { + select { + case line := <-ch: + if strings.Contains(line, "CONSOLE:hello-from-docker-logs") { + stopTail() + select { + case <-done: + case <-time.After(2 * time.Second): + } + return + } + case err := <-done: + t.Fatalf("docker logs follow exited before output: %v", err) + case <-deadline: + t.Fatal("did not receive TTY output from docker logs follow") + } + } +} + +func TestDockerSendCommandRejectsClosedContainerStdin(t *testing.T) { + if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" { + t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test") + } + + name := fmt.Sprintf("adpanel-closed-stdin-smoke-%d", time.Now().UnixNano()) + _ = exec.Command("docker", "rm", "-f", name).Run() + t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() }) + + startScript := `while read line; do echo "CONSOLE:$line"; done; sleep 30` + if out, err := exec.Command("docker", "run", "-d", "--name", name, "-t", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil { + t.Fatalf("docker run failed: %v: %s", err, string(out)) + } + + d := Docker{} + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + stdinMgr := newStdinManager(&d, false) + defer stdinMgr.stop() + + err := d.sendCommand(ctx, stdinMgr, name, "hello-closed-stdin", []string{"sh"}) + if err == nil { + t.Fatal("expected closed container stdin to be rejected") + } + if !strings.Contains(err.Error(), "stdin is not open") { + t.Fatalf("expected stdin-not-open error, got %v", err) + } +} diff --git a/docker_engine.go b/docker_engine.go index 6e42bbe..37e8175 100644 --- a/docker_engine.go +++ b/docker_engine.go @@ -1,6 +1,7 @@ package main import ( + "bufio" "bytes" "context" "encoding/json" @@ -95,6 +96,22 @@ type dockerPullProgress struct { Error string `json:"error"` } +type dockerAttachOptions struct { + Stdin bool + Stdout bool + Stderr bool + Logs bool +} + +type dockerHijackedConn struct { + net.Conn + reader *bufio.Reader +} + +func (c *dockerHijackedConn) Read(p []byte) (int, error) { + return c.reader.Read(p) +} + type dockerImageInspectConfig struct { Entrypoint []string `json:"Entrypoint"` Cmd []string `json:"Cmd"` @@ -232,6 +249,80 @@ func (d Docker) engineRequest(ctx context.Context, method, rawPath string, query return respBody, resp.StatusCode, nil } +func (d Docker) attachContainerAPI(ctx context.Context, name string, opts dockerAttachOptions) (io.ReadWriteCloser, error) { + dockerName := dockerContainerName(name) + if dockerName == "" { + return nil, fmt.Errorf("missing container name") + } + if !opts.Stdin && !opts.Stdout && !opts.Stderr { + return nil, fmt.Errorf("no attach streams requested") + } + + var dialer net.Dialer + conn, err := dialer.DialContext(ctx, "unix", dockerEngineSocketPath) + if err != nil { + return nil, err + } + + _ = conn.SetDeadline(time.Now().Add(10 * time.Second)) + + query := url.Values{} + query.Set("stream", "1") + if opts.Stdin { + query.Set("stdin", "1") + } + if opts.Stdout { + query.Set("stdout", "1") + } + if opts.Stderr { + query.Set("stderr", "1") + } + if opts.Logs { + query.Set("logs", "1") + } + + req, err := http.NewRequestWithContext( + ctx, + http.MethodPost, + "http://docker"+dockerAPIPath("/containers/"+url.PathEscape(dockerName)+"/attach", query), + nil, + ) + if err != nil { + _ = conn.Close() + return nil, err + } + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "tcp") + + if err := req.Write(conn); err != nil { + _ = conn.Close() + return nil, err + } + + reader := bufio.NewReader(conn) + resp, err := http.ReadResponse(reader, req) + if err != nil { + _ = conn.Close() + return nil, err + } + if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusOK { + detail := "" + if resp.Body != nil { + body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096)) + _ = resp.Body.Close() + detail = decodeDockerAPIError(body) + } + _ = conn.Close() + if detail == "" { + detail = resp.Status + } + return nil, fmt.Errorf("failed to attach container %s: %s", dockerName, detail) + } + + _ = conn.SetDeadline(time.Time{}) + return &dockerHijackedConn{Conn: conn, reader: reader}, nil +} + func splitDockerImageRef(ref string) (string, string) { clean := strings.TrimSpace(ref) if clean == "" { @@ -249,6 +340,47 @@ func splitDockerImageRef(ref string) (string, string) { } func (d Docker) pullImageAPI(ctx context.Context, ref string) error { + var lastErr error + for attempt := 1; attempt <= 3; attempt++ { + err := d.pullImageAPIOnce(ctx, ref) + if err == nil { + return nil + } + lastErr = err + if ctx.Err() != nil || !isTransientDockerPullError(err) || attempt == 3 { + break + } + delay := time.Duration(attempt*attempt) * time.Second + timer := time.NewTimer(delay) + select { + case <-ctx.Done(): + timer.Stop() + return ctx.Err() + case <-timer.C: + } + } + return lastErr +} + +func (d Docker) ensureImageAvailableAPI(ctx context.Context, ref string) error { + imageRef := strings.TrimSpace(ref) + if imageRef == "" { + return fmt.Errorf("missing image reference") + } + if d.imageExistsLocally(ctx, imageRef) { + return nil + } + if err := d.pullImageAPI(ctx, imageRef); err != nil { + if isTransientDockerPullError(err) && d.imageExistsLocally(ctx, imageRef) { + fmt.Printf("[docker] pull failed for %s with transient error, using cached image: %v\n", imageRef, err) + return nil + } + return err + } + return nil +} + +func (d Docker) pullImageAPIOnce(ctx context.Context, ref string) error { image, tag := splitDockerImageRef(ref) if image == "" { return fmt.Errorf("missing image reference") @@ -290,12 +422,63 @@ func (d Docker) pullImageAPI(ctx context.Context, ref string) error { return nil } +func isTransientDockerPullError(err error) bool { + if err == nil { + return false + } + msg := strings.ToLower(err.Error()) + nonTransient := []string{ + "manifest unknown", + "not found", + "pull access denied", + "repository does not exist", + "requested access to the resource is denied", + "unauthorized", + "authentication required", + "invalid reference format", + } + for _, marker := range nonTransient { + if strings.Contains(msg, marker) { + return false + } + } + transient := []string{ + "tls: bad record mac", + "unexpected eof", + "connection reset", + "connection refused", + "connection timed out", + "i/o timeout", + "net/http", + "httpreadseeker", + "failed to copy", + "failed to do request", + "tls handshake timeout", + "temporary failure", + "503", + "502", + "504", + "too many requests", + } + for _, marker := range transient { + if strings.Contains(msg, marker) { + return true + } + } + return false +} + func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool) error { + dockerName := dockerContainerName(name) + if dockerName == "" { + return fmt.Errorf("missing container name") + } query := url.Values{} + query.Set("v", "1") if force { query.Set("force", "1") } - body, status, err := d.engineRequest(ctx, http.MethodDelete, "/containers/"+url.PathEscape(name), query, nil) + body, status, err := d.engineRequest(ctx, http.MethodDelete, "/containers/"+url.PathEscape(dockerName), query, nil) if err != nil { return err } @@ -303,11 +486,74 @@ func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool) return nil } if status < 200 || status >= 300 { - return fmt.Errorf("failed to remove container %s: %s", name, decodeDockerAPIError(body)) + return fmt.Errorf("failed to remove container %s: %s", dockerName, decodeDockerAPIError(body)) } return nil } +func (d Docker) killContainerAPI(ctx context.Context, name string) error { + dockerName := dockerContainerName(name) + if dockerName == "" { + return fmt.Errorf("missing container name") + } + query := url.Values{} + query.Set("signal", "SIGKILL") + body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(dockerName)+"/kill", query, nil) + if err != nil { + return err + } + if status == http.StatusNotFound { + return nil + } + if status == http.StatusConflict { + msg := strings.ToLower(decodeDockerAPIError(body)) + if strings.Contains(msg, "not running") || strings.Contains(msg, "is not running") { + return nil + } + } + if status < 200 || status >= 300 { + return fmt.Errorf("failed to kill container %s: %s", dockerName, decodeDockerAPIError(body)) + } + return nil +} + +func (d Docker) updateRestartNoAPI(ctx context.Context, name string) error { + dockerName := dockerContainerName(name) + if dockerName == "" { + return fmt.Errorf("missing container name") + } + req := dockerHostConfig{RestartPolicy: dockerRestartPolicy{Name: "no"}} + body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(dockerName)+"/update", nil, req) + if err != nil { + return err + } + if status == http.StatusNotFound { + return nil + } + if status < 200 || status >= 300 { + return fmt.Errorf("failed to disable restart policy for %s: %s", dockerName, decodeDockerAPIError(body)) + } + return nil +} + +func (d Docker) containerExistsAPI(ctx context.Context, name string) (bool, error) { + dockerName := dockerContainerName(name) + if dockerName == "" { + return false, fmt.Errorf("missing container name") + } + body, status, err := d.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(dockerName)+"/json", nil, nil) + if err != nil { + return false, err + } + if status == http.StatusNotFound { + return false, nil + } + if status < 200 || status >= 300 { + return false, fmt.Errorf("failed to inspect container %s: %s", dockerName, decodeDockerAPIError(body)) + } + return true, nil +} + func (d Docker) createContainerAPI(ctx context.Context, name string, req dockerContainerCreateRequest) (string, error) { query := url.Values{} query.Set("name", name) @@ -362,7 +608,7 @@ func (d Docker) runContainerAPI(ctx context.Context, name string, req dockerCont removeCancel() pullCtx, pullCancel := context.WithTimeout(ctx, 10*time.Minute) - if err := d.pullImageAPI(pullCtx, req.Image); err != nil { + if err := d.ensureImageAvailableAPI(pullCtx, req.Image); err != nil { pullCancel() return err } diff --git a/docker_engine_test.go b/docker_engine_test.go new file mode 100644 index 0000000..09d80cb --- /dev/null +++ b/docker_engine_test.go @@ -0,0 +1,268 @@ +package main + +import ( + "errors" + "path/filepath" + "testing" +) + +func TestIsTransientDockerPullError(t *testing.T) { + transient := []string{ + `failed to pull image eclipse-temurin:17-jre: failed to copy: httpReadSeeker: failed open: failed to do request: local error: tls: bad record MAC`, + `unexpected EOF`, + `Get "https://registry-1.docker.io/v2/": net/http: TLS handshake timeout`, + `received unexpected HTTP status: 503 Service Unavailable`, + } + for _, msg := range transient { + if !isTransientDockerPullError(errors.New(msg)) { + t.Fatalf("expected transient pull error for %q", msg) + } + } + + permanent := []string{ + `manifest unknown`, + `pull access denied, repository does not exist or may require authorization`, + `unauthorized: authentication required`, + `invalid reference format`, + } + for _, msg := range permanent { + if isTransientDockerPullError(errors.New(msg)) { + t.Fatalf("expected permanent pull error for %q", msg) + } + } +} + +func TestPreferDockerAPIConsoleTransportByDefault(t *testing.T) { + t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "") + if preferDockerCLIConsoleTransport() { + t.Fatalf("expected Docker API attach transport by default") + } +} + +func TestPreferDockerCLIConsoleTransportOverride(t *testing.T) { + t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "cli") + if !preferDockerCLIConsoleTransport() { + t.Fatalf("expected Docker CLI transport override to be honored") + } + t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "docker-api") + if preferDockerCLIConsoleTransport() { + t.Fatalf("expected Docker API transport override to be honored") + } +} + +func TestEnterpriseLinuxOSReleaseDetection(t *testing.T) { + if !isEnterpriseLinuxOSRelease("ID=rocky\nID_LIKE=\"rhel centos fedora\"\n") { + t.Fatalf("expected Rocky Linux to prefer enterprise Linux stdin fallback") + } + if !isEnterpriseLinuxOSRelease("ID=almalinux\nID_LIKE=\"rhel centos fedora\"\n") { + t.Fatalf("expected AlmaLinux to prefer enterprise Linux stdin fallback") + } + if isEnterpriseLinuxOSRelease("ID=ubuntu\nID_LIKE=debian\n") { + t.Fatalf("did not expect Ubuntu to prefer enterprise Linux stdin fallback") + } +} + +func TestPreferDockerCLIPTYStdinTransportOverride(t *testing.T) { + t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "pty") + if !preferDockerCLIPTYStdinTransport() { + t.Fatalf("expected Docker CLI PTY stdin override to be honored") + } + t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "docker-api") + if preferDockerCLIPTYStdinTransport() { + t.Fatalf("expected Docker API stdin override to be honored") + } +} + +func TestParseDockerLogSnapshotEntriesKeepsTimestamps(t *testing.T) { + raw := "2026-05-14T19:20:01.123456789Z server starting\n" + + "2026-05-14T19:20:02Z Done (3.2s)! For help, type \"help\"\n" + + entries := parseDockerLogSnapshotEntries(raw, 10) + if len(entries) != 2 { + t.Fatalf("expected 2 entries, got %#v", entries) + } + if entries[0].line != "server starting" { + t.Fatalf("expected timestamp prefix to be removed, got %q", entries[0].line) + } + if entries[0].ts != 1778786401123 { + t.Fatalf("expected nanosecond timestamp to be parsed as ms, got %d", entries[0].ts) + } + if entries[1].line != `Done (3.2s)! For help, type "help"` { + t.Fatalf("unexpected second line: %q", entries[1].line) + } + if entries[1].ts != 1778786402000 { + t.Fatalf("expected whole-second timestamp to be parsed as ms, got %d", entries[1].ts) + } +} + +func TestPterodactylRustKeepsHomeContainerVolume(t *testing.T) { + cfg := imageConfig{ + Entrypoint: []string{"/bin/bash", "/entrypoint.sh"}, + Workdir: "/home/container", + Env: map[string]string{}, + } + binds, dataDir := sanitizeCustomImageDefaultBinds( + "ghcr.io/pterodactyl/games:rust", + cfg, + []string{"/srv/adpanel/rust:/home/container"}, + "/home/container", + ) + if len(binds) != 1 || binds[0] != "/srv/adpanel/rust:/home/container" { + t.Fatalf("expected /home/container bind to be preserved, got %#v", binds) + } + if dataDir != "/home/container" { + t.Fatalf("expected dataDir /home/container, got %q", dataDir) + } +} + +func TestImageWorkdirBindIsKeptWhenItIsKnownGameDataPath(t *testing.T) { + cfg := imageConfig{ + Entrypoint: []string{"/entrypoint.sh"}, + Workdir: "/steamcmd/rust", + Env: map[string]string{}, + } + binds, dataDir := sanitizeCustomImageDefaultBinds( + "didstopia/rust-server:full", + cfg, + []string{"/srv/adpanel/rust:/steamcmd/rust"}, + "/steamcmd/rust", + ) + if len(binds) != 1 || binds[0] != "/srv/adpanel/rust:/steamcmd/rust" { + t.Fatalf("expected known data-path bind to be preserved, got %#v", binds) + } + if dataDir != "/steamcmd/rust" { + t.Fatalf("expected dataDir /steamcmd/rust, got %q", dataDir) + } +} + +func TestRustRestartRecreatesContainer(t *testing.T) { + if !shouldRecreateContainerOnRestart(map[string]any{"type": "rust"}) { + t.Fatalf("expected rust template restart to recreate the container") + } + if !shouldRecreateContainerOnRestart(map[string]any{ + "type": "custom", + "runtime": map[string]any{ + "image": "ghcr.io/pterodactyl/games", + "tag": "rust", + }, + }) { + t.Fatalf("expected pterodactyl rust image restart to recreate the container") + } + if shouldRecreateContainerOnRestart(map[string]any{"type": "minecraft"}) { + t.Fatalf("did not expect minecraft restart to use rust recreate path") + } +} + +func TestRustGetsDefaultHighFileLimit(t *testing.T) { + resources := withRuntimeDefaultFileLimit(nil, "rust", "ghcr.io/pterodactyl/games:rust") + if resources == nil || resources.FileLimit == nil || *resources.FileLimit != maxFileLimit { + t.Fatalf("expected rust to default to max file limit, got %#v", resources) + } + + customLimit := 65535 + resources = withRuntimeDefaultFileLimit(&resourceLimits{FileLimit: &customLimit}, "rust", "ghcr.io/pterodactyl/games:rust") + if resources == nil || resources.FileLimit == nil || *resources.FileLimit != customLimit { + t.Fatalf("expected explicit file limit to be preserved, got %#v", resources) + } + + if got := withRuntimeDefaultFileLimit(nil, "minecraft", "eclipse-temurin:21-jre"); got != nil { + t.Fatalf("did not expect non-rust runtime defaults, got %#v", got) + } +} + +func TestCfxRuntimeLayoutStaysInsideMountedServerDir(t *testing.T) { + serverDir := t.TempDir() + if err := ensureDir(filepath.Join(serverDir, "serverfiles")); err != nil { + t.Fatalf("failed to create nested legacy dir: %v", err) + } + if err := writeFileNoFollow(filepath.Join(serverDir, "serverfiles", "server.cfg"), []byte("sv_maxclients 32\n"), 0o644); err != nil { + t.Fatalf("failed to create legacy cfg: %v", err) + } + + runtimeObj := map[string]any{ + "volumes": []any{"{BOT_DIR}:/serverdata"}, + "workdir": "/serverdata", + "install": map[string]any{ + "runtimePath": "/serverdata", + }, + "env": map[string]any{ + "DATA_DIR": "/serverdata", + "SERVER_DIR": "/serverdata/serverfiles", + "DATA_PERM": "770", + "SERVER_KEY": "keep-me", + "START_VARS": "+set gamename rdr3", + "GAME_CONFIG": "old.cfg", + }, + } + + if !normalizeCfxRuntimeLayout("redm", runtimeObj, serverDir) { + t.Fatalf("expected legacy CFX runtime to be normalized") + } + + volumes := runtimeObj["volumes"].([]any) + if len(volumes) != 1 || volumes[0] != "{BOT_DIR}:/serverdata/serverfiles" { + t.Fatalf("expected server root to be mounted directly to CFX server dir, got %#v", volumes) + } + if runtimeObj["workdir"] != "/serverdata/serverfiles" { + t.Fatalf("expected CFX workdir inside mounted server dir, got %#v", runtimeObj["workdir"]) + } + if runtimeObj["runAsRoot"] != true { + t.Fatalf("expected CFX entrypoint to keep image root bootstrap enabled, got %#v", runtimeObj["runAsRoot"]) + } + + env := runtimeObj["env"].(map[string]string) + for key, want := range map[string]string{ + "DATA_DIR": "/serverdata/serverfiles", + "SERVER_DIR": "/serverdata/serverfiles", + "HOME": "/serverdata/serverfiles", + "DATA_PERM": "777", + "GAME_CONFIG": "server.cfg", + } { + if got := env[key]; got != want { + t.Fatalf("expected env %s=%q, got %q", key, want, got) + } + } + if env["SERVER_KEY"] != "keep-me" || env["START_VARS"] != "+set gamename rdr3" { + t.Fatalf("expected CFX-specific user env to be preserved, got %#v", env) + } + install := runtimeObj["install"].(map[string]any) + if install["runtimePath"] != "/serverdata/serverfiles" || install["mountPath"] != "/mnt/server" { + t.Fatalf("expected CFX install paths to stay aligned to mounted dir, got %#v", install) + } + if !pathExists(filepath.Join(serverDir, "server.cfg")) { + t.Fatalf("expected nested legacy serverfiles content to be migrated into server root") + } +} + +func TestLegacyRustRuntimeMigratesToPterodactyl(t *testing.T) { + meta := map[string]any{ + "type": "rust", + "template": "rust", + "runtime": map[string]any{ + "image": "didstopia/rust-server", + "tag": "full", + "volumes": []any{"{BOT_DIR}:/steamcmd/rust"}, + "workdir": "/", + "env": map[string]any{ + "RUST_SERVER_NAME": "Legacy Rust", + "RUST_RCON_PASSWORD": "secret", + "RUST_SERVER_QUERYPORT": "28016", + }, + }, + } + if !normalizeRustRuntimeForPterodactyl(meta) { + t.Fatalf("expected legacy rust metadata to be migrated") + } + runtimeObj := meta["runtime"].(map[string]any) + if runtimeObj["image"] != "ghcr.io/pterodactyl/games" || runtimeObj["tag"] != "rust" { + t.Fatalf("expected pterodactyl rust runtime, got %#v:%#v", runtimeObj["image"], runtimeObj["tag"]) + } + env := runtimeObj["env"].(map[string]string) + if env["SERVER_NAME"] != "Legacy Rust" || env["RCON_PASS"] != "secret" { + t.Fatalf("expected legacy env values to be preserved, got %#v", env) + } + volumes := runtimeObj["volumes"].([]any) + if len(volumes) != 1 || volumes[0] != "{BOT_DIR}:/home/container" { + t.Fatalf("expected home/container volume, got %#v", volumes) + } +} diff --git a/fix_max_width.js b/fix_max_width.js new file mode 100644 index 0000000..054c0df --- /dev/null +++ b/fix_max_width.js @@ -0,0 +1,11 @@ +const fs = require('fs'); +let cssContent = fs.readFileSync('public/css/bot.css', 'utf8'); +cssContent = cssContent.replace(/transition: opacity \.2s ease, transform \.25s ease;/g, 'transition: opacity .2s ease, max-width .25s cubic-bezier(0.4, 0, 0.2, 1);'); +cssContent = cssContent.replace(/width: 150px;/g, 'max-width: 150px;'); +cssContent = cssContent.replace(/width: 200px;/g, 'max-width: 200px;'); +cssContent = cssContent.replace(/width: 0;/g, 'max-width: 0;'); +fs.writeFileSync('public/css/bot.css', cssContent); + +let ejsContent = fs.readFileSync('views/bot.ejs', 'utf8'); +ejsContent = ejsContent.replace(/transition:\n\s*opacity 0\.2s cubic-bezier\(0\.4, 0, 0\.2, 1\),\n\s*transform 0\.25s cubic-bezier\(0\.4, 0, 0\.2, 1\);/g, 'transition: max-width 0.25s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);'); +fs.writeFileSync('views/bot.ejs', ejsContent); diff --git a/fix_max_width2.js b/fix_max_width2.js new file mode 100644 index 0000000..e433413 --- /dev/null +++ b/fix_max_width2.js @@ -0,0 +1,10 @@ +const fs = require('fs'); +let cssContent = fs.readFileSync('public/css/bot.css', 'utf8'); + +cssContent = cssContent.replace(/will-change: opacity, transform;/g, 'will-change: opacity, max-width;'); + +fs.writeFileSync('public/css/bot.css', cssContent); + +let ejsContent = fs.readFileSync('views/bot.ejs', 'utf8'); +ejsContent = ejsContent.replace(/transform: translateZ\(0\);\n\s*backface-visibility: hidden;/g, 'transform: translateZ(0);'); +fs.writeFileSync('views/bot.ejs', ejsContent); diff --git a/fs_server_scope_test.go b/fs_server_scope_test.go new file mode 100644 index 0000000..46e8ae8 --- /dev/null +++ b/fs_server_scope_test.go @@ -0,0 +1,50 @@ +package main + +import ( + "path/filepath" + "testing" +) + +// adpanel:fs-scope - lock in the server-scoped FS confinement (#2). The generic +// /v1/fs/* handlers must, when a server name is supplied, reject any path that +// belongs to a *different* server on the same disk root, even though that path is +// still under a valid volumes root (so safeUnderVolumes alone would allow it). +func TestSafeUnderServerOrVolumes_ScopesToSingleServer(t *testing.T) { + a, vol := newTestAgent(t) + + alphaFile := filepath.Join(vol, "alpha", "config", "app.cfg") + betaFile := filepath.Join(vol, "beta", "secrets.txt") + + // No scope: behaves exactly like safeUnderVolumes (back-compat). + if got, ok := a.safeUnderServerOrVolumes("", alphaFile); !ok || got != filepath.Clean(alphaFile) { + t.Fatalf("empty scope should accept any in-volume path, got (%q,%v)", got, ok) + } + + // Matching scope: accepted. + if got, ok := a.safeUnderServerOrVolumes("alpha", alphaFile); !ok || got != filepath.Clean(alphaFile) { + t.Fatalf("alpha scope should accept alpha path, got (%q,%v)", got, ok) + } + + // The server root itself is accepted (e.g. listing the root directory). + if _, ok := a.safeUnderServerOrVolumes("alpha", a.serverDir("alpha")); !ok { + t.Fatalf("alpha scope should accept alpha root") + } + + // Cross-server access is the key boundary: beta's files must be refused when + // the scope is alpha, even though betaFile is under a valid volumes root. + if _, ok := a.safeUnderServerOrVolumes("alpha", betaFile); ok { + t.Fatalf("alpha scope must reject beta's file %q", betaFile) + } + + // A traversal that climbs out of alpha into beta must also be refused. + escape := filepath.Join(vol, "alpha", "..", "beta", "secrets.txt") + if _, ok := a.safeUnderServerOrVolumes("alpha", escape); ok { + t.Fatalf("alpha scope must reject traversal into beta: %q", escape) + } + + // An unknown/invalid scope name resolves to a server dir that exists nowhere, + // so nothing matches and access is denied (fail-closed). + if _, ok := a.safeUnderServerOrVolumes("does-not-exist", alphaFile); ok { + t.Fatalf("unknown scope should not match alpha path") + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..ae076dc --- /dev/null +++ b/go.mod @@ -0,0 +1,14 @@ +module adpanel-node + +go 1.24.0 + +toolchain go1.24.11 + +require ( + github.com/creack/pty v1.1.24 + github.com/ulikunitz/xz v0.5.14 + golang.org/x/crypto v0.46.0 + nhooyr.io/websocket v1.8.17 +) + +require golang.org/x/sys v0.39.0 // indirect diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..5020187 --- /dev/null +++ b/go.sum @@ -0,0 +1,12 @@ +github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s= +github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= +github.com/ulikunitz/xz v0.5.14 h1:uv/0Bq533iFdnMHZdRBTOlaNMdb1+ZxXIlHDZHIHcvg= +github.com/ulikunitz/xz v0.5.14/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= +golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU= +golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0= +golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk= +golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks= +golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q= +golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg= +nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y= +nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c= diff --git a/index.js b/index.js index 7a92b89..8973a4e 100644 --- a/index.js +++ b/index.js @@ -29,8 +29,11 @@ let _FileStore; function getLazyFileStore() { if (!_FileStore) _FileStore = requ let _FormData; function getLazyFormData() { if (!_FormData) _FormData = require("form-data"); return _FormData; } const db = require("./db"); const mysql = require("mysql2/promise"); +const { PanelMetricsCollector } = require("./utils/panel-metrics"); +let panelMetrics = null; const DASHBOARD_CSS = path.join(process.cwd(), "public", "css", "dashboard.css"); const BOT_CSS = path.join(process.cwd(), "public", "css", "bot.css"); +const DASHBOARD_BACKGROUND_CONFIG = path.join(process.cwd(), "data", "dashboard-background.json"); const { makeCssBackground } = require("./utils/background"); const { brandingMiddleware, @@ -57,8 +60,10 @@ const { sanitizeDockerTemplatePayload, sanitizeDockerInstallPayload, sanitizeEnvPayload, + sanitizePortProtocolPayload, } = require("./utils/server-template-payload"); const { deleteServerByName } = require("./utils/server-delete"); +const { getTechnicalServerName } = require("./utils/server-name"); const { applyRemoteAssetToServer } = require("./utils/server-asset-apply"); const { ensureStealthConfig } = require("./utils/stealth"); const { @@ -175,6 +180,14 @@ app.use((req, res, next) => { } return next(); }); + +// Ultra-cheap request counter for the admin /status RPS metric. A single +// integer increment per request; the panel-metrics collector samples and resets +// it on its own cadence. No allocation, no I/O on the hot path. +app.use((req, _res, next) => { + if (panelMetrics) panelMetrics._reqCounter++; + next(); +}); const TRUST_PROXY = process.env.TRUST_PROXY || "loopback"; app.set("trust proxy", TRUST_PROXY); const FREEZE_PROTOTYPES = ["1", "true", "yes", "on"].includes(String(process.env.FREEZE_PROTOTYPES ?? "1").trim().toLowerCase()); @@ -792,14 +805,21 @@ async function startServerOnNode(node, name, hostPort) { } } -async function streamExportToImport({ sourceNode, destNode, serverName, onProgress }) { +async function streamExportToImport({ sourceNode, destNode, serverName, targetDiskId, onProgress }) { const sourceBase = buildNodeBaseUrl(sourceNode.address, sourceNode.api_port || 8080, sourceNode.ssl_enabled, nodeUnderCloudflare(sourceNode)); const destBase = buildNodeBaseUrl(destNode.address, destNode.api_port || 8080, destNode.ssl_enabled, nodeUnderCloudflare(destNode)); if (!sourceBase) throw new Error("invalid source node address"); if (!destBase) throw new Error("invalid destination node address"); const srcUrl = `${sourceBase}/v1/servers/${encodeURIComponent(serverName)}/export`; - const dstUrl = `${destBase}/v1/servers/${encodeURIComponent(serverName)}/import-tar`; + // adpanel:multidisk - the destination node owns its own disks; the source's + // disk identity is stripped on import. Default to the destination's primary + // disk; pass an explicit diskId only when the panel wants to place the server + // on a specific secondary disk of the destination node. + const diskParam = (typeof targetDiskId === "string" && targetDiskId.trim() && targetDiskId.trim() !== "primary") + ? `?diskId=${encodeURIComponent(targetDiskId.trim())}` + : ""; + const dstUrl = `${destBase}/v1/servers/${encodeURIComponent(serverName)}/import-tar${diskParam}`; const srcHeaders = { Authorization: `Bearer ${sourceNode.token}`, @@ -993,7 +1013,10 @@ function issueSshTerminalToken(req) { } function issueActionToken(req, action, resource = {}, opts = {}) { - const ttlSeconds = Number(opts.ttlSeconds ?? 300); + // Default action-session window is 10 minutes so admins can sit in a + // settings popup for a while before submitting without hitting a spurious + // "invalid or missing token" error (similar to Pterodactyl's behavior). + const ttlSeconds = Number(opts.ttlSeconds ?? 600); const oneTime = !!opts.oneTime; const now = Date.now(); @@ -1413,11 +1436,43 @@ function mapUserRow(row) { id: row.id, email: row.email, password: row.password, - secret: row.secret, + secret: row.secret ? String(row.secret).trim() : null, admin: !!row.admin, + suspended: !!row.suspended, + suspended_at: row.suspended_at === null || row.suspended_at === undefined ? null : Number(row.suspended_at), + suspended_by: row.suspended_by || null, }; } +function hasTwoFactorEnabled(user) { + return !!String(user?.secret || "").trim(); +} + +function verifyTotpForUser(user, rawCode) { + const secret = String(user?.secret || "").trim(); + if (!secret) return { ok: true, skipped: true }; + const code = normalizeTotpCode(rawCode); + if (!code) return { ok: false, code: "invalid-format" }; + return { + ok: speakeasy.totp.verify({ + secret, + encoding: "base32", + token: code, + window: 1, + }), + skipped: false, + }; +} + +async function verifyPasswordForUser(user, rawPassword, label = "bcrypt-timeout") { + if (!user || !user.password || typeof rawPassword !== "string" || !rawPassword) return false; + return withTimeout( + bcrypt.compare(String(rawPassword), String(user.password || "")), + 8000, + label + ).catch(() => false); +} + function mapServerRow(row) { if (!row) return null; const runtime = parseDbJson(row.runtime, null); @@ -1433,6 +1488,9 @@ function mapServerRow(row) { ip: row.ip || null, port: row.port === null || row.port === undefined ? null : Number(row.port), status: row.status || null, + suspended: !!row.suspended, + suspended_at: row.suspended_at === null || row.suspended_at === undefined ? null : Number(row.suspended_at), + suspended_by: row.suspended_by || null, runtime, docker, acl: parseDbJson(row.acl, null), @@ -1640,10 +1698,13 @@ function clampPercent(value) { } function withTimeout(promise, ms, label = "timeout") { + let timer; return Promise.race([ - promise, - new Promise((_, reject) => setTimeout(() => reject(new Error(label)), ms)), - ]); + Promise.resolve(promise), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(label)), ms); + }), + ]).finally(() => clearTimeout(timer)); } const TRUSTED_PROXY_IPS = new Set( @@ -2219,7 +2280,7 @@ app.use((req, res, next) => { const HOST = process.env.HOST || "0.0.0.0"; const HTTP_PORT = parseInt(process.env.HTTP_PORT || "3000", 10); const SSH_TERM_PORT = parseInt(process.env.SSH_TERM_PORT || "9393", 10); -const SSH_TERM_PUBLIC_URL = (process.env.SSH_TERM_PUBLIC_URL || "").trim(); +const SSH_TERM_INTERNAL_URL = (process.env.SSH_TERM_INTERNAL_URL || process.env.SSH_TERM_ORIGIN || "").trim(); const NGINX_ENABLED = parseBoolean(process.env.NGINX_ENABLED, false); const APP_HOST = process.env.APP_HOST || HOST; const APP_PORT = parseInt(process.env.APP_PORT || "", 10) || 3001; @@ -2291,11 +2352,11 @@ const HOP_BY_HOP_HEADERS = new Set([ ]); function getSshTerminalOrigin(req) { - const raw = SSH_TERM_PUBLIC_URL; + const raw = SSH_TERM_INTERNAL_URL; if (raw) { const value = /^https?:\/\//i.test(raw) ? raw - : `${isRequestSecure(req) ? "https" : "http"}://${raw}`; + : `http://${raw}`; try { return new URL(value); } catch { @@ -2305,6 +2366,94 @@ function getSshTerminalOrigin(req) { return new URL(`http://127.0.0.1:${SSH_TERM_PORT}`); } +let sshTerminalRecoveryInFlight = null; +let sshTerminalRecoveryLastAttempt = 0; + +function runLocalCommand(command, args, timeoutMs = 15000) { + return new Promise((resolve) => { + let child; + let done = false; + const finish = (ok) => { + if (done) return; + done = true; + resolve(!!ok); + }; + try { + child = spawn(command, args, { stdio: "ignore" }); + } catch { + return finish(false); + } + const timer = setTimeout(() => { + try { child.kill("SIGTERM"); } catch { } + finish(false); + }, timeoutMs); + child.on("error", () => { + clearTimeout(timer); + finish(false); + }); + child.on("exit", (code) => { + clearTimeout(timer); + finish(code === 0); + }); + }); +} + +async function probeSshTerminalHealth(upstreamOrigin, timeoutMs = 2500) { + let timer; + try { + const healthUrl = new URL("/healthz", upstreamOrigin); + const controller = new AbortController(); + timer = setTimeout(() => controller.abort(), timeoutMs); + const response = await fetch(healthUrl.toString(), { signal: controller.signal }); + return response.ok; + } catch { + return false; + } finally { + if (timer) clearTimeout(timer); + } +} + +async function recoverSshTerminalService(upstreamOrigin) { + if (await probeSshTerminalHealth(upstreamOrigin, 1200)) return true; + if (!fs.existsSync("/run/systemd/system")) return false; + + const now = Date.now(); + if (sshTerminalRecoveryInFlight) return sshTerminalRecoveryInFlight; + if (now - sshTerminalRecoveryLastAttempt < 30000) return false; + sshTerminalRecoveryLastAttempt = now; + + sshTerminalRecoveryInFlight = (async () => { + const repairScript = path.join(__dirname, "initialize.sh"); + const restarted = + await runLocalCommand("systemctl", ["restart", "adpanel-sshterm"], 20000) || + await runLocalCommand("sudo", ["-n", "systemctl", "restart", "adpanel-sshterm"], 20000); + let repaired = restarted; + const runRepair = async () => fs.existsSync(repairScript) && ( + await runLocalCommand("bash", [repairScript, "--sshterm-only"], 120000) || + await runLocalCommand("sudo", ["-n", "bash", repairScript, "--sshterm-only"], 120000) + ); + if (!repaired) repaired = await runRepair(); + if (!repaired) return false; + for (let i = 0; i < 8; i += 1) { + if (await probeSshTerminalHealth(upstreamOrigin, 1500)) return true; + await new Promise(resolve => setTimeout(resolve, 500)); + } + if (restarted && await runRepair()) { + for (let i = 0; i < 8; i += 1) { + if (await probeSshTerminalHealth(upstreamOrigin, 1500)) return true; + await new Promise(resolve => setTimeout(resolve, 500)); + } + } + return false; + })(); + + try { + return await sshTerminalRecoveryInFlight; + } finally { + sshTerminalRecoveryInFlight = null; + } +} + function sanitizeProxyResponseHeaders(sourceHeaders) { const out = {}; for (const [key, value] of Object.entries(sourceHeaders || {})) { @@ -2410,13 +2559,22 @@ const REDIS_URL = (() => { const SESSION_MAX_AGE_MS = 365 * 24 * 60 * 60 * 1000; const SESSION_TTL_SECONDS = Math.floor(SESSION_MAX_AGE_MS / 1000); +const REDIS_SESSION_REQUIRED = SESSION_STORE !== "file"; +const RAW_REDIS_STARTUP_TIMEOUT_MS = parseInt(process.env.REDIS_STARTUP_TIMEOUT_MS || "", 10); +const REDIS_STARTUP_TIMEOUT_MS = Number.isFinite(RAW_REDIS_STARTUP_TIMEOUT_MS) && RAW_REDIS_STARTUP_TIMEOUT_MS >= 0 + ? RAW_REDIS_STARTUP_TIMEOUT_MS + : 120000; +const REDIS_ENSURE_PERSISTENCE = parseBoolean(process.env.REDIS_ENSURE_PERSISTENCE, REDIS_SESSION_REQUIRED); let sessionStore = null; let redisClient = null; let redisSessionReady = false; +let redisReadyPromise = null; +let redisStartupError = null; +let redisHasConnected = false; // Redis is the default session store. Set SESSION_STORE=file to force file-based sessions. -if (SESSION_STORE !== "file") { +if (REDIS_SESSION_REQUIRED) { try { const { createClient } = require("redis"); const RedisStoreModule = require("connect-redis"); @@ -2434,11 +2592,7 @@ if (SESSION_STORE !== "file") { url: REDIS_URL || "redis://127.0.0.1:6379", socket: { reconnectStrategy: (retries) => { - if (retries > 20) { - console.error("[session] Redis: too many reconnect attempts, giving up."); - return new Error("Redis max reconnect attempts exceeded"); - } - const delay = Math.min(retries * 200, 5000); + const delay = Math.min(500 + retries * 250, 5000); console.log(`[session] Redis reconnecting in ${delay}ms (attempt ${retries})...`); return delay; }, @@ -2450,21 +2604,32 @@ if (SESSION_STORE !== "file") { console.error("[session] Redis error:", err?.message || err); }); redisClient.on("ready", () => { - if (redisSessionReady) { + if (redisHasConnected) { console.log("[session] Redis connection restored"); } + redisHasConnected = true; + redisSessionReady = true; }); redisClient.on("reconnecting", () => { + redisSessionReady = false; console.warn("[session] Redis reconnecting..."); }); + redisClient.on("end", () => { + redisSessionReady = false; + }); - redisClient.connect() + redisReadyPromise = redisClient.connect() .then(() => { + redisStartupError = null; redisSessionReady = true; console.log("[session] Redis connected successfully"); + return true; }) .catch((err) => { - console.warn("[session] Redis initial connect failed (will keep retrying):", err?.message || err); + redisStartupError = err; + redisSessionReady = false; + console.error("[session] Redis initial connect failed:", err?.message || err); + return false; }); sessionStore = new RedisStore({ @@ -2481,7 +2646,11 @@ if (SESSION_STORE !== "file") { } redisClient = null; redisSessionReady = false; - console.warn("[session] Redis store unavailable, falling back to file store:", err?.message || err); + redisReadyPromise = null; + redisStartupError = null; + redisHasConnected = false; + console.error("[session] Redis store is required but unavailable:", err?.message || err); + process.exit(1); } } else { console.log("[session] File-based sessions forced via SESSION_STORE=file"); @@ -2583,13 +2752,13 @@ const sessionRevoke2faRateLimiter = rateLimit({ const ip = getRequestIp(req); const email = String(req.session?.user || "anon").trim().toLowerCase(); const sid = String(req.sessionID || "no-session"); - return `session-revoke-2fa:${ip}:${email}:${sid}`; + return `session-revoke-verify:${ip}:${email}:${sid}`; }, - skip: (req) => hasSessionRevokeGrace(req), + skip: (req) => !hasDestructiveActionCredentialPayload(req), handler: (req, res) => { - securityLog("Session revoke 2FA rate limit exceeded", req); - console.log(`[SECURITY] Session revoke 2FA rate limit exceeded | User: ${req.session?.user || 'unknown'} | IP: ${getRequestIp(req)}`); - res.status(429).json({ error: "Too many 2FA verification attempts. Please wait 10 minutes and try again.", code: "2fa-rate-limit" }); + securityLog("Session revoke verification rate limit exceeded", req); + console.log(`[SECURITY] Session revoke verification rate limit exceeded | User: ${req.session?.user || 'unknown'} | IP: ${getRequestIp(req)}`); + res.status(429).json({ error: "Too many verification attempts. Please wait 10 minutes and try again.", code: "verification-rate-limit" }); } }); @@ -2633,18 +2802,16 @@ const REMEMBER_LOGIN_SECRET = const REMEMBER_LOGIN_MAX_AGE_MS = SESSION_MAX_AGE_MS; const REMEMBER_LOGIN_REFRESH_WINDOW_MS = 30 * 24 * 60 * 60 * 1000; const REMEMBER_LOGIN_VALIDATE_INTERVAL_MS = 6 * 60 * 60 * 1000; -const REMEMBER_LOGIN_REGISTRY_FILE = path.join(__dirname, ".remember-logins.json"); -const REMEMBER_LOGIN_LEGACY_CUTOFF_FILE = path.join(__dirname, ".remember-login-legacy-cutoffs.json"); +const REMEMBER_LOGIN_REGISTRY_REDIS_KEY = "adpanel:remember-logins:v1"; +const REMEMBER_LOGIN_LEGACY_CUTOFF_REDIS_KEY = "adpanel:remember-login-legacy-cutoffs:v1"; +const REMEMBER_LOGIN_REDIS_INIT_TIMEOUT_MS = 15_000; -let rememberLoginRegistry = readJson(REMEMBER_LOGIN_REGISTRY_FILE, {}); -if (!rememberLoginRegistry || typeof rememberLoginRegistry !== "object" || Array.isArray(rememberLoginRegistry)) { - rememberLoginRegistry = {}; -} - -let rememberLoginLegacyCutoffs = readJson(REMEMBER_LOGIN_LEGACY_CUTOFF_FILE, {}); -if (!rememberLoginLegacyCutoffs || typeof rememberLoginLegacyCutoffs !== "object" || Array.isArray(rememberLoginLegacyCutoffs)) { - rememberLoginLegacyCutoffs = {}; -} +let rememberLoginRegistry = {}; +let rememberLoginLegacyCutoffs = {}; +let rememberLoginStoreReady = !redisClient; +let rememberLoginStoreReadyPromise = null; +let rememberLoginRedisWriteQueue = Promise.resolve(); +let rememberLoginRedisWarningPrinted = false; function normalizeRememberLoginRegistry(raw) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; @@ -2664,19 +2831,16 @@ function normalizeRememberLoginRegistry(raw) { email: String(entry.email || "").trim().toLowerCase(), issuedAt: Number(entry.issuedAt || 0) || 0, expiresAt, + lastSeenAt: Number(entry.lastSeenAt || entry.updatedAt || entry.issuedAt || 0) || 0, + userAgent: String(entry.userAgent || "").trim().slice(0, 255), + firstIp: String(entry.firstIp || "").trim().slice(0, 64), + lastIp: String(entry.lastIp || entry.ip || "").trim().slice(0, 64), }; } return normalized; } -rememberLoginRegistry = normalizeRememberLoginRegistry(rememberLoginRegistry); - -function persistRememberLoginRegistry() { - rememberLoginRegistry = normalizeRememberLoginRegistry(rememberLoginRegistry); - safeWriteJson(REMEMBER_LOGIN_REGISTRY_FILE, rememberLoginRegistry); -} - function normalizeRememberLoginLegacyCutoffs(raw) { if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; @@ -2690,11 +2854,183 @@ function normalizeRememberLoginLegacyCutoffs(raw) { return normalized; } -rememberLoginLegacyCutoffs = normalizeRememberLoginLegacyCutoffs(rememberLoginLegacyCutoffs); +function rememberLoginRedisAvailable() { + return !!(redisClient && (redisClient.isOpen || redisClient.isReady || redisSessionReady)); +} + +async function ensureRememberLoginRedisReady() { + if (!redisClient) return false; + if (redisClient.isReady) return true; + if (redisReadyPromise) { + await withTimeout(redisReadyPromise, REMEMBER_LOGIN_REDIS_INIT_TIMEOUT_MS, "remember-login-redis-timeout"); + } + return !!(redisClient && (redisClient.isOpen || redisClient.isReady)); +} + +function parseRedisHashJson(rawHash) { + const out = {}; + if (!rawHash || typeof rawHash !== "object") return out; + for (const [key, rawValue] of Object.entries(rawHash)) { + const id = String(key || "").trim(); + if (!id) continue; + try { + out[id] = JSON.parse(String(rawValue || "{}")); + } catch { + continue; + } + } + return out; +} + +async function loadRememberLoginRedisHash(key, normalizer) { + if (!(await ensureRememberLoginRedisReady())) return {}; + const raw = await redisClient.hGetAll(key); + return normalizer(parseRedisHashJson(raw)); +} + +async function writeRememberLoginRedisHash(key, values) { + if (!(await ensureRememberLoginRedisReady())) return false; + const normalized = values && typeof values === "object" && !Array.isArray(values) ? values : {}; + const entries = Object.entries(normalized); + const multi = redisClient.multi(); + multi.del(key); + if (entries.length > 0) { + const payload = {}; + for (const [id, value] of entries) { + payload[String(id)] = JSON.stringify(value); + } + multi.hSet(key, payload); + } + await multi.exec(); + return true; +} + +function queueRememberLoginRedisPersist(label, writer) { + if (!redisClient) { + if (!rememberLoginRedisWarningPrinted) { + rememberLoginRedisWarningPrinted = true; + console.warn("[auth] Redis is unavailable for remember-logins; persistent browser logins require Redis."); + } + return false; + } + + rememberLoginRedisWriteQueue = rememberLoginRedisWriteQueue + .then(() => writer()) + .catch((err) => { + console.warn(`[auth] Failed to persist ${label} in Redis:`, err?.message || err); + }); + return true; +} + +function persistRememberLoginRegistry() { + rememberLoginRegistry = normalizeRememberLoginRegistry(rememberLoginRegistry); + return queueRememberLoginRedisPersist("remember-login registry", () => + writeRememberLoginRedisHash(REMEMBER_LOGIN_REGISTRY_REDIS_KEY, rememberLoginRegistry) + ); +} function persistRememberLoginLegacyCutoffs() { rememberLoginLegacyCutoffs = normalizeRememberLoginLegacyCutoffs(rememberLoginLegacyCutoffs); - safeWriteJson(REMEMBER_LOGIN_LEGACY_CUTOFF_FILE, rememberLoginLegacyCutoffs); + return queueRememberLoginRedisPersist("remember-login legacy cutoffs", () => + writeRememberLoginRedisHash(REMEMBER_LOGIN_LEGACY_CUTOFF_REDIS_KEY, rememberLoginLegacyCutoffs) + ); +} + +async function initializeRememberLoginStores() { + if (rememberLoginStoreReady) return; + + if (!redisClient) { + rememberLoginStoreReady = true; + rememberLoginRegistry = normalizeRememberLoginRegistry(rememberLoginRegistry); + rememberLoginLegacyCutoffs = normalizeRememberLoginLegacyCutoffs(rememberLoginLegacyCutoffs); + return; + } + + try { + if (!(await ensureRememberLoginRedisReady())) { + throw new Error("Redis is not ready for remember-logins"); + } + + const [redisRegistry, redisCutoffs] = await Promise.all([ + loadRememberLoginRedisHash(REMEMBER_LOGIN_REGISTRY_REDIS_KEY, normalizeRememberLoginRegistry), + loadRememberLoginRedisHash(REMEMBER_LOGIN_LEGACY_CUTOFF_REDIS_KEY, normalizeRememberLoginLegacyCutoffs), + ]); + + rememberLoginRegistry = redisRegistry; + rememberLoginLegacyCutoffs = redisCutoffs; + rememberLoginStoreReady = true; + } catch (err) { + rememberLoginStoreReady = false; + console.warn("[auth] Remember-login Redis load failed:", err?.message || err); + throw err; + } +} + +async function ensureRememberLoginStoreReady() { + if (rememberLoginStoreReady) return; + if (!rememberLoginStoreReadyPromise) { + rememberLoginStoreReadyPromise = initializeRememberLoginStores().finally(() => { + rememberLoginStoreReadyPromise = null; + }); + } + await rememberLoginStoreReadyPromise; +} + +async function waitForRedisSessionStoreReady() { + if (!redisClient) return; + if (redisClient.isReady) { + redisSessionReady = true; + return; + } + + const waitPromise = redisReadyPromise || Promise.resolve(false); + const ready = REDIS_STARTUP_TIMEOUT_MS > 0 + ? await withTimeout(waitPromise, REDIS_STARTUP_TIMEOUT_MS, "redis-startup-timeout") + : await waitPromise; + + if (!ready || !redisClient.isReady) { + const detail = redisStartupError?.message || "Redis did not become ready"; + throw new Error(`Redis session store is not ready: ${detail}`); + } + + await redisClient.ping(); + redisSessionReady = true; +} + +async function getRedisConfigValue(name) { + const raw = await redisClient.configGet(name); + if (!raw || typeof raw !== "object") return ""; + return String(raw[name] ?? raw[String(name).toLowerCase()] ?? "").trim(); +} + +async function ensureRedisPersistenceConfigured() { + if (!redisClient || !REDIS_ENSURE_PERSISTENCE) return; + + try { + const appendOnly = (await getRedisConfigValue("appendonly")).toLowerCase(); + if (appendOnly === "yes") return; + + console.warn("[session] Redis appendonly persistence is disabled; enabling AOF for durable session and remember-login data."); + await redisClient.sendCommand(["CONFIG", "SET", "appendonly", "yes"]); + try { + await redisClient.sendCommand(["CONFIG", "SET", "appendfsync", "everysec"]); + } catch (err) { + console.warn("[session] Redis appendfsync tuning failed:", err?.message || err); + } + try { + await redisClient.sendCommand(["CONFIG", "REWRITE"]); + } catch (err) { + console.warn("[session] Redis CONFIG REWRITE failed; AOF is enabled for this runtime but may need manual redis.conf persistence:", err?.message || err); + } + } catch (err) { + console.warn("[session] Could not verify or enable Redis persistence; Redis remains the only session store, so enable AOF/RDB manually:", err?.message || err); + } +} + +async function prepareSessionBackendForStartup() { + await waitForRedisSessionStoreReady(); + await ensureRedisPersistenceConfigured(); + await ensureRememberLoginStoreReady(); } function getRememberLoginLegacyCutoff(userId) { @@ -2712,6 +3048,25 @@ function setRememberLoginLegacyCutoff(userId) { return cutoff; } +function revokeRememberLoginsForUser(user) { + const userId = String(user?.id || "").trim(); + const email = String(user?.email || "").trim().toLowerCase(); + let revoked = 0; + + for (const [rememberId, entry] of Object.entries(rememberLoginRegistry || {})) { + const entryUserId = String(entry?.uid || "").trim(); + const entryEmail = String(entry?.email || "").trim().toLowerCase(); + if ((userId && entryUserId === userId) || (email && entryEmail === email)) { + delete rememberLoginRegistry[rememberId]; + revoked += 1; + } + } + + if (revoked > 0) persistRememberLoginRegistry(); + if (userId) setRememberLoginLegacyCutoff(userId); + return revoked; +} + function getRememberLoginRegistryEntry(rememberId) { const id = String(rememberId || "").trim(); if (!id) return null; @@ -2743,13 +3098,28 @@ function upsertRememberLoginRegistryEntry(req, user, expiresAt, issuedAt = Date. const rememberId = ensureRememberLoginSessionId(req); if (!rememberId) return ""; + const email = String(user.email || req.session.user || "").trim().toLowerCase(); + const currentIp = String(getRequestIp(req) || "").trim().slice(0, 64); + const audit = normalizeBrowserSessionAudit(req.session.browserSessionAudit, { + email, + createdAt: issuedAt, + lastSeenAt: issuedAt, + userAgent: String(req.get?.("user-agent") || "").trim().slice(0, 255), + firstIp: currentIp, + lastIp: currentIp, + rememberLoginId: rememberId, + }); rememberLoginRegistry[rememberId] = { uid: String(user.id), sid: String(req.sessionID || ""), - email: String(user.email || req.session.user || "").trim().toLowerCase(), + email, issuedAt: Number(issuedAt) || Date.now(), expiresAt: Number(expiresAt) || (Date.now() + REMEMBER_LOGIN_MAX_AGE_MS), + lastSeenAt: Number(audit.lastSeenAt || issuedAt) || Date.now(), + userAgent: String(audit.userAgent || "").trim().slice(0, 255), + firstIp: String(audit.firstIp || "").trim().slice(0, 64), + lastIp: String(audit.lastIp || audit.firstIp || "").trim().slice(0, 64), }; persistRememberLoginRegistry(); return rememberId; @@ -2763,6 +3133,57 @@ function revokeRememberLoginRegistryEntry(rememberId) { return true; } +function findRememberLoginIdBySessionId(sessionId, email = "") { + const sid = String(sessionId || "").trim(); + const targetEmail = String(email || "").trim().toLowerCase(); + if (!sid) return ""; + + for (const [rememberId, entry] of Object.entries(rememberLoginRegistry || {})) { + if (String(entry?.sid || "").trim() !== sid) continue; + if (targetEmail && String(entry?.email || "").trim().toLowerCase() !== targetEmail) continue; + return String(rememberId || "").trim(); + } + + return ""; +} + +function syncRememberLoginRegistryAudit(rememberId, audit, email = "") { + const id = String(rememberId || "").trim(); + const entry = id ? rememberLoginRegistry[id] : null; + if (!entry || !audit || typeof audit !== "object") return false; + + let changed = false; + const nextEmail = String(email || audit.email || entry.email || "").trim().toLowerCase(); + const nextLastSeenAt = Number(audit.lastSeenAt || entry.lastSeenAt || entry.issuedAt || 0) || 0; + const nextUserAgent = String(audit.userAgent || entry.userAgent || "").trim().slice(0, 255); + const nextFirstIp = String(audit.firstIp || entry.firstIp || "").trim().slice(0, 64); + const nextLastIp = String(audit.lastIp || audit.firstIp || entry.lastIp || entry.firstIp || "").trim().slice(0, 64); + + if (nextEmail && String(entry.email || "").trim().toLowerCase() !== nextEmail) { + entry.email = nextEmail; + changed = true; + } + if (nextLastSeenAt && Number(entry.lastSeenAt || 0) !== nextLastSeenAt) { + entry.lastSeenAt = nextLastSeenAt; + changed = true; + } + if (nextUserAgent && String(entry.userAgent || "") !== nextUserAgent) { + entry.userAgent = nextUserAgent; + changed = true; + } + if (nextFirstIp && String(entry.firstIp || "") !== nextFirstIp) { + entry.firstIp = nextFirstIp; + changed = true; + } + if (nextLastIp && String(entry.lastIp || "") !== nextLastIp) { + entry.lastIp = nextLastIp; + changed = true; + } + + if (changed) persistRememberLoginRegistry(); + return changed; +} + function isManagedRememberLoginToken(parsedToken, user = null) { if (!parsedToken?.jti) return false; const entry = getRememberLoginRegistryEntry(parsedToken.jti); @@ -2943,6 +3364,13 @@ async function restoreRememberedLogin(req, res) { return false; } + if (user.suspended) { + clearRememberLoginSessionState(req); + clearRememberLoginCookie(res); + revokeRememberLoginsForUser(user); + return false; + } + if (!safeCompare(parsed.fp, getRememberLoginFingerprint(user))) { clearRememberLoginSessionState(req); clearRememberLoginCookie(res); @@ -2970,9 +3398,9 @@ async function restoreRememberedLogin(req, res) { req.session.browserSessionAudit = buildBrowserSessionAuditFromRequest(req, user.email, req.session.rememberLoginId); req.currentUser = user; clearRememberLoginSessionState(req); - await new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve()))); const expiresAt = setRememberLoginCookie(req, res, user); markRememberLoginSessionFresh(req, expiresAt); + await new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve()))); return true; } @@ -2997,6 +3425,7 @@ app.use(sessionMiddleware); app.use(async (req, res, next) => { try { if (req._staticAsset) return next(); + await ensureRememberLoginStoreReady(); if (req.session?.user) { await ensureRememberLoginCookie(req, res); @@ -3013,6 +3442,49 @@ app.use(async (req, res, next) => { } }); +app.use(async (req, res, next) => { + try { + if (req._staticAsset || !req.session?.user) return next(); + + const user = await findUserByEmail(req.session.user); + if (!user?.suspended) return next(); + + const suspendedEmail = String(user.email || req.session.user || "").trim().toLowerCase(); + const sessionId = String(req.sessionID || ""); + const rememberLoginId = String(req.session.rememberLoginId || req.session.browserSessionAudit?.rememberLoginId || "").trim(); + if (rememberLoginId) revokeRememberLoginRegistryEntry(rememberLoginId); + revokeRememberLoginsForUser(user); + + await new Promise((resolve) => { + req.session.destroy((err) => { + if (err) console.warn("[security] Failed to destroy suspended user session:", err?.message || err); + resolve(); + }); + }); + + removeActiveBrowserSessionCacheEntry(sessionId); + invalidateActiveBrowserSessionCache(); + res.clearCookie("adpanel.sid", { + httpOnly: true, + sameSite: "lax", + secure: SESSION_COOKIE_SECURE, + path: "/", + }); + clearRememberLoginCookie(res); + req.currentUser = null; + + console.log(`[SECURITY] Suspended account session blocked | User: ${suspendedEmail} | Session: ${getSessionDisplayId(sessionId)} | IP: ${getRequestIp(req)}`); + + if (req.path.startsWith("/api/")) { + return res.status(403).json({ error: "Your account is suspended", code: "account-suspended" }); + } + + return res.redirect(303, "/login?error=Your%20account%20is%20suspended"); + } catch (err) { + return next(err); + } +}); + // Middleware to ensure session TTL is refreshed on every authenticated request app.use((req, res, next) => { if (req.session && req.session.user && req.session.touch) { @@ -3025,10 +3497,18 @@ app.use((req, res, next) => { const BROWSER_SESSION_AUDIT_TOUCH_INTERVAL_MS = 60 * 1000; const ACTIVE_BROWSER_SESSION_SCAN_TTL_MS = 15 * 1000; const ACTIVE_BROWSER_SESSION_SCAN_CONCURRENCY = 25; -const SESSION_REVOKE_2FA_GRACE_MS = 10 * 60 * 1000; +const SESSION_REVOKE_2FA_GRACE_MS = 15 * 60 * 1000; const ACTIVE_BROWSER_SESSION_PAGE_SIZE = 25; const SESSION_REVOKE_TARGET_TOKEN_TTL_MS = 10 * 60 * 1000; const SESSION_REVOKE_TARGET_TOKEN_MAX = 250; +const DESTRUCTIVE_ACTION_GRACE_TABLE = "destructive_action_grants"; +const DESTRUCTIVE_ACTION_GRACE_MAX_MEMORY = 5000; +const DESTRUCTIVE_ACTION_GRACE_CLEANUP_MS = 5 * 60 * 1000; +const DESTRUCTIVE_ACTION_GRACE_SECRET = + crypto.createHmac("sha256", ACTION_TOKEN_SECRET).update("adpanel-destructive-action-grace-v1").digest("hex"); + +const destructiveActionGraceMemory = new Map(); +let destructiveActionGraceLastCleanup = 0; const activeBrowserSessionCache = { scannedAt: 0, @@ -3173,6 +3653,9 @@ function touchBrowserSessionAudit(req) { if (changed) { req.session.browserSessionAudit = currentAudit; + if (rememberLoginId) { + syncRememberLoginRegistryAudit(rememberLoginId, currentAudit, req.session.user); + } } upsertActiveBrowserSessionCacheEntry(req.sessionID, { @@ -3369,70 +3852,431 @@ async function getCachedActiveBrowserSessions({ force = false } = {}) { return activeBrowserSessionCache.promise; } -function getSessionRevokeGraceState(req) { +async function destroyBrowserSessionsForUser(user, options = {}) { + const email = String(user?.email || options.email || "").trim().toLowerCase(); + const excludeSessionId = String(options.excludeSessionId || "").trim(); + const result = { + destroyed: 0, + skipped: 0, + rememberLoginsRevoked: revokeRememberLoginsForUser(user), + errors: [], + }; + + if (!email) return result; + + let activeSessions = []; + try { + activeSessions = await getCachedActiveBrowserSessions({ force: true }); + } catch (err) { + result.errors.push(`scan:${err?.message || err}`); + activeSessions = Array.from(activeBrowserSessionCache.sessions.values()); + } + + const targets = (Array.isArray(activeSessions) ? activeSessions : []) + .filter((entry) => String(entry?.email || "").trim().toLowerCase() === email) + .filter((entry) => { + if (!excludeSessionId) return true; + if (String(entry?.sessionId || "") === excludeSessionId) { + result.skipped += 1; + return false; + } + return true; + }); + + await mapWithConcurrency(targets, ACTIVE_BROWSER_SESSION_SCAN_CONCURRENCY, async (entry) => { + const sessionId = String(entry?.sessionId || "").trim(); + if (!sessionId) return; + + const rememberLoginId = String(entry?.rememberLoginId || "").trim(); + if (rememberLoginId && revokeRememberLoginRegistryEntry(rememberLoginId)) { + result.rememberLoginsRevoked += 1; + } + + try { + await callSessionStore("destroy", sessionId); + removeActiveBrowserSessionCacheEntry(sessionId); + result.destroyed += 1; + } catch (err) { + result.errors.push(`${getSessionDisplayId(sessionId)}:${err?.message || err}`); + } + }); + + invalidateActiveBrowserSessionCache(); + return result; +} + +function hashDestructiveActionGraceValue(label, value) { + return crypto + .createHmac("sha256", DESTRUCTIVE_ACTION_GRACE_SECRET) + .update(String(label || "value")) + .update("\0") + .update(String(value || "")) + .digest("hex"); +} + +function getSessionRevokeGraceUaHash(req) { + return hashDestructiveActionGraceValue( + "ua", + String(req?.get?.("user-agent") || "").trim().slice(0, 255) + ); +} + +function getSessionRevokeGraceIpHash(req) { + return hashDestructiveActionGraceValue( + "ip", + String(getRequestIp(req) || "").trim().slice(0, 128) + ); +} + +function getSessionRevokeGraceSessionHash(req) { + return hashDestructiveActionGraceValue("sid", String(req?.sessionID || "")); +} + +function pruneDestructiveActionGraceMemory(now = Date.now()) { + if (now - destructiveActionGraceLastCleanup < DESTRUCTIVE_ACTION_GRACE_CLEANUP_MS) return; + destructiveActionGraceLastCleanup = now; + for (const [grantId, grant] of destructiveActionGraceMemory.entries()) { + if (!grant || Number(grant.expiresAt || 0) <= now) { + destructiveActionGraceMemory.delete(grantId); + } + } + if (destructiveActionGraceMemory.size <= DESTRUCTIVE_ACTION_GRACE_MAX_MEMORY) return; + const overflow = destructiveActionGraceMemory.size - DESTRUCTIVE_ACTION_GRACE_MAX_MEMORY; + let removed = 0; + for (const grantId of destructiveActionGraceMemory.keys()) { + destructiveActionGraceMemory.delete(grantId); + removed += 1; + if (removed >= overflow) break; + } +} + +async function cleanupExpiredDestructiveActionGrants(now = Date.now()) { + pruneDestructiveActionGraceMemory(now); + try { + await db.query( + `DELETE FROM ${DESTRUCTIVE_ACTION_GRACE_TABLE} WHERE expires_at <= ? OR revoked_at IS NOT NULL`, + [now] + ); + } catch (err) { + console.warn("[security] Failed to cleanup destructive action grants:", err?.message || err); + } +} + +function clearSessionRevokeGrace(req, grantId = "") { + const id = String(grantId || req?.session?.sessionRevoke2fa?.grantId || "").trim(); + if (id) destructiveActionGraceMemory.delete(id); + if (req?.session?.sessionRevoke2fa) delete req.session.sessionRevoke2fa; +} + +function getSessionRevokeGraceCandidate(req, currentUser = null) { if (!req?.session) return null; const state = req.session.sessionRevoke2fa; - if (!state || typeof state !== "object") return null; + if (!state || typeof state !== "object" || Number(state.v || 0) !== 2) { + if (state) clearSessionRevokeGrace(req); + return null; + } + const now = Date.now(); + const grantId = String(state.grantId || "").trim(); + const secret = String(state.secret || "").trim(); const email = String(state.email || "").trim().toLowerCase(); + const userId = Number(state.userId || 0); const verifiedAt = Number(state.verifiedAt || 0); - if (!email || !Number.isFinite(verifiedAt) || verifiedAt <= 0) { - delete req.session.sessionRevoke2fa; - return null; - } + const expiresAt = Number(state.expiresAt || 0); + const sessionHash = String(state.sessionHash || "").trim(); + const ipHash = String(state.ipHash || "").trim(); + const uaHash = String(state.uaHash || "").trim(); - if (Date.now() - verifiedAt > SESSION_REVOKE_2FA_GRACE_MS) { - delete req.session.sessionRevoke2fa; - return null; - } - - if (String(req.session.user || "").trim().toLowerCase() !== email) { - delete req.session.sessionRevoke2fa; - return null; - } - - const stateIp = String(state.ip || "").trim(); - const currentIp = String(getRequestIp(req) || "").trim(); - if (stateIp && currentIp && stateIp !== currentIp) { - delete req.session.sessionRevoke2fa; - return null; - } - - const stateUaHash = String(state.uaHash || "").trim(); - if (stateUaHash && stateUaHash !== getSessionRevokeGraceUaHash(req)) { - delete req.session.sessionRevoke2fa; + if ( + !/^[a-f0-9]{64}$/i.test(grantId) || + !/^[a-f0-9]{64}$/i.test(secret) || + !email || + !Number.isSafeInteger(userId) || + userId <= 0 || + !Number.isFinite(verifiedAt) || + !Number.isFinite(expiresAt) || + verifiedAt <= 0 || + expiresAt <= now || + expiresAt - verifiedAt > SESSION_REVOKE_2FA_GRACE_MS || + sessionHash !== getSessionRevokeGraceSessionHash(req) || + ipHash !== getSessionRevokeGraceIpHash(req) || + uaHash !== getSessionRevokeGraceUaHash(req) || + String(req.session.user || "").trim().toLowerCase() !== email || + (currentUser && Number(currentUser.id || 0) !== userId) + ) { + clearSessionRevokeGrace(req, grantId); return null; } return { + grantId, + secret, + secretHash: hashDestructiveActionGraceValue("secret", secret), email, + userId, verifiedAt, - expiresAt: verifiedAt + SESSION_REVOKE_2FA_GRACE_MS, + expiresAt, + sessionHash, + ipHash, + uaHash, }; } -function hasSessionRevokeGrace(req) { - return !!getSessionRevokeGraceState(req); +function getSessionRevokeGraceState(req, currentUser = null) { + const candidate = getSessionRevokeGraceCandidate(req, currentUser); + if (!candidate) return null; + + pruneDestructiveActionGraceMemory(); + const memoryGrant = destructiveActionGraceMemory.get(candidate.grantId); + if ( + !memoryGrant || + Number(memoryGrant.expiresAt || 0) <= Date.now() || + Number(memoryGrant.userId || 0) !== candidate.userId || + String(memoryGrant.email || "") !== candidate.email || + !safeCompare(String(memoryGrant.secretHash || ""), candidate.secretHash) || + !safeCompare(String(memoryGrant.sessionHash || ""), candidate.sessionHash) || + !safeCompare(String(memoryGrant.ipHash || ""), candidate.ipHash) || + !safeCompare(String(memoryGrant.uaHash || ""), candidate.uaHash) + ) { + clearSessionRevokeGrace(req, candidate.grantId); + return null; + } + + return { + email: candidate.email, + userId: candidate.userId, + grantId: candidate.grantId, + verifiedAt: candidate.verifiedAt, + expiresAt: candidate.expiresAt, + }; } -function getSessionRevokeGraceUaHash(req) { - return crypto - .createHash("sha256") - .update(String(req?.get?.("user-agent") || "").trim().slice(0, 255)) - .digest("hex"); +async function getVerifiedSessionRevokeGraceState(req, currentUser = null) { + const candidate = getSessionRevokeGraceCandidate(req, currentUser); + if (!candidate) return null; + + const memoryState = getSessionRevokeGraceState(req, currentUser); + if (!memoryState) return null; + + try { + const rows = await db.query( + `SELECT grant_id, user_id, email, session_hash, secret_hash, ip_hash, ua_hash, verified_at, expires_at, revoked_at + FROM ${DESTRUCTIVE_ACTION_GRACE_TABLE} + WHERE grant_id = ? LIMIT 1`, + [candidate.grantId] + ); + const row = Array.isArray(rows) ? rows[0] : null; + const now = Date.now(); + if ( + !row || + row.revoked_at !== null && row.revoked_at !== undefined || + Number(row.user_id || 0) !== candidate.userId || + String(row.email || "").trim().toLowerCase() !== candidate.email || + Number(row.verified_at || 0) !== candidate.verifiedAt || + Number(row.expires_at || 0) !== candidate.expiresAt || + Number(row.expires_at || 0) <= now || + !safeCompare(String(row.session_hash || ""), candidate.sessionHash) || + !safeCompare(String(row.secret_hash || ""), candidate.secretHash) || + !safeCompare(String(row.ip_hash || ""), candidate.ipHash) || + !safeCompare(String(row.ua_hash || ""), candidate.uaHash) + ) { + clearSessionRevokeGrace(req, candidate.grantId); + return null; + } + + return memoryState; + } catch (err) { + console.warn("[security] Destructive action grant DB validation failed:", err?.message || err); + clearSessionRevokeGrace(req, candidate.grantId); + return null; + } } -function setSessionRevokeGrace(req) { - if (!req?.session?.user) return 0; - const verifiedAt = Date.now(); +async function hasSessionRevokeGrace(req, currentUser = null) { + return !!(await getVerifiedSessionRevokeGraceState(req, currentUser)); +} + +async function setSessionRevokeGrace(req, currentUser, subject = "sensitive action") { + if (!req?.session?.user || !currentUser?.id) return 0; + + const now = Date.now(); + await cleanupExpiredDestructiveActionGrants(now); + + const verifiedAt = now; + const expiresAt = verifiedAt + SESSION_REVOKE_2FA_GRACE_MS; + const grantId = crypto.randomBytes(32).toString("hex"); + const secret = crypto.randomBytes(32).toString("hex"); + const email = String(currentUser.email || req.session.user || "").trim().toLowerCase(); + const userId = Number(currentUser.id || 0); + const sessionHash = getSessionRevokeGraceSessionHash(req); + const secretHash = hashDestructiveActionGraceValue("secret", secret); + const ipHash = getSessionRevokeGraceIpHash(req); + const uaHash = getSessionRevokeGraceUaHash(req); + const cleanSubject = String(subject || "sensitive action").slice(0, 190); + + await db.query( + `INSERT INTO ${DESTRUCTIVE_ACTION_GRACE_TABLE} + (grant_id, user_id, email, session_hash, secret_hash, ip_hash, ua_hash, verified_at, expires_at, subject) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [grantId, userId, email, sessionHash, secretHash, ipHash, uaHash, verifiedAt, expiresAt, cleanSubject] + ); + + destructiveActionGraceMemory.set(grantId, { + userId, + email, + sessionHash, + secretHash, + ipHash, + uaHash, + verifiedAt, + expiresAt, + }); + req.session.sessionRevoke2fa = { - email: String(req.session.user || "").trim().toLowerCase(), + v: 2, + grantId, + secret, + email, + userId, verifiedAt, - ip: String(getRequestIp(req) || "").trim().slice(0, 64), - uaHash: getSessionRevokeGraceUaHash(req), + expiresAt, + sessionHash, + ipHash, + uaHash, }; - return verifiedAt + SESSION_REVOKE_2FA_GRACE_MS; + + return expiresAt; +} + +function getDestructiveActionSecurity(req, currentUser, verifiedGraceState) { + const revokeGrace = arguments.length >= 3 ? verifiedGraceState : getSessionRevokeGraceState(req, currentUser); + const twoFactorEnabled = hasTwoFactorEnabled(currentUser); + return { + twoFactorEnabled, + authMethod: twoFactorEnabled ? "2fa" : "password", + requiresVerification: !revokeGrace, + requiresTwoFactor: twoFactorEnabled && !revokeGrace, + graceExpiresAt: revokeGrace?.expiresAt || 0, + }; +} + +async function getDestructiveActionSecurityAsync(req, currentUser) { + const revokeGrace = await getVerifiedSessionRevokeGraceState(req, currentUser); + return getDestructiveActionSecurity(req, currentUser, revokeGrace); +} + +async function verifyDestructiveActionStepUp(req, currentUser, subject = "destructive action") { + if (!currentUser || !currentUser.password) { + return { ok: false, status: 403, body: { error: "not authorized" } }; + } + + if (hasTwoFactorEnabled(currentUser)) { + const twoFactor = verifyTotpForUser(currentUser, req.body?.twoFactorCode); + if (twoFactor.code === "invalid-format") { + return { ok: false, status: 403, body: { error: "A valid 6-digit code is required", code: "2fa-required" } }; + } + if (!twoFactor.ok) { + console.log(`[SECURITY] ${subject} denied - invalid 2FA | User: ${req.session?.user || "unknown"} | IP: ${getRequestIp(req)}`); + return { ok: false, status: 403, body: { error: "Incorrect 2FA code", code: "invalid-2fa" } }; + } + return { ok: true, authMethod: "2fa" }; + } + + const currentPassword = String(req.body?.currentPassword || ""); + if (!currentPassword) { + return { ok: false, status: 403, body: { error: "Current password is required", code: "password-required" } }; + } + + const passwordOk = await verifyPasswordForUser(currentUser, currentPassword, "bcrypt-destructive-action-timeout"); + if (!passwordOk) { + console.log(`[SECURITY] ${subject} denied - invalid password | User: ${req.session?.user || "unknown"} | IP: ${getRequestIp(req)}`); + return { ok: false, status: 403, body: { error: "Incorrect current password", code: "invalid-password" } }; + } + + return { ok: true, authMethod: "password" }; +} + +function hasDestructiveActionCredentialPayload(req) { + const body = req?.body || {}; + const password = typeof body.currentPassword === "string" ? body.currentPassword : ""; + const twoFactorCode = typeof body.twoFactorCode === "string" ? body.twoFactorCode : ""; + return !!password || !!normalizeTotpCode(twoFactorCode); +} + +function buildStepUpRequiredBody(req, currentUser) { + const twoFactorEnabled = hasTwoFactorEnabled(currentUser); + const passwordMode = !twoFactorEnabled; + const security = { + twoFactorEnabled, + authMethod: twoFactorEnabled ? "2fa" : "password", + requiresVerification: true, + requiresTwoFactor: twoFactorEnabled, + graceExpiresAt: 0, + }; + return { + error: passwordMode ? "Current password is required" : "A valid 6-digit code is required", + code: passwordMode ? "password-required" : "2fa-required", + revokeSecurity: security, + }; +} + +async function persistDestructiveActionGrace(req, currentUser, context = "sensitive action") { + let graceExpiresAt = await setSessionRevokeGrace(req, currentUser, context); + try { + await new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve()))); + const graceState = await getVerifiedSessionRevokeGraceState(req, currentUser); + return graceExpiresAt || graceState?.expiresAt || 0; + } catch (saveErr) { + console.warn(`[security] Failed to persist ${context} grace window:`, saveErr?.message || saveErr); + return 0; + } +} + +async function requireDestructiveActionStepUp(req, res, currentUser, subject = "sensitive action") { + const graceState = await getVerifiedSessionRevokeGraceState(req, currentUser); + if (graceState) { + return { ok: true, graceExpiresAt: graceState.expiresAt, usedFreshVerification: false }; + } + + if (!hasDestructiveActionCredentialPayload(req)) { + res.status(403).json(buildStepUpRequiredBody(req, currentUser)); + return { ok: false, handled: true }; + } + + const verification = await verifyDestructiveActionStepUp(req, currentUser, subject); + if (!verification.ok) { + res.status(verification.status || 403).json({ + ...(verification.body || { error: "Verification failed" }), + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + }); + return { ok: false, handled: true }; + } + + const graceExpiresAt = await persistDestructiveActionGrace(req, currentUser, subject); + return { ok: true, graceExpiresAt, usedFreshVerification: true }; +} + +async function requireDatabaseInstallStepUp(req, res, currentUser, subject = "database install") { + const graceState = await getVerifiedSessionRevokeGraceState(req, currentUser); + if (graceState) { + return { ok: true, graceExpiresAt: graceState.expiresAt, usedFreshVerification: false }; + } + + const verification = await verifyDestructiveActionStepUp(req, currentUser, subject); + if (!verification.ok) { + return { + ok: false, + handled: true, + response: res.status(verification.status || 403).json({ + ...(verification.body || { error: "Verification failed" }), + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + }), + }; + } + + const graceExpiresAt = await persistDestructiveActionGrace(req, currentUser, subject); + return { ok: true, graceExpiresAt, usedFreshVerification: true }; } function getSessionDisplayId(sessionId) { @@ -3442,6 +4286,103 @@ function getSessionDisplayId(sessionId) { return `${raw.slice(0, 8)}...${raw.slice(-6)}`; } +function getRememberLoginDisplayId(rememberLoginId) { + const raw = String(rememberLoginId || "").trim(); + if (!raw) return ""; + if (raw.length <= 18) return `saved:${raw}`; + return `saved:${raw.slice(0, 8)}...${raw.slice(-6)}`; +} + +function isValidSessionStoreId(sessionId) { + const raw = String(sessionId || "").trim(); + return !!raw && raw.length <= 255 && /^[A-Za-z0-9_-]+$/.test(raw); +} + +function isValidRememberLoginId(rememberLoginId) { + const raw = String(rememberLoginId || "").trim(); + return !!raw && raw.length <= 128 && /^[A-Za-z0-9_-]+$/.test(raw); +} + +function buildRememberedBrowserSessionRecord(rememberLoginId, rawEntry) { + const id = String(rememberLoginId || "").trim(); + const entry = rawEntry && typeof rawEntry === "object" ? rawEntry : null; + if (!id || !entry) return null; + + const expiresAt = Number(entry.expiresAt || 0); + if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return null; + + const email = String(entry.email || "").trim().toLowerCase(); + if (!email) return null; + + const issuedAt = Number(entry.issuedAt || 0) || 0; + const lastSeenAt = Number(entry.lastSeenAt || issuedAt || 0) || 0; + const sessionId = String(entry.sid || "").trim(); + + return { + targetType: "remembered", + status: "remembered", + sessionId, + rememberLoginId: id, + email, + createdAt: issuedAt, + lastSeenAt, + expiresAt, + userAgent: String(entry.userAgent || "").trim().slice(0, 255), + ip: String(entry.lastIp || entry.firstIp || "").trim().slice(0, 64), + }; +} + +function normalizeRememberLoginRegistryInMemory() { + const beforeKeys = Object.keys(rememberLoginRegistry || {}); + rememberLoginRegistry = normalizeRememberLoginRegistry(rememberLoginRegistry); + const afterKeys = Object.keys(rememberLoginRegistry || {}); + if (beforeKeys.length !== afterKeys.length) { + persistRememberLoginRegistry(); + } + return rememberLoginRegistry; +} + +async function getBrowserLoginSessionsInventory({ force = false } = {}) { + let scannedActiveSessions = []; + try { + scannedActiveSessions = await getCachedActiveBrowserSessions({ force }); + } catch (err) { + console.warn("[session] Active session scan failed while building browser login inventory:", err?.message || err); + scannedActiveSessions = Array.from(activeBrowserSessionCache.sessions.values()); + } + + const activeSessions = (Array.isArray(scannedActiveSessions) ? scannedActiveSessions : []) + .map((record) => ({ + ...record, + targetType: "session", + status: "active", + })); + + const activeSessionIds = new Set( + activeSessions + .map((record) => String(record.sessionId || "").trim()) + .filter(Boolean) + ); + const activeRememberIds = new Set( + activeSessions + .map((record) => String(record.rememberLoginId || "").trim()) + .filter(Boolean) + ); + + const rememberedSessions = Object.entries(normalizeRememberLoginRegistryInMemory()) + .map(([rememberId, entry]) => buildRememberedBrowserSessionRecord(rememberId, entry)) + .filter(Boolean) + .filter((record) => { + const rememberId = String(record.rememberLoginId || "").trim(); + const sessionId = String(record.sessionId || "").trim(); + if (rememberId && activeRememberIds.has(rememberId)) return false; + if (sessionId && activeSessionIds.has(sessionId)) return false; + return true; + }); + + return [...activeSessions, ...rememberedSessions]; +} + function pruneSessionRevokeTargetTokens(req) { if (!req?.session) return {}; @@ -3454,11 +4395,15 @@ function pruneSessionRevokeTargetTokens(req) { for (const [token, value] of Object.entries(targets)) { const entry = value && typeof value === "object" ? value : {}; + const targetType = entry.targetType === "remembered" ? "remembered" : "session"; const sessionId = String(entry.sessionId || "").trim(); + const rememberLoginId = String(entry.rememberLoginId || "").trim(); const expiresAt = Number(entry.expiresAt || 0); const issuedAt = Number(entry.issuedAt || 0) || 0; - if (!token || !sessionId || !Number.isFinite(expiresAt) || expiresAt <= now) continue; - normalized[token] = { sessionId, expiresAt, issuedAt }; + if (!token || !Number.isFinite(expiresAt) || expiresAt <= now) continue; + if (targetType === "session" && !sessionId) continue; + if (targetType === "remembered" && !rememberLoginId) continue; + normalized[token] = { targetType, sessionId, rememberLoginId, expiresAt, issuedAt }; } const entries = Object.entries(normalized) @@ -3472,15 +4417,38 @@ function pruneSessionRevokeTargetTokens(req) { return normalized; } -function issueSessionRevokeTargetToken(req, sessionId) { - const sid = String(sessionId || "").trim(); - if (!req?.session || !sid) return ""; +function normalizeSessionRevokeTarget(target) { + if (typeof target === "string") { + const sessionId = String(target || "").trim(); + if (!sessionId) return null; + return { targetType: "session", sessionId, rememberLoginId: "" }; + } + + const raw = target && typeof target === "object" ? target : {}; + const targetType = raw.targetType === "remembered" || raw.type === "remembered" ? "remembered" : "session"; + const sessionId = String(raw.sessionId || "").trim(); + const rememberLoginId = String(raw.rememberLoginId || raw.rememberId || "").trim(); + + if (targetType === "session") { + if (!sessionId) return null; + return { targetType, sessionId, rememberLoginId }; + } + + if (!rememberLoginId) return null; + return { targetType, sessionId, rememberLoginId }; +} + +function issueSessionRevokeTargetToken(req, target) { + const normalizedTarget = normalizeSessionRevokeTarget(target); + if (!req?.session || !normalizedTarget) return ""; const targets = pruneSessionRevokeTargetTokens(req); const token = crypto.randomBytes(24).toString("base64url"); const now = Date.now(); targets[token] = { - sessionId: sid, + targetType: normalizedTarget.targetType, + sessionId: normalizedTarget.sessionId, + rememberLoginId: normalizedTarget.rememberLoginId, issuedAt: now, expiresAt: now + SESSION_REVOKE_TARGET_TOKEN_TTL_MS, }; @@ -3490,12 +4458,12 @@ function issueSessionRevokeTargetToken(req, sessionId) { function resolveSessionRevokeTargetToken(req, token) { const raw = String(token || "").trim(); - if (!raw || raw.length > 128 || !/^[A-Za-z0-9_-]+$/.test(raw)) return ""; + if (!raw || raw.length > 128 || !/^[A-Za-z0-9_-]+$/.test(raw)) return null; const targets = pruneSessionRevokeTargetTokens(req); const entry = targets[raw]; - if (!entry) return ""; - return String(entry.sessionId || "").trim(); + if (!entry) return null; + return normalizeSessionRevokeTarget(entry); } function clearSessionRevokeTargetToken(req, token) { @@ -3973,7 +4941,10 @@ if (NODE_COMPRESSION) { app.set("views", path.join(__dirname, "views")); app.set("view engine", "ejs"); -app.set("view cache", false); +// Cache compiled EJS templates in production to avoid recompiling large views +// (index.ejs/bot.ejs are >1.7k lines) on every request. Disabled in development +// so template/theme edits hot-reload without a restart. +app.set("view cache", process.env.NODE_ENV === "production"); app.use((req, res, next) => { if (req._staticAsset) return next(); @@ -4288,6 +5259,16 @@ const REDIS_KEYS = { allNodes: 'adpanel:status:nodes:all' }; +const REDIS_STATUS_GET_TIMEOUT_MS = Math.max(100, parseInt(process.env.REDIS_STATUS_GET_TIMEOUT_MS || "500", 10) || 500); + +async function redisStatusGetBestEffort(key) { + if (!redisClient) return null; + try { + return await withTimeout(redisClient.get(key), REDIS_STATUS_GET_TIMEOUT_MS, "redis-status-cache-timeout"); + } catch { + return null; + } +} async function getCachedServerStatus(serverName) { const name = String(serverName || '').trim(); @@ -4295,7 +5276,7 @@ async function getCachedServerStatus(serverName) { if (redisClient) { try { - const cached = await redisClient.get(REDIS_KEYS.serverStatus(name)); + const cached = await redisStatusGetBestEffort(REDIS_KEYS.serverStatus(name)); if (cached) { const parsed = normalizeServerStatusRecord(JSON.parse(cached)); if (Date.now() - parsed.updatedAt < STATUS_CACHE_TTL_MS) { @@ -4320,7 +5301,7 @@ async function getCachedServerStatusLenient(serverName) { if (redisClient) { try { - const cached = await redisClient.get(REDIS_KEYS.serverStatus(name)); + const cached = await redisStatusGetBestEffort(REDIS_KEYS.serverStatus(name)); if (cached) { const parsed = normalizeServerStatusRecord(JSON.parse(cached)); if (Date.now() - parsed.updatedAt < SSR_CACHE_LENIENT_MS) { @@ -4344,7 +5325,7 @@ async function getCachedNodeStatus(nodeId) { if (redisClient) { try { - const cached = await redisClient.get(REDIS_KEYS.nodeStatus(id)); + const cached = await redisStatusGetBestEffort(REDIS_KEYS.nodeStatus(id)); if (cached) { const parsed = JSON.parse(cached); if (Date.now() - parsed.updatedAt < STATUS_CACHE_TTL_MS * 3) { @@ -4964,6 +5945,243 @@ function parseRedisUrlForBullMQ(redisUrl) { const SCHEDULER_REDIS_URL = REDIS_URL || process.env.SCHEDULER_REDIS_URL || ""; +// Maps a scheduler action to the per-server permission a user must still hold +// at execution time. Used to re-verify authorization when a job actually runs, +// not only when it was created. Returns null for actions gated elsewhere (the +// ADPanel Agent actions are additionally gated by userCanUseAdpanelAgent). +function schedulerRequiredPermissionForAction(actionType) { + switch (actionType) { + case "console_command": return "console_write"; + case "server_start": return "server_start"; + case "server_stop": return "server_stop"; + case "create_file": return "files_create"; + case "modify_file": return "files_write"; + case "backup": return "backups_create"; + case "planner_next_to_agent": return "scheduler_access"; + case "agent_prompt": return "scheduler_access"; + default: return null; + } +} + +// Disables a recurring schedule so it stops firing after authorization is lost. +// One-time jobs need no disabling: failing them is enough since they do not +// repeat. For repeatable jobs we remove the repeatable entry by matching the +// serverName + action signature stored in the repeatable job name. +async function disableRecurringScheduleForJob(job, reason) { + try { + if (!schedulerQueue || !job) return; + // Repeatable jobs carry repeatJobKey; bail out for plain one-time jobs. + const repeatKey = job.repeatJobKey || job.opts?.repeat?.key || null; + const data = job.data || {}; + const repeatableJobs = await schedulerQueue.getRepeatableJobs(); + for (const r of repeatableJobs) { + let matches = false; + if (repeatKey && r.key === repeatKey) { + matches = true; + } else { + try { + const nameData = JSON.parse(r.name || "{}"); + matches = nameData.serverName === data.serverName && + nameData.actionType === data.actionType && + nameData.name === data.name; + } catch { + matches = false; + } + } + if (matches) { + try { + await schedulerQueue.removeRepeatableByKey(r.key); + console.warn(`[scheduler] Disabled recurring schedule for ${data.serverName} (${data.actionType}) - ${reason}`); + } catch (e) { + console.warn(`[scheduler] Failed to disable recurring schedule ${r.key}: ${e.message}`); + } + } + } + } catch (err) { + console.warn(`[scheduler] disableRecurringScheduleForJob error: ${err?.message || err}`); + } +} + +// Re-validates, at execution time, that the user who created the scheduled job +// is still authorized to run it. This closes the gap where a job keeps running +// with the node token after the creator loses access or permissions, or is +// suspended/deleted. On failure the recurring schedule is disabled and the job +// is failed so it does not silently keep executing. +async function ensureScheduledJobStillAuthorized(job) { + const { actionType, serverName, userName, userId } = job.data || {}; + const email = userName || null; + + // Legacy jobs created before creator tracking existed have no userName. Fail + // closed: without a known creator we cannot re-verify authorization. + if (!email) { + await disableRecurringScheduleForJob(job, "missing creator identity"); + throw new Error("Scheduled job has no associated user; refusing to run"); + } + + const user = await findUserByEmail(email); + if (!user) { + await disableRecurringScheduleForJob(job, "user no longer exists"); + throw new Error(`Scheduled job creator no longer exists (${email})`); + } + if (user.suspended) { + await disableRecurringScheduleForJob(job, "user suspended"); + throw new Error(`Scheduled job creator is suspended (${email})`); + } + + const hasAccess = await userHasAccessToServer(email, serverName); + if (!hasAccess) { + await disableRecurringScheduleForJob(job, "server access revoked"); + throw new Error(`Scheduled job creator lost access to server ${serverName}`); + } + + const requiredPermission = schedulerRequiredPermissionForAction(actionType); + if (requiredPermission) { + const perms = await getEffectivePermsForUserOnServer(email, serverName); + if (!perms || !perms[requiredPermission]) { + await disableRecurringScheduleForJob(job, `permission ${requiredPermission} revoked`); + throw new Error(`Scheduled job creator lacks permission ${requiredPermission} on ${serverName}`); + } + } + + // ADPanel Agent actions require an extra capability check, mirroring the + // create-time gate. + if (actionType === "planner_next_to_agent" || actionType === "agent_prompt") { + if (!userCanUseAdpanelAgent(user)) { + await disableRecurringScheduleForJob(job, "ADPanel Agent access revoked"); + throw new Error(`Scheduled job creator lost ADPanel Agent access (${email})`); + } + } +} + +// Proactively cancels scheduled jobs created by a given user. This is invoked +// when authorization changes (account deleted/suspended, server access or a +// required permission revoked) so that pending one-time jobs and recurring +// schedules are removed immediately instead of lingering until their next +// run, where they would be rejected by the execution-time re-check. +// +// Options: +// - serverName: when provided, only cancels schedules for that server. A +// reauthorize=true also re-validates remaining authorization per job and +// only cancels the ones the user can no longer run (used when a single +// permission is changed but access to the server is retained). +// - reason: short string used for logging/auditing. +// +// Matching is by the creator identity stored on each job (job.data.userName), +// compared case-insensitively. Only the affected user's schedules are touched; +// other users' schedules on the same server are never removed. +async function cancelSchedulesCreatedBy(email, options = {}) { + if (!schedulerQueue) return { removed: 0 }; + const target = String(email || "").trim().toLowerCase(); + if (!target) return { removed: 0 }; + + const serverFilter = options.serverName ? String(options.serverName).trim().toLowerCase() : null; + const reauthorize = !!options.reauthorize; + const reason = String(options.reason || "authorization change"); + let removed = 0; + + const matchesUser = (data) => + data && String(data.userName || "").trim().toLowerCase() === target; + const matchesServer = (data) => + !serverFilter || String(data?.serverName || "").trim().toLowerCase() === serverFilter; + + // When only re-authorizing (e.g. a single permission toggle), keep jobs the + // user is still allowed to run. Returns true when the job should be removed. + const shouldRemoveForReauthorize = async (data) => { + if (!reauthorize) return true; + try { + const actionType = data?.actionType; + const serverName = data?.serverName; + const stillHasAccess = await userHasAccessToServer(target, serverName); + if (!stillHasAccess) return true; + const requiredPermission = schedulerRequiredPermissionForAction(actionType); + if (requiredPermission) { + const perms = await getEffectivePermsForUserOnServer(target, serverName); + if (!perms || !perms[requiredPermission]) return true; + } + if (actionType === "planner_next_to_agent" || actionType === "agent_prompt") { + const u = await findUserByEmail(target); + if (!u || !userCanUseAdpanelAgent(u)) return true; + } + return false; + } catch { + // Fail closed: if we cannot confirm the user is still authorized, remove. + return true; + } + }; + + try { + // 1) One-time and queued jobs (waiting/active/delayed/paused). + const states = ["waiting", "active", "delayed", "paused"]; + const jobLists = await Promise.all( + states.map((s) => schedulerQueue.getJobs([s], 0, 2000).catch(() => [])) + ); + for (const list of jobLists) { + for (const job of list || []) { + const data = job?.data; + if (!matchesUser(data) || !matchesServer(data)) continue; + if (!(await shouldRemoveForReauthorize(data))) continue; + try { + await job.remove(); + removed++; + } catch (e) { + console.warn(`[scheduler] cancelSchedulesCreatedBy: could not remove job ${job.id}: ${e.message}`); + } + } + } + + // 2) Recurring (repeatable) schedules. The repeatable entry name holds the + // serverName/action signature; the creator identity lives on delayed + // instances. We match the repeatable by server+action signature for the + // affected user's known schedules removed above, plus by inspecting any + // remaining delayed instances. To be safe and explicit, we cross-check + // each repeatable against the per-server jobs we just identified. + const repeatableJobs = await schedulerQueue.getRepeatableJobs().catch(() => []); + for (const r of repeatableJobs) { + let nameData = null; + try { nameData = JSON.parse(r.name || "{}"); } catch { nameData = null; } + if (!nameData) continue; + if (serverFilter && String(nameData.serverName || "").trim().toLowerCase() !== serverFilter) continue; + + // Determine the creator of this recurring schedule by inspecting a + // delayed instance, if present. Fall back to keeping it when we cannot + // confidently attribute it to the affected user (avoids nuking other + // users' recurring schedules). + let creatorMatches = false; + let instanceData = null; + try { + const delayed = await schedulerQueue.getJobs(["delayed"], 0, 2000).catch(() => []); + const inst = (delayed || []).find((j) => { + const d = j?.data; + return d && d.serverName === nameData.serverName && + d.actionType === nameData.actionType && d.name === nameData.name; + }); + if (inst) { + instanceData = inst.data; + creatorMatches = matchesUser(inst.data); + } + } catch { /* ignore */ } + + if (!creatorMatches) continue; + if (reauthorize && instanceData && !(await shouldRemoveForReauthorize(instanceData))) continue; + + try { + await schedulerQueue.removeRepeatableByKey(r.key); + removed++; + } catch (e) { + console.warn(`[scheduler] cancelSchedulesCreatedBy: could not remove repeatable ${r.key}: ${e.message}`); + } + } + + if (removed > 0) { + console.log(`[scheduler] Cancelled ${removed} schedule(s) created by ${target}${serverFilter ? ` on ${serverFilter}` : ""} - ${reason}`); + } + } catch (err) { + console.error(`[scheduler] cancelSchedulesCreatedBy error for ${target}: ${err?.message || err}`); + } + + return { removed }; +} + async function initializeScheduler() { if (!SCHEDULER_ENABLED || !SCHEDULER_REDIS_URL) { if (!SCHEDULER_REDIS_URL) { @@ -4987,6 +6205,16 @@ async function initializeScheduler() { console.log(`[scheduler] Processing job ${job.id}: ${actionType} for server ${serverName}`); try { + const scheduledEntry = await findServer(serverName); + if (isServerSuspended(scheduledEntry)) { + throw new Error("Server is suspended"); + } + + // Re-verify the creator is still authorized at execution time. This + // prevents a scheduled job from keeping access after the user loses a + // permission, loses server access, or is suspended/deleted. + await ensureScheduledJobStillAuthorized(job); + switch (actionType) { case "console_command": { const command = payload?.command; @@ -5011,6 +6239,7 @@ async function initializeScheduler() { throw new Error(result.json?.error || `Command failed: ${result.status}`); } + recordActivity(serverName, "console_command", { command, source: "scheduler" }, userName || userId || "scheduler", "scheduler"); console.log(`[scheduler] Console command executed: ${command}`); return { success: true, action: "console_command", command }; } @@ -5059,6 +6288,7 @@ async function initializeScheduler() { } console.log(`[scheduler] Server stopped: ${serverName}`); + await clearConsoleHistoryForServer(serverName, { clearNode: false, emit: true }); return { success: true, action: "server_stop", server: serverName }; } @@ -5633,13 +6863,17 @@ setInterval(() => { app.use(rateLimiterMiddleware); async function loadUsers() { - const rows = await db.query( - "SELECT id, email, admin, agent_access FROM users" - ); + const rows = await withTimeout(db.query( + "SELECT id, email, secret, admin, suspended, suspended_at, suspended_by, agent_access FROM users" + ), 8000, "load-users-timeout"); return rows.map(r => ({ id: r.id, email: r.email, + has2FA: hasTwoFactorEnabled(r), admin: !!r.admin, + suspended: !!r.suspended, + suspended_at: r.suspended_at === null || r.suspended_at === undefined ? null : Number(r.suspended_at), + suspended_by: r.suspended_by || null, agent_access: !!(r && r.agent_access) })); } @@ -5649,16 +6883,16 @@ async function findUserByEmail(email) { let rows; try { - rows = await db.query( - "SELECT id, email, password, secret, admin, agent_access, avatar_url, preferences FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", + rows = await withTimeout(db.query( + "SELECT id, email, password, secret, admin, suspended, suspended_at, suspended_by, agent_access, avatar_url, preferences FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", [email] - ); + ), 8000, "find-user-timeout"); } catch (err) { if (err.code === 'ER_BAD_FIELD_ERROR' && err.message?.includes('avatar_url')) { - rows = await db.query( - "SELECT id, email, password, secret, admin, agent_access FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", + rows = await withTimeout(db.query( + "SELECT id, email, password, secret, admin, suspended, suspended_at, suspended_by, agent_access FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", [email] - ); + ), 8000, "find-user-legacy-timeout"); } else { throw err; } @@ -5685,13 +6919,13 @@ async function findUserById(id) { let rows; try { rows = await db.query( - "SELECT id, email, password, secret, admin, agent_access, avatar_url, preferences FROM users WHERE id = ? LIMIT 1", + "SELECT id, email, password, secret, admin, suspended, suspended_at, suspended_by, agent_access, avatar_url, preferences FROM users WHERE id = ? LIMIT 1", [id] ); } catch (err) { if (err.code === 'ER_BAD_FIELD_ERROR' && err.message?.includes('avatar_url')) { rows = await db.query( - "SELECT id, email, password, secret, admin, agent_access FROM users WHERE id = ? LIMIT 1", + "SELECT id, email, password, secret, admin, suspended, suspended_at, suspended_by, agent_access FROM users WHERE id = ? LIMIT 1", [id] ); } else { @@ -5913,7 +7147,7 @@ async function loadServersIndex() { if (_siCache && (now - _siCacheTs) < SI_CACHE_TTL) return _siCache.slice(); if (_siInflight) return (await _siInflight).slice(); _siInflight = db.query( - "SELECT id, name, display_name, legacy_id, bot, template, start, node_id, ip, port, status, runtime, docker, acl, resources FROM servers" + "SELECT id, name, display_name, legacy_id, bot, template, start, node_id, ip, port, status, suspended, suspended_at, suspended_by, runtime, docker, acl, resources FROM servers" ).then(rows => { const mapped = rows.map(mapServerRow); _siCache = mapped; @@ -5967,8 +7201,8 @@ async function saveServersIndex(list) { const resources = toDbJson(cleanEntry.resources); await conn.execute( `INSERT INTO servers - (name, display_name, legacy_id, bot, template, start, node_id, ip, port, status, runtime, docker, acl, resources) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + (name, display_name, legacy_id, bot, template, start, node_id, ip, port, status, suspended, suspended_at, suspended_by, runtime, docker, acl, resources) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE display_name = COALESCE(VALUES(display_name), display_name), legacy_id = VALUES(legacy_id), @@ -5979,6 +7213,9 @@ async function saveServersIndex(list) { ip = VALUES(ip), port = VALUES(port), status = VALUES(status), + suspended = VALUES(suspended), + suspended_at = VALUES(suspended_at), + suspended_by = VALUES(suspended_by), runtime = VALUES(runtime), docker = VALUES(docker), acl = VALUES(acl), @@ -5994,6 +7231,9 @@ async function saveServersIndex(list) { cleanEntry.ip || null, cleanEntry.port == null ? null : Number(cleanEntry.port), cleanEntry.status || null, + cleanEntry.suspended ? 1 : 0, + cleanEntry.suspended_at === null || cleanEntry.suspended_at === undefined ? null : Number(cleanEntry.suspended_at), + cleanEntry.suspended_by || null, runtime, docker, acl, @@ -6029,8 +7269,8 @@ async function upsertServerIndexEntry(entry) { const legacyId = merged.id ? String(merged.id) : null; await db.query( `INSERT INTO servers - (name, display_name, legacy_id, bot, template, start, node_id, ip, port, status, runtime, docker, acl, resources) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + (name, display_name, legacy_id, bot, template, start, node_id, ip, port, status, suspended, suspended_at, suspended_by, runtime, docker, acl, resources) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ON DUPLICATE KEY UPDATE display_name = COALESCE(VALUES(display_name), display_name), legacy_id = VALUES(legacy_id), @@ -6041,6 +7281,9 @@ async function upsertServerIndexEntry(entry) { ip = VALUES(ip), port = VALUES(port), status = VALUES(status), + suspended = VALUES(suspended), + suspended_at = VALUES(suspended_at), + suspended_by = VALUES(suspended_by), runtime = VALUES(runtime), docker = VALUES(docker), acl = VALUES(acl), @@ -6056,6 +7299,9 @@ async function upsertServerIndexEntry(entry) { merged.ip || null, merged.port == null ? null : Number(merged.port), merged.status || null, + merged.suspended ? 1 : 0, + merged.suspended_at === null || merged.suspended_at === undefined ? null : Number(merged.suspended_at), + merged.suspended_by || null, toDbJson(merged.runtime), toDbJson(merged.docker), toDbJson(merged.acl), @@ -6141,7 +7387,7 @@ async function findServer(botName) { const needle = String(botName || "").trim().toLowerCase(); if (!needle) return null; const rows = await db.query( - `SELECT id, name, legacy_id, bot, template, start, node_id, ip, port, status, runtime, docker, acl, resources + `SELECT id, name, display_name, legacy_id, bot, template, start, node_id, ip, port, status, suspended, suspended_at, suspended_by, runtime, docker, acl, resources FROM servers WHERE LOWER(name) = ? OR LOWER(legacy_id) = ? OR LOWER(bot) = ? LIMIT 1`, @@ -6150,6 +7396,387 @@ async function findServer(botName) { return mapServerRow(rows[0]) || null; } +function isServerSuspended(entry) { + return !!(entry && entry.suspended); +} + +function sendSuspendedServerJson(res, entry = null) { + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); + return res.status(423).json({ + error: "server suspended", + code: "server-suspended", + server: entry?.name || null, + suspendedAt: entry?.suspended_at || null, + suspendedBy: entry?.suspended_by || null, + }); +} + +const serverSuspensionLocks = new Map(); +const SERVER_SUSPENSION_KILL_TIMEOUT_MS = 25_000; +const SERVER_SUSPENSION_VERIFY_TIMEOUT_MS = 30_000; +const SERVER_SUSPENSION_VERIFY_INTERVAL_MS = 1_000; + +function serverSuspensionLockKey(serverName) { + return String(serverName || "").trim().toLowerCase(); +} + +async function withServerSuspensionLock(serverName, fn) { + const key = serverSuspensionLockKey(serverName); + if (!key) return fn(); + + const previous = serverSuspensionLocks.get(key) || Promise.resolve(); + let release; + const current = new Promise((resolve) => { + release = resolve; + }); + const tail = previous.catch(() => { }).then(() => current); + serverSuspensionLocks.set(key, tail); + + await previous.catch(() => { }); + try { + return await fn(); + } finally { + release(); + if (serverSuspensionLocks.get(key) === tail) { + serverSuspensionLocks.delete(key); + } + } +} + +function sleepMs(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function isMissingServerStatus(value) { + const raw = String(value || "").trim().toLowerCase(); + return raw === "missing" || raw === "not-found" || raw === "not_found" || raw === "404"; +} + +function normalizePowerState(value) { + if (isMissingServerStatus(value)) return "missing"; + return normalizeStatusLabel(value) || null; +} + +function findServerStatusInNodeList(servers, serverName) { + const needle = String(serverName || "").trim().toLowerCase(); + if (!needle || !Array.isArray(servers)) return null; + return servers.find((item) => String(item?.name || "").trim().toLowerCase() === needle) || null; +} + +function buildNodeRequestContext(node) { + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return null; + return { + baseUrl, + headers: nodeAuthHeadersFor(node, true), + }; +} + +async function getNodeServerPowerState(node, serverName, timeoutMs = 8_000) { + const ctx = buildNodeRequestContext(node); + if (!ctx) return { ok: false, state: null, error: "invalid node address" }; + + const listRes = await httpRequestJson(`${ctx.baseUrl}/v1/servers`, "GET", ctx.headers, null, timeoutMs); + if (listRes.status === 200 && Array.isArray(listRes.json?.servers)) { + const item = findServerStatusInNodeList(listRes.json.servers, serverName); + if (!item) return { ok: true, state: "missing", source: "list" }; + const state = normalizePowerState(item.status || item.state); + return { ok: !!state, state, source: "list", raw: item.status || item.state || null }; + } + + const singleRes = await httpRequestJson( + `${ctx.baseUrl}/v1/servers/${encodeURIComponent(serverName)}`, + "GET", + ctx.headers, + null, + timeoutMs + ); + if (singleRes.status === 404) return { ok: true, state: "missing", source: "single" }; + if (singleRes.status === 200 && singleRes.json) { + const rawState = singleRes.json.status || singleRes.json.state || + (singleRes.json.running === true ? "running" : (singleRes.json.running === false ? "stopped" : "")); + const state = normalizePowerState(rawState); + if (state) return { ok: true, state, source: "single", raw: rawState }; + } + + return { + ok: false, + state: null, + error: listRes.status === 0 && singleRes.status === 0 + ? "node did not respond" + : `node did not report server power state (${listRes.status}/${singleRes.status})`, + }; +} + +function runLocalCommand(command, args, timeoutMs = 8_000) { + return new Promise((resolve) => { + let stdout = ""; + let stderr = ""; + let settled = false; + let child = null; + const finish = (result) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve({ + stdout: stdout.trim(), + stderr: stderr.trim(), + ...result, + }); + }; + const timer = setTimeout(() => { + try { child?.kill("SIGKILL"); } catch { } + finish({ code: -1, timedOut: true }); + }, timeoutMs); + + try { + child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"] }); + child.stdout?.on("data", (chunk) => { stdout += chunk.toString("utf8"); }); + child.stderr?.on("data", (chunk) => { stderr += chunk.toString("utf8"); }); + child.on("error", (err) => finish({ code: -1, error: err?.message || String(err) })); + child.on("close", (code) => finish({ code: Number.isFinite(code) ? code : -1 })); + } catch (err) { + finish({ code: -1, error: err?.message || String(err) }); + } + }); +} + +function isDockerNoSuchContainer(result) { + const text = `${result?.stdout || ""}\n${result?.stderr || ""}`.toLowerCase(); + return text.includes("no such object") || + text.includes("no such container") || + text.includes("not found"); +} + +async function verifyLocalDockerStopped(containerName) { + const inspect = await runLocalCommand("docker", ["inspect", "-f", "{{.State.Running}}", containerName], 5_000); + if (inspect.code !== 0) { + return isDockerNoSuchContainer(inspect) + ? { ok: true, state: "missing" } + : { ok: false, state: null, error: inspect.stderr || inspect.error || "docker inspect failed" }; + } + const running = String(inspect.stdout || "").trim().toLowerCase() === "true"; + return { ok: true, state: running ? "online" : "stopped" }; +} + +async function forceStopLocalServerForSuspension(entry) { + const containerName = String(entry?.name || "").trim(); + if (!containerName || !/^[A-Za-z0-9_.-]+$/.test(containerName)) { + return { ok: false, statusCode: 400, error: "server name is not safe for local Docker control" }; + } + + const before = await verifyLocalDockerStopped(containerName); + if (before.ok && (before.state === "stopped" || before.state === "missing")) { + return { ok: true, method: "local-docker", state: before.state }; + } + + await runLocalCommand("docker", ["kill", containerName], 8_000); + const rm = await runLocalCommand("docker", ["rm", "-f", "-v", containerName], 12_000); + if (rm.code !== 0 && !isDockerNoSuchContainer(rm)) { + return { ok: false, statusCode: 502, error: rm.stderr || rm.error || "failed to force-remove local server container" }; + } + + const deadline = Date.now() + SERVER_SUSPENSION_VERIFY_TIMEOUT_MS; + let last = null; + while (Date.now() < deadline) { + last = await verifyLocalDockerStopped(containerName); + if (last.ok && (last.state === "stopped" || last.state === "missing")) { + return { ok: true, method: "local-docker", state: last.state }; + } + await sleepMs(SERVER_SUSPENSION_VERIFY_INTERVAL_MS); + } + return { + ok: false, + statusCode: 502, + error: last?.error || "local server did not confirm stopped after forced kill", + }; +} + +async function forceStopServerForSuspension(entry) { + if (!entry?.name) return { ok: false, statusCode: 404, error: "server not found" }; + + if (!isRemoteEntry(entry)) { + return forceStopLocalServerForSuspension(entry); + } + + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) return { ok: false, statusCode: 502, error: "node not found; cannot safely suspend server" }; + + const ctx = buildNodeRequestContext(node); + if (!ctx) return { ok: false, statusCode: 502, error: "invalid node address; cannot safely suspend server" }; + + const sendKill = async () => httpRequestJson( + `${ctx.baseUrl}/v1/servers/${encodeURIComponent(entry.name)}/kill`, + "POST", + ctx.headers, + null, + SERVER_SUSPENSION_KILL_TIMEOUT_MS + ); + + let killAttempts = 0; + const killOnce = async () => { + killAttempts += 1; + const killRes = await sendKill(); + if (!([200, 202].includes(killRes.status)) || killRes.json?.ok === false) { + const detail = killRes.json?.detail || killRes.json?.error || killRes.json?.message || `node status ${killRes.status}`; + return { ok: false, error: detail }; + } + return { ok: true }; + }; + + const firstKill = await killOnce(); + if (!firstKill.ok) { + return { ok: false, statusCode: 502, error: `server force-stop failed: ${firstKill.error}` }; + } + + const deadline = Date.now() + SERVER_SUSPENSION_VERIFY_TIMEOUT_MS; + let lastState = null; + while (Date.now() < deadline) { + lastState = await getNodeServerPowerState(node, entry.name, 8_000); + if (lastState.ok && (lastState.state === "stopped" || lastState.state === "missing")) { + return { ok: true, method: "node-kill", state: lastState.state, killAttempts }; + } + if (lastState.state === "online" && killAttempts < 3) { + await killOnce(); + } + await sleepMs(SERVER_SUSPENSION_VERIFY_INTERVAL_MS); + } + + return { + ok: false, + statusCode: 502, + error: lastState?.error || `server did not confirm stopped after forced kill${lastState?.raw ? ` (${lastState.raw})` : ""}`, + }; +} + +async function setServerSuspensionState(serverName, nextSuspended, actorEmail) { + const requested = String(serverName || "").trim(); + if (!requested) return { ok: false, statusCode: 400, error: "missing name" }; + + return withServerSuspensionLock(requested, async () => { + const entry = await findServer(requested); + if (!entry?.name) return { ok: false, statusCode: 404, error: "server not found" }; + + const suspended = nextSuspended === true; + let stopResult = null; + if (suspended) { + stopResult = await forceStopServerForSuspension(entry); + if (!stopResult.ok) return stopResult; + } + + const suspendedAt = suspended ? Date.now() : null; + const suspendedBy = suspended ? String(actorEmail || "").trim().toLowerCase() : null; + const nextStatus = suspended ? "stopped" : (entry.status || null); + const result = await db.query( + "UPDATE servers SET suspended = ?, suspended_at = ?, suspended_by = ?, status = ? WHERE name = ?", + [suspended ? 1 : 0, suspendedAt, suspendedBy, nextStatus, entry.name] + ); + + if (!result || Number(result.affectedRows || 0) !== 1) { + return { ok: false, statusCode: 409, error: "server state changed; reload servers and try again" }; + } + + invalidateServerIndexCache(); + if (suspended) { + try { await setCachedServerStatus(entry.name, { status: "stopped", nodeId: entry.nodeId || null }); } catch { } + try { stopResourceStatsWatcher(entry.name); } catch { } + } + return { + ok: true, + server: entry.name, + displayName: entry.displayName || entry.name, + suspended, + suspendedAt, + suspendedBy, + forceStopped: suspended ? true : undefined, + forceStop: stopResult || undefined, + }; + }); +} + +function decodeServerPathSegment(value) { + const raw = String(value || "").trim(); + if (!raw) return ""; + try { + return decodeURIComponent(raw); + } catch { + return raw; + } +} + +function getSuspensionGuardTarget(req) { + const pathname = String(req?.path || ""); + let match = pathname.match(/^\/server\/([^/]+)/); + if (match) return { name: decodeServerPathSegment(match[1]), page: true }; + match = pathname.match(/^\/bot\/([^/]+)/); + if (match) return { name: decodeServerPathSegment(match[1]), page: true }; + match = pathname.match(/^\/api\/nodes\/server\/([^/]+)/); + if (match) return { name: decodeServerPathSegment(match[1]), page: false }; + match = pathname.match(/^\/api\/server\/([^/]+)/); + if (match) return { name: decodeServerPathSegment(match[1]), page: false }; + match = pathname.match(/^\/api\/server-info\/([^/]+)/); + if (match) return { name: decodeServerPathSegment(match[1]), page: false }; + match = pathname.match(/^\/api\/subdomains\/([^/]+)/); + if (match) return { name: decodeServerPathSegment(match[1]), page: false }; + match = pathname.match(/^\/api\/scheduler\/([^/]+)/); + if (match) { + const firstSegment = decodeServerPathSegment(match[1]).toLowerCase(); + if (!firstSegment || firstSegment === "status") return null; + return { name: decodeServerPathSegment(match[1]), page: false }; + } + match = pathname.match(/^\/api\/servers\/([^/]+)/); + if (match) { + const firstSegment = decodeServerPathSegment(match[1]).toLowerCase(); + if (!firstSegment || firstSegment === "statuses" || firstSegment === "create") return null; + return { name: decodeServerPathSegment(match[1]), page: false }; + } + return null; +} + +function renderSuspendedServerPage(res, entry = null) { + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); + return res.status(423).render("suspended", { + server: entry?.name || null, + displayName: entry?.displayName || entry?.name || null, + suspendedAt: entry?.suspended_at || null, + suspendedBy: entry?.suspended_by || null, + }); +} + +app.use(async (req, res, next) => { + try { + if (req._staticAsset) return next(); + const target = getSuspensionGuardTarget(req); + if (!target?.name) return next(); + if (!(await isAuthenticated(req))) return next(); + + const entry = await findServer(target.name); + if (!entry || !isServerSuspended(entry)) return next(); + + const allowed = (await isAdmin(req)) || (await userHasAccessToServer(req.session.user, entry.name || target.name)); + if (!allowed) return next(); + + if (target.page) return renderSuspendedServerPage(res, entry); + return sendSuspendedServerJson(res, entry); + } catch (err) { + return next(err); + } +}); + +async function markServerDeletingStatus(name) { + const rawName = String(name || "").trim(); + if (!rawName) return false; + const needle = rawName.toLowerCase(); + await db.query( + `UPDATE servers + SET status = 'deleting' + WHERE LOWER(name) = ? OR LOWER(legacy_id) = ? OR LOWER(bot) = ?`, + [needle, needle, needle] + ).catch(() => {}); + invalidateServerIndexCache(); + return true; +} + function findServerIndex(list, botName) { const needle = String(botName || "").trim().toLowerCase(); if (!needle) return -1; @@ -6166,11 +7793,237 @@ function isRemoteEntry(entry) { return !!(entry && entry.nodeId && entry.nodeId !== "local"); } +let serverDeleteJobsReady = false; +let serverDeleteJobsInitPromise = null; +let serverDeleteWorkerStarted = false; +let serverDeleteWorkerRunning = false; +let serverDeleteWorkerTimer = null; + +async function initServerDeleteJobsTable() { + if (serverDeleteJobsReady) return; + if (serverDeleteJobsInitPromise) return serverDeleteJobsInitPromise; + serverDeleteJobsInitPromise = (async () => { + await db.query(` + CREATE TABLE IF NOT EXISTS server_delete_jobs ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + server_name VARCHAR(120) NOT NULL, + technical_name VARCHAR(120) NOT NULL, + node_id VARCHAR(64) NOT NULL, + status ENUM('queued','running','completed','failed') NOT NULL DEFAULT 'queued', + attempts INT UNSIGNED NOT NULL DEFAULT 0, + next_attempt_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_error TEXT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + UNIQUE KEY uniq_server_delete_jobs_server (server_name), + KEY idx_server_delete_jobs_status_next (status, next_attempt_at), + KEY idx_server_delete_jobs_node (node_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + serverDeleteJobsReady = true; + })().finally(() => { + serverDeleteJobsInitPromise = null; + }); + return serverDeleteJobsInitPromise; +} + +function nodeDeleteJobNodeId(node) { + return String(node?.uuid || node?.id || node?.name || "").trim(); +} + +async function enqueueServerDeleteJob({ name, technicalName, node }) { + const serverName = String(name || "").trim(); + const cleanTechnicalName = String(technicalName || serverName).trim(); + const nodeId = nodeDeleteJobNodeId(node); + if (!serverName || !cleanTechnicalName || !nodeId) { + throw new Error("cannot queue delete job without server and node identity"); + } + await initServerDeleteJobsTable(); + await db.query(` + INSERT INTO server_delete_jobs (server_name, technical_name, node_id, status, attempts, next_attempt_at, last_error) + VALUES (?, ?, ?, 'queued', 0, CURRENT_TIMESTAMP, NULL) + ON DUPLICATE KEY UPDATE + technical_name = VALUES(technical_name), + node_id = VALUES(node_id), + status = 'queued', + attempts = 0, + next_attempt_at = CURRENT_TIMESTAMP, + last_error = NULL, + updated_at = CURRENT_TIMESTAMP + `, [serverName, cleanTechnicalName, nodeId]); + console.log(`[delete-job] Queued durable delete for ${serverName} on node ${nodeId}`); +} + +function kickServerDeleteWorker(delayMs = 0) { + if (serverDeleteWorkerTimer) clearTimeout(serverDeleteWorkerTimer); + serverDeleteWorkerTimer = setTimeout(() => { + serverDeleteWorkerTimer = null; + runServerDeleteJobsOnce().catch((err) => { + console.warn("[delete-job] Worker pass failed:", err?.message || err); + }); + }, Math.max(0, delayMs)); + serverDeleteWorkerTimer.unref?.(); +} + +function startServerDeleteWorker() { + if (serverDeleteWorkerStarted) return; + serverDeleteWorkerStarted = true; + setInterval(() => kickServerDeleteWorker(0), 30_000).unref?.(); + kickServerDeleteWorker(1500); +} + +function serverDeleteBackoffSeconds(attempts) { + const n = Math.max(1, Number(attempts || 1)); + if (n <= 2) return 10; + if (n <= 5) return 30; + if (n <= 10) return 120; + return 600; +} + +function isRemoteServerMissingResponse(response) { + const status = Number(response?.status || 0); + if (status === 404 || status === 410) return true; + const raw = String(response?.json?.error || response?.json?.detail || response?.json?.message || "").toLowerCase(); + return raw.includes("not found") || raw.includes("not exist") || raw.includes("no such server") || raw.includes("no such container"); +} + +async function markServerDeleteJobRetry(job, err) { + const attempts = Number(job?.attempts || 0) + 1; + const delaySeconds = serverDeleteBackoffSeconds(attempts); + const message = String(err?.message || err || "delete failed").slice(0, 4000); + await db.query(` + UPDATE server_delete_jobs + SET status = 'queued', + attempts = ?, + next_attempt_at = DATE_ADD(CURRENT_TIMESTAMP, INTERVAL ${delaySeconds} SECOND), + last_error = ?, + updated_at = CURRENT_TIMESTAMP + WHERE id = ? + `, [attempts, message, job.id]); + console.warn(`[delete-job] ${job.server_name} not confirmed deleted yet; retry ${attempts} in ${delaySeconds}s: ${message}`); +} + +async function waitForRemoteServerGone(baseUrl, headers, technicalName, { timeoutMs = 30_000, intervalMs = 1000 } = {}) { + const deadline = Date.now() + timeoutMs; + let lastStatus = 0; + while (Date.now() < deadline) { + const deleteStatus = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/delete-status`, + "GET", + headers, + null, + Math.min(8000, Math.max(2000, intervalMs + 1500)) + ); + if (deleteStatus.status === 200 && deleteStatus.json?.deleteStatus === true) { + lastStatus = deleteStatus.status; + if (deleteStatus.json.deleted === true) return true; + if ( + deleteStatus.json.containerExists === false && + deleteStatus.json.serverDirExists === false && + deleteStatus.json.metaExists === false && + deleteStatus.json.backupsDirExists === false + ) { + return true; + } + } + + const response = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}`, + "GET", + headers, + null, + Math.min(8000, Math.max(2000, intervalMs + 1500)) + ); + lastStatus = response.status; + if (isRemoteServerMissingResponse(response)) return true; + await new Promise((resolve) => setTimeout(resolve, intervalMs)); + } + throw new Error(lastStatus === 0 ? "node did not confirm delete" : `server still exists on node after delete request (${lastStatus})`); +} + +async function processServerDeleteJob(job) { + const node = await findNodeByIdOrName(job.node_id); + if (!node) throw new Error(`node not found: ${job.node_id}`); + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) throw new Error("invalid node address"); + + const headers = nodeAuthHeadersFor(node, true); + const technicalName = String(job.technical_name || job.server_name || "").trim(); + const serverName = String(job.server_name || technicalName).trim(); + + try { + await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 5_000); + } catch { + } + + const response = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}?async=true&force=true&brutal=true`, + "DELETE", + headers, + null, + 15_000 + ); + + if (!((response.status === 200 || response.status === 202) && response.json && response.json.ok) && !isRemoteServerMissingResponse(response) && response.status !== 0) { + const message = response.json && (response.json.error || response.json.detail || response.json.message) + ? (response.json.error || response.json.detail || response.json.message) + : `remote delete failed (${response.status})`; + throw new Error(message); + } + + if (!isRemoteServerMissingResponse(response)) { + await waitForRemoteServerGone(baseUrl, headers, technicalName); + } + + await deleteServerSchedules(serverName); + await removeAccessForServerName(serverName); + await removeServerIndexEntry(serverName); + await db.query("DELETE FROM server_delete_jobs WHERE id = ?", [job.id]); + console.log(`[delete-job] Confirmed full delete for ${serverName} on node ${job.node_id}`); +} + +async function runServerDeleteJobsOnce() { + if (serverDeleteWorkerRunning) return; + serverDeleteWorkerRunning = true; + try { + await initServerDeleteJobsTable(); + await db.query(` + UPDATE server_delete_jobs + SET status = 'queued', next_attempt_at = CURRENT_TIMESTAMP + WHERE status = 'running' AND updated_at < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 2 MINUTE) + `); + const jobs = await db.query(` + SELECT id, server_name, technical_name, node_id, status, attempts + FROM server_delete_jobs + WHERE status IN ('queued','failed') AND next_attempt_at <= CURRENT_TIMESTAMP + ORDER BY next_attempt_at ASC, id ASC + LIMIT 5 + `); + for (const job of jobs || []) { + const updated = await db.query( + "UPDATE server_delete_jobs SET status = 'running', updated_at = CURRENT_TIMESTAMP WHERE id = ? AND status IN ('queued','failed')", + [job.id] + ); + if (updated && typeof updated.affectedRows === "number" && updated.affectedRows === 0) continue; + try { + await processServerDeleteJob(job); + } catch (err) { + await markServerDeleteJobRetry(job, err); + } + } + } finally { + serverDeleteWorkerRunning = false; + } +} + const ALLOWED_PERM_KEYS = [ "files_read", "files_delete", "files_rename", "files_archive", + "files_write", "console_read", "console_write", "server_stop", @@ -6194,6 +8047,7 @@ async function getEffectivePermsForUserOnServer(email, serverName) { files_delete: false, files_rename: false, files_archive: false, + files_write: false, console_read: false, console_write: false, server_stop: false, @@ -6232,6 +8086,14 @@ async function getEffectivePermsForUserOnServer(email, serverName) { if (!Object.prototype.hasOwnProperty.call(rec, "console_read") && rec.console_write) { merged.console_read = true; } + // Back-compat: files_write is a newer, separate permission for overwriting + // existing files. ACLs created before it existed only have files_create, which + // historically also allowed overwrites. Preserve that behavior so no existing + // grant silently loses access: a files_create grant without an explicit + // files_write key implies files_write. + if (!Object.prototype.hasOwnProperty.call(rec, "files_write") && rec.files_create) { + merged.files_write = true; + } if (rec.backups_manage) { merged.backups_view = true; merged.backups_create = true; @@ -6475,6 +8337,112 @@ async function verifyExternalCaptcha(token, remoteIp) { return { ok: true }; } +function cloneJsonPayload(value) { + if (value == null) return value; + return JSON.parse(JSON.stringify(value)); +} + +function unknownJsonFieldFromNodeResponse(res) { + if (!res || res.status !== 400 || !res.json) return ""; + const text = [res.json.error, res.json.detail, res.json.message] + .map(v => String(v || "")) + .filter(Boolean) + .join(" "); + const match = text.match(/json:\s*unknown field\s+"([^"]+)"/i); + return match ? match[1] : ""; +} + +function removeJsonFieldDeep(value, fieldName) { + if (!value || !fieldName) return 0; + let removed = 0; + if (Array.isArray(value)) { + for (const item of value) removed += removeJsonFieldDeep(item, fieldName); + return removed; + } + if (typeof value !== "object") return 0; + if (Object.prototype.hasOwnProperty.call(value, fieldName)) { + delete value[fieldName]; + removed += 1; + } + for (const item of Object.values(value)) removed += removeJsonFieldDeep(item, fieldName); + return removed; +} + +const NODE_REQUEST_CRITICAL_FIELDS = new Set([ + "name", + "templateId", + "docker", + "image", + "tag", + "command", + "adpanelStartup", + "pterodactylStartup", + "ports", + "portProtocols", + "volumes", + "workdir", + "workingDir", + "env", + "install", + "installation", +]); + +async function httpRequestJsonPruningUnknownFields(fullUrl, method, headers, body, timeoutMs, label = "node-request") { + const requestBody = cloneJsonPayload(body); + const prunedUnknownFields = []; + for (let attempt = 0; attempt < 10; attempt += 1) { + const res = await httpRequestJson(fullUrl, method, headers, requestBody, timeoutMs); + const unknownField = unknownJsonFieldFromNodeResponse(res); + if (!unknownField) return { res, body: requestBody, prunedUnknownFields }; + if (NODE_REQUEST_CRITICAL_FIELDS.has(unknownField)) { + console.warn(`[${label}] Remote daemon rejected required JSON field "${unknownField}"; refusing to prune runtime Docker config.`); + return { res, body: requestBody, prunedUnknownFields, blockedUnknownField: unknownField }; + } + const removed = removeJsonFieldDeep(requestBody, unknownField); + if (!removed || prunedUnknownFields.includes(unknownField)) { + return { res, body: requestBody, prunedUnknownFields }; + } + prunedUnknownFields.push(unknownField); + console.warn(`[${label}] Remote daemon rejected unsupported JSON field "${unknownField}"; retrying without it.`); + } + const res = await httpRequestJson(fullUrl, method, headers, requestBody, timeoutMs); + return { res, body: requestBody, prunedUnknownFields }; +} + +function dockerConfigForNodeRequest(docker) { + if (!docker || typeof docker !== "object") return null; + const allowed = [ + "image", + "tag", + "command", + "adpanelStartup", + "pterodactylStartup", + "ports", + "portProtocols", + "volumes", + "workdir", + "workingDir", + "env", + "restart", + "restartPolicy", + "runAsRoot", + "install", + "installation", + "console", + ]; + const out = {}; + for (const key of allowed) { + if (!Object.prototype.hasOwnProperty.call(docker, key)) continue; + const value = docker[key]; + if (value === undefined || value === null) continue; + if (typeof value === "string" && value.trim() === "") continue; + if (Array.isArray(value) && value.length === 0) continue; + if (typeof value === "object" && !Array.isArray(value) && Object.keys(value).length === 0) continue; + out[key] = value; + } + return Object.keys(out).length ? out : null; +} + async function createOnRemoteNode(node, payload) { const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); if (!baseUrl) throw new Error("invalid node address"); @@ -6484,13 +8452,22 @@ async function createOnRemoteNode(node, payload) { const headers = { Authorization: `Bearer ${node.token}`, "Content-Type": "application/json" }; - let res = await httpRequestJson( - `${baseUrl}/v1/servers/create`, + const createUrl = `${baseUrl}/v1/servers/create`; + let requestPayload = cloneJsonPayload(payload); + let createAttempt = await httpRequestJsonPruningUnknownFields( + createUrl, "POST", headers, - payload, - 600_000 + requestPayload, + 600_000, + "node-create" ); + let res = createAttempt.res; + requestPayload = createAttempt.body; + + if (createAttempt.prunedUnknownFields.length) { + console.warn(`[createOnRemoteNode] Node ${node.name || node.address} ignored unsupported create fields: ${createAttempt.prunedUnknownFields.join(", ")}`); + } if (isRecoverableNodeCreateStatus(res.status)) { console.warn(`[createOnRemoteNode] recoverable transport status ${res.status} — verifying server on node...`); @@ -6501,13 +8478,16 @@ async function createOnRemoteNode(node, payload) { if (recovered) { return { ok: true, name: payload.name, recovered: true }; } - res = await httpRequestJson( - `${baseUrl}/v1/servers/create`, + createAttempt = await httpRequestJsonPruningUnknownFields( + createUrl, "POST", headers, - payload, - 600_000 + requestPayload, + 600_000, + "node-create-retry" ); + res = createAttempt.res; + requestPayload = createAttempt.body; } if (res.status !== 200 || !(res.json && res.json.ok)) { @@ -6548,18 +8528,80 @@ async function findServerUsingNodePort(node, port, excludeName = "") { if (!entry || !entryBelongsToNode(entry, node)) continue; const name = String(entry.name || entry.bot || entry.id || "").trim().toLowerCase(); if (excluded && name === excluded) continue; - if (Number(entry.port) === p) return entry; + if (serverEntryAssignedHostPorts(entry).includes(p)) return entry; } return null; } -async function checkRemoteNodePortAvailability(node, port) { +function collectPortList(value) { + const raw = Array.isArray(value) ? value : []; + const ports = []; + const seen = new Set(); + for (const entry of raw) { + const port = validatePort(entry); + if (!port || seen.has(port)) continue; + seen.add(port); + ports.push(port); + } + return ports; +} + +function serverEntryAssignedHostPorts(entry) { + const ports = []; + const seen = new Set(); + const add = (value) => { + const port = validatePort(value); + if (!port || seen.has(port)) return; + seen.add(port); + ports.push(port); + }; + + add(entry?.port); + for (const port of collectPortList(entry?.resources?.ports)) add(port); + + return ports; +} + +function dockerTemplateHostPortRequirements(docker, mainHostPort) { + const templatePorts = collectPortList(docker?.ports); + const requirements = []; + const primaryHostPort = validatePort(mainHostPort); + if (primaryHostPort) { + requirements.push({ + hostPort: primaryHostPort, + containerPort: templatePorts[0] || primaryHostPort, + protocols: dockerPortProtocolsFor(docker, templatePorts[0] || primaryHostPort), + primary: true, + }); + } + return requirements; +} + +function dockerPortProtocolsFor(docker, containerPort) { + const rawProtocols = docker?.portProtocols || docker?.port_protocols || docker?.protocols || {}; + const key = String(validatePort(containerPort) || ""); + const values = rawProtocols && typeof rawProtocols === "object" && !Array.isArray(rawProtocols) + ? rawProtocols[key] + : null; + const rawList = Array.isArray(values) ? values : (values ? [values] : []); + const protocols = rawList + .map((entry) => String(entry || "").trim().toLowerCase()) + .filter((entry) => entry === "tcp" || entry === "udp" || entry === "sctp"); + return protocols.length ? [...new Set(protocols)] : ["tcp"]; +} + +async function checkRemoteNodePortAvailability(node, port, protocols = []) { const p = validatePort(port); if (!p) return { ok: false, verified: false, error: "invalid-port" }; const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); if (!baseUrl) return { ok: false, verified: false, error: "invalid-node-address" }; const headers = nodeAuthHeadersFor(node, true); - const url = `${baseUrl}/v1/ports/check?port=${encodeURIComponent(String(p))}`; + const cleanProtocols = (Array.isArray(protocols) ? protocols : []) + .map((entry) => String(entry || "").trim().toLowerCase()) + .filter((entry) => entry === "tcp" || entry === "udp" || entry === "sctp"); + const params = new URLSearchParams({ port: String(p) }); + if (cleanProtocols.length) params.set("protocols", [...new Set(cleanProtocols)].join(",")); + const url = `${baseUrl}/v1/ports/check?${params.toString()}`; const r = await httpRequestJson(url, "GET", headers, null, 10_000); if (r.status === 200 && r.json && r.json.ok) { return { ok: true, verified: true, ...r.json }; @@ -6800,8 +8842,64 @@ async function resolveRemoteFsContext(botName) { if (!node) return { remote: false }; const safeName = sanitizeServerName(entry.name || botName); if (!safeName) return { remote: false }; - const baseDir = `${NODE_VOLUME_ROOT}/${safeName}`; - return { remote: true, node, baseDir }; + // adpanel:multidisk - resolve the per-server baseDir from the node instead of + // assuming the hardcoded NODE_VOLUME_ROOT. Cached per server to avoid a node + // round-trip on every FS request; falls back to the legacy primary path if the + // node is older or unreachable, preserving single-disk behavior. + let baseDir = `${NODE_VOLUME_ROOT}/${safeName}`; + try { + const resolved = await resolveServerBaseDir(node, safeName); + if (resolved) baseDir = resolved; + } catch (_) { + /* fall back to legacy primary path */ + } + return { remote: true, node, baseDir, serverName: safeName }; +} + +const _serverBaseDirCache = new Map(); // key: `${nodeId}:${name}` -> { baseDir, at } +const SERVER_BASEDIR_TTL_MS = 5 * 60 * 1000; + +// adpanel:multidisk - validate a node-reported base dir before using it as a +// safeJoinUnix prefix. Independent of the node's own checks: the panel rejects +// anything that is not a clean, absolute Unix path whose final segment equals the +// sanitized server name. Blocks traversal/NUL injection and spoofed responses. +function validateServerBaseDir(baseDir, expectedName) { + if (typeof baseDir !== "string" || !baseDir || baseDir.includes("\0")) return null; + // Reject traversal in the raw value *before* normalization collapses it. + if (baseDir.split("/").includes("..")) return null; + const normalized = path.posix.normalize(baseDir).replace(/\/+$/, ""); + if (!normalized.startsWith("/") || normalized === "/" || normalized === "") return null; + if (normalized.split("/").includes("..")) return null; + const safeName = sanitizeServerName(expectedName); + if (!safeName) return null; + const segments = normalized.split("/"); + if (segments[segments.length - 1] !== safeName) return null; + return normalized; +} + +async function resolveServerBaseDir(node, safeName) { + const key = `${node.id || node.uuid || node.name}:${safeName}`; + const cached = _serverBaseDirCache.get(key); + if (cached && Date.now() - cached.at < SERVER_BASEDIR_TTL_MS) { + return cached.baseDir; + } + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return null; + const res = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(safeName)}`, + "GET", + { Authorization: `Bearer ${node.token}` }, + null, + 5000 + ); + if (res.status === 200 && res.json && res.json.ok === true) { + const validated = validateServerBaseDir(res.json.baseDir, safeName); + if (validated) { + _serverBaseDirCache.set(key, { baseDir: validated, at: Date.now() }); + return validated; + } + } + return null; } app.use("/api/dashboard-assistant", createDashboardAssistantRouter({ @@ -6851,6 +8949,9 @@ app.use("/api/dashboard-assistant", createDashboardAssistantRouter({ deleteServerSchedules, removeServerIndexEntry, removeAccessForServerName, + markServerDeletingStatus, + enqueueServerDeleteJob, + kickServerDeleteWorker, }, name), applyRemoteAssetToServer: (params) => applyRemoteAssetToServer({ findServer, @@ -7335,6 +9436,120 @@ function runtimeDataDirForTemplate(templateId, dockerConfig = null) { return '/data'; } +function sanitizeTemplateConsoleProcessTargets(values) { + const source = Array.isArray(values) ? values : (values == null ? [] : [values]); + const out = []; + const seen = new Set(); + for (const value of source) { + let target = String(value ?? "").replace(/\0/g, "").replace(/[\r\n]/g, "").trim(); + target = target.replace(/^['"]+|['"]+$/g, ""); + if (!target || target === "") continue; + if (target.length > 120) target = target.slice(0, 120); + if (seen.has(target)) continue; + seen.add(target); + out.push(target); + if (out.length >= 12) break; + } + return out; +} + +function consoleProcessTargetsFromConfig(consoleConfig) { + if (!consoleConfig) return []; + if (typeof consoleConfig === "string" || Array.isArray(consoleConfig)) { + return sanitizeTemplateConsoleProcessTargets(consoleConfig); + } + if (typeof consoleConfig !== "object") return []; + for (const key of ["targetProcesses", "target_processes", "processes", "processNames", "process_names"]) { + const targets = sanitizeTemplateConsoleProcessTargets(consoleConfig[key]); + if (targets.length) return targets; + } + for (const key of ["targetProcess", "target_process", "process", "target"]) { + const targets = sanitizeTemplateConsoleProcessTargets(consoleConfig[key]); + if (targets.length) return targets; + } + return []; +} + +function defaultConsoleProcessTargetsForTemplate(templateId) { + switch (normalizeTemplateId(templateId)) { + case "7-days-to-die": + case "7dtd": + case "sdtd": + return ["7DaysToDieServer", "7DaysToDieServer.x86_64"]; + case "ark": + case "ark-survival-evolved": + return ["ShooterGameServer"]; + case "assetto-corsa": + return ["server-manager", "acServer"]; + case "csgo": + case "cs2": + case "counter-strike-2": + return ["cs2", "srcds_linux"]; + case "dayz": + return ["DayZServer", "DayZServer_x64", "dayzserver"]; + case "fivem": + case "five-m": + case "redm": + return ["FXServer", "fxserver"]; + case "hytale": + return ["hytale-server", "java"]; + case "minecraft": + return ["java", "bedrock_server"]; + case "palworld": + return ["PalServer-Linux-Test", "PalServer"]; + case "project-zomboid": + case "zomboid": + return ["ProjectZomboid64", "ProjectZomboid32", "java"]; + case "ragemp": + case "rage-mp": + return ["ragemp-server", "ragemp"]; + case "rust": + return ["RustDedicated"]; + case "valheim": + return ["valheim_server", "valheim_server.x86_64"]; + default: + return []; + } +} + +function defaultConsoleProcessTargetsForImage(image) { + const lower = String(image || "").trim().toLowerCase(); + if (!lower) return []; + if (lower.includes("hytale")) return defaultConsoleProcessTargetsForTemplate("hytale"); + if (lower.includes("redm")) return defaultConsoleProcessTargetsForTemplate("redm"); + if (lower.includes("fivem")) return defaultConsoleProcessTargetsForTemplate("fivem"); + if (lower.includes("dayz") || lower.includes("day-z")) return defaultConsoleProcessTargetsForTemplate("dayz"); + if (lower.includes("zomboid")) return defaultConsoleProcessTargetsForTemplate("project-zomboid"); + if (lower.includes("palworld")) return defaultConsoleProcessTargetsForTemplate("palworld"); + if (lower.includes("valheim")) return defaultConsoleProcessTargetsForTemplate("valheim"); + if (lower.includes("rust")) return defaultConsoleProcessTargetsForTemplate("rust"); + if (lower.includes("ragemp")) return defaultConsoleProcessTargetsForTemplate("ragemp"); + if (lower.includes("ark")) return defaultConsoleProcessTargetsForTemplate("ark-survival-evolved"); + if (lower.includes("7dtd") || lower.includes("7daystodie") || lower.includes("7-days-to-die") || lower.includes("sdtd")) return defaultConsoleProcessTargetsForTemplate("7-days-to-die"); + if (lower.includes("assetto")) return defaultConsoleProcessTargetsForTemplate("assetto-corsa"); + if (lower.includes("cs2") || lower.includes("csgo")) return defaultConsoleProcessTargetsForTemplate("cs2"); + return []; +} + +function normalizeTemplateConsoleForRuntime(templateId, consoleConfig = null, image = "") { + const source = consoleConfig && typeof consoleConfig === "object" && !Array.isArray(consoleConfig) + ? { ...consoleConfig } + : {}; + const rawMode = String(source.type || source.mode || consoleConfig || "stdin").trim().toLowerCase(); + const mode = ["stdin", "exec", "exec-shell", "shell"].includes(rawMode) ? rawMode : "stdin"; + const targets = consoleProcessTargetsFromConfig(consoleConfig); + const defaultTargets = targets.length + ? targets + : (defaultConsoleProcessTargetsForTemplate(templateId).length + ? defaultConsoleProcessTargetsForTemplate(templateId) + : defaultConsoleProcessTargetsForImage(image)); + return { + ...source, + type: mode, + ...(defaultTargets.length ? { targetProcesses: sanitizeTemplateConsoleProcessTargets(defaultTargets) } : {}), + }; +} + function defaultTemplateBotDirVolumeForWorkdir(workdir) { const normalizedWorkdir = normalizeRuntimeWorkdirInput(workdir) || '/data'; return `{BOT_DIR}:${normalizedWorkdir}`; @@ -7357,6 +9572,9 @@ function normalizeTemplateDockerForRuntime(templateId, dockerConfig = null, star image: String(docker.image || "").trim(), tag: String(docker.tag || "").trim(), ports: Array.isArray(docker.ports) ? docker.ports.slice() : [], + portProtocols: docker.portProtocols && typeof docker.portProtocols === "object" && !Array.isArray(docker.portProtocols) + ? { ...docker.portProtocols } + : {}, volumes: Array.isArray(docker.volumes) ? docker.volumes.slice() : [], workdir: normalizeRuntimeWorkdirInput(docker.workdir || docker.workingDir || docker.working_dir), env: docker.env && typeof docker.env === "object" && !Array.isArray(docker.env) ? { ...docker.env } : {}, @@ -7367,9 +9585,18 @@ function normalizeTemplateDockerForRuntime(templateId, dockerConfig = null, star docker.pterodactylStartup || docker.pterodactyl_startup ), + startupDisplay: sanitizeADPanelStartupInput( + docker.startupDisplay || + docker.startup_display || + docker.startupPreview || + docker.startup_preview || + docker.imageDefaultStartup || + docker.image_default_startup + ), install: sanitizeDockerInstallPayload(docker.install || docker.installation), restart: String(docker.restart || (managedTemplate ? "unless-stopped" : "no")).trim() || (managedTemplate ? "unless-stopped" : "no"), - console: docker.console || { type: "stdin" }, + runAsRoot: docker.runAsRoot === true || docker.run_as_root === true, + console: normalizeTemplateConsoleForRuntime(normalized, docker.console, docker.image), }; if (!docker.workdir && managedTemplate) { docker.workdir = runtimeDataDirForTemplate(normalized, docker); @@ -8278,7 +10505,166 @@ async function fetchJson(u) { return JSON.parse(buf.toString("utf8")); } -app.post("/api/captcha/local", (req, res) => { +const PENDING_CAPTCHA_LOGIN_TTL_MS = parseInt(process.env.PENDING_CAPTCHA_LOGIN_TTL_MS || "300000", 10) || 300000; + +function getPendingCaptchaLoginRequestFingerprint(req) { + return crypto + .createHash("sha256") + .update(String(getRequestIp(req) || "")) + .update("\n") + .update(String(req?.get?.("user-agent") || "")) + .digest("hex"); +} + +function clearPendingCaptchaLogin(req) { + if (!req?.session) return; + delete req.session.pendingCaptchaLogin; +} + +function getPendingCaptchaLogin(req) { + const pending = req?.session?.pendingCaptchaLogin; + if (!pending || typeof pending !== "object") return null; + + const expiresAt = Number(pending.expiresAt || 0); + const email = String(pending.email || "").trim().toLowerCase(); + const userFingerprint = String(pending.userFingerprint || ""); + const requestFingerprint = String(pending.requestFingerprint || ""); + + if (!email || !userFingerprint || !requestFingerprint || !expiresAt || expiresAt <= Date.now()) { + clearPendingCaptchaLogin(req); + if (req?.session) { + req.session.captchaSolved = false; + req.session.captchaRequired = false; + } + return null; + } + + if (!safeCompare(requestFingerprint, getPendingCaptchaLoginRequestFingerprint(req))) { + clearPendingCaptchaLogin(req); + if (req?.session) { + req.session.captchaSolved = false; + req.session.captchaRequired = false; + } + return null; + } + + return pending; +} + +function beginPendingCaptchaLogin(req, user, options = {}) { + if (!req?.session || !user?.email || !user?.password) return false; + + const now = Date.now(); + req.session.pendingCaptchaLogin = { + email: String(user.email || "").trim().toLowerCase(), + userId: String(user.id || ""), + userFingerprint: getRememberLoginFingerprint(user), + requestFingerprint: getPendingCaptchaLoginRequestFingerprint(req), + twoFactorVerified: !!options.twoFactorVerified, + createdAt: now, + expiresAt: now + PENDING_CAPTCHA_LOGIN_TTL_MS, + }; + req.session.captchaRequired = true; + req.session.captchaSolved = false; + delete req.session.lastExternalCaptchaToken; + + if (EXTERNAL_CAPTCHA_ENABLED) { + req.session.localCaptcha = null; + } else if (LOCAL_CAPTCHA_ENABLED) { + assignLocalCaptcha(req); + } + + return true; +} + +function buildPendingLoginCaptchaChallenge(req) { + const pending = getPendingCaptchaLogin(req); + const captchaRequired = !!(pending && ANY_CAPTCHA_ENABLED && req.session?.captchaRequired && !req.session?.captchaSolved); + const useExternalCaptcha = EXTERNAL_CAPTCHA_ENABLED && captchaRequired; + const shouldShowLocal = LOCAL_CAPTCHA_ENABLED && !useExternalCaptcha && captchaRequired; + let captchaQuestion = null; + + if (shouldShowLocal) { + captchaQuestion = getCurrentCaptchaQuestion(req); + if (!captchaQuestion) captchaQuestion = assignLocalCaptcha(req); + } + + return { + captchaRequired, + useExternalCaptcha, + shouldShowLocal, + externalCaptchaAutoStart: useExternalCaptcha && captchaRequired, + captchaQuestion, + }; +} + +async function completePendingCaptchaLogin(req, res) { + const pending = getPendingCaptchaLogin(req); + if (!pending) return { ok: false, status: 409, error: "no-pending-login" }; + if (req.session?.captchaRequired && !req.session?.captchaSolved) { + return { ok: false, status: 403, error: "captcha-required" }; + } + + const user = await findUserByEmail(pending.email); + if (!user || !user.password) { + clearPendingCaptchaLogin(req); + return { ok: false, status: 401, error: "login-expired" }; + } + + if (user.suspended) { + clearPendingCaptchaLogin(req); + revokeRememberLoginsForUser(user); + clearRememberLoginCookie(res); + return { + ok: false, + status: 403, + error: "Your account is suspended", + redirect: "/login?error=Your%20account%20is%20suspended", + }; + } + + if (pending.userId && String(user.id || "") !== String(pending.userId)) { + clearPendingCaptchaLogin(req); + return { ok: false, status: 401, error: "login-expired" }; + } + + const expectedUserFingerprint = getRememberLoginFingerprint(user); + if (!expectedUserFingerprint || !safeCompare(String(pending.userFingerprint || ""), expectedUserFingerprint)) { + clearPendingCaptchaLogin(req); + return { ok: false, status: 401, error: "login-expired" }; + } + + if (hasTwoFactorEnabled(user) && !pending.twoFactorVerified) { + clearPendingCaptchaLogin(req); + return { ok: false, status: 401, error: "login-expired" }; + } + + const clientIp = getRequestIp(req); + await withTimeout( + new Promise((resolve, reject) => req.session.regenerate((err) => (err ? reject(err) : resolve()))), + 5000, + "session-regenerate-timeout" + ); + + req.session.user = user.email; + const rememberLoginId = ensureRememberLoginSessionId(req); + req.session.browserSessionAudit = buildBrowserSessionAuditFromRequest(req, user.email, rememberLoginId); + clearLocalCaptcha(req); + clearPendingCaptchaLogin(req); + markRememberLoginSessionFresh(req, setRememberLoginCookie(req, res, user)); + upsertActiveBrowserSessionCacheEntry(req.sessionID, req.session); + + await withTimeout( + new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve()))), + 5000, + "session-save-timeout" + ); + + resetLoginAttempts(clientIp); + return { ok: true, redirect: "/" }; +} + +app.post("/api/captcha/local", async (req, res) => { if (!LOCAL_CAPTCHA_ENABLED) return res.status(400).json({ ok: false, error: "not-enabled" }); if (!req.session || !req.session.localCaptcha) return res.status(400).json({ ok: false, error: "no-captcha" }); @@ -8303,7 +10689,17 @@ app.post("/api/captcha/local", (req, res) => { return res.status(400).json({ ok: false, error: r.error || "skip-failed" }); } if (r.done) { - return req.session.save(() => res.json({ ok: true, done: true })); + const completedLogin = await completePendingCaptchaLogin(req, res); + if (completedLogin.ok) { + return res.json({ ok: true, done: true, redirect: completedLogin.redirect || "/" }); + } + req.session.captchaSolved = false; + clearLocalCaptcha(req); + return req.session.save(() => res.status(completedLogin.status || 409).json({ + ok: false, + error: completedLogin.error || "login-not-finalized", + redirect: completedLogin.redirect || "/login", + })); } const nextQ = getCurrentCaptchaQuestion(req); return res.json({ ok: true, done: false, question: nextQ, remainingSkips: r.remainingSkips }); @@ -8317,7 +10713,17 @@ app.post("/api/captcha/local", (req, res) => { return res.status(400).json({ ok: false, error: "invalid" }); } if (r.done) { - return req.session.save(() => res.json({ ok: true, done: true })); + const completedLogin = await completePendingCaptchaLogin(req, res); + if (completedLogin.ok) { + return res.json({ ok: true, done: true, redirect: completedLogin.redirect || "/" }); + } + req.session.captchaSolved = false; + clearLocalCaptcha(req); + return req.session.save(() => res.status(completedLogin.status || 409).json({ + ok: false, + error: completedLogin.error || "login-not-finalized", + redirect: completedLogin.redirect || "/login", + })); } const nextQ = getCurrentCaptchaQuestion(req); @@ -8329,6 +10735,12 @@ app.post("/api/captcha/verify", async (req, res) => { const token = req.body?.token || req.body?.["g-recaptcha-response"]; if (!token) return res.status(400).json({ ok: false, error: "missing-token" }); if (!EXTERNAL_CAPTCHA_ENABLED) return res.status(400).json({ ok: false, error: "not-enabled" }); + if (!getPendingCaptchaLogin(req)) { + req.session.captchaSolved = false; + req.session.captchaRequired = false; + clearLocalCaptcha(req); + return req.session.save(() => res.status(409).json({ ok: false, error: "no-pending-login", redirect: "/login" })); + } const clientIp = getRequestIp(req); const result = await verifyExternalCaptcha(token, clientIp); @@ -8337,7 +10749,23 @@ app.post("/api/captcha/verify", async (req, res) => { req.session.captchaSolved = true; req.session.captchaRequired = false; clearLocalCaptcha(req); - return req.session.save(() => res.json({ ok: true })); + try { + const completedLogin = await completePendingCaptchaLogin(req, res); + if (completedLogin.ok) { + return res.json({ ok: true, redirect: completedLogin.redirect || "/" }); + } + req.session.captchaSolved = false; + req.session.captchaRequired = false; + clearLocalCaptcha(req); + return req.session.save(() => res.status(completedLogin.status || 409).json({ + ok: false, + error: completedLogin.error || "login-not-finalized", + redirect: completedLogin.redirect || "/login", + })); + } catch (err) { + console.error("[login] captcha finalize error:", err); + return res.status(500).json({ ok: false, error: "login-finalize-failed" }); + } }); const DOCKER_TAG_CACHE_TTL_MS = 10 * 60 * 1000; @@ -8480,6 +10908,9 @@ function isAllowedNodeToken(token, node) { async function isOpenNodeRoute(req) { const p = req.path || ""; + if (typeof nodesRouter.isOpenNodeInstallerRoute === "function" && await nodesRouter.isOpenNodeInstallerRoute(req)) { + return true; + } const match = /^\/api\/nodes\/([^/]+)\/(heartbeat|config\.yml)$/.exec(p); if (!match) return false; @@ -8703,6 +11134,25 @@ app.use("/api/settings/maintenance", async (req, res, next) => { } }); +app.delete("/api/nodes/:id", sessionRevoke2faRateLimiter, async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } + + const nodeId = String(req.params.id || "").trim().slice(0, 160); + const stepUp = await requireDestructiveActionStepUp(req, res, currentUser, `Node delete "${nodeId}"`); + if (!stepUp.ok) return; + + return next(); + } catch (err) { + return next(err); + } +}); + app.use(nodesRouter); app.use("/api/subdomains", subdomainsRouter); @@ -8775,6 +11225,10 @@ async function proxySshTerminalIndex(req, res) { }, }); } catch { + if (!retryFlag && await recoverSshTerminalService(upstreamOrigin)) { + const fresh = issueSshTerminalToken(req); + return res.redirect(`/ssh-terminal/?token=${encodeURIComponent(fresh)}&_retry=1`); + } return res.status(502).type("text/plain").send("ssh terminal service unavailable"); } @@ -9191,47 +11645,40 @@ app.get("/login", (req, res) => { const csrfToken = ensureLoginCsrfToken(req); const qErr = req.query?.error ? String(req.query.error) : null; - const hasError = !!qErr; - const underAttack = !!res.locals.underAttack || isLoginUnderAttack(); + const pendingCaptchaLogin = getPendingCaptchaLogin(req); - if (req.session && req.session.captchaSolved) { + if (pendingCaptchaLogin && !ANY_CAPTCHA_ENABLED) { + clearPendingCaptchaLogin(req); clearLocalCaptcha(req); - req.session.captchaRequired = false; } - if (req.session && !req.session.captchaRequired && !hasError && !underAttack) { + if (req.session && !getPendingCaptchaLogin(req)) { clearLocalCaptcha(req); req.session.captchaRequired = false; req.session.captchaSolved = false; } - let captchaQuestion = null; - const captchaRequired = ANY_CAPTCHA_ENABLED && (underAttack || (req.session?.captchaRequired && !req.session?.captchaSolved)); - const useExternalCaptcha = EXTERNAL_CAPTCHA_ENABLED && captchaRequired; - const shouldShowLocal = LOCAL_CAPTCHA_ENABLED && !useExternalCaptcha && captchaRequired; - const externalCaptchaAutoStart = useExternalCaptcha && captchaRequired; - if (shouldShowLocal) { - if (!req.session.localCaptcha) assignLocalCaptcha(req); - captchaQuestion = getCurrentCaptchaQuestion(req); - if (!captchaQuestion) captchaQuestion = assignLocalCaptcha(req); - } + const challenge = buildPendingLoginCaptchaChallenge(req); applyLoginPageSecurityHeaders(req, res, { - useExternalCaptcha, + useExternalCaptcha: EXTERNAL_CAPTCHA_ENABLED, externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, }); return res.render("login", { error: qErr || null, + requiresTwoFactor: false, + loginEmail: "", botProofSeed, csrfToken, loginCss: getInlineLoginCss(), - useExternalCaptcha, - externalCaptchaAutoStart, + useExternalCaptcha: challenge.useExternalCaptcha, + externalCaptchaAvailable: EXTERNAL_CAPTCHA_ENABLED, + externalCaptchaAutoStart: challenge.externalCaptchaAutoStart, externalCaptchaSiteKey: EXTERNAL_CAPTCHA_SITE_KEY, externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, - showLocalCaptcha: shouldShowLocal && !!captchaQuestion, - captchaQuestion, + showLocalCaptcha: challenge.shouldShowLocal && !!challenge.captchaQuestion, + captchaQuestion: challenge.captchaQuestion, }); }); @@ -9254,54 +11701,47 @@ app.post("/login", async (req, res) => { contentType.includes("application/json") || String(req.get("x-requested-with") || "") === "XMLHttpRequest"; const externalCaptchaEnabled = EXTERNAL_CAPTCHA_ENABLED; - const localCaptchaEnabled = LOCAL_CAPTCHA_ENABLED; const captchaAvailable = ANY_CAPTCHA_ENABLED; - let justSolvedCaptcha = false; const sendError = (status, message, options = {}) => { const csrfToken = rotateLoginCsrfToken(req); - const preserveCaptchaState = !!options.preserveCaptchaState; - if (wantsJson) return res.status(status).json({ ok: false, error: message }); - try { - if (req.session) { - if (preserveCaptchaState || justSolvedCaptcha || req.session.captchaSolved) { - } else { - if (captchaAvailable) req.session.captchaRequired = true; - req.session.captchaSolved = false; - if (localCaptchaEnabled && !externalCaptchaEnabled && !req.session.localCaptcha) { - assignLocalCaptcha(req); - } - } - } - } catch { } + const requiresTwoFactor = !!options.requiresTwoFactor; + const loginEmail = String(options.loginEmail || "").trim().toLowerCase(); const botProofSeed = ensureBotProofSeed(req, res); - const underAttack = !!res.locals.underAttack || isLoginUnderAttack(); - let captchaQuestion = null; - const captchaRequired = captchaAvailable && (underAttack || (req.session?.captchaRequired && !req.session?.captchaSolved)); - const useExternalCaptcha = externalCaptchaEnabled && captchaRequired; - const shouldShowLocal = localCaptchaEnabled && !useExternalCaptcha && captchaRequired; - const externalCaptchaAutoStart = useExternalCaptcha && captchaRequired; - if (shouldShowLocal) { - if (!req.session.localCaptcha) assignLocalCaptcha(req); - captchaQuestion = getCurrentCaptchaQuestion(req) || assignLocalCaptcha(req); + const challenge = buildPendingLoginCaptchaChallenge(req); + + if (wantsJson) { + res.setHeader("Cache-Control", "no-store"); + return res.status(status).json({ + ok: false, + error: message, + requires2FA: requiresTwoFactor, + csrfToken, + captchaRequired: challenge.captchaRequired, + useExternalCaptcha: challenge.useExternalCaptcha, + showLocalCaptcha: challenge.shouldShowLocal && !!challenge.captchaQuestion, + }); } applyLoginPageSecurityHeaders(req, res, { - useExternalCaptcha, + useExternalCaptcha: externalCaptchaEnabled, externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, }); const renderData = { error: message, + requiresTwoFactor, + loginEmail, botProofSeed, csrfToken, loginCss: getInlineLoginCss(), - useExternalCaptcha, - externalCaptchaAutoStart, + useExternalCaptcha: challenge.useExternalCaptcha, + externalCaptchaAvailable: externalCaptchaEnabled, + externalCaptchaAutoStart: challenge.externalCaptchaAutoStart, externalCaptchaSiteKey: EXTERNAL_CAPTCHA_SITE_KEY, externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, - showLocalCaptcha: shouldShowLocal && !!captchaQuestion, - captchaQuestion, + showLocalCaptcha: challenge.shouldShowLocal && !!challenge.captchaQuestion, + captchaQuestion: challenge.captchaQuestion, }; if (req.session?.save) { @@ -9316,15 +11756,65 @@ app.post("/login", async (req, res) => { return res.redirect(303, "/"); }; - if (!isValidLoginCsrfToken(req, req.body?._csrf)) { - return sendError(403, "Security token expired. Please refresh and try again.", { preserveCaptchaState: true }); - } + const sendCaptchaChallenge = (user, options = {}) => { + const twoFactorVerified = !!options.twoFactorVerified; + const loginEmail = String(user?.email || "").trim().toLowerCase(); + if (!beginPendingCaptchaLogin(req, user, { twoFactorVerified })) { + return sendError(500, "Internal login error."); + } - const withTimeout = (p, ms, label) => - Promise.race([ - p, - new Promise((_, rej) => setTimeout(() => rej(new Error(label || "timeout")), ms)), - ]); + const csrfToken = rotateLoginCsrfToken(req); + const botProofSeed = ensureBotProofSeed(req, res); + const challenge = buildPendingLoginCaptchaChallenge(req); + + const jsonPayload = { + ok: false, + error: "", + requires2FA: false, + captchaRequired: challenge.captchaRequired, + useExternalCaptcha: challenge.useExternalCaptcha, + showLocalCaptcha: challenge.shouldShowLocal && !!challenge.captchaQuestion, + csrfToken, + }; + + if (wantsJson) { + res.setHeader("Cache-Control", "no-store"); + if (req.session?.save) { + return req.session.save(() => res.status(403).json(jsonPayload)); + } + return res.status(403).json(jsonPayload); + } + + applyLoginPageSecurityHeaders(req, res, { + useExternalCaptcha: externalCaptchaEnabled, + externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, + }); + + const renderData = { + error: null, + requiresTwoFactor: false, + loginEmail, + botProofSeed, + csrfToken, + loginCss: getInlineLoginCss(), + useExternalCaptcha: challenge.useExternalCaptcha, + externalCaptchaAvailable: externalCaptchaEnabled, + externalCaptchaAutoStart: challenge.externalCaptchaAutoStart, + externalCaptchaSiteKey: EXTERNAL_CAPTCHA_SITE_KEY, + externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, + showLocalCaptcha: challenge.shouldShowLocal && !!challenge.captchaQuestion, + captchaQuestion: challenge.captchaQuestion, + }; + + if (req.session?.save) { + return req.session.save(() => res.status(403).render("login", renderData)); + } + return res.status(403).render("login", renderData); + }; + + if (!isValidLoginCsrfToken(req, req.body?._csrf)) { + return sendError(403, "Security token expired. Please refresh and try again."); + } try { if (isNonBrowserRequest(req)) { @@ -9335,10 +11825,6 @@ app.post("/login", async (req, res) => { if (req.body?.company) { return sendError(400, "Invalid submission."); } - const captchaToken = req.body?.captchaToken || req.body?.["g-recaptcha-response"]; - const botProof = String(req.body?.botProof || "").trim(); - const localCaptchaToken = req.body?.localCaptchaToken; - const captchaSelectionRaw = req.body?.captchaSelection; const emailStr = String(email || "").trim().toLowerCase(); const passStr = String(password || ""); @@ -9357,67 +11843,7 @@ app.post("/login", async (req, res) => { return sendError(429, "Try again later."); } - const underAttack = !!res.locals.underAttack || isLoginUnderAttack(); - if (underAttack && req.session && captchaAvailable) { - req.session.captchaRequired = true; - req.session.captchaSolved = false; - } - - const suspicious = isSuspiciousLogin(req, rec); - const captchaRequired = captchaAvailable && (underAttack || (req.session?.captchaRequired && !req.session?.captchaSolved)); - const needCaptcha = captchaAvailable && (captchaRequired || suspicious || underAttack); - - if (req.session?.captchaSolved) { - } else if (needCaptcha && externalCaptchaEnabled) { - if (req.session) req.session.captchaRequired = true; - if (!captchaToken) { - if (req.session) req.session.captchaSolved = false; - return sendError(403, ""); - } - if (req.session.lastExternalCaptchaToken && req.session.lastExternalCaptchaToken === captchaToken) { - if (localCaptchaEnabled) assignLocalCaptcha(req); - return sendError(400, "Captcha verification failed"); - } - const verify = await verifyExternalCaptcha(captchaToken, clientIp); - if (!verify.ok) return sendError(400, "Captcha verification failed"); - req.session.lastExternalCaptchaToken = captchaToken || ""; - req.session.captchaSolved = true; - justSolvedCaptcha = true; - } else if (needCaptcha && localCaptchaEnabled) { - if (req.session) req.session.captchaRequired = true; - if (!localCaptchaToken && !captchaSelectionRaw) { - if (req.session) req.session.captchaSolved = false; - return sendError(403, ""); - } - let selected = []; - if (Array.isArray(captchaSelectionRaw)) selected = captchaSelectionRaw.map(Number); - else if (typeof captchaSelectionRaw === "string") { - selected = captchaSelectionRaw - .split(",") - .map(s => Number(s.trim())) - .filter(Number.isInteger); - } - const valid = validateLocalCaptcha(req, selected, localCaptchaToken); - if (!valid.ok) { - assignLocalCaptcha(req); - return sendError(400, valid.expired ? "Captcha expired. Try again." : "Captcha incorrect"); - } - if (!valid.done) { - return sendError(400, "Captcha not finished yet."); - } - req.session.captchaSolved = true; - justSolvedCaptcha = true; - } - - if (needCaptcha && !justSolvedCaptcha && !req.session?.captchaSolved && !isBotProofValid(req, botProof)) { - if (req.session) { - req.session.captchaRequired = true; - req.session.captchaSolved = false; - } - return sendError(403, ""); - } - - if (!emailStr || !passStr || !codeStr) { + if (!emailStr || !passStr) { return sendError(400, "The fields are empty."); } @@ -9431,14 +11857,28 @@ app.post("/login", async (req, res) => { return sendError(400, "Invalid credentials"); } - const verified = speakeasy.totp.verify({ - secret: user.secret, - encoding: "base32", - token: codeStr, - window: 1, - }); - if (!verified) { - return sendError(400, "Invalid credentials"); + if (user.suspended) { + clearRememberLoginCookie(res); + revokeRememberLoginsForUser(user); + return sendError(403, "Your account is suspended"); + } + + const userHasTwoFactor = hasTwoFactorEnabled(user); + if (userHasTwoFactor) { + if (!codeStr) { + return sendError(401, "Enter your 2FA code to continue.", { + requiresTwoFactor: true, + loginEmail: emailStr, + }); + } + + const twoFactor = verifyTotpForUser(user, codeStr); + if (!twoFactor.ok) { + return sendError(400, "Invalid credentials", { + requiresTwoFactor: true, + loginEmail: emailStr, + }); + } } const isActuallySecure = isRequestSecure(req); @@ -9449,15 +11889,27 @@ app.post("/login", async (req, res) => { ); } + if (captchaAvailable) { + return sendCaptchaChallenge(user, { twoFactorVerified: userHasTwoFactor }); + } + + const latestUser = await findUserByEmail(user.email); + if (!latestUser || latestUser.suspended) { + clearRememberLoginCookie(res); + if (latestUser?.suspended) revokeRememberLoginsForUser(latestUser); + return sendError(403, "Your account is suspended"); + } + await withTimeout( new Promise((resolve, reject) => req.session.regenerate((err) => (err ? reject(err) : resolve()))), 5000, "session-regenerate-timeout" ); - req.session.user = user.email; + req.session.user = latestUser.email; const rememberLoginId = ensureRememberLoginSessionId(req); - req.session.browserSessionAudit = buildBrowserSessionAuditFromRequest(req, user.email, rememberLoginId); + req.session.browserSessionAudit = buildBrowserSessionAuditFromRequest(req, latestUser.email, rememberLoginId); + markRememberLoginSessionFresh(req, setRememberLoginCookie(req, res, latestUser)); upsertActiveBrowserSessionCacheEntry(req.sessionID, req.session); await withTimeout( @@ -9466,7 +11918,6 @@ app.post("/login", async (req, res) => { "session-save-timeout" ); - setRememberLoginCookie(req, res, user); clearLocalCaptcha(req); resetLoginAttempts(clientIp); return sendOk(); @@ -9578,8 +12029,8 @@ app.get("/api/settings/security", async (req, res) => { trusted_subnets: security.trusted_subnets || [], captcha_enabled: captchaEnabled, actionTokens: { - updateSecurity: issueActionToken(req, "POST /api/settings/security", {}, { ttlSeconds: 300 }), - updateCaptcha: issueActionToken(req, "POST /api/settings/captcha", {}, { ttlSeconds: 300 }) + updateSecurity: issueActionToken(req, "POST /api/settings/security", {}, { ttlSeconds: 600 }), + updateCaptcha: issueActionToken(req, "POST /api/settings/captcha", {}, { ttlSeconds: 600 }) } }); }); @@ -9657,18 +12108,20 @@ app.get("/api/maintenance/status", async (req, res) => { app.get("/api/settings/maintenance", async (req, res) => { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const currentUser = await findUserByEmail(req.session.user); const state = getMaintenanceState(); return res.json({ ...state, is_active: isMaintenanceActive(), + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), actionTokens: { - enableMaintenance: issueActionToken(req, "POST /api/settings/maintenance", {}, { ttlSeconds: 300 }), - disableMaintenance: issueActionToken(req, "DELETE /api/settings/maintenance", {}, { ttlSeconds: 300 }) + enableMaintenance: issueActionToken(req, "POST /api/settings/maintenance", {}, { ttlSeconds: 600 }), + disableMaintenance: issueActionToken(req, "DELETE /api/settings/maintenance", {}, { ttlSeconds: 600 }) } }); }); -app.post("/api/settings/maintenance", async (req, res) => { +app.post("/api/settings/maintenance", sessionRevoke2faRateLimiter, async (req, res) => { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); if (!requireActionTokenOr403(req, res, "POST /api/settings/maintenance")) return; @@ -9677,6 +12130,9 @@ app.post("/api/settings/maintenance", async (req, res) => { const user = await findUserByEmail(req.session.user); if (!user || !user.admin) return res.status(403).json({ error: "not authorized" }); + const stepUp = await requireDestructiveActionStepUp(req, res, user, "Maintenance activation"); + if (!stepUp.ok) return; + const state = getMaintenanceState(); if (scheduled_at && !immediate) { @@ -9723,7 +12179,12 @@ app.post("/api/settings/maintenance", async (req, res) => { startMaintenanceChecker(); console.log(`[maintenance] ${state.enabled ? "Enabled" : "Scheduled"} by ${user.email}${state.scheduled_at ? " for " + state.scheduled_at : ""}`); - return res.json({ ok: true, state: { enabled: state.enabled, scheduled_at: state.scheduled_at } }); + return res.json({ + ok: true, + state: { enabled: state.enabled, scheduled_at: state.scheduled_at }, + graceExpiresAt: stepUp.graceExpiresAt || (await getVerifiedSessionRevokeGraceState(req, user))?.expiresAt || 0, + revokeSecurity: await getDestructiveActionSecurityAsync(req, user), + }); }); app.delete("/api/settings/maintenance", async (req, res) => { @@ -9770,8 +12231,8 @@ app.get("/api/settings/sessions", async (req, res) => { const requestedPage = Math.max(1, parseInt(req.query?.page, 10) || 1); try { - const activeSessions = await getCachedActiveBrowserSessions(); - const sortedSessions = [...activeSessions].sort((a, b) => { + const browserSessions = await getBrowserLoginSessionsInventory(); + const sortedSessions = [...browserSessions].sort((a, b) => { const lastSeenDiff = Number(b.lastSeenAt || 0) - Number(a.lastSeenAt || 0); if (lastSeenDiff !== 0) return lastSeenDiff; return Number(b.createdAt || 0) - Number(a.createdAt || 0); @@ -9789,23 +12250,34 @@ app.get("/api/settings/sessions", async (req, res) => { const items = filteredSessions .slice(startIndex, searchActive ? undefined : endIndex) .map((entry) => ({ - sessionId: getSessionDisplayId(entry.sessionId), - displayId: getSessionDisplayId(entry.sessionId), + sessionId: entry.targetType === "remembered" + ? getSessionDisplayId(entry.sessionId) || getRememberLoginDisplayId(entry.rememberLoginId) + : getSessionDisplayId(entry.sessionId), + displayId: entry.targetType === "remembered" + ? getSessionDisplayId(entry.sessionId) || getRememberLoginDisplayId(entry.rememberLoginId) + : getSessionDisplayId(entry.sessionId), + targetType: entry.targetType === "remembered" ? "remembered" : "session", + status: entry.status === "remembered" ? "remembered" : "active", email: entry.email, createdAt: entry.createdAt, lastSeenAt: entry.lastSeenAt, expiresAt: entry.expiresAt, userAgent: entry.userAgent, ip: entry.ip, - isCurrent: entry.sessionId === String(req.sessionID || ""), - revokeToken: issueSessionRevokeTargetToken(req, entry.sessionId), + isCurrent: entry.targetType !== "remembered" && entry.sessionId === String(req.sessionID || ""), + revokeToken: issueSessionRevokeTargetToken(req, entry.targetType === "remembered" + ? { targetType: "remembered", sessionId: entry.sessionId, rememberLoginId: entry.rememberLoginId } + : { targetType: "session", sessionId: entry.sessionId, rememberLoginId: entry.rememberLoginId }), })); - const revokeGrace = getSessionRevokeGraceState(req); + const activeTotal = sortedSessions.filter((entry) => entry.status !== "remembered").length; + const rememberedTotal = sortedSessions.filter((entry) => entry.status === "remembered").length; return res.json({ items, total, + activeTotal, + rememberedTotal, page, pageSize: ACTIVE_BROWSER_SESSION_PAGE_SIZE, totalPages, @@ -9813,17 +12285,13 @@ app.get("/api/settings/sessions", async (req, res) => { searchActive, from: total > 0 ? startIndex + 1 : 0, to: total > 0 ? (searchActive ? total : endIndex) : 0, - revokeSecurity: { - twoFactorEnabled: !!currentUser.secret, - requiresTwoFactor: !revokeGrace, - graceExpiresAt: revokeGrace?.expiresAt || 0, - }, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), actionTokens: { revokeSession: issueActionToken(req, "POST /api/settings/sessions/revoke", {}, { ttlSeconds: 600 }), }, }); } catch (err) { - console.error("[security] Failed to load active browser sessions:", err); + console.error("[security] Failed to load browser sessions:", err); return res.status(500).json({ error: "failed to load sessions" }); } }); @@ -9838,51 +12306,140 @@ app.post("/api/settings/sessions/revoke", sessionRevoke2faRateLimiter, async (re return res.status(403).json({ error: "not authorized" }); } - if (!currentUser.secret) { - return res.status(403).json({ - error: "Enable 2FA before revoking sessions.", - code: "2fa-not-enabled", - }); + const revokeToken = String(req.body?.revokeToken || "").trim(); + const resolvedTarget = resolveSessionRevokeTargetToken(req, revokeToken); + let targetType = resolvedTarget?.targetType === "remembered" ? "remembered" : "session"; + let sessionId = String(resolvedTarget?.sessionId || "").trim(); + let rememberLoginId = String(resolvedTarget?.rememberLoginId || "").trim(); + + if (!resolvedTarget && req.body?.sessionId) { + sessionId = String(req.body.sessionId || "").trim(); + targetType = "session"; } - const revokeToken = String(req.body?.revokeToken || "").trim(); - let sessionId = resolveSessionRevokeTargetToken(req, revokeToken); - if (!sessionId && req.body?.sessionId) { - sessionId = String(req.body.sessionId || "").trim(); - } - if (!sessionId) { + if (targetType === "remembered" && !rememberLoginId) { return res.status(400).json({ error: "Session action expired. Reload Sessions and try again.", code: "session-action-expired", }); } - if (!sessionId || sessionId.length > 255 || !/^[A-Za-z0-9_-]+$/.test(sessionId)) { + + if (targetType !== "remembered" && !sessionId) { + return res.status(400).json({ + error: "Session action expired. Reload Sessions and try again.", + code: "session-action-expired", + }); + } + + if (targetType === "remembered" && !isValidRememberLoginId(rememberLoginId)) { + return res.status(400).json({ error: "Invalid saved login id", code: "invalid-remember-login-id" }); + } + + if (targetType !== "remembered" && !isValidSessionStoreId(sessionId)) { return res.status(400).json({ error: "Invalid session id", code: "invalid-session-id" }); } - const targetDisplayId = getSessionDisplayId(sessionId); - let graceState = getSessionRevokeGraceState(req); - let usedFreshTwoFactor = false; + const targetDisplayId = targetType === "remembered" + ? getRememberLoginDisplayId(rememberLoginId) + : getSessionDisplayId(sessionId); - if (!graceState) { - const twoFactorCode = String(req.body?.twoFactorCode || "").replace(/\s+/g, ""); - if (!/^\d{6}$/.test(twoFactorCode)) { - return res.status(403).json({ error: "A valid 6-digit code is required", code: "2fa-required" }); + const stepUp = await requireDestructiveActionStepUp(req, res, currentUser, `Session revoke "${targetDisplayId}"`); + if (!stepUp.ok) return; + const graceState = await getVerifiedSessionRevokeGraceState(req, currentUser); + + const revokeRememberedTarget = async (targetRememberLoginId, fallbackSessionId = "") => { + const savedLoginId = String(targetRememberLoginId || "").trim(); + if (!isValidRememberLoginId(savedLoginId)) { + return res.status(400).json({ error: "Invalid saved login id", code: "invalid-remember-login-id" }); } - const verified = speakeasy.totp.verify({ - secret: currentUser.secret, - encoding: "base32", - token: twoFactorCode, - window: 1, - }); - - if (!verified) { - console.log(`[SECURITY] Session revoke denied - invalid 2FA | User: ${req.session.user} | IP: ${getRequestIp(req)} | Session: ${targetDisplayId}`); - return res.status(403).json({ error: "Incorrect 2FA code", code: "invalid-2fa" }); + const registryEntry = getRememberLoginRegistryEntry(savedLoginId); + if (!registryEntry) { + clearSessionRevokeTargetToken(req, revokeToken); + invalidateActiveBrowserSessionCache(); + return res.status(404).json({ error: "Saved login not found or already revoked", code: "saved-login-not-found" }); } - usedFreshTwoFactor = true; + const targetEmail = String(registryEntry.email || "").trim().toLowerCase(); + const registrySessionId = String(registryEntry.sid || fallbackSessionId || "").trim(); + const currentRememberLoginId = String(req.session?.rememberLoginId || req.session?.browserSessionAudit?.rememberLoginId || "").trim(); + const revokeCurrentSession = currentRememberLoginId === savedLoginId || registrySessionId === String(req.sessionID || ""); + const displayId = registrySessionId ? getSessionDisplayId(registrySessionId) : getRememberLoginDisplayId(savedLoginId); + let destroyedSession = false; + + try { + revokeRememberLoginRegistryEntry(savedLoginId); + clearSessionRevokeTargetToken(req, revokeToken); + + if (revokeCurrentSession) { + await new Promise((resolve, reject) => { + req.session.destroy((err) => (err ? reject(err) : resolve())); + }); + if (registrySessionId) removeActiveBrowserSessionCacheEntry(registrySessionId); + invalidateActiveBrowserSessionCache(); + res.clearCookie("adpanel.sid", { + httpOnly: true, + sameSite: "lax", + secure: SESSION_COOKIE_SECURE, + path: "/", + }); + clearRememberLoginCookie(res); + + console.log(`[SECURITY] Saved browser login revoked | Admin: ${currentUser.email} | Target: ${targetEmail} | Login: ${getRememberLoginDisplayId(savedLoginId)} | Session: ${displayId || "none"} | Self: yes | IP: ${getRequestIp(req)}`); + return res.json({ + ok: true, + revoked: true, + revokedPersistentLogin: true, + destroyedSession: true, + sessionId: displayId, + displayId, + targetEmail, + revokedCurrentSession: true, + graceExpiresAt: 0, + }); + } + + if (registrySessionId && isValidSessionStoreId(registrySessionId)) { + try { + const storedSession = await callSessionStore("get", registrySessionId); + const storedEmail = String(storedSession?.user || "").trim().toLowerCase(); + const storedRememberLoginId = String(storedSession?.rememberLoginId || storedSession?.browserSessionAudit?.rememberLoginId || "").trim(); + const sameUser = !targetEmail || !storedEmail || storedEmail === targetEmail; + const sameRememberLogin = !storedRememberLoginId || storedRememberLoginId === savedLoginId; + + if (storedSession && sameUser && sameRememberLogin) { + await callSessionStore("destroy", registrySessionId); + removeActiveBrowserSessionCacheEntry(registrySessionId); + destroyedSession = true; + } + } catch (sessionErr) { + console.warn("[security] Saved login revoked but matching session destroy failed:", sessionErr?.message || sessionErr); + } + } + + invalidateActiveBrowserSessionCache(); + const graceExpiresAt = stepUp.graceExpiresAt || graceState?.expiresAt || 0; + + console.log(`[SECURITY] Saved browser login revoked | Admin: ${currentUser.email} | Target: ${targetEmail} | Login: ${getRememberLoginDisplayId(savedLoginId)} | Session: ${displayId || "none"} | Self: no | IP: ${getRequestIp(req)}`); + return res.json({ + ok: true, + revoked: true, + revokedPersistentLogin: true, + destroyedSession, + sessionId: displayId, + displayId, + targetEmail, + revokedCurrentSession: false, + graceExpiresAt: graceExpiresAt || graceState?.expiresAt || 0, + }); + } catch (err) { + console.error("[security] Failed to revoke saved browser login:", err); + return res.status(500).json({ error: "failed to revoke saved login" }); + } + }; + + if (targetType === "remembered") { + return revokeRememberedTarget(rememberLoginId, sessionId); } let targetSession = null; @@ -9894,6 +12451,9 @@ app.post("/api/settings/sessions/revoke", sessionRevoke2faRateLimiter, async (re } if (!targetSession || !targetSession.user) { + if (rememberLoginId) { + return revokeRememberedTarget(rememberLoginId, sessionId); + } clearSessionRevokeTargetToken(req, revokeToken); removeActiveBrowserSessionCacheEntry(sessionId); invalidateActiveBrowserSessionCache(); @@ -9906,7 +12466,12 @@ app.post("/api/settings/sessions/revoke", sessionRevoke2faRateLimiter, async (re rememberLoginId: String(targetSession.rememberLoginId || targetSession.browserSessionAudit?.rememberLoginId || "").trim(), }; const targetEmail = String(targetRecord.email || "").trim().toLowerCase(); - const targetRememberLoginId = String(targetRecord.rememberLoginId || "").trim(); + const targetRememberLoginId = String( + targetRecord.rememberLoginId || + rememberLoginId || + findRememberLoginIdBySessionId(sessionId, targetEmail) || + "" + ).trim(); const isCurrentSession = sessionId === String(req.sessionID || ""); if (targetRememberLoginId) { @@ -9954,17 +12519,7 @@ app.post("/api/settings/sessions/revoke", sessionRevoke2faRateLimiter, async (re removeActiveBrowserSessionCacheEntry(sessionId); invalidateActiveBrowserSessionCache(); - let graceExpiresAt = graceState?.expiresAt || 0; - if (usedFreshTwoFactor) { - graceExpiresAt = setSessionRevokeGrace(req); - try { - await new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve()))); - graceState = getSessionRevokeGraceState(req); - } catch (saveErr) { - console.warn("[security] Failed to persist session revoke 2FA grace window:", saveErr?.message || saveErr); - graceExpiresAt = 0; - } - } + const graceExpiresAt = stepUp.graceExpiresAt || graceState?.expiresAt || 0; console.log(`[SECURITY] Browser session revoked | Admin: ${currentUser.email} | Target: ${targetEmail} | Session: ${targetDisplayId} | Self: no | IP: ${getRequestIp(req)}`); return res.json({ @@ -9999,6 +12554,7 @@ const PROTECTED_FILES = new Set([ "user-access.json", ".env", "store-templates.json", + "Templates", "versions.json", "node_modules", ".git", @@ -10369,7 +12925,7 @@ app.get("/api/settings/panel-info", async (req, res) => { architecture: info.architecture, autoUpdateEnabled: !!info.autoUpdate, actionTokens: { - checkUpdate: issueActionToken(req, "POST /api/settings/panel-update/check", {}, { ttlSeconds: 300 }), + checkUpdate: issueActionToken(req, "POST /api/settings/panel-update/check", {}, { ttlSeconds: 600 }), installUpdate: issueActionToken(req, "POST /api/settings/panel-update/install", {}, { ttlSeconds: 600, oneTime: true }), setAutoUpdate: issueActionToken(req, "POST /api/settings/panel-update/auto", {}, { ttlSeconds: 300 }), }, @@ -10740,6 +13296,94 @@ function startNodeAutoUpdateScheduler() { }, 15000).unref(); } +// --- adpanel:multidisk panel API (admin-only) --- +// Proxies to the node's /v1/disks endpoints. The node remains the source of truth +// and re-validates everything; the panel adds an admin guard, server-side path/limit +// re-validation (defense in depth), and HMAC signing identical to node-update. +function validateDiskMountPathPanel(p) { + const s = String(p || "").trim(); + if (!s) return { ok: false, error: "mount path required" }; + if (!s.startsWith("/")) return { ok: false, error: "mount path must be absolute" }; + if (s.includes("..") || s.includes("\0")) return { ok: false, error: "invalid mount path" }; + if (s.length > 1 && s.endsWith("/")) return { ok: false, error: "mount path must not end with '/'" }; + const denied = ["/", "/var/lib/node", "/etc", "/proc", "/sys", "/dev", "/boot", "/root", "/bin", "/sbin", "/usr", "/lib", "/lib64"]; + for (const d of denied) { + if (s === d || s.startsWith(d + "/")) return { ok: false, error: `mount path ${s} is not allowed` }; + } + return { ok: true, value: s }; +} + +app.get("/api/nodes/:id/disks", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "node not found" }); + const result = await callNodeUpdateApi(node, "/v1/disks", { method: "GET", timeoutMs: 8000 }); + if (result.status !== 200 || !(result.json && result.json.ok)) { + return res.status(502).json({ error: "failed to list disks", detail: result.json?.error || result.error || "" }); + } + const disks = Array.isArray(result.json.disks) ? result.json.disks : []; + disks.sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0)); + return res.json({ disks }); + } catch (err) { + return next(err); + } +}); + +app.post("/api/nodes/:id/disks", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "node not found" }); + const check = validateDiskMountPathPanel(req.body?.mountPath); + if (!check.ok) return res.status(400).json({ error: check.error }); + const limitGb = Number(req.body?.limitGb); + if (!Number.isFinite(limitGb) || limitGb <= 0) { + return res.status(400).json({ error: "limitGb must be a positive number" }); + } + const result = await callNodeUpdateApi(node, "/v1/disks", { + method: "POST", + body: { mountPath: check.value, limitGb: Math.floor(limitGb) }, + timeoutMs: 15000, + action: "disk-add", + subject: check.value, + }); + if (result.status !== 200 || !(result.json && result.json.ok)) { + return res.status(result.status === 0 ? 502 : result.status).json({ + error: result.json?.error || result.error || "failed to add disk", + }); + } + return res.json({ ok: true, disk: result.json.disk }); + } catch (err) { + return next(err); + } +}); + +app.delete("/api/nodes/:id/disks/:diskId", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "node not found" }); + const diskId = String(req.params.diskId || "").trim(); + if (!diskId || diskId === "primary") return res.status(400).json({ error: "cannot remove primary disk" }); + const result = await callNodeUpdateApi(node, "/v1/disks", { + method: "DELETE", + body: { id: diskId }, + timeoutMs: 15000, + action: "disk-remove", + subject: diskId, + }); + if (result.status !== 200 || !(result.json && result.json.ok)) { + return res.status(result.status === 0 ? 502 : result.status).json({ + error: result.json?.error || result.error || "failed to remove disk", + }); + } + return res.json({ ok: true }); + } catch (err) { + return next(err); + } +}); + app.get("/api/settings/node-update/info", async (req, res) => { try { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); @@ -13166,7 +15810,13 @@ async function performAiConsoleCommand(req, serverName, command) { throw new Error(extractAiPanelResultError(result, "Failed to send that console command.")); } - rememberConsoleCommand(serverName, commandCheck.command); + // Remote servers get the command inline from the node's log stream (single + // source of truth); recording it here would duplicate it. Record locally only + // for non-remote servers. + const aiEntry = await findServer(serverName); + if (!isRemoteEntry(aiEntry)) { + rememberConsoleCommand(serverName, commandCheck.command); + } return { ok: true, command: commandCheck.command }; } @@ -13214,6 +15864,17 @@ async function resolveBotToolServerOrError({ accessibleServers, requestedServer, }; } + if (isServerSuspended(resolved.entry)) { + return { + error: { + ok: false, + error: `${resolved.entry.displayName || resolved.entry.name} is suspended.`, + code: "server-suspended", + }, + entry: resolved.entry, + }; + } + const perms = await getEffectivePermsForUserOnServer(userEmail, resolved.entry.name); const missingPerms = requiredPerms.filter((permKey) => !perms?.[permKey]); if (missingPerms.length) { @@ -15057,28 +17718,28 @@ async function executeAiAgentFileOperations({ operations, serverName, userEmail, const full = safeJoinUnix(ctx.baseDir, relPath); if (action === "list") { - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/list", { path: full }, 60000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/list", { path: full, server: ctx.serverName }, 60000); if (status !== 200 || !json?.ok) throw new Error(json?.error || `status ${status}`); summaries.push(`Contents of ${relPath}:\n${summarizeAiAgentDirectory(json.entries)}`); } else if (action === "read") { - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, encoding: "utf8" }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, server: ctx.serverName, encoding: "utf8" }, 120000); if (status !== 200 || !json?.ok) throw new Error(json?.error || `status ${status}`); const content = String(json.content || ""); summaries.push(`Read ${relPath}:\n\`\`\`\n${content.slice(0, AI_AGENT_FILE_READ_MAX_CHARS)}${content.length > AI_AGENT_FILE_READ_MAX_CHARS ? "\n...[truncated]" : ""}\n\`\`\``); } else if (action === "mkdir") { - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/mkdir", { path: full }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/mkdir", { path: full, server: ctx.serverName }, 120000); if (status !== 200 || !json?.ok) throw new Error(json?.error || `status ${status}`); recordActivity(serverName, "ai_agent_file_mkdir", { path: relPath }, userEmail, getRequestIp(req)); summaries.push(`Created folder ${relPath}.`); } else if (action === "create" || action === "write") { const content = String(op.content ?? ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/write", { path: full, content, encoding: "utf8" }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/write", { path: full, server: ctx.serverName, content, encoding: "utf8" }, 120000); if (status === 507 && json?.error === "disk_limit_exceeded") throw new Error(json.message || "disk limit exceeded"); if (status !== 200 || !json?.ok) throw new Error(json?.error || `status ${status}`); recordActivity(serverName, action === "create" ? "ai_agent_file_create" : "ai_agent_file_write", { path: relPath }, userEmail, getRequestIp(req)); summaries.push(`${action === "create" ? "Created" : "Modified"} ${relPath}.`); } else if (action === "delete") { - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/delete", { path: full, isDir: false }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/delete", { path: full, server: ctx.serverName, isDir: false }, 120000); if (status !== 200 || !json?.ok) throw new Error(json?.error || `status ${status}`); recordActivity(serverName, "ai_agent_file_delete", { path: relPath }, userEmail, getRequestIp(req)); summaries.push(`Deleted ${relPath}.`); @@ -17767,11 +20428,22 @@ async function checkServiceRunning(serviceName) { return new Promise((resolve) => { const child = spawn("systemctl", ["is-active", serviceName]); let output = ""; + let settled = false; + const finish = (running) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(!!running); + }; + const timer = setTimeout(() => { + try { child.kill("SIGKILL"); } catch { } + finish(false); + }, 5000); child.stdout.on("data", (d) => { output += d.toString(); }); - child.on("close", (code) => { - resolve(output.trim() === "active"); + child.on("close", () => { + finish(output.trim() === "active"); }); - child.on("error", () => resolve(false)); + child.on("error", () => finish(false)); }); } @@ -18814,6 +21486,7 @@ app.get("/db-open/:service", async (req, res) => { app.get("/api/settings/database", async (req, res) => { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const currentUser = await findUserByEmail(req.session.user); const data = loadDatabaseConfig(); const safeUsers = (data.users || []).map(u => ({ username: u.username, @@ -18825,6 +21498,7 @@ app.get("/api/settings/database", async (req, res) => { disable: issueActionToken(req, "POST /api/settings/database/disable", {}, { ttlSeconds: 120, oneTime: true }), createUser: issueActionToken(req, "POST /api/settings/database/users", {}, { ttlSeconds: 120, oneTime: true }), changeType: issueActionToken(req, "POST /api/settings/database/change-type", {}, { ttlSeconds: 120, oneTime: true }), + verifyInstall: issueActionToken(req, "POST /api/settings/database/verify-install", {}, { ttlSeconds: 600 }), pgadminSetup: issueActionToken(req, "POST /api/settings/database/pgadmin/setup", {}, { ttlSeconds: 120, oneTime: true }), pgadminDisable: issueActionToken(req, "POST /api/settings/database/pgadmin/disable", {}, { ttlSeconds: 120, oneTime: true }), mongodbSetup: issueActionToken(req, "POST /api/settings/database/mongodb/setup", {}, { ttlSeconds: 120, oneTime: true }), @@ -18843,13 +21517,49 @@ app.get("/api/settings/database", async (req, res) => { port: data.config.port } : null, users: safeUsers, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), actionTokens }); }); -app.post("/api/settings/database/setup", async (req, res) => { +app.post("/api/settings/database/verify-install", sessionRevoke2faRateLimiter, async (req, res) => { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + res.set("Cache-Control", "no-store"); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/verify-install")) return; + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } + + const rawService = String(req.body?.service || "database").trim().toLowerCase(); + const serviceLabels = { + phpmyadmin: "phpMyAdmin", + pgadmin: "pgAdmin4", + pgadmin4: "pgAdmin4", + mongodb: "MongoDB", + mongo: "MongoDB", + }; + const serviceLabel = serviceLabels[rawService] || "Database"; + const stepUp = await requireDatabaseInstallStepUp(req, res, currentUser, `${serviceLabel} install verification`); + if (!stepUp.ok) return; + + return res.json({ + ok: true, + graceExpiresAt: stepUp.graceExpiresAt || (await getVerifiedSessionRevokeGraceState(req, currentUser))?.expiresAt || 0, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + }); +}); + +app.post("/api/settings/database/setup", sessionRevoke2faRateLimiter, async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } if (!requireActionTokenOr403(req, res, "POST /api/settings/database/setup")) return; + const stepUp = await requireDatabaseInstallStepUp(req, res, currentUser, "phpMyAdmin setup"); + if (!stepUp.ok) return; const { type, host, port, username, password } = req.body || {}; @@ -19356,9 +22066,15 @@ app.get("/api/settings/database/pgadmin/status", async (req, res) => { }); }); -app.post("/api/settings/database/pgadmin/setup", async (req, res) => { +app.post("/api/settings/database/pgadmin/setup", sessionRevoke2faRateLimiter, async (req, res) => { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } if (!requireActionTokenOr403(req, res, "POST /api/settings/database/pgadmin/setup")) return; + const stepUp = await requireDatabaseInstallStepUp(req, res, currentUser, "pgAdmin4 setup"); + if (!stepUp.ok) return; const { email, password, dbUser, dbHost, dbPort } = req.body || {}; @@ -19573,9 +22289,15 @@ app.get("/api/settings/database/mongodb/status", async (req, res) => { }); }); -app.post("/api/settings/database/mongodb/setup", async (req, res) => { +app.post("/api/settings/database/mongodb/setup", sessionRevoke2faRateLimiter, async (req, res) => { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } if (!requireActionTokenOr403(req, res, "POST /api/settings/database/mongodb/setup")) return; + const stepUp = await requireDatabaseInstallStepUp(req, res, currentUser, "MongoDB setup"); + if (!stepUp.ok) return; const { username, password, host, port } = req.body || {}; @@ -20135,6 +22857,7 @@ app.post("/api/templates/startup-command", async (req, res) => { const startFile = String(template.start || defaultStartFileForTemplate(templateId) || "").trim(); const docker = normalizeTemplateDockerForRuntime(templateId, template.docker, startFile); const adpanelStartup = sanitizeADPanelStartupInput(docker?.adpanelStartup); + const startupDisplay = sanitizeADPanelStartupInput(docker?.startupDisplay); const fallback = normalizeLegacyRuntimeProcessCommandInput( templateId, docker?.command || defaultRuntimeCommandForTemplate(templateId, docker, startFile) @@ -20151,7 +22874,17 @@ app.post("/api/templates/startup-command", async (req, res) => { source: "adpanel-startup", imageRef: image ? `${image}:${tag}` : "", templateManaged: true, - warning: "Startup is managed by the template installer/runtime environment.", + warning: "Startup is managed by this template.", + }); + } + if (startupDisplay) { + return res.json({ + ok: true, + command: startupDisplay, + source: "image-default", + imageRef: image ? `${image}:${tag}` : "", + templateManaged: true, + warning: "Using Docker image default ENTRYPOINT/CMD without overriding it.", }); } if (!image) { @@ -20218,8 +22951,15 @@ app.post("/api/templates/startup-command", async (req, res) => { warning = detail || null; } + const sourceIsImageDefault = source === 'image-default'; + const imageDefaultInspectAvailable = (source === 'image-inspect' || sourceIsImageDefault) && ( + (Array.isArray(inspectEntrypoint) && inspectEntrypoint.length > 0) || + (Array.isArray(inspectCmd) && inspectCmd.length > 0) + ); + if ( - source === 'image-inspect' && + !sourceIsImageDefault && + imageDefaultInspectAvailable && command && (looksLikeWrapperEntrypointOnlyCommand(command, inspectEntrypoint, inspectCmd) || looksLikePathOnlyScriptCommand(command)) ) { @@ -20229,6 +22969,11 @@ app.post("/api/templates/startup-command", async (req, res) => { warning = warning ? `${warning}; inspect returned wrapper/path-only command` : 'inspect returned wrapper/path-only command'; + } else { + source = 'image-default'; + warning = warning + ? `${warning}; using Docker image default ENTRYPOINT/CMD without overriding it` + : 'Using Docker image default ENTRYPOINT/CMD without overriding it.'; } } @@ -20238,6 +22983,36 @@ app.post("/api/templates/startup-command", async (req, res) => { } const commandError = validateRuntimeProcessCommandInput(command); + if (sourceIsImageDefault && imageDefaultInspectAvailable) { + return res.json({ + ok: true, + command: String(command || "").trim(), + source: "image-default", + imageRef: `${image}:${tag}`, + warning: warning || "Using Docker image default ENTRYPOINT/CMD without overriding it.", + inspect: { + entrypoint: inspectEntrypoint, + cmd: inspectCmd, + workingDir: inspectWorkingDir || '/', + env: inspectEnv, + }, + }); + } + if ((!command || commandError) && imageDefaultInspectAvailable) { + return res.json({ + ok: true, + command: String(command || "").trim(), + source: "image-default", + imageRef: `${image}:${tag}`, + warning: warning || "Using Docker image default ENTRYPOINT/CMD without overriding it.", + inspect: { + entrypoint: inspectEntrypoint, + cmd: inspectCmd, + workingDir: inspectWorkingDir || '/', + env: inspectEnv, + }, + }); + } if (!command || commandError) { return res.status(502).json({ error: commandError || "failed to infer startup command", @@ -20279,36 +23054,497 @@ app.get("/api/settings/templates", async (req, res) => { return res.json({ templates, total, page, totalPages }); }); +function sanitizeTemplateImageUrl(value) { + const raw = String(value || "").trim(); + if (!raw) return ""; + if (raw.length > 2048 || /[\x00-\x1f"\\]/.test(raw)) return ""; + if (raw.startsWith("/") && !raw.startsWith("//")) { + if (raw.includes("..")) return ""; + return raw; + } + try { + const parsed = new URL(raw); + if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return ""; + return parsed.href; + } catch { + return ""; + } +} + +const TEMPLATE_STORE_CACHE_DIR = path.join(__dirname, "Templates"); +const TEMPLATE_STORE_MANIFEST_FILE = path.join(TEMPLATE_STORE_CACHE_DIR, "manifest.json"); +const TEMPLATE_STORE_LOCAL_OVERRIDE_DIR = path.join(__dirname, "github"); +const TEMPLATE_STORE_REPO = String(process.env.ADPANEL_TEMPLATE_STORE_REPO || "antonndev/ADTemplates").trim(); +const TEMPLATE_STORE_REF = String(process.env.ADPANEL_TEMPLATE_STORE_REF || "main").trim(); +const TEMPLATE_STORE_SYNC_INTERVAL_MS = Math.max( + 5 * 60 * 1000, + parseInt(process.env.ADPANEL_TEMPLATE_STORE_SYNC_MS || "", 10) || 60 * 60 * 1000 +); +const TEMPLATE_STORE_FILE_MAX_BYTES = Math.max( + 32 * 1024, + parseInt(process.env.ADPANEL_TEMPLATE_STORE_FILE_MAX_BYTES || "", 10) || 512 * 1024 +); +const TEMPLATE_STORE_CATEGORIES = [ + { id: "games", label: "Games" }, + { id: "communication", label: "Communication" }, + { id: "development", label: "Development" }, + { id: "hosting", label: "Hosting" }, + { id: "media", label: "Media" }, +]; +const TEMPLATE_STORE_CATEGORY_IDS = new Set(TEMPLATE_STORE_CATEGORIES.map((category) => category.id)); +let templateStoreSyncPromise = null; +let templateStoreLastSyncError = ""; + +function safeTemplateStoreCategoryId(value) { + const clean = String(value || "").trim().toLowerCase(); + return TEMPLATE_STORE_CATEGORY_IDS.has(clean) ? clean : ""; +} + +function safeTemplateStoreFileName(value) { + const name = path.basename(String(value || "").trim()); + if (!/^[a-z0-9][a-z0-9._-]*\.json$/i.test(name)) return ""; + return name; +} + +function templateStoreLocalOverrideDirs(category) { + const candidates = [ + category?.id, + category?.label, + String(category?.label || "").replace(/\s+/g, "-").toLowerCase(), + ].filter(Boolean); + return [...new Set(candidates)].map((name) => path.join(TEMPLATE_STORE_LOCAL_OVERRIDE_DIR, name)); +} + +async function readTemplateStoreLocalOverrides(category) { + const overrides = []; + const seen = new Set(); + for (const dir of templateStoreLocalOverrideDirs(category)) { + let names = []; + try { + names = await fsp.readdir(dir); + } catch { + continue; + } + for (const rawName of names) { + const fileName = safeTemplateStoreFileName(rawName); + if (!fileName || seen.has(fileName)) continue; + seen.add(fileName); + const localPath = path.join(dir, fileName); + try { + const raw = await fsp.readFile(localPath, "utf8"); + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== "object") throw new Error("Template JSON must be an object or array"); + const normalizedPayload = Array.isArray(parsed) + ? parsed.map((item) => normalizeTemplateDefinition(item)) + : normalizeTemplateDefinition(parsed); + const prettyRaw = `${JSON.stringify(normalizedPayload, null, 2)}\n`; + overrides.push({ + fileName, + raw: prettyRaw, + hash: crypto.createHash("sha256").update(prettyRaw).digest("hex"), + }); + } catch (err) { + console.warn(`[template-store] Ignoring invalid local override ${localPath}:`, err?.message || err); + } + } + } + return overrides; +} + +function templateStoreGithubBlobUrl(repo, ref, relPath) { + return `https://github.com/${repo}/blob/${encodeURIComponent(ref)}/${String(relPath || "").split("/").map(encodeURIComponent).join("/")}`; +} + +function templateStoreJsdelivrRawUrl(repo, ref, relPath) { + return `https://cdn.jsdelivr.net/gh/${repo}@${encodeURIComponent(ref)}/${String(relPath || "").split("/").map(encodeURIComponent).join("/")}`; +} + +async function writeFileAtomic(targetPath, content) { + await fsp.mkdir(path.dirname(targetPath), { recursive: true }); + const tempPath = `${targetPath}.${process.pid}.${Date.now()}.tmp`; + await fsp.writeFile(tempPath, content, "utf8"); + await fsp.rename(tempPath, targetPath); +} + +async function readTemplateStoreManifest() { + try { + const raw = await fsp.readFile(TEMPLATE_STORE_MANIFEST_FILE, "utf8"); + const parsed = JSON.parse(raw); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null; + } catch { + return null; + } +} + +async function templateStoreHasCachedFiles() { + for (const category of TEMPLATE_STORE_CATEGORIES) { + try { + const names = await fsp.readdir(path.join(TEMPLATE_STORE_CACHE_DIR, category.id)); + if (names.some((name) => /\.json$/i.test(name))) return true; + } catch { } + } + return false; +} + +function normalizeTemplateStoreFlatFile(file) { + const rawName = String(file?.name || file?.path || "").trim().replace(/^\/+/, ""); + const parts = rawName.split("/").filter(Boolean); + if (parts.length !== 2) return null; + const categoryId = safeTemplateStoreCategoryId(parts[0]); + const fileName = safeTemplateStoreFileName(parts[1]); + if (!categoryId || !fileName) return null; + return { + categoryId, + fileName, + relPath: `${categoryId}/${fileName}`, + hash: typeof file?.hash === "string" ? file.hash : "", + size: Number.isFinite(Number(file?.size)) ? Number(file.size) : 0, + }; +} + +async function fetchTemplateStoreFileRaw(relPath) { + const rawUrl = `https://raw.githubusercontent.com/${TEMPLATE_STORE_REPO}/${encodeURIComponent(TEMPLATE_STORE_REF)}/${String(relPath).split("/").map(encodeURIComponent).join("/")}`; + try { + const buf = await httpGetRaw(rawUrl, { maxBytes: TEMPLATE_STORE_FILE_MAX_BYTES, timeoutMs: 15000, maxRedirects: 3 }); + return { raw: buf.toString("utf8"), source: "github-raw", url: rawUrl }; + } catch (githubErr) { + const cdnUrl = templateStoreJsdelivrRawUrl(TEMPLATE_STORE_REPO, TEMPLATE_STORE_REF, relPath); + const buf = await httpGetRaw(cdnUrl, { maxBytes: TEMPLATE_STORE_FILE_MAX_BYTES, timeoutMs: 15000, maxRedirects: 3 }); + return { raw: buf.toString("utf8"), source: "jsdelivr", url: cdnUrl, fallbackReason: githubErr?.message || "" }; + } +} + +async function listTemplateStoreFilesFromJsdelivr() { + const flatUrl = `https://data.jsdelivr.com/v1/package/gh/${TEMPLATE_STORE_REPO}@${encodeURIComponent(TEMPLATE_STORE_REF)}/flat`; + const result = await httpRequestJson(flatUrl, "GET", { + Accept: "application/json", + "User-Agent": "ADPanel/1.0", + }, null, 15000); + if (result.status < 200 || result.status >= 300 || !result.json || !Array.isArray(result.json.files)) { + throw new Error(`jsDelivr returned ${result.status || "invalid response"}`); + } + return result.json.files.map(normalizeTemplateStoreFlatFile).filter(Boolean); +} + +async function listTemplateStoreFilesFromGithub() { + const treeUrl = `https://api.github.com/repos/${TEMPLATE_STORE_REPO}/git/trees/${encodeURIComponent(TEMPLATE_STORE_REF)}?recursive=1`; + const headers = { + Accept: "application/vnd.github+json", + "User-Agent": "ADPanel/1.0", + }; + const githubToken = String(process.env.ADPANEL_TEMPLATE_STORE_GITHUB_TOKEN || process.env.GITHUB_TOKEN || "").trim(); + if (githubToken) headers.Authorization = `Bearer ${githubToken}`; + const result = await httpRequestJson(treeUrl, "GET", headers, null, 15000); + if (result.status < 200 || result.status >= 300 || !result.json || !Array.isArray(result.json.tree)) { + throw new Error(`GitHub returned ${result.status || "invalid response"}`); + } + return result.json.tree + .filter((entry) => entry && entry.type === "blob" && /\.json$/i.test(String(entry.path || ""))) + .map((entry) => normalizeTemplateStoreFlatFile({ + name: entry.path, + hash: entry.sha || "", + size: entry.size || 0, + })) + .filter(Boolean); +} + +async function listTemplateStoreRemoteFiles() { + try { + return { files: await listTemplateStoreFilesFromGithub(), source: "github" }; + } catch (githubErr) { + const fallback = await listTemplateStoreFilesFromJsdelivr(); + return { files: fallback, source: "jsdelivr", fallbackReason: githubErr?.message || "" }; + } +} + +async function pruneTemplateStoreCategory(categoryId, keepNames) { + const dir = path.join(TEMPLATE_STORE_CACHE_DIR, categoryId); + try { + const names = await fsp.readdir(dir); + await Promise.all(names + .filter((name) => /\.json$/i.test(name) && !keepNames.has(name)) + .map((name) => fsp.unlink(path.join(dir, name)).catch(() => { }))); + } catch { } +} + +async function syncTemplateStoreCache(reason = "scheduled") { + if (templateStoreSyncPromise) return templateStoreSyncPromise; + + templateStoreSyncPromise = (async () => { + await fsp.mkdir(TEMPLATE_STORE_CACHE_DIR, { recursive: true }); + for (const category of TEMPLATE_STORE_CATEGORIES) { + await fsp.mkdir(path.join(TEMPLATE_STORE_CACHE_DIR, category.id), { recursive: true }); + } + + const startedAt = new Date().toISOString(); + const remote = await listTemplateStoreRemoteFiles(); + const byCategory = new Map(); + for (const category of TEMPLATE_STORE_CATEGORIES) byCategory.set(category.id, []); + for (const file of remote.files) { + if (byCategory.has(file.categoryId)) byCategory.get(file.categoryId).push(file); + } + + const manifestCategories = {}; + let totalFiles = 0; + let syncedFiles = 0; + + for (const category of TEMPLATE_STORE_CATEGORIES) { + const files = (byCategory.get(category.id) || []).sort((a, b) => a.fileName.localeCompare(b.fileName, undefined, { numeric: true })); + const keepNames = new Set(); + const manifestFiles = []; + + for (const file of files) { + keepNames.add(file.fileName); + totalFiles += 1; + try { + const fetched = await fetchTemplateStoreFileRaw(file.relPath); + const parsed = JSON.parse(fetched.raw); + if (!parsed || typeof parsed !== "object") throw new Error("Template JSON must be an object or array"); + const normalizedPayload = Array.isArray(parsed) + ? parsed.map((item) => normalizeTemplateDefinition(item)) + : normalizeTemplateDefinition(parsed); + const prettyRaw = `${JSON.stringify(normalizedPayload, null, 2)}\n`; + const localPath = path.join(TEMPLATE_STORE_CACHE_DIR, category.id, file.fileName); + await writeFileAtomic(localPath, prettyRaw); + syncedFiles += 1; + manifestFiles.push({ + name: file.fileName, + path: file.relPath, + category: category.id, + hash: file.hash, + size: Buffer.byteLength(prettyRaw), + source: fetched.source, + url: fetched.url, + html_url: templateStoreGithubBlobUrl(TEMPLATE_STORE_REPO, TEMPLATE_STORE_REF, file.relPath), + download_url: templateStoreJsdelivrRawUrl(TEMPLATE_STORE_REPO, TEMPLATE_STORE_REF, file.relPath), + }); + } catch (err) { + console.warn(`[template-store] Failed to cache ${file.relPath}:`, err?.message || err); + } + } + + const localOverrides = await readTemplateStoreLocalOverrides(category); + for (const override of localOverrides) { + keepNames.add(override.fileName); + totalFiles += 1; + const relPath = `${category.id}/${override.fileName}`; + const localPath = path.join(TEMPLATE_STORE_CACHE_DIR, category.id, override.fileName); + await writeFileAtomic(localPath, override.raw); + syncedFiles += 1; + const meta = { + name: override.fileName, + path: relPath, + category: category.id, + hash: override.hash, + size: Buffer.byteLength(override.raw), + source: "local-override", + url: "", + html_url: "", + download_url: "", + }; + const existingIndex = manifestFiles.findIndex((item) => item.name === override.fileName); + if (existingIndex >= 0) manifestFiles[existingIndex] = meta; + else manifestFiles.push(meta); + } + manifestFiles.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true })); + await pruneTemplateStoreCategory(category.id, keepNames); + manifestCategories[category.id] = { + ...category, + count: manifestFiles.length, + files: manifestFiles, + }; + } + + const manifest = { + version: 1, + repo: TEMPLATE_STORE_REPO, + ref: TEMPLATE_STORE_REF, + source: remote.source, + fallbackReason: remote.fallbackReason || "", + reason, + startedAt, + syncedAt: new Date().toISOString(), + syncIntervalMs: TEMPLATE_STORE_SYNC_INTERVAL_MS, + totalFiles, + syncedFiles, + categories: manifestCategories, + }; + + await writeFileAtomic(TEMPLATE_STORE_MANIFEST_FILE, `${JSON.stringify(manifest, null, 2)}\n`); + templateStoreLastSyncError = ""; + console.log(`[template-store] Cached ${syncedFiles}/${totalFiles} templates from ${remote.source}.`); + return manifest; + })().catch(async (err) => { + templateStoreLastSyncError = err?.message || String(err); + console.warn("[template-store] Sync failed:", templateStoreLastSyncError); + const manifest = await readTemplateStoreManifest(); + if (manifest) return manifest; + throw err; + }).finally(() => { + templateStoreSyncPromise = null; + }); + + return templateStoreSyncPromise; +} + +async function ensureTemplateStoreCacheFresh({ waitForFirstSync = true, force = false } = {}) { + const manifest = await readTemplateStoreManifest(); + const hasCache = await templateStoreHasCachedFiles(); + const lastSync = Date.parse(manifest?.syncedAt || "") || 0; + const stale = !lastSync || (Date.now() - lastSync) >= TEMPLATE_STORE_SYNC_INTERVAL_MS; + + if (force || !hasCache) { + return syncTemplateStoreCache(force ? "manual" : "first-load"); + } + if (stale && !templateStoreSyncPromise) { + syncTemplateStoreCache("stale-refresh").catch(() => { }); + } + if (waitForFirstSync && !manifest && templateStoreSyncPromise) { + return templateStoreSyncPromise; + } + return manifest; +} + +async function readTemplateStoreCategoryFromCache(categoryId) { + const category = TEMPLATE_STORE_CATEGORIES.find((item) => item.id === categoryId); + if (!category) return null; + + await ensureTemplateStoreCacheFresh({ waitForFirstSync: true }); + const manifest = await readTemplateStoreManifest(); + const manifestFiles = new Map((manifest?.categories?.[categoryId]?.files || []).map((file) => [file.name, file])); + const dir = path.join(TEMPLATE_STORE_CACHE_DIR, categoryId); + let names = []; + try { + names = await fsp.readdir(dir); + } catch { } + + const files = []; + for (const name of names.filter((item) => safeTemplateStoreFileName(item)).sort((a, b) => a.localeCompare(b, undefined, { numeric: true }))) { + try { + const raw = await fsp.readFile(path.join(dir, name), "utf8"); + const payload = JSON.parse(raw); + const relPath = `${categoryId}/${name}`; + const meta = manifestFiles.get(name) || {}; + files.push({ + name, + path: relPath, + type: "file", + html_url: meta.html_url || templateStoreGithubBlobUrl(TEMPLATE_STORE_REPO, TEMPLATE_STORE_REF, relPath), + download_url: meta.download_url || templateStoreJsdelivrRawUrl(TEMPLATE_STORE_REPO, TEMPLATE_STORE_REF, relPath), + source: meta.source || "cache", + payload, + }); + } catch (err) { + console.warn(`[template-store] Ignoring invalid cached template ${categoryId}/${name}:`, err?.message || err); + } + } + + return { + category, + files, + cache: { + repo: TEMPLATE_STORE_REPO, + ref: TEMPLATE_STORE_REF, + syncedAt: manifest?.syncedAt || null, + stale: !manifest?.syncedAt || ((Date.now() - (Date.parse(manifest.syncedAt) || 0)) >= TEMPLATE_STORE_SYNC_INTERVAL_MS), + syncing: !!templateStoreSyncPromise, + error: templateStoreLastSyncError || "", + source: manifest?.source || "cache", + }, + }; +} + +function scheduleTemplateStoreSync() { + setTimeout(() => { + syncTemplateStoreCache("startup").catch(() => { }); + }, 2500).unref?.(); + setInterval(() => { + syncTemplateStoreCache("scheduled").catch(() => { }); + }, TEMPLATE_STORE_SYNC_INTERVAL_MS).unref?.(); +} + +scheduleTemplateStoreSync(); + +app.get("/api/settings/template-store/categories", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const manifest = await ensureTemplateStoreCacheFresh({ waitForFirstSync: false }); + const categories = TEMPLATE_STORE_CATEGORIES.map((category) => ({ + ...category, + count: Number(manifest?.categories?.[category.id]?.count || 0), + })); + return res.json({ + ok: true, + categories, + cache: { + repo: TEMPLATE_STORE_REPO, + ref: TEMPLATE_STORE_REF, + syncedAt: manifest?.syncedAt || null, + syncing: !!templateStoreSyncPromise, + error: templateStoreLastSyncError || "", + source: manifest?.source || "cache", + }, + }); +}); + +app.post("/api/settings/template-store/sync", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + try { + const manifest = await ensureTemplateStoreCacheFresh({ force: true }); + return res.json({ ok: true, manifest }); + } catch (err) { + return res.status(502).json({ error: err?.message || "template store sync failed" }); + } +}); + +app.get("/api/settings/template-store/:category", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const categoryId = safeTemplateStoreCategoryId(req.params.category); + if (!categoryId) return res.status(404).json({ error: "unknown category" }); + try { + const data = await readTemplateStoreCategoryFromCache(categoryId); + return res.json({ ok: true, ...data }); + } catch (err) { + return res.status(502).json({ error: err?.message || "template store cache unavailable" }); + } +}); + app.post("/api/settings/templates", async (req, res) => { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const body = (req.body && typeof req.body === "object" && !Array.isArray(req.body)) ? req.body : {}; + const sourceDocker = (body.docker && typeof body.docker === "object" && !Array.isArray(body.docker)) ? body.docker : {}; + const hasBodyField = (field) => Object.prototype.hasOwnProperty.call(body, field); const { - id, - name, + id = body.template_id, + name = body.template_name, description, - dockerImage, - dockerTag, - templateImage, - defaultPort, - ports, - volumes, - env, + dockerImage = body.docker_image || sourceDocker.image, + dockerTag = body.docker_tag || sourceDocker.tag, + templateImage = body.template_image || body.image, + defaultPort = body.default_port, + ports = sourceDocker.ports, + volumes = sourceDocker.volumes, + env = sourceDocker.env, command, startup, - startupCommand, - adpanelStartup, - install, - installation, - dockerWorkdir, + startupCommand = body.startup_command, + adpanelStartup = body.adpanel_startup || body.pterodactylStartup || body.pterodactyl_startup || sourceDocker.adpanelStartup || sourceDocker.adpanel_startup || sourceDocker.pterodactylStartup || sourceDocker.pterodactyl_startup, + install = sourceDocker.install, + installation = sourceDocker.installation, + dockerWorkdir = sourceDocker.workdir || sourceDocker.workingDir || sourceDocker.working_dir, workdir, - } = req.body || {}; + } = body; const cleanId = String(id || "").trim().toLowerCase(); const cleanName = String(name || "").trim(); const cleanDesc = String(description || "").trim(); const cleanImage = String(dockerImage || "").trim(); const cleanTag = String(dockerTag || "latest").trim() || "latest"; - const cleanTemplateImage = String(templateImage || "").trim(); - const cleanCommand = normalizeLegacyRuntimeProcessCommandInput(cleanId, command || startup); + const rawTemplateImage = String(templateImage || "").trim(); + const cleanTemplateImage = sanitizeTemplateImageUrl(rawTemplateImage); + const commandInput = hasBodyField("command") + ? command + : (sourceDocker.command || startup); + const cleanCommand = normalizeLegacyRuntimeProcessCommandInput(cleanId, commandInput); const cleanStartupCommand = String(startupCommand || "").trim(); const cleanADPanelStartup = sanitizeADPanelStartupInput(adpanelStartup); const cleanInstall = sanitizeDockerInstallPayload(install || installation); @@ -20318,6 +23554,7 @@ app.post("/api/settings/templates", async (req, res) => { if (!cleanId || !/^[a-z0-9_-]{2,60}$/.test(cleanId)) return res.status(400).json({ error: "invalid id" }); if (!cleanName) return res.status(400).json({ error: "missing name" }); if (!cleanImage) return res.status(400).json({ error: "missing docker image" }); + if (rawTemplateImage && !cleanTemplateImage) return res.status(400).json({ error: "invalid template image url" }); if (rawWorkdir && !cleanWorkdir) return res.status(400).json({ error: "invalid workdir (must be an absolute path like /app)" }); if (cleanStartupCommand) { return res.status(400).json({ error: "Raw Docker startup commands are no longer supported. Configure image, ports, volumes, env, and the in-container command instead." }); @@ -20332,6 +23569,9 @@ app.post("/api/settings/templates", async (req, res) => { const cleanPorts = validatePortListInput(ports); if (cleanPorts === null) return res.status(400).json({ error: "invalid ports" }); + const rawPortProtocols = sourceDocker.portProtocols || sourceDocker.port_protocols || sourceDocker.protocols || body.portProtocols || body.port_protocols; + const cleanPortProtocols = sanitizePortProtocolPayload(rawPortProtocols, cleanPorts) || {}; + let cleanVolumes = cleanWorkdir ? [defaultTemplateBotDirVolumeForWorkdir(cleanWorkdir)] : []; if (Array.isArray(volumes) && volumes.length > 0) { cleanVolumes = volumes.map(v => String(v).trim()).filter(Boolean); @@ -20352,14 +23592,15 @@ app.post("/api/settings/templates", async (req, res) => { image: cleanImage, tag: cleanTag, ports: cleanPorts, + ...(Object.keys(cleanPortProtocols).length ? { portProtocols: cleanPortProtocols } : {}), volumes: cleanVolumes, ...(cleanWorkdir ? { workdir: cleanWorkdir } : {}), env: cleanEnv, - ...(cleanCommand ? { command: cleanCommand } : {}), + ...(cleanCommand && !cleanADPanelStartup ? { command: cleanCommand } : {}), ...(cleanADPanelStartup ? { adpanelStartup: cleanADPanelStartup } : {}), ...(cleanInstall ? { install: cleanInstall } : {}), restart: "unless-stopped", - console: { type: "stdin" }, + console: normalizeTemplateConsoleForRuntime(cleanId, sourceDocker.console, cleanImage), }, }; @@ -20413,9 +23654,10 @@ app.put("/api/settings/templates/:id", async (req, res) => { const cleanTag = String(dockerTag || currentDocker.tag || "latest").trim() || "latest"; const hasTemplateImage = Object.prototype.hasOwnProperty.call(body, "templateImage"); - const cleanTemplateImage = hasTemplateImage + const rawTemplateImage = hasTemplateImage ? String(templateImage || "").trim() : String(current.templateImage || "").trim(); + const cleanTemplateImage = sanitizeTemplateImageUrl(rawTemplateImage); const hasCommandInput = Object.prototype.hasOwnProperty.call(body, "command") || Object.prototype.hasOwnProperty.call(body, "startup"); @@ -20445,6 +23687,7 @@ app.put("/api/settings/templates/:id", async (req, res) => { if (!cleanName) return res.status(400).json({ error: "missing name" }); if (!cleanImage) return res.status(400).json({ error: "missing docker image" }); + if (rawTemplateImage && !cleanTemplateImage) return res.status(400).json({ error: "invalid template image url" }); if (rawWorkdir && !cleanWorkdir) return res.status(400).json({ error: "invalid workdir (must be an absolute path like /app)" }); if (cleanStartupCommand) { return res.status(400).json({ error: "Raw Docker startup commands are no longer supported. Configure image, ports, volumes, env, and the in-container command instead." }); @@ -20456,6 +23699,14 @@ app.put("/api/settings/templates/:id", async (req, res) => { const cleanPorts = validatePortListInput(hasPortsInput ? ports : currentDocker.ports); if (cleanPorts === null) return res.status(400).json({ error: "invalid ports" }); + const hasPortProtocolsInput = Object.prototype.hasOwnProperty.call(body, "portProtocols") + || Object.prototype.hasOwnProperty.call(body, "port_protocols") + || Object.prototype.hasOwnProperty.call(body, "protocols"); + const rawPortProtocols = hasPortProtocolsInput + ? (body.portProtocols || body.port_protocols || body.protocols) + : (currentDocker.portProtocols || currentDocker.port_protocols || currentDocker.protocols); + const cleanPortProtocols = sanitizePortProtocolPayload(rawPortProtocols, cleanPorts) || {}; + let cleanVolumes = cleanWorkdir ? [defaultTemplateBotDirVolumeForWorkdir(cleanWorkdir)] : []; const workdirChanged = normalizeRuntimeWorkdirInput(currentDocker.workdir || "") !== cleanWorkdir; const autoAlignCurrentBotDirVolume = shouldAutoAlignBotDirVolume(currentDocker.volumes); @@ -20479,14 +23730,18 @@ app.put("/api/settings/templates/:id", async (req, res) => { if (env && typeof env === "object" && !Array.isArray(env)) { for (const [k, v] of Object.entries(env)) { if (k && typeof k === "string") { - cleanEnv[k.trim()] = String(v ?? ""); + const envKey = k.trim(); + if (!envKey || POLLUTION_KEYS.has(envKey)) continue; + cleanEnv[envKey] = String(v ?? ""); } } } } else if (currentDocker.env && typeof currentDocker.env === "object" && !Array.isArray(currentDocker.env)) { for (const [k, v] of Object.entries(currentDocker.env)) { if (k && typeof k === "string") { - cleanEnv[k.trim()] = String(v ?? ""); + const envKey = k.trim(); + if (!envKey || POLLUTION_KEYS.has(envKey)) continue; + cleanEnv[envKey] = String(v ?? ""); } } } @@ -20506,14 +23761,15 @@ app.put("/api/settings/templates/:id", async (req, res) => { image: cleanImage, tag: cleanTag, ports: cleanPorts, + ...(Object.keys(cleanPortProtocols).length ? { portProtocols: cleanPortProtocols } : {}), volumes: cleanVolumes, ...(cleanWorkdir ? { workdir: cleanWorkdir } : {}), env: cleanEnv, - ...(cleanCommand ? { command: cleanCommand } : {}), + ...(cleanCommand && !cleanADPanelStartup ? { command: cleanCommand } : {}), ...(cleanADPanelStartup ? { adpanelStartup: cleanADPanelStartup } : {}), ...(cleanInstall ? { install: cleanInstall } : {}), restart: "unless-stopped", - console: { type: "stdin" }, + console: normalizeTemplateConsoleForRuntime(cleanId, sourceDocker.console || currentDocker.console, cleanImage), }, }; @@ -20548,10 +23804,21 @@ const SERVER_START = Date.now(); app.get("/", async (req, res) => { try { - const serverIndex = await loadServersIndex(); const email = req.session?.user || null; - const userObj = email ? await findUserByEmail(email) : null; - const safeUser = userObj ? { email: userObj.email, admin: !!userObj.admin, avatar_url: userObj.avatar_url || null } : null; + if (!email) { + return res.redirect(303, "/login"); + } + + const userObj = await findUserByEmail(email); + if (!userObj) { + if (req.session?.destroy) { + return req.session.destroy(() => res.redirect(303, "/login")); + } + return res.redirect(303, "/login"); + } + + const serverIndex = await loadServersIndex(); + const safeUser = { email: userObj.email, admin: !!userObj.admin, avatar_url: userObj.avatar_url || null }; const allNames = serverIndex.map(e => e && e.name).filter(Boolean); @@ -20559,7 +23826,12 @@ app.get("/", async (req, res) => { if (safeUser && safeUser.admin) { botsToShow = allNames; } else { - const access = email ? await getAccessListForEmail(email) : []; + const access = email + ? await withTimeout(Promise.resolve().then(() => getAccessListForEmail(email)), 5000, "dashboard-access-timeout").catch((err) => { + console.warn("[dashboard] Access list lookup timed out:", err?.message || err); + return []; + }) + : []; botsToShow = access.includes("all") ? allNames : allNames.filter(n => access.includes(n)); } @@ -20578,11 +23850,22 @@ app.get("/", async (req, res) => { const dashPage = Math.min(Math.max(parseInt(req.query.page, 10) || 1, 1), dashTotalPages); botsToShow = botsToShow.slice((dashPage - 1) * dashLimit, dashPage * dashLimit); - const { results: cachedStatuses } = await getAllCachedServerStatusesLenient(botsToShow); + const statusPayload = await withTimeout( + getAllCachedServerStatusesLenient(botsToShow), + 1500, + "dashboard-status-cache-timeout" + ).catch((err) => { + console.warn("[dashboard] Status cache lookup timed out; rendering without live metrics:", err?.message || err); + return { results: new Map() }; + }); + const cachedStatuses = statusPayload?.results instanceof Map ? statusPayload.results : new Map(); const templates = loadTemplatesFile() || []; const templateMap = new Map(templates.filter(Boolean).map(t => [normalizeTemplateId(t.id), t])); - const nodes = await loadNodes(); + const nodes = await withTimeout(Promise.resolve().then(() => loadNodes()), 1500, "dashboard-nodes-timeout").catch((err) => { + console.warn("[dashboard] Node list lookup timed out; rendering without node names:", err?.message || err); + return []; + }); const nodeMap = new Map(nodes.map(n => [n.uuid || n.id || n.name, n])); const serverMap = new Map(serverIndex.filter(e => e && e.name).map(e => [e.name, e])); @@ -20649,10 +23932,134 @@ app.get("/", async (req, res) => { } }); +const requireAdminForStatusPage = async (req, res, next) => { + try { + const email = req.session?.user || null; + if (!email) { + return res.redirect(303, "/login"); + } + + const userObj = await findUserByEmail(email); + if (!userObj) { + if (req.session?.destroy) { + return req.session.destroy(() => res.redirect(303, "/login")); + } + return res.redirect(303, "/login"); + } + + if (!userObj.admin) { + console.warn(`[status] Forbidden access attempt by non-admin user: ${userObj.email}`); + res.set("Content-Type", "text/html; charset=utf-8"); + return res.status(403).send( + `403 Forbidden` + + `` + + `
403

Admin only

` + + `

The status page is restricted to administrators. You'll be redirected back shortly.

` + + `

Return to dashboard

` + ); + } + + req.statusPageUser = { email: userObj.email, admin: !!userObj.admin, avatar_url: userObj.avatar_url || null }; + return next(); + } catch (err) { + console.error("[status] Auth check failed:", err); + return res.status(500).send("Internal error"); + } +}; + +app.get("/status", requireAdminForStatusPage, async (req, res) => { + try { + const safeUser = req.statusPageUser; + const serverIndex = await loadServersIndex(); + const brandingConfig = loadBrandingConfig(); + + const allNames = serverIndex.map(e => e && e.name).filter(Boolean); + const visibleNames = allNames; + + return res.render("status", { + bots: visibleNames.map(name => ({ name })), + isAdmin: true, + user: safeUser, + serverStartTime: SERVER_START, + globalAlert: getActiveGlobalAlert(), + quickActions: loadQuickActions().admin, + avatarUrl: resolveUserAvatarUrl(safeUser), + branding: brandingConfig || {}, + panelVersion: (typeof PANEL_VERSION !== "undefined" && PANEL_VERSION) || null + }); + } catch (err) { + console.error("Error in GET /status", err); + return res.status(500).send("Internal error"); + } +}); + +// Admin-only monitoring history (RRD-style, one row per minute). Used by the +// /status page to render the per-day graph. Validated with the same isAdmin +// check used everywhere else; non-admins get a hard 403 and can never read it. +app.get("/api/status/metrics/day", async (req, res) => { + if (!(await isAdmin(req))) { + return res.status(403).json({ error: "Admin access required" }); + } + try { + const day = String(req.query.day || "").trim(); + let target = day; + if (!/^\d{4}-\d{2}-\d{2}$/.test(target)) { + target = new Date().toISOString().slice(0, 10); + } + const points = panelMetrics ? await panelMetrics.getHistoryForDay(target) : []; + return res.json({ ok: true, day: target, points }); + } catch (err) { + console.error("Error in GET /api/status/metrics/day", err); + return res.status(500).json({ error: "internal error" }); + } +}); + +app.get("/api/status/metrics/summary", async (req, res) => { + if (!(await isAdmin(req))) { + return res.status(403).json({ error: "Admin access required" }); + } + try { + const days = panelMetrics ? await panelMetrics.getDailySummary() : []; + return res.json({ ok: true, days }); + } catch (err) { + console.error("Error in GET /api/status/metrics/summary", err); + return res.status(500).json({ error: "internal error" }); + } +}); + +app.get("/api/status/snapshot", async (req, res) => { + if (!(await isAdmin(req))) { + return res.status(403).json({ error: "Admin access required" }); + } + try { + const snapshot = panelMetrics ? await panelMetrics.getSnapshot() : null; + return res.json({ ok: true, snapshot }); + } catch (err) { + console.error("Error in GET /api/status/snapshot", err); + return res.status(500).json({ error: "internal error" }); + } +}); + app.get("/settings", async (req, res) => { - if (!(await isAdmin(req))) return res.redirect("/"); - const user = await findUserByEmail(req.session.user); - res.render("settings", { user, cspNonce: res.locals.cspNonce }); + try { + if (!(await isAdmin(req))) return res.redirect("/"); + const user = await findUserByEmail(req.session.user); + const destructiveActionSecurity = await getDestructiveActionSecurityAsync(req, user); + return res.render("settings", { + user, + destructiveActionSecurity, + cspNonce: res.locals.cspNonce, + dashboardBackground: loadDashboardBackgroundConfig() + }); + } catch (err) { + console.error("Error in GET /settings", err); + return res.status(500).send("Settings temporarily unavailable"); + } }); app.get("/account", async (req, res) => { @@ -20720,6 +24127,7 @@ app.get("/api/account", async (req, res) => { username: user.username || user.email.split('@')[0], email: user.email, isAdmin: adminCheck, + has2FA: hasTwoFactorEnabled(user), userId: user.id || null, createdAt: user.created_at || null, avatarUrl: resolveUserAvatarUrl({ ...user, admin: adminCheck }), @@ -20934,30 +24342,24 @@ app.post("/api/account/2fa/generate", async (req, res) => { return res.status(401).json({ error: "User not found" }); } - const { currentCode } = req.body || {}; + const { currentCode, currentPassword } = req.body || {}; - if (!currentCode || typeof currentCode !== 'string') { - return res.status(400).json({ error: "Current 2FA code is required" }); - } - - const codeStr = currentCode.replace(/\s+/g, ""); - if (!/^\d{6}$/.test(codeStr)) { - return res.status(400).json({ error: "Invalid 2FA code format" }); - } - - if (!user.secret) { - return res.status(400).json({ error: "2FA is not enabled for this account" }); - } - - const verified = speakeasy.totp.verify({ - secret: user.secret, - encoding: "base32", - token: codeStr, - window: 1, - }); - - if (!verified) { - return res.status(403).json({ error: "Incorrect current 2FA code" }); + if (hasTwoFactorEnabled(user)) { + const twoFactor = verifyTotpForUser(user, currentCode); + if (twoFactor.code === "invalid-format") { + return res.status(400).json({ error: "Invalid 2FA code format" }); + } + if (!twoFactor.ok) { + return res.status(403).json({ error: "Incorrect current 2FA code" }); + } + } else { + if (!currentPassword || typeof currentPassword !== "string") { + return res.status(400).json({ error: "Current password is required" }); + } + const passwordOk = await verifyPasswordForUser(user, currentPassword, "bcrypt-2fa-enable-timeout"); + if (!passwordOk) { + return res.status(403).json({ error: "Incorrect current password" }); + } } const newSecret = speakeasy.generateSecret({ length: 20 }); @@ -20973,7 +24375,7 @@ app.post("/api/account/2fa/generate", async (req, res) => { try { const qrCodeUrl = await qrcode.toDataURL(otpauthUrl); req.session.pending2faSecret = newSecret.base32; - req.session.pending2faFrom = 'standard'; + req.session.pending2faFrom = hasTwoFactorEnabled(user) ? 'standard' : 'enable'; return res.json({ ok: true, newSecret: newSecret.base32, @@ -21074,67 +24476,97 @@ app.post("/api/admin/user/reset-2fa", async (req, res) => { return res.status(400).json({ error: "Cannot reset your own 2FA through admin panel. Use account settings." }); } - const speakeasy = require("speakeasy"); - const newSecret = speakeasy.generateSecret({ length: 20 }); - const appName = process.env.APP_NAME || "ADPanel"; - const otpauthUrl = speakeasy.otpauthURL({ - secret: newSecret.base32, - label: targetUser.email, - issuer: appName, - encoding: "base32", - }); + // Step-up authentication: the acting admin must re-verify with their own + // password or 2FA before this destructive action is allowed. This mirrors + // the protection used by other destructive admin actions (maintenance, + // session revoke) and prevents abuse via a hijacked admin session. + const actingAdmin = await findUserByEmail(req.session.user); + if (!actingAdmin || !actingAdmin.admin) { + return res.status(403).json({ error: "Admin access required" }); + } + const stepUp = await requireDestructiveActionStepUp(req, res, actingAdmin, "Admin 2FA reset"); + if (!stepUp.ok) return; - const qrcode = require("qrcode"); + // Security model: the admin must NEVER learn the target user's TOTP seed, + // otherwise the admin could generate valid codes for that account and + // non-repudiation is broken. Instead of generating a new secret on the + // admin's behalf, we clear the user's 2FA. The user re-enrolls their own + // authenticator from account settings after their next login. try { - const qrCodeUrl = await qrcode.toDataURL(otpauthUrl); + await db.query( + "UPDATE users SET secret = NULL WHERE LOWER(email) = LOWER(?)", + [targetUser.email] + ); + + console.log(`[admin] 2FA cleared for user ${targetUser.email} by admin ${req.session.user} | IP: ${getRequestIp(req)}`); + try { + recordActivity({ + action: "admin_reset_2fa", + details: `Reset (cleared) 2FA for ${targetUser.email}`, + user: req.session.user, + }); + } catch (_) { } + return res.json({ ok: true, email: targetUser.email, - newSecret: newSecret.base32, - qrCodeUrl: qrCodeUrl + cleared: true, + message: "2FA has been reset. The user must set up 2FA again from their account settings.", }); } catch (err) { - console.error("[admin] 2FA reset QR generation error:", err); - return res.status(500).json({ error: "Failed to generate QR code" }); + console.error("[admin] 2FA reset error:", err); + return res.status(500).json({ error: "Failed to reset 2FA" }); } }); +// Backward-compatibility endpoint. The previous flow generated a TOTP seed on +// the admin's behalf and saved it here, which exposed the seed to the admin +// (non-repudiation risk). This endpoint no longer accepts an admin-supplied +// secret. It now performs the same safe action as reset-2fa: it clears the +// target user's 2FA so they re-enroll their own authenticator. app.post("/api/admin/user/confirm-2fa-reset", async (req, res) => { if (!(await isAdmin(req))) { return res.status(403).json({ error: "Admin access required" }); } if (!requireActionTokenOr403(req, res, "POST /api/admin/user/confirm-2fa-reset")) return; - const { email, newSecret } = req.body || {}; + const { email } = req.body || {}; if (!email || typeof email !== "string") { return res.status(400).json({ error: "Target email required" }); } - if (!newSecret || typeof newSecret !== "string") { - return res.status(400).json({ error: "New secret required" }); - } - - if (!/^[A-Z2-7]+=*$/i.test(newSecret) || newSecret.length < 16) { - return res.status(400).json({ error: "Invalid secret format" }); - } - const targetUser = await findUserByEmail(email); if (!targetUser) { return res.status(404).json({ error: "User not found" }); } + if (targetUser.email.toLowerCase() === req.session.user.toLowerCase()) { + return res.status(400).json({ error: "Cannot reset your own 2FA through admin panel. Use account settings." }); + } + + const actingAdmin = await findUserByEmail(req.session.user); + if (!actingAdmin || !actingAdmin.admin) { + return res.status(403).json({ error: "Admin access required" }); + } + const stepUp = await requireDestructiveActionStepUp(req, res, actingAdmin, "Admin 2FA reset"); + if (!stepUp.ok) return; + try { await db.query( - "UPDATE users SET secret = ? WHERE LOWER(email) = LOWER(?)", - [newSecret, email] + "UPDATE users SET secret = NULL WHERE LOWER(email) = LOWER(?)", + [targetUser.email] ); - console.log(`[admin] 2FA reset for user ${email} by admin ${req.session.user}`); - return res.json({ ok: true }); + console.log(`[admin] 2FA cleared (confirm) for user ${targetUser.email} by admin ${req.session.user} | IP: ${getRequestIp(req)}`); + return res.json({ + ok: true, + cleared: true, + message: "2FA has been reset. The user must set up 2FA again from their account settings.", + }); } catch (err) { - console.error("[admin] 2FA reset save error:", err); - return res.status(500).json({ error: "Failed to update 2FA secret" }); + console.error("[admin] 2FA reset (confirm) error:", err); + return res.status(500).json({ error: "Failed to reset 2FA" }); } }); @@ -21230,7 +24662,7 @@ function normalizeProvisionedEmail(raw) { function getProvisionedPasswordError(password, email) { if (typeof password !== "string") return "Password required"; - if (password.length < 12) return "Password must be at least 12 characters"; + if (password.length < 8) return "Password must be at least 8 characters"; if (Buffer.byteLength(password, "utf8") > 72) return "Password must be 72 bytes or less"; if (/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/.test(password)) return "Password contains invalid characters"; @@ -21250,16 +24682,10 @@ function getProvisionedPasswordError(password, email) { return "Use a stronger password"; } - const classes = [ - /[a-z]/.test(password), - /[A-Z]/.test(password), - /\d/.test(password), - /[^A-Za-z0-9]/.test(password) - ].filter(Boolean).length; - if (classes < 3 && password.length < 20) { - return "Use at least 3 character types or a longer passphrase"; - } - + // Note: we intentionally do NOT require a minimum number of character + // classes (e.g. an uppercase letter). A password of 8+ characters is + // accepted even if it is all lowercase. We still block trivially weak, + // common, sequential, and repeated passwords above for baseline safety. return ""; } @@ -21282,17 +24708,11 @@ async function verifyAdminProvisioningStepUp(req, adminUser, adminPassword, admi return "Admin re-authentication failed"; } - if (!adminUser.secret) return "2FA is required for admin creation"; - const code = normalizeTotpCode(adminTwoFactorCode); - if (!code) return "Enter a valid 6-digit 2FA code"; + if (!hasTwoFactorEnabled(adminUser)) return ""; - const twoFactorOk = speakeasy.totp.verify({ - secret: adminUser.secret, - encoding: "base32", - token: code, - window: 1, - }); - if (!twoFactorOk) { + const twoFactor = verifyTotpForUser(adminUser, adminTwoFactorCode); + if (twoFactor.code === "invalid-format") return "Enter a valid 6-digit 2FA code"; + if (!twoFactor.ok) { securityLog("Admin creation 2FA step-up failed", req); return "Admin re-authentication failed"; } @@ -21327,7 +24747,7 @@ async function generateHashedRecoveryCodes() { return { plainRecoveryCodes, hashedRecoveryCodes }; } -app.post("/api/admin/user/create", adminUserCreateRateLimiter, async (req, res) => { +app.post("/api/admin/user/create", async (req, res) => { if (!req.session || !req.session.user) { return res.status(401).json({ error: "Not authenticated" }); } @@ -21344,6 +24764,7 @@ app.post("/api/admin/user/create", adminUserCreateRateLimiter, async (req, res) if (!requireActionTokenOr403(req, res, "POST /api/admin/user/create")) return; const { email, password, confirmPassword, role: rawRole, adminPassword, adminTwoFactorCode } = req.body || {}; + const enableTwoFactor = parseBoolean(req.body?.enableTwoFactor, false); const role = normalizeProvisionedAccountRole(rawRole || "user"); if (!role) { return res.status(400).json({ error: "Invalid account type" }); @@ -21381,33 +24802,40 @@ app.post("/api/admin/user/create", adminUserCreateRateLimiter, async (req, res) "bcrypt-hash-timeout" ); - const secret = speakeasy.generateSecret({ length: 20 }); - const appName = process.env.APP_NAME || "ADPanel"; - const otpauthUrl = speakeasy.otpauthURL({ - secret: secret.base32, - label: emailLower, - issuer: appName, - encoding: "base32", - }); + let secretValue = null; + let qrCodeUrl = null; + let plainRecoveryCodes = []; + let recoveryCodesJson = null; + if (enableTwoFactor) { + const secret = speakeasy.generateSecret({ length: 20 }); + secretValue = secret.base32; + const appName = process.env.APP_NAME || "ADPanel"; + const otpauthUrl = speakeasy.otpauthURL({ + secret: secretValue, + label: emailLower, + issuer: appName, + encoding: "base32", + }); - const qrcode = require("qrcode"); - let qrCodeUrl; - try { - qrCodeUrl = await qrcode.toDataURL(otpauthUrl); - } catch (err) { - console.error("[admin] QR code generation error:", err); - return res.status(500).json({ error: "Failed to generate QR code" }); + const qrcode = require("qrcode"); + try { + qrCodeUrl = await qrcode.toDataURL(otpauthUrl); + } catch (err) { + console.error("[admin] QR code generation error:", err); + return res.status(500).json({ error: "Failed to generate QR code" }); + } + + const recovery = await generateHashedRecoveryCodes(); + plainRecoveryCodes = recovery.plainRecoveryCodes; + recoveryCodesJson = JSON.stringify(recovery.hashedRecoveryCodes); } - - const { plainRecoveryCodes, hashedRecoveryCodes } = await generateHashedRecoveryCodes(); - const recoveryCodesJson = JSON.stringify(hashedRecoveryCodes); const isAdminAccount = role === "admin"; const avatarUrl = isAdminAccount ? ADMIN_AVATAR_URL : getDefaultUserAvatar(emailLower); try { await db.query( `INSERT INTO users (email, password, secret, admin, recovery_codes, avatar_url) VALUES (?, ?, ?, ?, ?, ?)`, - [emailLower, passwordHash, secret.base32, isAdminAccount ? 1 : 0, recoveryCodesJson, avatarUrl] + [emailLower, passwordHash, secretValue, isAdminAccount ? 1 : 0, recoveryCodesJson, avatarUrl] ); console.log(`[admin] ${isAdminAccount ? "Admin user" : "User"} created: ${emailLower} by admin ${req.session.user} from ${getRequestIp(req)}`); @@ -21417,8 +24845,9 @@ app.post("/api/admin/user/create", adminUserCreateRateLimiter, async (req, res) email: emailLower, role, admin: isAdminAccount, - secret: secret.base32, - qrCodeUrl: qrCodeUrl, + has2FA: enableTwoFactor, + secret: secretValue, + qrCodeUrl, recoveryCodes: plainRecoveryCodes }); } catch (err) { @@ -22113,24 +25542,12 @@ app.post("/api/account/password/verify", async (req, res) => { return res.status(500).json({ error: "Verification failed" }); } - if (user.secret) { - if (!twoFactorCode || typeof twoFactorCode !== 'string') { - return res.status(400).json({ error: "2FA code is required" }); - } - - const codeStr = twoFactorCode.replace(/\s+/g, ""); - if (!/^\d{6}$/.test(codeStr)) { + if (hasTwoFactorEnabled(user)) { + const twoFactor = verifyTotpForUser(user, twoFactorCode); + if (twoFactor.code === "invalid-format") { return res.status(400).json({ error: "Invalid 2FA code format" }); } - - const verified = speakeasy.totp.verify({ - secret: user.secret, - encoding: "base32", - token: codeStr, - window: 1, - }); - - if (!verified) { + if (!twoFactor.ok) { return res.status(403).json({ error: "Incorrect 2FA code" }); } } @@ -22170,24 +25587,12 @@ app.post("/api/account/password/change", async (req, res) => { return res.status(500).json({ error: "Verification failed" }); } - if (user.secret) { - if (!twoFactorCode || typeof twoFactorCode !== 'string') { - return res.status(400).json({ error: "2FA code is required" }); - } - - const codeStr = twoFactorCode.replace(/\s+/g, ""); - if (!/^\d{6}$/.test(codeStr)) { + if (hasTwoFactorEnabled(user)) { + const twoFactor = verifyTotpForUser(user, twoFactorCode); + if (twoFactor.code === "invalid-format") { return res.status(400).json({ error: "Invalid 2FA code format" }); } - - const verified = speakeasy.totp.verify({ - secret: user.secret, - encoding: "base32", - token: codeStr, - window: 1, - }); - - if (!verified) { + if (!twoFactor.ok) { return res.status(403).json({ error: "Incorrect 2FA code" }); } } @@ -22238,24 +25643,12 @@ app.post("/api/account/email/verify", async (req, res) => { return res.status(500).json({ error: "Verification failed" }); } - if (user.secret) { - if (!twoFactorCode || typeof twoFactorCode !== 'string') { - return res.status(400).json({ error: "2FA code is required" }); - } - - const codeStr = twoFactorCode.replace(/\s+/g, ""); - if (!/^\d{6}$/.test(codeStr)) { + if (hasTwoFactorEnabled(user)) { + const twoFactor = verifyTotpForUser(user, twoFactorCode); + if (twoFactor.code === "invalid-format") { return res.status(400).json({ error: "Invalid 2FA code format" }); } - - const verified = speakeasy.totp.verify({ - secret: user.secret, - encoding: "base32", - token: codeStr, - window: 1, - }); - - if (!verified) { + if (!twoFactor.ok) { return res.status(403).json({ error: "Incorrect 2FA code" }); } } @@ -22306,24 +25699,12 @@ app.post("/api/account/email/change", async (req, res) => { return res.status(500).json({ error: "Verification failed" }); } - if (user.secret) { - if (!twoFactorCode || typeof twoFactorCode !== 'string') { - return res.status(400).json({ error: "2FA code is required" }); - } - - const codeStr = twoFactorCode.replace(/\s+/g, ""); - if (!/^\d{6}$/.test(codeStr)) { + if (hasTwoFactorEnabled(user)) { + const twoFactor = verifyTotpForUser(user, twoFactorCode); + if (twoFactor.code === "invalid-format") { return res.status(400).json({ error: "Invalid 2FA code format" }); } - - const verified = speakeasy.totp.verify({ - secret: user.secret, - encoding: "base32", - token: codeStr, - window: 1, - }); - - if (!verified) { + if (!twoFactor.ok) { return res.status(403).json({ error: "Incorrect 2FA code" }); } } @@ -22345,9 +25726,14 @@ app.post("/api/account/email/change", async (req, res) => { }); app.get("/settings/servers", async (req, res) => { - if (!(await isAdmin(req))) return res.redirect("/"); - const user = await findUserByEmail(req.session.user); - res.render("server", { user }); + try { + if (!(await isAdmin(req))) return res.redirect("/"); + const user = await findUserByEmail(req.session.user); + return res.render("server", { user }); + } catch (err) { + console.error("Error in GET /settings/servers", err); + return res.status(500).send("Settings temporarily unavailable"); + } }); let USER_COUNT_CACHE = 0; @@ -22380,7 +25766,7 @@ app.get("/api/me", async (req, res, next) => { user: { email: user.email, admin: !!user.admin, - has2FA: !!user.secret, + has2FA: hasTwoFactorEnabled(user), preferences: user.preferences || {} } }); @@ -23071,6 +26457,10 @@ app.get("/api/server/:name/activity", async (req, res) => { const offset = Math.max(0, parseInt(req.query.offset, 10) || 0); const limit = Math.min(200, Math.max(1, parseInt(req.query.limit, 10) || 50)); + if (typeof nodesRouter.flushActivityLogs === "function") { + try { await nodesRouter.flushActivityLogs(serverName); } catch { } + } + const safeName = String(serverName).replace(/[^a-zA-Z0-9_-]/g, "_"); const logPath = path.join(ACTIVITY_LOGS_DIR, `${safeName}.log`); @@ -23371,6 +26761,68 @@ function fileInfo(p) { return { p, exists, writable }; } +function normalizeDashboardBackgroundConfig(input) { + const type = String(input?.type || "").trim().toLowerCase(); + const value = typeof input?.value === "string" ? input.value.trim() : ""; + if (!type || !value) return null; + + const normalizedType = type === "url" ? "image" : type; + if (!["color", "image", "upload"].includes(normalizedType)) return null; + if (!makeCssBackground(normalizedType, value)) return null; + + const config = { type: normalizedType, value, updatedAt: new Date().toISOString() }; + if (typeof input?.name === "string" && input.name.trim()) config.name = path.basename(input.name.trim()).slice(0, 120); + return config; +} + +function parseDashboardBackgroundFromCss() { + try { + if (!fs.existsSync(DASHBOARD_CSS)) return null; + const css = fs.readFileSync(DASHBOARD_CSS, "utf8"); + const match = css.match(/--ui-bg\s*:\s*([^;]+);/); + if (!match) return null; + const raw = String(match[1] || "").trim(); + if (/^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(raw)) { + return { type: "color", value: raw }; + } + const urlMatch = raw.match(/^url\((["']?)(.*)\1\)$/i); + if (!urlMatch) return null; + let value = String(urlMatch[2] || "").trim(); + if (value.startsWith("/") && value.includes("?")) value = value.split("?")[0]; + if (makeCssBackground("image", value)) return { type: "image", value }; + } catch (err) { + console.error("[bg] Failed to parse CSS background:", err.message); + } + return null; +} + +function loadDashboardBackgroundConfig() { + try { + if (fs.existsSync(DASHBOARD_BACKGROUND_CONFIG)) { + const parsed = JSON.parse(fs.readFileSync(DASHBOARD_BACKGROUND_CONFIG, "utf8")); + const normalized = normalizeDashboardBackgroundConfig(parsed); + if (normalized) { + normalized.updatedAt = parsed.updatedAt || normalized.updatedAt; + return normalized; + } + } + } catch (err) { + console.error("[bg] Failed to load dashboard background config:", err.message); + } + return parseDashboardBackgroundFromCss(); +} + +function saveDashboardBackgroundConfig(config) { + const normalized = normalizeDashboardBackgroundConfig(config); + if (!normalized) return null; + const dir = path.dirname(DASHBOARD_BACKGROUND_CONFIG); + fs.mkdirSync(dir, { recursive: true }); + const tempPath = `${DASHBOARD_BACKGROUND_CONFIG}.${process.pid}.${Date.now()}.tmp`; + fs.writeFileSync(tempPath, JSON.stringify(normalized, null, 2), { encoding: "utf8", mode: 0o600 }); + fs.renameSync(tempPath, DASHBOARD_BACKGROUND_CONFIG); + return normalized; +} + app.post("/api/settings/background", async (req, res) => { try { if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); @@ -23379,15 +26831,19 @@ app.post("/api/settings/background", async (req, res) => { const { type, value } = req.body || {}; if (!type || typeof value === "undefined") return res.status(400).json({ error: "missing type/value" }); - const cssVal = makeCssBackground(type, value); + const normalized = normalizeDashboardBackgroundConfig(req.body || {}); + if (!normalized) return res.status(400).json({ error: "invalid background value" }); + + const cssVal = makeCssBackground(normalized.type, normalized.value); if (!cssVal) return res.status(400).json({ error: "invalid background value" }); const ok1 = setBodyBackgroundInFile(DASHBOARD_CSS, cssVal); const ok2 = setBodyBackgroundInFile(BOT_CSS, cssVal); if (ok1 && ok2) { + const savedBackground = saveDashboardBackgroundConfig(normalized); req.app.locals.themeVersion = Date.now(); - return res.json({ ok: true }); + return res.json({ ok: true, background: savedBackground }); } return res.status(500).json({ error: "failed", details: { ok1, ok2 } }); } catch (e) { @@ -23396,6 +26852,17 @@ app.post("/api/settings/background", async (req, res) => { } }); +app.get("/api/settings/background", async (req, res) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return res.json({ ok: true, background: loadDashboardBackgroundConfig() }); + } catch (e) { + console.error("[bg] GET ERROR:", e); + return res.status(500).json({ error: "exception", message: String(e?.message || e) }); + } +}); + const WEBHOOKS_CONFIG_PATH = path.join(__dirname, "webhooks-config.json"); const DANGEROUS_KEYS = new Set(["__proto__", "constructor", "prototype", "toString", "valueOf", "hasOwnProperty"]); @@ -23650,10 +27117,22 @@ nodesRouter.setWebhookDispatcher(dispatchWebhookForActivity); app.get("/api/settings/webhooks", async (req, res) => { const config = loadWebhooksConfig(); - res.json({ ok: true, config: maskConfigForResponse(config), categories: WEBHOOK_CATEGORIES }); + const currentUser = await findUserByEmail(req.session.user); + res.json({ + ok: true, + config: maskConfigForResponse(config), + categories: WEBHOOK_CATEGORIES, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + actionTokens: { + saveWebhook: issueActionToken(req, "POST /api/settings/webhooks", {}, { ttlSeconds: 300 }), + deleteWebhook: issueActionToken(req, "DELETE /api/settings/webhooks", {}, { ttlSeconds: 300 }), + }, + }); }); -app.post("/api/settings/webhooks", async (req, res) => { +app.post("/api/settings/webhooks", sessionRevoke2faRateLimiter, async (req, res) => { + if (!requireActionTokenOr403(req, res, "POST /api/settings/webhooks")) return; + const { mode, url, category } = req.body || {}; const hasMode = mode === "single" || mode === "multiple"; const hasUrl = typeof url === "string" && !!url.trim(); @@ -23682,6 +27161,22 @@ app.post("/api/settings/webhooks", async (req, res) => { if (DANGEROUS_KEYS.has(category)) { return res.status(400).json({ error: "Invalid category" }); } + } + } + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } + + let stepUp = { ok: true, graceExpiresAt: (await getVerifiedSessionRevokeGraceState(req, currentUser))?.expiresAt || 0 }; + if (hasUrl) { + stepUp = await requireDestructiveActionStepUp(req, res, currentUser, category ? `Webhook set "${category}"` : "Webhook set"); + if (!stepUp.ok) return; + } + + if (hasUrl) { + if (category) { if (!config.multiple) config.multiple = Object.create(null); config.multiple[category] = url.trim(); } else { @@ -23695,11 +27190,20 @@ app.post("/api/settings/webhooks", async (req, res) => { change: hasUrl ? (category ? `set_category:${category}` : "set_single") : `mode:${mode}`, }, userEmail, getRequestIp(req)); - if (saveWebhooksConfig(config)) return res.json({ ok: true, config: maskConfigForResponse(config) }); + if (saveWebhooksConfig(config)) { + return res.json({ + ok: true, + config: maskConfigForResponse(config), + graceExpiresAt: stepUp.graceExpiresAt || (await getVerifiedSessionRevokeGraceState(req, currentUser))?.expiresAt || 0, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + }); + } res.status(500).json({ error: "Failed to save" }); }); -app.delete("/api/settings/webhooks", async (req, res) => { +app.delete("/api/settings/webhooks", sessionRevoke2faRateLimiter, async (req, res) => { + if (!requireActionTokenOr403(req, res, "DELETE /api/settings/webhooks")) return; + const { category } = req.body || {}; const config = loadWebhooksConfig(); @@ -23710,6 +27214,17 @@ app.delete("/api/settings/webhooks", async (req, res) => { if (DANGEROUS_KEYS.has(category)) { return res.status(400).json({ error: "Invalid category" }); } + } + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } + + const stepUp = await requireDestructiveActionStepUp(req, res, currentUser, category ? `Webhook delete "${category}"` : "Webhook delete"); + if (!stepUp.ok) return; + + if (category) { if (config.multiple) delete config.multiple[category]; } else { config.single = null; @@ -23720,7 +27235,13 @@ app.delete("/api/settings/webhooks", async (req, res) => { target: category || "single", }, userEmail, getRequestIp(req)); - if (saveWebhooksConfig(config)) return res.json({ ok: true }); + if (saveWebhooksConfig(config)) { + return res.json({ + ok: true, + graceExpiresAt: stepUp.graceExpiresAt || (await getVerifiedSessionRevokeGraceState(req, currentUser))?.expiresAt || 0, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + }); + } res.status(500).json({ error: "Failed to save" }); }); @@ -23834,25 +27355,13 @@ app.post("/api/settings/change-password", async (req, res) => { return res.status(403).json({ error: "current password is incorrect" }); } - if (user.secret) { - if (!twoFactorCode) { + if (hasTwoFactorEnabled(user)) { + const twoFactor = verifyTotpForUser(user, twoFactorCode); + if (twoFactor.code === "invalid-format") { return res.status(400).json({ error: "2FA code required", requires2FA: true }); } - - const codeStr = String(twoFactorCode).replace(/\s+/g, ""); - if (!/^\d{6}$/.test(codeStr)) { - return res.status(400).json({ error: "invalid 2FA code format" }); - } - - const verified = speakeasy.totp.verify({ - secret: user.secret, - encoding: "base32", - token: codeStr, - window: 1, - }); - - if (!verified) { - return res.status(403).json({ error: "incorrect 2FA code" }); + if (!twoFactor.ok) { + return res.status(403).json({ error: "incorrect 2FA code", requires2FA: true }); } } @@ -23875,14 +27384,18 @@ app.post("/api/settings/change-password", async (req, res) => { app.get("/api/settings/servers", async (req, res, next) => { try { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const currentUser = await findUserByEmail(req.session.user); const index = await loadServersIndex(); let items = (index || []) - .filter(e => e && e.name) + .filter(e => e && e.name && String(e.status || "").toLowerCase() !== "deleting") .map(e => ({ name: e.name, displayName: e.displayName || null, nodeId: e.nodeId || null, template: e.template || null, + suspended: !!e.suspended, + suspendedAt: e.suspended_at || null, + suspendedBy: e.suspended_by || null, })) .sort((a, b) => a.name.localeCompare(b.name)); @@ -23896,9 +27409,30 @@ app.get("/api/settings/servers", async (req, res, next) => { const totalPages = Math.max(1, Math.ceil(total / limit)); const page = Math.min(Math.max(parseInt(req.query.page, 10) || 1, 1), totalPages); const offset = (page - 1) * limit; - items = items.slice(offset, offset + limit); + items = items.slice(offset, offset + limit).map((item) => ({ + ...item, + name: String(item.name || "").trim(), + deleteToken: issueActionToken( + req, + "DELETE /api/settings/servers/:name", + { serverName: String(item.name || "").trim() }, + { ttlSeconds: 600 } + ), + suspensionToken: issueActionToken( + req, + "POST /api/settings/servers/:name/suspension", + { serverName: String(item.name || "").trim() }, + { ttlSeconds: 600 } + ), + })); - return res.json({ items, total, page, totalPages }); + return res.json({ + items, + total, + page, + totalPages, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + }); } catch (err) { return next(err); } @@ -24002,6 +27536,7 @@ app.get("/api/servers/:name/permissions", async (req, res, next) => { app.get("/api/settings/accounts", async (req, res, next) => { try { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const currentUser = await findUserByEmail(req.session.user); const users = await loadUsers(); @@ -24015,16 +27550,33 @@ app.get("/api/settings/accounts", async (req, res, next) => { } const accounts = users - .filter(u => u && u.email) - .map(u => { - const emailLower = String(u.email).toLowerCase(); - return { - email: u.email, - servers: accessMap.get(emailLower) || [], - agent_access: !!u.agent_access, - admin: !!u.admin - }; - }) + .filter(u => u && u.email) + .map(u => { + const email = String(u.email || "").trim(); + const emailLower = email.toLowerCase(); + return { + email, + servers: accessMap.get(emailLower) || [], + agent_access: !!u.agent_access, + has2FA: !!u.has2FA, + admin: !!u.admin, + suspended: !!u.suspended, + suspendedAt: u.suspended_at || null, + suspendedBy: u.suspended_by || null, + deleteToken: issueActionToken( + req, + "DELETE /api/settings/accounts/:email", + { targetEmail: emailLower }, + { ttlSeconds: 600 } + ), + suspensionToken: u.admin ? "" : issueActionToken( + req, + "POST /api/settings/accounts/:email/suspension", + { targetEmail: emailLower }, + { ttlSeconds: 600 } + ) + }; + }) .sort((a, b) => { if (a.admin !== b.admin) return a.admin ? -1 : 1; return String(a.email || "").localeCompare(String(b.email || "")); @@ -24032,20 +27584,20 @@ app.get("/api/settings/accounts", async (req, res, next) => { const bots = (await loadServersIndex() || []).map(e => e?.name).filter(Boolean); - return res.json({ - accounts, - bots, - actionTokens: { - addAccess: issueActionToken(req, "POST /api/settings/accounts/:email/add", {}, { ttlSeconds: 300 }), - removeAccess: issueActionToken(req, "POST /api/settings/accounts/:email/remove", {}, { ttlSeconds: 300 }), - setAgentAccess: issueActionToken(req, "POST /api/settings/accounts/:email/agent-access", {}, { ttlSeconds: 300 }), - grantPerms: issueActionToken(req, "POST /api/settings/accounts/:email/grant-perms", {}, { ttlSeconds: 300 }), - deleteAccount: issueActionToken(req, "DELETE /api/settings/accounts/:email", {}, { ttlSeconds: 300 }), - changePassword: issueActionToken(req, "POST /api/settings/accounts/:email/change-password", {}, { ttlSeconds: 300 }), - createUser: issueActionToken(req, "POST /api/admin/user/create", {}, { ttlSeconds: 120, oneTime: true }), - reset2fa: issueActionToken(req, "POST /api/admin/user/reset-2fa", {}, { ttlSeconds: 300 }), - confirmReset2fa: issueActionToken(req, "POST /api/admin/user/confirm-2fa-reset", {}, { ttlSeconds: 300 }), - resetRecoveryCodes: issueActionToken(req, "POST /api/admin/user/reset-recovery-codes", {}, { ttlSeconds: 300 }), + return res.json({ + accounts, + bots, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + actionTokens: { + addAccess: issueActionToken(req, "POST /api/settings/accounts/:email/add", {}, { ttlSeconds: 600 }), + removeAccess: issueActionToken(req, "POST /api/settings/accounts/:email/remove", {}, { ttlSeconds: 600 }), + setAgentAccess: issueActionToken(req, "POST /api/settings/accounts/:email/agent-access", {}, { ttlSeconds: 600 }), + grantPerms: issueActionToken(req, "POST /api/settings/accounts/:email/grant-perms", {}, { ttlSeconds: 600 }), + changePassword: issueActionToken(req, "POST /api/settings/accounts/:email/change-password", {}, { ttlSeconds: 600 }), + createUser: issueActionToken(req, "POST /api/admin/user/create", {}, { ttlSeconds: 600 }), + reset2fa: issueActionToken(req, "POST /api/admin/user/reset-2fa", {}, { ttlSeconds: 600 }), + confirmReset2fa: issueActionToken(req, "POST /api/admin/user/confirm-2fa-reset", {}, { ttlSeconds: 600 }), + resetRecoveryCodes: issueActionToken(req, "POST /api/admin/user/reset-recovery-codes", {}, { ttlSeconds: 600 }), }, }); } catch (e) { @@ -24216,13 +27768,28 @@ app.post("/api/settings/accounts/:email/grant-perms", async (req, res, next) => if (!(await saveServersIndex(list))) return res.status(500).json({ error: "failed to write servers.json" }); try { await addAccessForEmail(email, server); } catch { } + + // After changing this user's permissions on the server, re-validate their + // schedules for that server and cancel only the ones they can no longer + // run. Schedules whose required permission is still held are kept, so a + // legitimate user notices no difference. + try { + await cancelSchedulesCreatedBy(email, { + serverName: server, + reauthorize: true, + reason: "server permissions changed", + }); + } catch (schedErr) { + console.warn("[grant-perms] Failed to re-validate user schedules:", schedErr?.message || schedErr); + } + return res.json({ ok: true }); } catch (err) { return next(err); } }); -app.delete("/api/settings/accounts/:email", async (req, res, next) => { +app.post("/api/settings/accounts/:email/suspension", sessionRevoke2faRateLimiter, async (req, res, next) => { try { if (!req.session || !req.session.user) { return res.status(401).json({ error: "not authenticated" }); @@ -24231,7 +27798,12 @@ app.delete("/api/settings/accounts/:email", async (req, res, next) => { if (!(await isAdmin(req))) { return res.status(403).json({ error: "admin required" }); } - if (!requireActionTokenOr403(req, res, "DELETE /api/settings/accounts/:email")) return; + + if (!req.is("application/json")) { + return res.status(415).json({ error: "JSON body required" }); + } + + res.set("Cache-Control", "no-store"); let targetEmail; try { @@ -24245,7 +27817,121 @@ app.delete("/api/settings/accounts/:email", async (req, res, next) => { return res.status(400).json({ error: "invalid email" }); } - if (targetEmail.toLowerCase() === req.session.user.toLowerCase()) { + const targetEmailLower = targetEmail.toLowerCase(); + if (!requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/suspension", { targetEmail: targetEmailLower })) return; + + if (typeof req.body?.suspended !== "boolean") { + return res.status(400).json({ error: "suspended must be a boolean" }); + } + + const nextSuspended = req.body.suspended === true; + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "admin required" }); + } + + const targetUser = await findUserByEmail(targetEmail); + if (!targetUser) { + return res.status(404).json({ error: "user not found" }); + } + + if (targetUser.admin) { + return res.status(403).json({ error: "admin accounts cannot be suspended through this endpoint" }); + } + + if (targetEmailLower === String(req.session.user || "").trim().toLowerCase()) { + return res.status(400).json({ error: "cannot change your own suspension state" }); + } + + const stepUp = await requireDestructiveActionStepUp( + req, + res, + currentUser, + `${nextSuspended ? "Account suspend" : "Account unsuspend"} "${targetEmailLower}"` + ); + if (!stepUp.ok) return; + const graceState = await getVerifiedSessionRevokeGraceState(req, currentUser); + + const suspendedAt = nextSuspended ? Date.now() : null; + const suspendedBy = nextSuspended ? String(currentUser.email || req.session.user || "").trim().toLowerCase() : null; + const updateResult = await db.query( + "UPDATE users SET suspended = ?, suspended_at = ?, suspended_by = ? WHERE id = ? AND admin = 0", + [nextSuspended ? 1 : 0, suspendedAt, suspendedBy, targetUser.id] + ); + + if (!updateResult || Number(updateResult.affectedRows || 0) !== 1) { + return res.status(409).json({ error: "account state changed; reload accounts and try again" }); + } + + const sessionInvalidation = nextSuspended + ? await destroyBrowserSessionsForUser({ ...targetUser, suspended: true }) + : { destroyed: 0, skipped: 0, rememberLoginsRevoked: 0, errors: [] }; + const socketsDisconnected = nextSuspended ? disconnectSocketsForUser(targetEmailLower) : 0; + + // When suspending, proactively cancel the user's schedules so nothing keeps + // running under their identity while suspended. Unsuspend leaves schedules + // untouched (they were already removed on suspend). + if (nextSuspended) { + try { + await cancelSchedulesCreatedBy(targetEmailLower, { reason: "account suspended" }); + } catch (schedErr) { + console.warn("[account-suspension] Failed to cancel user schedules:", schedErr?.message || schedErr); + } + } + + const graceExpiresAt = stepUp.graceExpiresAt || graceState?.expiresAt || 0; + + console.log(`[SECURITY] Account ${nextSuspended ? "suspended" : "unsuspended"} | Admin: ${currentUser.email} | Target: ${targetEmailLower} | Sessions destroyed: ${sessionInvalidation.destroyed} | Sockets disconnected: ${socketsDisconnected} | IP: ${getRequestIp(req)}`); + + return res.json({ + ok: true, + email: targetEmailLower, + suspended: nextSuspended, + suspendedAt, + suspendedBy, + sessionsDestroyed: sessionInvalidation.destroyed, + socketsDisconnected, + rememberLoginsRevoked: sessionInvalidation.rememberLoginsRevoked, + sessionInvalidationWarnings: sessionInvalidation.errors, + graceExpiresAt: graceExpiresAt || graceState?.expiresAt || 0, + }); + } catch (err) { + console.error("[account-suspension] Error:", err); + return next(err); + } +}); + +app.delete("/api/settings/accounts/:email", sessionRevoke2faRateLimiter, async (req, res, next) => { + try { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "not authenticated" }); + } + + if (!(await isAdmin(req))) { + return res.status(403).json({ error: "admin required" }); + } + res.set("Cache-Control", "no-store"); + + let targetEmail; + try { + targetEmail = decodeURIComponent(req.params.email || ""); + } catch { + targetEmail = req.params.email || ""; + } + targetEmail = String(targetEmail).trim(); + + if (!targetEmail || !targetEmail.includes("@") || targetEmail.length > 255) { + return res.status(400).json({ error: "invalid email" }); + } + const targetEmailLower = targetEmail.toLowerCase(); + if (!requireActionTokenOr403(req, res, "DELETE /api/settings/accounts/:email", { targetEmail: targetEmailLower })) return; + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "admin required" }); + } + + if (targetEmailLower === req.session.user.toLowerCase()) { return res.status(400).json({ error: "cannot delete yourself" }); } @@ -24254,6 +27940,10 @@ app.delete("/api/settings/accounts/:email", async (req, res, next) => { return res.status(404).json({ error: "user not found" }); } + const stepUp = await requireDestructiveActionStepUp(req, res, currentUser, `Account delete "${targetEmailLower}"`); + if (!stepUp.ok) return; + const graceState = await getVerifiedSessionRevokeGraceState(req, currentUser); + await db.query("DELETE FROM user_access WHERE user_id = ?", [targetUser.id]); try { @@ -24277,15 +27967,29 @@ app.delete("/api/settings/accounts/:email", async (req, res, next) => { await db.query("DELETE FROM users WHERE id = ?", [targetUser.id]); + // Proactively cancel any schedules this user created so they do not linger + // in the queue after the account no longer exists. + try { + await cancelSchedulesCreatedBy(targetEmailLower, { reason: "account deleted" }); + } catch (schedErr) { + console.warn("[delete-user] Failed to cancel user schedules:", schedErr?.message || schedErr); + } + + const graceExpiresAt = stepUp.graceExpiresAt || graceState?.expiresAt || 0; + console.log(`[delete-user] Admin ${req.session.user} deleted user ${targetEmail}`); - return res.json({ ok: true, message: "User deleted successfully" }); + return res.json({ + ok: true, + message: "User deleted successfully", + graceExpiresAt: graceExpiresAt || graceState?.expiresAt || 0, + }); } catch (err) { console.error("[delete-user] Error:", err); return next(err); } }); -app.post("/api/settings/accounts/:email/change-password", async (req, res, next) => { +app.post("/api/settings/accounts/:email/change-password", sessionRevoke2faRateLimiter, async (req, res, next) => { try { if (!req.session || !req.session.user) { return res.status(401).json({ error: "not authenticated" }); @@ -24330,6 +28034,14 @@ app.post("/api/settings/accounts/:email/change-password", async (req, res, next) return res.status(400).json({ error: "passwords do not match" }); } + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "admin required" }); + } + + const stepUp = await requireDestructiveActionStepUp(req, res, currentUser, `Password reset for "${targetEmail}"`); + if (!stepUp.ok) return; + const hashedPassword = await withTimeout(bcrypt.hash(newPassword, BCRYPT_ROUNDS), 10000, "bcrypt-hash-timeout"); await db.query( @@ -24338,7 +28050,12 @@ app.post("/api/settings/accounts/:email/change-password", async (req, res, next) ); console.log(`[admin-change-password] Admin ${req.session.user} changed password for user ${targetEmail}`); - return res.json({ ok: true, message: "Password changed successfully" }); + return res.json({ + ok: true, + message: "Password changed successfully", + graceExpiresAt: stepUp.graceExpiresAt || (await getVerifiedSessionRevokeGraceState(req, currentUser))?.expiresAt || 0, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + }); } catch (err) { console.error("[admin-change-password] Error:", err); return next(err); @@ -24365,7 +28082,7 @@ app.get("/api/servers/:name/files/list", async (req, res) => { try { const dir = safeJoinUnix(ctx.baseDir, rel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/list", { path: dir }, 60_000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/list", { path: dir, server: ctx.serverName }, 60_000); if (status === 0) { console.error(`[files/list] Node connection failed for ${name} - node may be offline`); @@ -24400,7 +28117,7 @@ app.get("/api/servers/:name/files/read", async (req, res) => { try { const full = safeJoinUnix(ctx.baseDir, rel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, encoding: "utf8" }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, server: ctx.serverName, encoding: "utf8" }, 120000); if (status === 404) return res.status(404).json({ error: "file not found" }); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_read_failed" }); @@ -24429,7 +28146,7 @@ app.get("/api/servers/:name/files/stream", async (req, res) => { try { const full = safeJoinUnix(ctx.baseDir, rel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, encoding: "utf8" }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, server: ctx.serverName, encoding: "utf8" }, 120000); if (status === 404) return res.status(404).end("file not found"); if (status !== 200 || !json || !json.ok) return res.status(502).end("node-read-failed"); @@ -24461,7 +28178,7 @@ app.get("/api/servers/:name/files/download", async (req, res) => { const full = safeJoinUnix(ctx.baseDir, rel || ""); const nodeBase = buildNodeBaseUrl(ctx.node.address, ctx.node.api_port || 8080, ctx.node.ssl_enabled, nodeUnderCloudflare(ctx.node)); if (!nodeBase) return res.status(502).end("node unreachable"); - const postData = JSON.stringify({ path: full }); + const postData = JSON.stringify({ path: full, server: ctx.serverName }); const lib = nodeBase.startsWith("https:") ? require("https") : require("http"); const url = new URL(`${nodeBase}/v1/fs/download`); const hdrs = nodeAuthHeadersFor(ctx.node, true); @@ -24501,7 +28218,12 @@ app.put("/api/servers/:name/files/write", async (req, res) => { } const perms = await getEffectivePermsForUserOnServer(req.session.user, name); - if (!perms.files_create) return res.status(403).json({ error: "not authorized" }); + const admin = await isAdmin(req); + const canCreate = admin || !!perms.files_create; + const canWrite = admin || !!perms.files_write; + if (!canCreate && !canWrite) return res.status(403).json({ error: "not authorized" }); + let writeMode = ""; + if (!(canCreate && canWrite)) writeMode = canCreate ? "create" : "update"; const rel = String(req.body?.path || ""); const content = String(req.body?.content ?? ""); @@ -24511,10 +28233,16 @@ app.put("/api/servers/:name/files/write", async (req, res) => { try { const full = safeJoinUnix(ctx.baseDir, rel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/write", { path: full, content, encoding: "utf8" }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/write", { path: full, server: ctx.serverName, content, encoding: "utf8", mode: writeMode }, 120000); if (status === 507 && json?.error === "disk_limit_exceeded") { return res.status(507).json(json); } + if (status === 409) { + return res.status(403).json({ error: "not authorized", permission: "files_write", detail: "overwriting existing files requires the files_write permission" }); + } + if (status === 404 && json && json.existed === false) { + return res.status(403).json({ error: "not authorized", permission: "files_create", detail: "creating new files requires the files_create permission" }); + } if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_write_failed" }); return res.json({ ok: true }); } catch (e) { @@ -24541,7 +28269,7 @@ app.post("/api/servers/:name/files/mkdir", async (req, res) => { try { const full = safeJoinUnix(ctx.baseDir, rel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/mkdir", { path: full }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/mkdir", { path: full, server: ctx.serverName }, 120000); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_mkdir_failed" }); return res.json({ ok: true }); } catch (e) { @@ -24569,7 +28297,7 @@ app.delete("/api/servers/:name/files/delete", async (req, res) => { try { const full = safeJoinUnix(ctx.baseDir, rel || ""); const isDir = String(req.query.isDir || req.body?.isDir || "0") === "1"; - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/delete", { path: full, isDir }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/delete", { path: full, server: ctx.serverName, isDir }, 120000); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_delete_failed" }); return res.json({ ok: true }); } catch (e) { @@ -24598,7 +28326,7 @@ app.post("/api/servers/:name/files/rename", async (req, res) => { try { const src = safeJoinUnix(ctx.baseDir, srcRel || ""); const dest = safeJoinUnix(ctx.baseDir, destRel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/rename", { src, dest }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/rename", { src, dest, server: ctx.serverName }, 120000); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_rename_failed" }); return res.json({ ok: true }); } catch (e) { @@ -24774,6 +28502,13 @@ app.post("/upload", async (req, res) => { return; } + const serverEntry = await findServer(bot); + if (isServerSuspended(serverEntry)) { + fileStream.resume(); + respond(423, { error: "server suspended", code: "server-suspended", server: serverEntry?.name || bot }); + return; + } + const perms = await getEffectivePermsForUserOnServer(currentEmail, bot); if (!perms.files_upload && !(await isAdmin(req))) { fileStream.resume(); @@ -24872,6 +28607,9 @@ app.post("/upload-url", express.json({ limit: "16kb" }), async (req, res) => { return res.status(403).json({ error: "no access to server" }); } + const serverEntry = await findServer(bot); + if (isServerSuspended(serverEntry)) return sendSuspendedServerJson(res, serverEntry); + const perms = await getEffectivePermsForUserOnServer(currentEmail, bot); if (!perms.files_upload && !(await isAdmin(req))) { return res.status(403).json({ error: "no upload permission" }); @@ -24936,6 +28674,9 @@ app.post("/extract", async (req, res) => { return res.status(403).json({ error: "no access to server" }); } + const serverEntry = await findServer(bot); + if (isServerSuspended(serverEntry)) return sendSuspendedServerJson(res, serverEntry); + const perms = await getEffectivePermsForUserOnServer(req.session.user, bot); if (!perms.files_create && !(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); @@ -24944,7 +28685,7 @@ app.post("/extract", async (req, res) => { try { const full = safeJoinUnix(ctx.baseDir, relPath); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/extract", { path: full }, 300_000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/extract", { path: full, server: ctx.serverName }, 300_000); if (status === 507 && json?.error === "disk_limit_exceeded") { return res.status(507).json(json); } @@ -24972,6 +28713,9 @@ app.post("/archive", async (req, res) => { return res.status(403).json({ error: "no access to server" }); } + const serverEntry = await findServer(bot); + if (isServerSuspended(serverEntry)) return sendSuspendedServerJson(res, serverEntry); + const perms = await getEffectivePermsForUserOnServer(req.session.user, bot); if (!perms.files_archive && !(await isAdmin(req))) { return res.status(403).json({ error: "not authorized", permission: "files_archive" }); @@ -24980,9 +28724,28 @@ app.post("/archive", async (req, res) => { const ctx = await resolveRemoteFsContext(bot); if (!ctx.remote) return res.status(404).json({ error: "server not found on node" }); + // #4 belt-and-suspenders: validate every archive input at the panel boundary + // (reject traversal / NUL / absolute) before forwarding the relative paths to + // the per-server node endpoint, which re-confines them under the server root. + let cleanPaths; + try { + cleanPaths = []; + if (paths.length > 1000) throw new Error("too many paths"); + for (const p of paths) { + const rel = String(p || ""); + if (!rel) continue; + safeJoinUnix(ctx.baseDir, rel); + cleanPaths.push(rel); + } + if (destDir) safeJoinUnix(ctx.baseDir, String(destDir)); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } + if (cleanPaths.length === 0) return res.status(400).json({ error: "missing bot or paths" }); + try { const botSeg = encodeURIComponent(bot); - const { status, json } = await nodeFsPost(ctx.node, `/v1/servers/${botSeg}/files/archive`, { paths, destDir }, 300_000); + const { status, json } = await nodeFsPost(ctx.node, `/v1/servers/${botSeg}/files/archive`, { paths: cleanPaths, destDir }, 300_000); if (status === 507 && json?.error === "disk_limit_exceeded") { return res.status(507).json(json); } @@ -25008,6 +28771,9 @@ app.post("/create", async (req, res) => { return res.status(403).send("Not authorized"); } + const serverEntry = await findServer(bot); + if (isServerSuspended(serverEntry)) return sendSuspendedServerJson(res, serverEntry); + const perms = await getEffectivePermsForUserOnServer(req.session.user, bot); if (!perms.files_create && !(await isAdmin(req))) return res.status(403).send("Not authorized"); @@ -25022,8 +28788,8 @@ app.post("/create", async (req, res) => { const target = safeJoinUnix(ctx.baseDir, relativePosix); const payload = type === "folder" - ? { path: safeJoinUnix(target, ".keep"), content: "", encoding: "utf8" } - : { path: target, content: "", encoding: "utf8" }; + ? { path: safeJoinUnix(target, ".keep"), server: ctx.serverName, content: "", encoding: "utf8" } + : { path: target, server: ctx.serverName, content: "", encoding: "utf8" }; const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/write", payload, 120000); if (status === 507 && json?.error === "disk_limit_exceeded") { @@ -25048,6 +28814,9 @@ app.post("/rename", async (req, res) => { return res.status(403).send("Not authorized"); } + const serverEntry = await findServer(bot); + if (isServerSuspended(serverEntry)) return sendSuspendedServerJson(res, serverEntry); + const perms = await getEffectivePermsForUserOnServer(req.session.user, bot); if (!perms.files_rename) return res.status(403).send("Not authorized"); @@ -25061,7 +28830,7 @@ app.post("/rename", async (req, res) => { const src = safeJoinUnix(ctx.baseDir, oldPath); const dest = safeJoinUnix(ctx.baseDir, relative); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/rename", { src, dest }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/rename", { src, dest, server: ctx.serverName }, 120000); if (status !== 200 || !json || !json.ok) return res.status(500).send("Rename failed"); return res.json({ ok: true, path: relative }); } catch (e) { @@ -25084,6 +28853,10 @@ app.get("/server/:server/resources", async (req, res) => { const hasAccess = (await isAdmin(req)) || (await userHasAccessToServer(req.session.user, botName)); if (!hasAccess) return res.status(403).send("Unauthorized"); + if (isServerSuspended(entry)) { + return renderSuspendedServerPage(res, entry); + } + return res.render("resource-popup", { bot: botName, cspNonce: res.locals.cspNonce }); } catch (err) { console.error(err); @@ -25110,6 +28883,10 @@ app.get("/server/:server", async (req, res, next) => { return res.status(404).render("404", { cspNonce: res.locals.cspNonce }); } + if (isServerSuspended(entry)) { + return renderSuspendedServerPage(res, entry); + } + const activeTransfer = getTransferJob(botName); const isTransferring = (entry && String(entry.status || "").toLowerCase() === "transferring") || (activeTransfer && !activeTransfer.finishedAt); if (isTransferring) { @@ -25488,9 +29265,37 @@ app.post("/api/servers/create", async (req, res) => { const targetNodeId = String(nodeId || "").trim(); if (!targetNodeId || targetNodeId === "local") return res.status(400).json({ error: "nodeId required" }); + const configuredNodes = await loadNodes(); + if (!configuredNodes.length) { + return res.status(400).json({ error: "No nodes configured. Add a node before creating servers." }); + } + const node = await findNodeByIdOrName(targetNodeId); if (!node) return res.status(400).json({ error: "node not found" }); + // adpanel:multidisk - resolve and verify the requested target disk belongs to + // this node. Empty/"primary" => default primary disk (back-compat). + let targetDiskId = String(req.body?.diskId || "").trim(); + if (targetDiskId && targetDiskId !== "primary") { + try { + const diskRes = await httpRequestJson( + `${buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node))}/v1/disks`, + "GET", + { Authorization: `Bearer ${node.token}` }, + null, + 8000 + ); + const disks = (diskRes.status === 200 && diskRes.json?.ok && Array.isArray(diskRes.json.disks)) ? diskRes.json.disks : []; + if (!disks.some((d) => String(d.id) === targetDiskId)) { + return res.status(400).json({ error: "Target disk does not belong to this node." }); + } + } catch (_) { + return res.status(502).json({ error: "Failed to verify target disk on node." }); + } + } else { + targetDiskId = ""; + } + const mcFork = req.body?.mcFork ? String(req.body.mcFork).toLowerCase() : "paper"; const mcVersion = req.body?.mcVersion ? String(req.body.mcVersion).trim() : "1.21.8"; let importUrl = req.body?.importUrl ? String(req.body.importUrl).trim() : null; @@ -25564,9 +29369,6 @@ app.post("/api/servers/create", async (req, res) => { } let sanitizedDocker = normalizeTemplateDockerForRuntime(templateId, template.docker); - if (sanitizedDocker && Array.isArray(sanitizedDocker.ports) && sanitizedDocker.ports.length > 1) { - sanitizedDocker.ports = [sanitizedDocker.ports[0]]; - } const requestedJavaVersion = Object.prototype.hasOwnProperty.call(req.body || {}, "javaVersion") ? normalizeMinecraftJavaVersionInput(req.body?.javaVersion) : ""; @@ -25605,30 +29407,43 @@ app.post("/api/servers/create", async (req, res) => { } const resolvedPort = hostPortRaw != null ? hostPortRaw : (validatePort(template.defaultPort) || 0); - if (resolvedPort > 0 && !isPortInNodeAllocation(node, resolvedPort)) { - const alloc = node.ports || {}; - let allocDesc = "none"; - if (alloc.mode === "range") allocDesc = `range ${alloc.start}–${alloc.start + alloc.count - 1}`; - else if (alloc.mode === "list" && Array.isArray(alloc.ports)) allocDesc = `list [${alloc.ports.slice(0, 10).join(", ")}${alloc.ports.length > 10 ? "…" : ""}]`; - return res.status(400).json({ error: `Port ${resolvedPort} is not in this node's allocated ports (${allocDesc}). Choose a port within the node's allocation.` }); + const requiredHostPorts = dockerTemplateHostPortRequirements(sanitizedDocker, resolvedPort); + const seenRequiredPorts = new Set(); + for (const requirement of requiredHostPorts) { + if (seenRequiredPorts.has(requirement.hostPort)) { + return res.status(400).json({ + error: `Port ${requirement.hostPort} would be used by more than one mapping. Choose a different main port or adjust the template ports.` + }); + } + seenRequiredPorts.add(requirement.hostPort); } - if (resolvedPort > 0) { - const conflict = await findServerUsingNodePort(node, resolvedPort, name); + + for (const requirement of requiredHostPorts) { + const checkPort = requirement.hostPort; + if (checkPort <= 0) continue; + if (!isPortInNodeAllocation(node, checkPort)) { + const alloc = node.ports || {}; + let allocDesc = "none"; + if (alloc.mode === "range") allocDesc = `range ${alloc.start}–${alloc.start + alloc.count - 1}`; + else if (alloc.mode === "list" && Array.isArray(alloc.ports)) allocDesc = `list [${alloc.ports.slice(0, 10).join(", ")}${alloc.ports.length > 10 ? "…" : ""}]`; + return res.status(400).json({ error: `Port ${checkPort} is not in this node's allocated ports (${allocDesc}). Choose ports within the node's allocation.` }); + } + const conflict = await findServerUsingNodePort(node, checkPort, name); if (conflict) { return res.status(409).json({ - error: `Port ${resolvedPort} is already assigned to server "${conflict.displayName || conflict.name || conflict.bot}" on this node.`, + error: `Port ${checkPort} is already assigned to server "${conflict.displayName || conflict.name || conflict.bot}" on this node.`, code: "port_in_use", - port: resolvedPort, + port: checkPort, server: conflict.name || conflict.bot || null }); } - const livePort = await checkRemoteNodePortAvailability(node, resolvedPort); + const livePort = await checkRemoteNodePortAvailability(node, checkPort, requirement.protocols); if (livePort.verified && livePort.available === false) { const owner = livePort.owner ? ` by ${livePort.owner}` : ""; return res.status(409).json({ - error: `Port ${resolvedPort} is already in use on the node${owner}.`, + error: `Port ${checkPort} is already in use on the node${owner}.`, code: "port_in_use", - port: resolvedPort, + port: checkPort, owner: livePort.owner || null, reason: livePort.reason || null }); @@ -25641,12 +29456,15 @@ app.post("/api/servers/create", async (req, res) => { mcFork, mcVersion, hostPort: hostPortRaw, - docker: sanitizedDocker, + docker: dockerConfigForNodeRequest(sanitizedDocker), autoStart: true, asyncSetup: true, importUrl: importUrl, resources: Object.keys(resources).length > 0 ? resources : null }; + if (targetDiskId) { + payload.diskId = targetDiskId; + } if (tpl === "minecraft" && sanitizedDocker?.javaVersion) { payload.javaVersion = sanitizedDocker.javaVersion; } @@ -25700,8 +29518,11 @@ app.post("/api/servers/create", async (req, res) => { workdir: sanitizedDocker.workdir, env: sanitizedDocker.env, ports: sanitizedDocker.ports, + portProtocols: sanitizedDocker.portProtocols, javaVersion: sanitizedDocker.javaVersion, + runAsRoot: sanitizedDocker.runAsRoot === true, adpanelStartup: sanitizedDocker.adpanelStartup, + startupDisplay: sanitizedDocker.startupDisplay, install: sanitizedDocker.install, }; } @@ -25734,24 +29555,108 @@ function isValidArchiveUrl(url) { } } -app.delete("/api/settings/servers/:name", async (req, res) => { +app.delete("/api/settings/servers/:name", sessionRevoke2faRateLimiter, async (req, res) => { if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); - const result = await deleteServerByName({ - findServer, - isRemoteEntry, - findNodeByIdOrName, - buildNodeBaseUrl, - nodeUnderCloudflare, - nodeAuthHeadersFor, - httpRequestJson, - deleteServerSchedules, - removeServerIndexEntry, - removeAccessForServerName, - }, req.params.name); + res.set("Cache-Control", "no-store"); + let nameParam = req.params.name || ""; + try { nameParam = decodeURIComponent(nameParam); } catch { } + const serverName = String(nameParam || "").trim(); + if (!serverName) return res.status(400).json({ error: "missing name" }); + if (!requireActionTokenOr403(req, res, "DELETE /api/settings/servers/:name", { serverName })) return; + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } + + const stepUp = await requireDestructiveActionStepUp(req, res, currentUser, `Server delete "${serverName}"`); + if (!stepUp.ok) return; + const graceState = await getVerifiedSessionRevokeGraceState(req, currentUser); + const graceExpiresAt = stepUp.graceExpiresAt || graceState?.expiresAt || 0; + + let result; + try { + result = await deleteServerByName({ + findServer, + isRemoteEntry, + findNodeByIdOrName, + buildNodeBaseUrl, + nodeUnderCloudflare, + nodeAuthHeadersFor, + httpRequestJson, + deleteServerSchedules, + removeServerIndexEntry, + removeAccessForServerName, + markServerDeletingStatus, + enqueueServerDeleteJob, + kickServerDeleteWorker, + }, serverName); + } catch (err) { + console.error("[delete-server] Error:", err); + return res.status(500).json({ error: err?.message || "delete failed" }); + } if (!result.ok) { return res.status(result.statusCode || 500).json({ error: result.error || "delete failed" }); } - return res.json(result); + + return res.status(result.deleting ? 202 : 200).json({ + ...result, + graceExpiresAt: graceExpiresAt || graceState?.expiresAt || 0, + }); +}); + +app.post("/api/settings/servers/:name/suspension", sessionRevoke2faRateLimiter, async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + res.set("Cache-Control", "no-store"); + if (!req.is("application/json")) { + return res.status(415).json({ error: "JSON body required" }); + } + + let nameParam = req.params.name || ""; + try { nameParam = decodeURIComponent(nameParam); } catch { } + const serverName = String(nameParam || "").trim(); + if (!serverName) return res.status(400).json({ error: "missing name" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/servers/:name/suspension", { serverName })) return; + + if (typeof req.body?.suspended !== "boolean") { + return res.status(400).json({ error: "suspended must be a boolean" }); + } + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } + + const nextSuspended = req.body.suspended === true; + const stepUp = await requireDestructiveActionStepUp( + req, + res, + currentUser, + `${nextSuspended ? "Server suspend" : "Server restore"} "${serverName}"` + ); + if (!stepUp.ok) return; + const graceState = await getVerifiedSessionRevokeGraceState(req, currentUser); + + const result = await setServerSuspensionState(serverName, nextSuspended, currentUser.email || req.session.user); + if (!result.ok) { + return res.status(result.statusCode || 500).json({ error: result.error || "failed to update server suspension" }); + } + + if (result.suspended) { + try { + io.to(result.server).emit("server:suspended", { server: result.server }); + io.to(getConsoleRoom(result.server)).emit("server:suspended", { server: result.server }); + } catch { } + } + + const graceExpiresAt = stepUp.graceExpiresAt || graceState?.expiresAt || 0; + console.log(`[SECURITY] Server ${result.suspended ? "suspended" : "restored"} | Admin: ${currentUser.email} | Server: ${result.server} | IP: ${getRequestIp(req)}`); + + return res.json({ + ...result, + graceExpiresAt: graceExpiresAt || graceState?.expiresAt || 0, + revokeSecurity: await getDestructiveActionSecurityAsync(req, currentUser), + }); }); app.post("/api/settings/servers/:name/template", async (req, res) => { @@ -25794,9 +29699,12 @@ app.post("/api/settings/servers/:name/template", async (req, res) => { const reinstallPayload = { templateId, - docker: normalizedTemplateDocker || null, + docker: dockerConfigForNodeRequest(normalizedTemplateDocker), hostPort, }; + if (normalizeTemplateId(templateId) === "minecraft" && normalizedTemplateDocker?.javaVersion) { + reinstallPayload.javaVersion = normalizedTemplateDocker.javaVersion; + } if (!signPanelAdminReinstallHeaders(headers, node, technicalName, templateId)) { return res.status(500).json({ error: "failed to sign reinstall request" }); @@ -25804,13 +29712,15 @@ app.post("/api/settings/servers/:name/template", async (req, res) => { console.log(`[template-change] Reinstalling server ${name} on node ${entry.nodeId} with template ${templateId}`); - const r = await httpRequestJson( + const reinstallAttempt = await httpRequestJsonPruningUnknownFields( `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/reinstall`, "POST", headers, reinstallPayload, - 3_600_000 + 3_600_000, + "node-reinstall" ); + const r = reinstallAttempt.res; if (r.status !== 200 || !(r.json && r.json.ok)) { const msg = (r.json && (r.json.error || r.json.detail)) ? (r.json.error || r.json.detail) : `reinstall failed (${r.status})`; @@ -25839,9 +29749,12 @@ app.post("/api/settings/servers/:name/template", async (req, res) => { workdir: normalizedTemplateDocker.workdir, env: normalizedTemplateDocker.env, ports: normalizedTemplateDocker.ports, + portProtocols: normalizedTemplateDocker.portProtocols, restart: normalizedTemplateDocker.restart, + runAsRoot: normalizedTemplateDocker.runAsRoot === true, console: normalizedTemplateDocker.console, adpanelStartup: normalizedTemplateDocker.adpanelStartup, + startupDisplay: normalizedTemplateDocker.startupDisplay, install: normalizedTemplateDocker.install, }; } @@ -25908,19 +29821,40 @@ app.post("/api/servers/:name/reinstall", async (req, res) => { templateId, }; + // Forward the server's stored docker/runtime config so the node can fully + // rebuild the container exactly like the original create. Without this the + // node has to reconstruct everything from its own old meta, and a custom + // server with no resolvable image is left without a running container. + const storedDocker = dockerConfigForNodeRequest(entry.docker) + || dockerConfigForNodeRequest(entry.runtime); + if (storedDocker) { + reinstallPayload.docker = storedDocker; + } + const storedHostPort = parseInt(entry.port, 10); + if (Number.isInteger(storedHostPort) && storedHostPort > 0) { + reinstallPayload.hostPort = storedHostPort; + } + if (templateId === "minecraft") { + const javaVersion = (entry.docker && entry.docker.javaVersion) + || (entry.runtime && entry.runtime.javaVersion); + if (javaVersion) reinstallPayload.javaVersion = String(javaVersion); + } + if (!signPanelAdminReinstallHeaders(headers, node, technicalName, templateId)) { return res.status(500).json({ error: "failed to sign reinstall request" }); } console.log(`[reinstall] User ${email} (admin=${isAdminUser}) reinstalling server ${name} with template ${templateId}`); - const r = await httpRequestJson( + const reinstallAttempt = await httpRequestJsonPruningUnknownFields( `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/reinstall`, "POST", headers, reinstallPayload, - 3_600_000 + 3_600_000, + "node-reinstall" ); + const r = reinstallAttempt.res; if (r.status !== 200 || !(r.json && r.json.ok)) { const msg = (r.json && (r.json.error || r.json.detail)) ? (r.json.error || r.json.detail) : `reinstall failed (${r.status})`; @@ -26097,13 +30031,15 @@ app.patch("/api/settings/servers/:name/resources", async (req, res) => { try { const headers = nodeAuthHeadersFor(node, true); - const r = await httpRequestJson( + const resourceAttempt = await httpRequestJsonPruningUnknownFields( `${baseUrl}/v1/servers/${encodeURIComponent(name)}/resources`, "PATCH", headers, payload, - 30_000 + 30_000, + "node-resources" ); + const r = resourceAttempt.res; if (r.status !== 200 || !(r.json && r.json.ok)) { const msg = (r.json && (r.json.error || r.json.detail)) ? (r.json.error || r.json.detail) : `failed to update resources (${r.status})`; @@ -26186,28 +30122,34 @@ app.patch("/api/settings/servers/:name/resources", async (req, res) => { }); app.get("/api/settings/servers/:name/resources", async (req, res) => { - if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!req.currentUser) return res.status(401).json({ error: "not authenticated" }); let nameParam = req.params.name || ""; try { nameParam = decodeURIComponent(nameParam); } catch { } const name = String(nameParam).trim(); if (!name) return res.status(400).json({ error: "missing server name" }); - const me = req.session?.user; - const isAdminUser = await isAdmin(req); + const serverEntryPromise = findServer(name); + const isAdminUser = req.isAdmin === true; if (!isAdminUser) { + const me = req.session?.user; const hasAccess = await userHasAccessToServer(me, name); if (!hasAccess) return res.status(403).json({ error: "not authorized" }); } - const serverEntry = await findServer(name); + const serverEntry = await serverEntryPromise; if (!serverEntry) return res.status(404).json({ error: "server not found" }); if (!isRemoteEntry(serverEntry)) { return res.status(400).json({ error: "server is not on a remote node" }); } - const node = await findNodeByIdOrName(serverEntry.nodeId); + const nodePromise = findNodeByIdOrName(serverEntry.nodeId); + const resultTemplateId = serverEntry?.template || serverEntry?.type; + const isMinecraft = isMinecraftTemplateLike(resultTemplateId, ""); + const javaVersionsPromise = isMinecraft ? getMinecraftJavaVersions() : null; + + const node = await nodePromise; if (!node) return res.status(400).json({ error: "node not found" }); const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); @@ -26236,7 +30178,6 @@ app.get("/api/settings/servers/:name/resources", async (req, res) => { if (!result.template && serverEntry.template) { result.template = serverEntry.template; } - const resultTemplateId = serverEntry?.template || serverEntry?.type; const resultTemplateInfo = findTemplateById(resultTemplateId); if (!result.templateName && resultTemplateInfo?.name) { result.templateName = resultTemplateInfo.name; @@ -26267,7 +30208,8 @@ app.get("/api/settings/servers/:name/resources", async (req, res) => { if (!result.hostPort && serverEntry.port != null) { result.hostPort = Number(serverEntry.port); } - if (isMinecraftTemplateLike(resultTemplateId, result.templateName || "")) { + const isMinecraftResult = isMinecraft || isMinecraftTemplateLike(resultTemplateId, result.templateName || ""); + if (isMinecraftResult) { const runtimeForJava = (serverEntry.runtime && typeof serverEntry.runtime === "object") ? serverEntry.runtime : ((serverEntry.docker && typeof serverEntry.docker === "object") ? serverEntry.docker : {}); @@ -26277,8 +30219,25 @@ app.get("/api/settings/servers/:name/resources", async (req, res) => { minecraftJavaVersionFromTag(runtimeForJava.tag) || minecraftJavaVersionFromTag(String(result.imageRef || "").split(":").pop()) || minecraftJavaVersionFromTag(DEFAULT_MINECRAFT_PROCESS_TAG); - result.minecraftJava = await minecraftJavaOptionsPayload(selectedJavaVersion); - result.javaVersion = result.minecraftJava.selected; + let versions = javaVersionsPromise ? await javaVersionsPromise : await getMinecraftJavaVersions(); + const selected = normalizeMinecraftJavaVersionInput(selectedJavaVersion) || + minecraftJavaVersionFromTag(DEFAULT_MINECRAFT_PROCESS_TAG) || + (versions.includes("21") ? "21" : versions[0]) || + "21"; + if (!versions.includes(selected)) { + versions = mergeMinecraftJavaVersions([...versions, selected]); + } + result.minecraftJava = { + selected, + image: DEFAULT_MINECRAFT_PROCESS_IMAGE, + tag: minecraftJavaTag(selected), + options: versions.map((version) => ({ + version, + tag: minecraftJavaTag(version), + label: `Java ${version}`, + })), + }; + result.javaVersion = selected; } return res.json(result); } catch (e) { @@ -26700,6 +30659,8 @@ function getSshTerminalWsTarget(req) { return target; } +let activeSshTerminalSessions = 0; + function proxySshTerminalUpgrade(req, socket, head) { let target; try { @@ -26772,6 +30733,10 @@ function attachSshTerminalUpgradeProxy(server) { try { const parsed = new URL(req.url || "", "http://adpanel.local"); if (parsed.pathname !== "/ssh-terminal/ws") return; + activeSshTerminalSessions++; + socket.once("close", () => { + if (activeSshTerminalSessions > 0) activeSshTerminalSessions--; + }); proxySshTerminalUpgrade(req, socket, head); } catch { try { socket.destroy(); } catch { } @@ -26828,6 +30793,87 @@ broadcastNodeUpdate = function (nodeId, status) { }); }; +// --------------------------------------------------------------------------- +// Admin /status monitoring: service-status probe + metrics collector wiring. +// All of this is admin-gated at the socket room / REST layer. +// --------------------------------------------------------------------------- +function readPanelVersion() { + try { + const raw = fs.readFileSync(path.join(__dirname, "panel-information.json"), "utf8"); + const arr = JSON.parse(raw); + const entry = Array.isArray(arr) ? arr[0] : arr; + return (entry && (entry["panel-version"] || entry.version)) || null; + } catch (_) { + return null; + } +} +const PANEL_VERSION = readPanelVersion(); + +async function probeDatabaseStatus() { + const start = Date.now(); + try { + await withTimeout(db.query("SELECT 1"), 2000, "db-ping-timeout"); + return { ok: true, latencyMs: Date.now() - start }; + } catch (_) { + return { ok: false, latencyMs: null }; + } +} + +async function collectMonitorServiceStatus() { + const out = { + database: { ok: false, latencyMs: null }, + nodes: { online: 0, total: 0 }, + containers: { running: 0, stopped: 0, total: 0 }, + sshSessions: activeSshTerminalSessions, + activeSockets: 0, + panelVersion: PANEL_VERSION, + }; + + out.database = await probeDatabaseStatus(); + + try { + out.activeSockets = io?.sockets?.sockets ? io.sockets.sockets.size : 0; + } catch (_) { /* ignore */ } + + try { + const nodes = await withTimeout(Promise.resolve(loadNodes()), 2000, "nodes-timeout").catch(() => []); + out.nodes.total = Array.isArray(nodes) ? nodes.length : 0; + if (Array.isArray(nodes)) { + const checks = await Promise.all(nodes.map(async (n) => { + const id = n.uuid || n.id || n.name; + const st = await getCachedNodeStatus(id).catch(() => null); + return st && st.online === true; + })); + out.nodes.online = checks.filter(Boolean).length; + } + } catch (_) { /* ignore */ } + + try { + const index = await withTimeout(Promise.resolve(loadServersIndex()), 2000, "servers-timeout").catch(() => []); + const names = (Array.isArray(index) ? index : []).map((e) => e && e.name).filter(Boolean); + out.containers.total = names.length; + const statuses = await Promise.all(names.map(async (name) => { + const st = await getCachedServerStatusLenient(name).catch(() => null); + const s = (st && st.status) ? String(st.status).toLowerCase() : ""; + return s === "running" || s === "online"; + })); + out.containers.running = statuses.filter(Boolean).length; + out.containers.stopped = out.containers.total - out.containers.running; + } catch (_) { /* ignore */ } + + return out; +} + +panelMetrics = new PanelMetricsCollector({ + db, + io, + room: "monitor", + startTime: SERVER_START, + panelVersion: PANEL_VERSION, + getServiceStatus: collectMonitorServiceStatus, +}); +panelMetrics.start(); + const LOG_CHUNK_MAX_CHARS = parseInt(process.env.LOG_CHUNK_MAX_CHARS || "", 10) || 10000; function stripAnsiSafe(input) { @@ -26922,17 +30968,43 @@ function getConsoleRoom(room) { return `console:${String(room || "").trim()}`; } -function _emitLine(room, text) { - const cleaned = cleanLog(room, text); +// Detects the node's embedded command marker. Returns the bare command text +// when present, or null otherwise. The node is the authoritative ordering +// source, so a marker line is recorded as a "command" entry at the position it +// arrived, never as output. +function extractConsoleCommandMarker(text) { + const raw = String(text || ""); + const idx = raw.indexOf(CONSOLE_COMMAND_MARKER_PREFIX); + if (idx === -1) return null; + const command = raw.slice(idx + CONSOLE_COMMAND_MARKER_PREFIX.length).trim(); + return command || null; +} + +function _emitLine(room, text, ts = Date.now()) { + const markerCommand = extractConsoleCommandMarker(text); + if (markerCommand) { + rememberConsoleLine(room, markerCommand, "command", ts); + try { io.to(getConsoleRoom(room)).emit("console:command", { server: room, command: markerCommand, ts }); } catch { } + return; + } + let cleaned = cleanLog(room, text); + cleaned = filterConsoleCommandArtifactTextForServer(room, cleaned); if (!cleaned) return; - rememberConsoleLine(room, cleaned, "output"); + rememberConsoleLine(room, cleaned, "output", ts); io.to(getConsoleRoom(room)).emit("output", escapeHtml(cleaned)); } -function emitOutput(socket, room, text) { - const cleaned = cleanLog(room, text); +function emitOutput(socket, room, text, ts = Date.now()) { + const markerCommand = extractConsoleCommandMarker(text); + if (markerCommand) { + rememberConsoleLine(room, markerCommand, "command", ts); + try { io.to(getConsoleRoom(room)).emit("console:command", { server: room, command: markerCommand, ts }); } catch { } + return; + } + let cleaned = cleanLog(room, text); + cleaned = filterConsoleCommandArtifactTextForServer(room, cleaned); if (!cleaned) return; - rememberConsoleLine(room, cleaned, "output"); + rememberConsoleLine(room, cleaned, "output", ts); const safe = escapeHtml(cleaned); try { io.to(getConsoleRoom(room)).emit("output", safe); } catch { } } @@ -26947,7 +31019,11 @@ function emitPanel(room, message) { const remoteLogClients = Object.create(null); function tailLogsRemote(name, baseUrl, headers, options = {}) { - if (remoteLogClients[name]) return; + const force = options && options.force === true; + if (remoteLogClients[name]) { + if (!force) return; + stopTailLogsRemote(name); + } const requestedTail = Number(options && options.tail); const safeTail = Number.isFinite(requestedTail) && requestedTail >= 0 @@ -26965,12 +31041,22 @@ function tailLogsRemote(name, baseUrl, headers, options = {}) { hdrs.Connection = "keep-alive"; const req = lib.request(url, { method: "GET", headers: hdrs }); + const clearClient = () => { + if (remoteLogClients[name] === req) { + delete remoteLogClients[name]; + } + }; req.on("socket", (s) => { try { s.setNoDelay(true); } catch { } }); req.on("response", (res) => { + if (res.statusCode !== 200) { + clearClient(); + try { res.resume(); } catch { } + return; + } res.setEncoding("utf8"); const MAX_BUF = 256 * 1024; @@ -26984,7 +31070,14 @@ function tailLogsRemote(name, baseUrl, headers, options = {}) { try { const obj = JSON.parse(payload); - if (obj && obj.line) _emitLine(name, obj.line); + if (obj && obj.line) { + const rawTs = obj.ts ?? obj.time ?? obj.timestamp; + const numericTs = Number(rawTs); + const parsedTs = Number.isFinite(numericTs) && numericTs > 0 + ? numericTs + : (rawTs ? Date.parse(String(rawTs)) : NaN); + _emitLine(name, obj.line, Number.isFinite(parsedTs) && parsedTs > 0 ? parsedTs : Date.now()); + } else if (typeof obj === "string") _emitLine(name, obj); } catch { _emitLine(name, payload); @@ -27019,16 +31112,20 @@ function tailLogsRemote(name, baseUrl, headers, options = {}) { res.on("end", () => { try { flushEvent(); } catch { } - delete remoteLogClients[name]; + clearClient(); }); res.on("aborted", () => { - delete remoteLogClients[name]; + clearClient(); + }); + + res.on("error", () => { + clearClient(); }); }); req.on("error", () => { - delete remoteLogClients[name]; + clearClient(); }); req.end(); @@ -27078,7 +31175,7 @@ function startRoomStatusWatcher(room, baseUrl, headers) { return; } - const rec = { last: null, failures: 0, timer: null, nodeOnline: true, baseUrl, headers }; + const rec = { last: null, failures: 0, timer: null, nodeOnline: true, serverMissing: false, baseUrl, headers }; async function tick() { if (getRoomClientCount(room) === 0) return stopRoomStatusWatcher(room); @@ -27097,6 +31194,27 @@ function startRoomStatusWatcher(room, baseUrl, headers) { throw new Error("connection-failed"); } + // A definitive 404/410 means the NODE is reachable but the server no longer + // exists on it. This is NOT a node-connection failure and must not be allowed + // to flap the offline overlay (the "404 not found" popup that previously stayed + // stuck after the node came back online). Treat the node as online, surface a + // distinct serverMissing signal so the client can render a real "server gone" + // state, and reset the failure counter so we stop oscillating. + if (status === 404 || status === 410) { + rec.failures = 0; + if (!rec.nodeOnline) { + rec.nodeOnline = true; + io.to(room).emit("nodeStatus", { nodeOnline: true }); + emitPanel(room, "Node connection restored"); + } + if (!rec.serverMissing) { + rec.serverMissing = true; + io.to(room).emit("nodeStatus", { nodeOnline: true, serverMissing: true }); + } + rec.last = "stopped"; + return; + } + if (status !== 200 || !json) { if (!rec.nodeOnline) { rec.nodeOnline = true; @@ -27105,6 +31223,12 @@ function startRoomStatusWatcher(room, baseUrl, headers) { throw new Error("bad-status"); } + // The server is present on the node again; clear any prior missing flag. + if (rec.serverMissing) { + rec.serverMissing = false; + io.to(room).emit("nodeStatus", { nodeOnline: true, serverMissing: false }); + } + const rawStatus = (typeof json.status === "string" && json.status) || (typeof json.state === "string" && json.state) || @@ -27121,9 +31245,13 @@ function startRoomStatusWatcher(room, baseUrl, headers) { } if (rec.last && rec.last !== label) { - if (label === "online") emitPanel(room, "Server started"); - else if (label === "stopped") emitPanel(room, "Server stopped"); - else emitPanel(room, `Server status: ${label}`); + if (label === "online") { + emitPanel(room, "Server started"); + } else if (label === "stopped") { + await clearConsoleHistoryForServer(room, { clearNode: true, emit: true }); + } else { + emitPanel(room, `Server status: ${label}`); + } try { const entry = await findServer(room); @@ -27305,7 +31433,11 @@ function buildResourcePayload(serverName, nodeStats, cachedStatus) { disk: { used: (stats.disk?.usedMb ?? 0) / 1024, total: (stats.disk?.limitMb ?? 0) / 1024, - percent: stats.disk?.percent ?? 0 + percent: stats.disk?.percent ?? 0, + // adpanel:backup-storage - carry the "server files vs backups" split + // through to the UI so storage can be shown as files + backups. + serverMb: stats.disk?.serverMb ?? null, + backupsMb: stats.disk?.backupsMb ?? null }, network: stats.network || nodeStats.network || null, uptime: nodeStats.uptime ?? null, @@ -27439,6 +31571,43 @@ function getSocketIp(socket) { } const socketConnectionsPerIp = new Map(); +const activeSocketsByEmail = new Map(); + +function trackActiveSocketForEmail(email, socket) { + const emailLower = String(email || "").trim().toLowerCase(); + if (!emailLower || !socket) return; + let sockets = activeSocketsByEmail.get(emailLower); + if (!sockets) { + sockets = new Set(); + activeSocketsByEmail.set(emailLower, sockets); + } + sockets.add(socket); + socket.on("disconnect", () => { + const current = activeSocketsByEmail.get(emailLower); + if (!current) return; + current.delete(socket); + if (current.size === 0) activeSocketsByEmail.delete(emailLower); + }); +} + +function disconnectSocketsForUser(email, reason = "account-suspended") { + const emailLower = String(email || "").trim().toLowerCase(); + if (!emailLower) return 0; + const sockets = activeSocketsByEmail.get(emailLower); + if (!sockets || sockets.size === 0) return 0; + + let disconnected = 0; + for (const socket of Array.from(sockets)) { + try { + socket.emit("account:suspended", { reason }); + socket.disconnect(true); + disconnected += 1; + } catch { + } + } + activeSocketsByEmail.delete(emailLower); + return disconnected; +} io.use((socket, next) => { const ip = getSocketIp(socket); @@ -27451,11 +31620,20 @@ io.use((socket, next) => { return next(new Error("origin-not-allowed")); } - sessionMiddleware(socket.request, socket.request.res || {}, (err) => { + sessionMiddleware(socket.request, socket.request.res || {}, async (err) => { if (err) return next(err); const email = socket.request.session?.user; if (!email) return next(new Error("unauthorized")); + try { + const user = await findUserByEmail(email); + if (!user || user.suspended) { + return next(new Error("account-suspended")); + } + } catch (authErr) { + return next(authErr); + } + const currentConnections = socketConnectionsPerIp.get(ip) || 0; if (currentConnections >= 10) { console.warn(`[SECURITY] Max socket connections exceeded: ${ip}`); @@ -27475,19 +31653,62 @@ io.use((socket, next) => { const consoleHistory = new Map(); const CONSOLE_HISTORY_MAX_SERVERS = Math.max(100, parseInt(process.env.CONSOLE_HISTORY_MAX_SERVERS || "", 10) || 2000); -const CONSOLE_HISTORY_MAX_LINES = Math.min(Math.max(parseInt(process.env.CONSOLE_HISTORY_MAX_LINES || "", 10) || 500, 100), 2000); +const CONSOLE_HISTORY_MAX_LINES = Math.min(Math.max(parseInt(process.env.CONSOLE_HISTORY_MAX_LINES || "", 10) || 5000, 100), 5000); const CONSOLE_HISTORY_MAX_LINE_CHARS = Math.min(Math.max(parseInt(process.env.CONSOLE_HISTORY_MAX_LINE_CHARS || "", 10) || 12000, 1000), 50000); const CONSOLE_HISTORY_NODE_CACHE_TTL_MS = 1200; +// Marker prefix emitted by the node to embed a user-issued console command as a +// single in-order line in the same log stream as its output. The node is the +// single source of truth for console ordering; when the panel sees this prefix +// it stores the line as a "command" entry (not output), preserving its exact +// position in the stream. Keep in sync with consoleCommandMarkerPrefix in main.go. +const CONSOLE_COMMAND_MARKER_PREFIX = "ADPANELCMD>> "; +// Backfill window (lines) requested when the panel attaches a fresh log tail +// as a result of a console command. Ensures output produced by the first +// command after a (re)start is captured into consoleHistory and survives a +// browser refresh, instead of being lost to the tail=0 attach race. +const CONSOLE_COMMAND_BACKFILL_TAIL = Math.min(Math.max(parseInt(process.env.CONSOLE_COMMAND_BACKFILL_TAIL || "", 10) || 50, 1), 500); +const CONSOLE_COMMAND_HISTORY_FILE = path.join(process.cwd(), "data", "console-command-history.json"); +const CONSOLE_HISTORY_RESET_FILE = path.join(process.cwd(), "data", "console-history-reset.json"); const consoleHistoryNodeFetchCache = new Map(); const consoleHistoryNodeFetchInflight = new Map(); +const consoleHistoryResetAt = new Map(); + +// Monotonic sequence assigned to every console history entry at insertion +// time. Ordering is driven by this sequence (not by timestamps), so that +// commands and their output always render in the exact order they happened, +// regardless of clock skew between the panel and the node (Pterodactyl-style +// stable, append-only console ordering). +let consoleHistorySeqCounter = 0; +function nextConsoleHistorySeq() { + consoleHistorySeqCounter += 1; + return consoleHistorySeqCounter; +} +function consoleHistorySortComparator(a, b) { + const sa = Number(a?.seq || 0); + const sb = Number(b?.seq || 0); + if (sa && sb && sa !== sb) return sa - sb; + const ta = Number(a?.ts || 0); + const tb = Number(b?.ts || 0); + if (ta !== tb) return ta - tb; + return sa - sb; +} function normalizeConsoleHistoryEntries(entries) { return (Array.isArray(entries) ? entries : []) - .map((item) => ({ - line: String(item?.line || "").slice(0, CONSOLE_HISTORY_MAX_LINE_CHARS), - ts: Number(item?.ts || 0) || Date.now(), - source: String(item?.source || "output"), - })) + .map((item) => { + const seq = Number(item?.seq || 0); + const at = Number(item?.at || 0); + return { + line: String(item?.line || "").slice(0, CONSOLE_HISTORY_MAX_LINE_CHARS), + ts: Number(item?.ts || 0) || Date.now(), + source: String(item?.source || "output"), + seq: Number.isFinite(seq) && seq > 0 ? seq : 0, + // Panel wall-clock at insertion time. Used for staleness checks so we + // never compare against node timestamps (which can be hours off due to + // timezone/clock differences between panel and node). + at: Number.isFinite(at) && at > 0 ? at : 0, + }; + }) .filter((item) => item.line) .slice(-CONSOLE_HISTORY_MAX_LINES); } @@ -27496,14 +31717,165 @@ function cloneConsoleHistoryEntries(entries) { return normalizeConsoleHistoryEntries(entries).map((item) => ({ line: item.line, ts: item.ts, + seq: item.seq, + at: item.at, source: item.source, })); } +function loadPersistedConsoleCommandHistory() { + try { + const raw = fs.readFileSync(CONSOLE_COMMAND_HISTORY_FILE, "utf8"); + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return new Map(); + const out = new Map(); + for (const [name, entries] of Object.entries(parsed)) { + const server = String(name || "").trim(); + if (!server) continue; + const commands = normalizeConsoleHistoryEntries(entries) + .filter((item) => String(item?.source || "output") === "command") + .slice(-100); + if (commands.length) out.set(server, commands); + } + return out; + } catch { + return new Map(); + } +} + +function mergePersistedConsoleCommandHistory(serverName = "") { + const persisted = loadPersistedConsoleCommandHistory(); + const onlyName = String(serverName || "").trim(); + for (const [name, commands] of persisted.entries()) { + if (onlyName && name !== onlyName) continue; + const current = normalizeConsoleHistoryEntries(consoleHistory.get(name)); + const merged = assignConsoleHistorySequences(mergeConsoleHistoryWithCommands(current, commands)); + if (merged.length) consoleHistory.set(name, merged); + } +} + +function persistConsoleCommandHistoryNow() { + try { + const persisted = loadPersistedConsoleCommandHistory(); + for (const [name, history] of consoleHistory.entries()) { + const server = String(name || "").trim(); + if (!server) continue; + const commands = normalizeConsoleHistoryEntries(history) + .filter((item) => String(item?.source || "output") === "command") + .slice(-100); + if (commands.length) persisted.set(server, mergeConsoleCommandHistoryEntries(persisted.get(server), commands)); + else persisted.delete(server); + } + const obj = {}; + for (const [name, commands] of persisted.entries()) { + if (commands.length) obj[name] = commands; + } + fs.mkdirSync(path.dirname(CONSOLE_COMMAND_HISTORY_FILE), { recursive: true }); + const tmp = `${CONSOLE_COMMAND_HISTORY_FILE}.${process.pid}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(obj)); + fs.renameSync(tmp, CONSOLE_COMMAND_HISTORY_FILE); + } catch (err) { + console.debug("[consoleHistory] command persistence error:", err?.message || err); + } +} + +function removePersistedConsoleCommandHistory(serverName) { + const name = String(serverName || "").trim(); + if (!name) return; + try { + const persisted = loadPersistedConsoleCommandHistory(); + persisted.delete(name); + const obj = {}; + for (const [key, commands] of persisted.entries()) { + if (commands.length) obj[key] = commands; + } + fs.mkdirSync(path.dirname(CONSOLE_COMMAND_HISTORY_FILE), { recursive: true }); + const tmp = `${CONSOLE_COMMAND_HISTORY_FILE}.${process.pid}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(obj)); + fs.renameSync(tmp, CONSOLE_COMMAND_HISTORY_FILE); + } catch (err) { + console.debug("[consoleHistory] command persistence remove error:", err?.message || err); + } +} + +function loadPersistedConsoleHistoryResetMarkers() { + try { + const raw = fs.readFileSync(CONSOLE_HISTORY_RESET_FILE, "utf8"); + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return; + for (const [name, value] of Object.entries(parsed)) { + const server = String(name || "").trim(); + const ts = Number(value || 0); + if (server && Number.isFinite(ts) && ts > 0) { + consoleHistoryResetAt.set(server, ts); + } + } + } catch { } +} + +function persistConsoleHistoryResetMarkers() { + try { + const obj = {}; + for (const [name, ts] of consoleHistoryResetAt.entries()) { + if (name && Number(ts) > 0) obj[name] = Number(ts); + } + fs.mkdirSync(path.dirname(CONSOLE_HISTORY_RESET_FILE), { recursive: true }); + const tmp = `${CONSOLE_HISTORY_RESET_FILE}.${process.pid}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(obj)); + fs.renameSync(tmp, CONSOLE_HISTORY_RESET_FILE); + } catch (err) { + console.debug("[consoleHistory] reset marker persistence error:", err?.message || err); + } +} + +function getConsoleHistoryResetAt(serverName) { + const name = String(serverName || "").trim(); + if (!name) return 0; + return Number(consoleHistoryResetAt.get(name) || 0) || 0; +} + +function setConsoleHistoryResetAt(serverName, resetAt = Date.now()) { + const name = String(serverName || "").trim(); + const ts = Number(resetAt || Date.now()) || Date.now(); + if (!name) return 0; + const next = Math.max(getConsoleHistoryResetAt(name), ts); + consoleHistoryResetAt.set(name, next); + persistConsoleHistoryResetMarkers(); + return next; +} + +loadPersistedConsoleHistoryResetMarkers(); + function consoleHistoryEntryKey(item) { return `${String(item?.source || "output")}\u0000${String(item?.line || "")}`; } +function consoleCommandHistoryKey(item) { + const ts = Number(item?.ts || 0) || 0; + const line = normalizeConsoleCommandArtifactText(item?.line || ""); + return line ? `${ts}\u0000${line}` : ""; +} + +function consoleHistoryOutputKey(item) { + if (String(item?.source || "output") === "command") return ""; + const line = String(item?.line || "").trimEnd(); + return line ? `${String(item?.source || "output")}\u0000${line}` : ""; +} + +// Dedupe key for command markers. Uses normalized command text plus a coarse +// time bucket so the SAME keypress arriving from two sources (live stream + +// node ring-buffer warm, which carry different clocks) collapses to one entry, +// while the same command intentionally repeated later stays a separate line. +const CONSOLE_COMMAND_DEDUPE_BUCKET_MS = 15000; +function consoleHistoryCommandDedupeKey(item) { + if (String(item?.source || "output") !== "command") return ""; + const line = normalizeConsoleCommandArtifactText(item?.line || ""); + if (!line) return ""; + const ts = Number(item?.ts || 0) || 0; + const bucket = ts > 0 ? Math.round(ts / CONSOLE_COMMAND_DEDUPE_BUCKET_MS) : 0; + return `${line}\u0000${bucket}`; +} + function findConsoleHistoryOverlap(baseEntries, incomingEntries) { const base = normalizeConsoleHistoryEntries(baseEntries); const incoming = normalizeConsoleHistoryEntries(incomingEntries); @@ -27526,16 +31898,68 @@ function findConsoleHistoryOverlap(baseEntries, incomingEntries) { return { start: -1, size: 0 }; } +// Assign a stable monotonic sequence to any entries that lack one, preserving +// the given array order. Used after merging entries from sources that do not +// carry a seq (node backfill, on-disk persisted commands) so that the final +// in-memory array has a fully-ordered, gap-free sequence for rendering. +function assignConsoleHistorySequences(entries) { + const list = Array.isArray(entries) ? entries : []; + // Walk in array order. Whenever we hit an entry without a seq, give it the + // next monotonic value so it slots in exactly where the merge placed it. + // Entries that already have a seq keep it, and the running cursor is kept at + // least as large as any seq seen so far to preserve monotonic order. + let cursor = consoleHistorySeqCounter; + for (const item of list) { + if (!item) continue; + const seq = Number(item.seq || 0); + if (seq > 0) { + if (seq > cursor) cursor = seq; + } else { + cursor += 1; + item.seq = cursor; + } + } + if (cursor > consoleHistorySeqCounter) consoleHistorySeqCounter = cursor; + return list; +} + function mergeConsoleHistoryEntries(...groups) { const merged = []; for (const group of groups) { const incoming = normalizeConsoleHistoryEntries(group); if (!incoming.length) continue; + const existingOutput = new Set( + merged + .map(consoleHistoryOutputKey) + .filter(Boolean) + ); + // Track recently-merged command markers so the SAME command coming from a + // second source (e.g. the live stream stored it, then a node warm replays + // it from the ring buffer with a different clock) collapses to one entry + // instead of doubling. Keyed by normalized command text + a coarse 15s time + // bucket so a genuinely repeated command stays a separate line, but a + // cross-source duplicate of the same keypress does not. + const existingCommand = new Set( + merged + .map(consoleHistoryCommandDedupeKey) + .filter(Boolean) + ); const overlap = findConsoleHistoryOverlap(merged, incoming); const toAppend = overlap.size > 0 ? incoming.slice(overlap.start + overlap.size) : incoming; for (const item of toAppend) { + if (String(item?.source || "output") === "command") { + const cmdKey = consoleHistoryCommandDedupeKey(item); + if (cmdKey && existingCommand.has(cmdKey)) continue; + if (cmdKey) existingCommand.add(cmdKey); + merged.push(item); + if (merged.length > CONSOLE_HISTORY_MAX_LINES) merged.shift(); + continue; + } + const outputKey = consoleHistoryOutputKey(item); + if (outputKey && existingOutput.has(outputKey)) continue; + if (outputKey) existingOutput.add(outputKey); merged.push(item); if (merged.length > CONSOLE_HISTORY_MAX_LINES) merged.shift(); } @@ -27543,20 +31967,196 @@ function mergeConsoleHistoryEntries(...groups) { return merged.slice(-CONSOLE_HISTORY_MAX_LINES); } -async function fetchRecentConsoleHistoryFromNode(serverName, limit = 100) { +function mergeConsoleCommandHistoryEntries(...groups) { + const merged = []; + const seen = new Set(); + for (const group of groups) { + for (const item of normalizeConsoleHistoryEntries(group)) { + if (String(item?.source || "output") !== "command") continue; + const key = consoleCommandHistoryKey(item); + if (!key || seen.has(key)) continue; + seen.add(key); + merged.push({ + line: item.line, + ts: Number(item.ts || 0) || Date.now(), + source: "command", + seq: Number(item.seq || 0) || 0, + }); + } + } + return merged + .sort((a, b) => (Number(a?.ts || 0) - Number(b?.ts || 0))) + .slice(-100); +} + +function mergeConsoleHistoryWithCommands(history, commands) { + const merged = normalizeConsoleHistoryEntries(history).slice(); + const seenCommands = new Set( + merged + .filter((item) => String(item?.source || "output") === "command") + .map(consoleCommandHistoryKey) + .filter(Boolean) + ); + for (const command of mergeConsoleCommandHistoryEntries(commands)) { + const key = consoleCommandHistoryKey(command); + if (!key || seenCommands.has(key)) continue; + seenCommands.add(key); + merged.push(command); + } + // When some entries already carry a seq (live in-memory history), order by + // seq so command/output interleaving is stable. For a cold start where only + // ts is available (persisted commands), ts ordering is the best signal. + const hasSeq = merged.some((item) => Number(item?.seq || 0) > 0); + merged.sort(hasSeq + ? consoleHistorySortComparator + : (a, b) => (Number(a?.ts || 0) - Number(b?.ts || 0))); + return merged.slice(-CONSOLE_HISTORY_MAX_LINES); +} + +function normalizeConsoleCommandArtifactText(value) { + return stripAnsiSafe(String(value || "")) + .replace(/\r\n/g, "\n") + .replace(/\r/g, "\n") + .replace(/[\r\n]+/g, " ") + .replace(/\s+/g, " ") + .trim() + .replace(/^['"](.+)['"]$/s, "$1") + .trim(); +} + +function firstConsoleCommandToken(value) { + const text = normalizeConsoleCommandArtifactText(value); + if (!text) return ""; + if (text.startsWith('"') || text.startsWith("'")) { + const end = text.indexOf(text[0], 1); + return end > 1 ? text.slice(1, end).trim() : ""; + } + return text.split(/\s+/, 1)[0] || ""; +} + +function duplicatedFirstConsoleCommandArtifact(value) { + const command = normalizeConsoleCommandArtifactText(value); + if (!command) return ""; + const chars = Array.from(command); + return chars.length ? `${chars[0]}${command}` : ""; +} + +function isPrefixedConsoleCommandArtifact(value, commandValue) { + const text = normalizeConsoleCommandArtifactText(value); + const command = normalizeConsoleCommandArtifactText(commandValue); + if (!text || !command || text === command) return false; + if (!text.endsWith(command)) return false; + const prefix = text.slice(0, text.length - command.length); + return !!prefix && command.startsWith(prefix); +} + +function buildConsoleHistoryCommandSets(history) { + const exact = new Set(); + const first = new Set(); + const duplicated = new Set(); + const commands = []; + for (const item of normalizeConsoleHistoryEntries(history)) { + if (String(item?.source || "output") !== "command") continue; + const command = normalizeConsoleCommandArtifactText(item.line); + if (!command) continue; + exact.add(command); + commands.push(command); + const token = firstConsoleCommandToken(command); + if (token) first.add(token); + const duplicate = duplicatedFirstConsoleCommandArtifact(command); + if (duplicate) duplicated.add(duplicate); + } + return { exact, first, duplicated, commands }; +} + +function isKnownConsoleCommandArtifactValue(value, known, allowFirstToken = false) { + const text = normalizeConsoleCommandArtifactText(value); + if (!text) return false; + return known.exact.has(text) || (allowFirstToken && known.first.has(text)); +} + +function isConsoleCommandArtifactLine(line, known) { + const text = normalizeConsoleCommandArtifactText(line); + if (!text) return false; + if (isKnownConsoleCommandArtifactValue(text, known, false)) return true; + if (known.duplicated && known.duplicated.has(text)) return true; + if (Array.isArray(known.commands) && known.commands.some((command) => isPrefixedConsoleCommandArtifact(text, command))) return true; + + let match = text.match(/^\$\s+(.+)$/); + if (match && isKnownConsoleCommandArtifactValue(match[1], known, false)) return true; + + match = text.match(/^(?:\/bin\/)?sh:\s+\d+:\s+(.+?):\s+not found$/i); + if (match && isKnownConsoleCommandArtifactValue(match[1], known, true)) return true; + + match = text.match(/^(?:\/bin\/)?bash:\s+line\s+\d+:\s+(.+?):\s+command not found$/i); + if (match && isKnownConsoleCommandArtifactValue(match[1], known, true)) return true; + + match = text.match(/^(?:\/bin\/)?bash:\s+(.+?):\s+command not found$/i); + if (match && isKnownConsoleCommandArtifactValue(match[1], known, true)) return true; + + return false; +} + +function filterConsoleCommandArtifacts(history) { + const entries = normalizeConsoleHistoryEntries(history); + const known = buildConsoleHistoryCommandSets(entries); + if (!known.exact.size) return entries; + + const filtered = []; + for (const item of entries) { + if (String(item?.source || "output") === "command") { + filtered.push(item); + continue; + } + + const lines = String(item.line || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n").split("\n"); + const kept = lines.filter((line) => !isConsoleCommandArtifactLine(line, known)); + const cleanedLine = kept.join("\n").trimEnd(); + if (!cleanedLine) continue; + filtered.push({ ...item, line: cleanedLine }); + } + return filtered.slice(-CONSOLE_HISTORY_MAX_LINES); +} + +function filterConsoleCommandArtifactTextForServer(serverName, text) { + const value = String(text || ""); + if (!value) return ""; + const history = normalizeConsoleHistoryEntries(consoleHistory.get(String(serverName || ""))); + const known = buildConsoleHistoryCommandSets(history); + if (!known.exact.size) return value; + const kept = value + .replace(/\r\n/g, "\n") + .replace(/\r/g, "\n") + .split("\n") + .filter((line) => !isConsoleCommandArtifactLine(line, known)); + return kept.join("\n").trimEnd(); +} + +function shouldFilterConsoleCommandArtifactsForServer(entry) { + const runtime = entry && entry.runtime && typeof entry.runtime === "object" ? entry.runtime : {}; + const consoleConfig = runtime && runtime.console; + const rawMode = consoleConfig && typeof consoleConfig === "object" && !Array.isArray(consoleConfig) + ? String(consoleConfig.type || consoleConfig.mode || "").trim().toLowerCase() + : String(consoleConfig || "").trim().toLowerCase(); + if (["exec", "exec-shell", "shell"].includes(rawMode)) return false; + return true; +} + +async function fetchRecentConsoleHistoryFromNode(serverName, limit = 100, options = {}) { const requestedLimit = Math.min(Math.max(parseInt(limit, 10) || 100, 1), CONSOLE_HISTORY_MAX_LINES); const requestedName = String(serverName || "").trim(); if (!requestedName) return []; + const bypassCache = options && options.bypassCache === true; const cacheKey = `${requestedName}:${requestedLimit}`; const now = Date.now(); const cached = consoleHistoryNodeFetchCache.get(cacheKey); - if (cached && (now - cached.ts) <= CONSOLE_HISTORY_NODE_CACHE_TTL_MS) { + if (!bypassCache && cached && (now - cached.ts) <= CONSOLE_HISTORY_NODE_CACHE_TTL_MS) { return cloneConsoleHistoryEntries(cached.lines); } const inFlight = consoleHistoryNodeFetchInflight.get(cacheKey); - if (inFlight) { + if (!bypassCache && inFlight) { const shared = await inFlight; return cloneConsoleHistoryEntries(shared); } @@ -27601,9 +32201,31 @@ async function fetchRecentConsoleHistoryFromNode(serverName, limit = 100) { resolve(collected.slice(-requestedLimit)); }; - const idleTimer = setTimeout(finish, 350); - idleTimer.unref?.(); - const maxTimer = setTimeout(finish, 1500); + // The node streams the full persisted snapshot first and then keeps + // the SSE connection open for live lines. We finish once the snapshot + // burst has been delivered and the stream goes idle (no new data for + // IDLE_MS), with MAX_MS as an absolute safety cap. + // + // IMPORTANT: the idle timer MUST be re-armed after every data chunk. + // Previously it was cleared on the first chunk and never rescheduled, + // so the read always ran to the hard cap. During an active boot the + // snapshot + live boot output stream continuously, so the cap fired + // mid-stream and `collected.slice(-requestedLimit)` returned only the + // tail of what had arrived so far (the "logs disappear after refresh + // right after start, but reappear once the server is idle" bug). By + // re-arming on each chunk we wait for the snapshot to be fully + // delivered and the stream to fall idle, capturing the whole console. + const IDLE_MS = 600; + const MAX_MS = 4000; + let idleTimer = null; + const armIdleTimer = () => { + if (settled) return; + if (idleTimer) clearTimeout(idleTimer); + idleTimer = setTimeout(finish, IDLE_MS); + idleTimer.unref?.(); + }; + armIdleTimer(); + const maxTimer = setTimeout(finish, MAX_MS); maxTimer.unref?.(); const flushEvent = () => { @@ -27618,13 +32240,27 @@ async function fetchRecentConsoleHistoryFromNode(serverName, limit = 100) { ? parsed : ""; if (!line) return; - const item = { line: String(line), ts: Date.now(), source: "output" }; + const parsedTs = Number(parsed?.ts ?? parsed?.time ?? parsed?.timestamp); + const dateTs = !Number.isFinite(parsedTs) && (parsed?.ts || parsed?.time || parsed?.timestamp) + ? Date.parse(String(parsed?.ts || parsed?.time || parsed?.timestamp)) + : NaN; + const ts = Number.isFinite(parsedTs) && parsedTs > 0 + ? parsedTs + : (Number.isFinite(dateTs) && dateTs > 0 ? dateTs : Date.now()); + // The node embeds commands in the same stream via a marker prefix. + // Recognise them so they are restored as "command" entries in the + // exact position they occurred, keeping the node the single source + // of truth for ordering. + const markerCommand = extractConsoleCommandMarker(line); + const item = markerCommand + ? { line: markerCommand, ts, source: "command" } + : { line: String(line), ts, source: "output" }; collected.push(item); } catch { } }; nres.on("data", (chunk) => { - clearTimeout(idleTimer); + if (idleTimer) clearTimeout(idleTimer); buf += Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk || ""); while (true) { @@ -27645,6 +32281,11 @@ async function fetchRecentConsoleHistoryFromNode(serverName, limit = 100) { dataLines.push(line.slice(5).trimStart()); } } + // Re-arm the idle timer so we only finish once the node has stopped + // sending (snapshot fully delivered + stream idle), not on the first + // chunk. Without this the read ends prematurely during an active + // boot and returns a truncated snapshot. + armIdleTimer(); }); nres.on("end", () => { clearTimeout(idleTimer); @@ -27693,32 +32334,75 @@ async function getConsoleHistorySnapshot(serverName, limit = 200, options = {}) const safeLimit = Math.min(Math.max(parseInt(limit, 10) || 200, 1), CONSOLE_HISTORY_MAX_LINES); const includeCommands = options && options.includeCommands === true; - let history = normalizeConsoleHistoryEntries(consoleHistory.get(name)); - const latestOutputEntry = [...history].reverse().find((item) => String(item?.source || "output") !== "command"); - const lastOutputTs = latestOutputEntry - ? Number(latestOutputEntry.ts || 0) - : 0; - const newestEntryIsCommand = history.length > 0 && String(history[history.length - 1]?.source || "output") === "command"; - const historyIsStale = !lastOutputTs || (Date.now() - lastOutputTs > 5000); - const nodeWarmThreshold = Math.min(safeLimit, 40); + const clientResetAt = Math.max(0, Number(options?.clientResetAt || 0) || 0); + const serverResetAt = getConsoleHistoryResetAt(name); + const resetAt = Math.max(serverResetAt, clientResetAt); - if (history.length < nodeWarmThreshold || newestEntryIsCommand || historyIsStale) { + // SINGLE SOURCE OF TRUTH (Wings-style): + // + // The node owns the one authoritative, ordered console stream: its in-memory + // ring buffer contains command markers and output already interleaved in true + // arrival order. The panel must NOT maintain a second, competing record that + // can drift from it. + // + // For REMOTE servers we therefore always read the node ring buffer and serve + // it verbatim. This makes a browser refresh deterministically identical to the + // live view: the very same bytes the node streamed live are replayed from the + // same buffer. Previously the panel served its own consoleHistory, which was + // unreliable because the panel's persistent node SSE is torn down whenever no + // socket client is in the console room (e.g. the browser is on the EventSource + // transport), leaving the panel with commands-but-no-output and producing the + // "refresh shows only > cmd" bug. + // + // For LOCAL servers the node IS the panel, so the in-process consoleHistory is + // already the single source and we use it directly. + let history; + const entry = await findServer(name).catch(() => null); + const remote = entry ? isRemoteEntry(entry) : false; + + const canUseNode = clientResetAt <= serverResetAt || options?.allowNodeHistoryAfterClientReset === true; + if (remote && canUseNode) { const nodeHistory = await fetchRecentConsoleHistoryFromNode(name, safeLimit); - if (nodeHistory.length > 0) { - history = mergeConsoleHistoryEntries(history, nodeHistory); - consoleHistory.set(name, history); - } + // Do NOT re-filter node history by resetAt. The node's persisted console log + // is already run-scoped: it is truncated by the node on every container + // (re)start, so whatever it returns belongs to the current run by + // construction. Applying the panel's wall-clock resetAt here additionally + // deleted legitimate current-run lines whenever the node's synthetic + // per-line timestamps fell below the panel's reset wall clock (e.g. boot + // lines emitted in the first seconds after start, or under panel/node clock + // skew). That is exactly the "after a refresh only the last few startup + // lines survive, the rest reappear minutes later" bug. Trust the node's + // run-scoping and serve verbatim; the `canUseNode` guard above already + // prevents serving stale node history after a client-side clear. + history = assignConsoleHistorySequences( + normalizeConsoleHistoryEntries(nodeHistory) + ); + // Keep the panel's mirror in sync so socket-transport clients and other + // consumers see the same authoritative ordering. + if (history.length) consoleHistory.set(name, cloneConsoleHistoryEntries(history)); + } else { + history = normalizeConsoleHistoryEntries(consoleHistory.get(name)) + .filter((item) => Number(item?.ts || 0) >= resetAt); } - const responseHistory = includeCommands + // Serve the stored history verbatim. Every line is already cleaned exactly + // once (node-side cleanLogLine + ingest-time artifact filtering). We never + // re-filter here: doing so retroactively deleted legitimate output that + // happened to match a known command name, which made a command's output show + // live but vanish after a refresh. + const responseHistory = (includeCommands ? history - : history.filter((item) => String(item?.source || "output") !== "command"); + : history.filter((item) => String(item?.source || "output") !== "command")) + .slice() + .sort(consoleHistorySortComparator); return { total: responseHistory.length, + resetAt, lines: responseHistory.slice(-safeLimit).map((item) => ({ line: String(item?.line || ""), ts: Number(item?.ts || 0) || Date.now(), + seq: Number(item?.seq || 0), source: String(item?.source || "output"), })), }; @@ -27726,9 +32410,11 @@ async function getConsoleHistorySnapshot(serverName, limit = 200, options = {}) function resetConsoleHistoryState(serverName) { const name = String(serverName || "").trim(); - if (!name) return; + if (!name) return 0; + const resetAt = setConsoleHistoryResetAt(name); consoleHistory.delete(name); + removePersistedConsoleCommandHistory(name); for (const key of Array.from(consoleHistoryNodeFetchCache.keys())) { if (key.startsWith(`${name}:`)) { @@ -27741,28 +32427,163 @@ function resetConsoleHistoryState(serverName) { consoleHistoryNodeFetchInflight.delete(key); } } + return resetAt; } -function rememberConsoleLine(bot, line, source = "output") { +async function resetNodeConsoleHistory(serverName) { + const requestedName = String(serverName || "").trim(); + if (!requestedName) return { ok: false, skipped: true, error: "missing server" }; + + const entry = await findServer(requestedName); + if (!entry || !isRemoteEntry(entry)) return { ok: true, skipped: true }; + + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) return { ok: false, skipped: true, error: "node not found" }; + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return { ok: false, skipped: true, error: "invalid node address" }; + + const headers = nodeAuthHeadersFor(node, true); + const response = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(entry.name || requestedName)}/logs/reset`, + "POST", + headers, + null, + 8_000 + ); + + if (response.status === 200 && response.json && response.json.ok !== false) { + return { ok: true, skipped: false }; + } + return { + ok: false, + skipped: false, + status: response.status, + error: response.json?.error || response.json?.detail || `node status ${response.status}`, + }; +} + +async function fetchConsoleServerStatusLabel(serverName) { + const state = await fetchConsoleServerState(serverName); + return state?.label || null; +} + +async function fetchConsoleServerState(serverName) { + const requestedName = String(serverName || "").trim(); + if (!requestedName) return null; + + const entry = await findServer(requestedName); + if (!entry || !isRemoteEntry(entry)) return null; + + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) return null; + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return null; + + try { + const response = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(entry.name || requestedName)}`, + "GET", + nodeAuthHeadersFor(node, true), + null, + 3_000 + ); + if (response.status !== 200 || !response.json) return null; + const label = normalizeStatusLabel(response.json.status || response.json.state); + const uptimeSeconds = Number(response.json.uptime || response.json.uptimeSeconds || 0) || 0; + const startedAt = label === "online" && uptimeSeconds > 0 + ? Math.max(0, Date.now() - (uptimeSeconds * 1000)) + : 0; + return { label, startedAt, raw: response.json }; + } catch { + return null; + } +} + +async function clearConsoleHistoryForServer(serverName, options = {}) { + const requestedName = String(serverName || "").trim(); + if (!requestedName) return { ok: false, resetAt: 0, error: "missing server" }; + + const entry = await findServer(requestedName); + const canonicalName = String(entry?.name || requestedName).trim(); + const resetAt = resetConsoleHistoryState(canonicalName); + let nodeReset = { ok: true, skipped: true }; + if (options.clearNode !== false) { + try { + nodeReset = await resetNodeConsoleHistory(canonicalName); + } catch (err) { + nodeReset = { ok: false, skipped: false, error: err?.message || String(err) }; + } + } + + if (options.emit !== false) { + try { + io.to(getConsoleRoom(canonicalName)).emit("console:reset", { server: canonicalName, resetAt }); + } catch { } + } + return { ok: true, server: canonicalName, resetAt, nodeReset }; +} + +if (typeof nodesRouter.setServerActionObserver === "function") { + nodesRouter.setServerActionObserver(async ({ serverName, action }) => { + const normalizedAction = String(action || "").trim().toLowerCase(); + if (normalizedAction === "stop" || normalizedAction === "kill") { + await clearConsoleHistoryForServer(serverName, { clearNode: false, emit: true }); + } + }); +} + +function rememberConsoleLine(bot, line, source = "output", ts = Date.now()) { if (!bot || !line) return; const name = String(bot); - const item = normalizeConsoleHistoryEntries([{ line, ts: Date.now(), source }])[0]; + const item = normalizeConsoleHistoryEntries([{ line, ts, source }])[0]; if (!item) return; let arr = consoleHistory.get(name) || []; + // Guard against duplicate output lines introduced by a backfill tail that + // replays recently-stored lines. Compare against the most recent insertions + // (by insertion order, not timestamp, since node timestamps can skew) so + // genuinely repeated output spaced further apart is still preserved. + if (item.source === "output" && arr.length) { + const lookback = Math.min(arr.length, 25); + for (let i = arr.length - 1; i >= arr.length - lookback; i--) { + const prev = arr[i]; + if (String(prev?.source || "output") === "output" && String(prev?.line || "") === item.line) { + return; + } + } + } + if (!consoleHistory.has(name) && consoleHistory.size >= CONSOLE_HISTORY_MAX_SERVERS) { const oldest = consoleHistory.keys().next().value; if (oldest !== undefined) consoleHistory.delete(oldest); } + // Assign a monotonic sequence at insertion time. This is the authoritative + // ordering used everywhere downstream. + item.seq = nextConsoleHistorySeq(); + // Record panel wall-clock at insertion for skew-free staleness checks. + item.at = Date.now(); + arr.push(item); if (arr.length > CONSOLE_HISTORY_MAX_LINES) arr.shift(); if (consoleHistory.has(name)) consoleHistory.delete(name); consoleHistory.set(name, arr); } -function rememberConsoleCommand(bot, line) { - rememberConsoleLine(bot, line, "command"); +function rememberConsoleCommand(bot, line, options = {}) { + const name = String(bot || "").trim(); + const command = String(line || "").trim(); + const ts = Number(options?.ts || Date.now()) || Date.now(); + rememberConsoleLine(name, command, "command", ts); + persistConsoleCommandHistoryNow(); + if (options.emit !== false && name && command) { + try { + io.to(getConsoleRoom(name)).emit("console:command", { server: name, command, ts }); + } catch { } + } + return ts; } async function removeLegacyConsoleHistoryStorage() { @@ -27790,6 +32611,51 @@ setInterval(() => { } catch (err) { console.debug("[consoleHistory] sweep error:", err.message); } }, 60 * 60 * 1000).unref(); +app.post("/api/servers/:name/console-history/command", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const rawServerName = String(req.params.name || "").trim(); + const email = req.session.user; + const user = email ? await findUserByEmail(email) : null; + const isAdminUser = !!(user && user.admin); + + if (!isAdminUser && !(await userHasAccessToServer(email, rawServerName))) { + return res.status(403).json({ error: "no access to server" }); + } + + const entry = await findServer(rawServerName); + const serverName = entry?.name || rawServerName; + if (!serverName) { + return res.status(404).json({ error: "server not found" }); + } + + if (!isAdminUser) { + const perms = await getEffectivePermsForUserOnServer(email, serverName); + if (!perms?.console_write) { + return res.status(403).json({ error: "not authorized", permission: "console_write" }); + } + } + + const commandCheck = typeof nodesRouter.sanitizeConsoleCommand === "function" + ? nodesRouter.sanitizeConsoleCommand(req.body?.command) + : { ok: true, command: String(req.body?.command || "").trim() }; + if (!commandCheck.ok) { + return res.status(400).json({ error: commandCheck.error || "invalid_command", detail: commandCheck.detail || null }); + } + + // For remote servers the node embeds the command inline in the log stream + // (single source of truth), so recording it here too would duplicate it. + // Only record locally for non-remote servers, which have no node marker. + if (!isRemoteEntry(entry)) { + rememberConsoleCommand(serverName, commandCheck.command); + } + return res.json({ ok: true, server: serverName }); + } catch (err) { + return next(err); + } +}); + app.post("/api/servers/:name/console-history/reset", async (req, res, next) => { try { if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); @@ -27816,8 +32682,8 @@ app.post("/api/servers/:name/console-history/reset", async (req, res, next) => { } } - resetConsoleHistoryState(serverName); - return res.json({ ok: true, server: serverName }); + const result = await clearConsoleHistoryForServer(serverName, { clearNode: true, emit: true }); + return res.json({ ok: true, server: serverName, resetAt: result.resetAt, nodeReset: result.nodeReset }); } catch (err) { return next(err); } @@ -27845,11 +32711,34 @@ app.get("/api/servers/:name/console-history", async (req, res, next) => { } } + const clientResetAt = Math.max(0, Number(req.query.clientResetAt || 0) || 0); + const serverState = await fetchConsoleServerState(serverName); + const currentStatus = serverState?.label || null; + const persistedStatus = normalizeStatusLabel(entry?.status || entry?.state); + const localStatus = String(entry?.status || entry?.state || "").trim().toLowerCase(); + const locallyStartingOrRunning = /start|restart|online|running/.test(localStatus); + const resetAtForClearCheck = Math.max(getConsoleHistoryResetAt(serverName), clientResetAt); + mergePersistedConsoleCommandHistory(serverName); + const hasRecentCommandAfterReset = normalizeConsoleHistoryEntries(consoleHistory.get(serverName)) + .some((item) => String(item?.source || "output") === "command" + && Number(item?.ts || 0) >= resetAtForClearCheck + && (Date.now() - (Number(item?.ts || 0) || 0)) <= 5 * 60 * 1000); + if (((currentStatus === "stopped" && !locallyStartingOrRunning) || (!currentStatus && persistedStatus === "stopped")) + && !hasRecentCommandAfterReset) { + const clearNode = currentStatus === "stopped"; + const result = await clearConsoleHistoryForServer(serverName, { clearNode, emit: false }); + return res.json({ ok: true, server: serverName, total: 0, resetAt: result.resetAt, nodeReset: result.nodeReset, lines: [] }); + } + + const serverStartedAfterLocalClear = clientResetAt > 0 && currentStatus === "online" && Number(serverState?.startedAt || 0) > clientResetAt; const snapshot = await getConsoleHistorySnapshot(serverName, req.query.limit, { includeCommands: String(req.query.includeCommands || "").trim() === "1", + filterCommandArtifacts: shouldFilterConsoleCommandArtifactsForServer(entry), + clientResetAt, + allowNodeHistoryAfterClientReset: serverStartedAfterLocalClear, }); - return res.json({ ok: true, server: serverName, total: snapshot.total, lines: snapshot.lines }); + return res.json({ ok: true, server: serverName, total: snapshot.total, resetAt: snapshot.resetAt || 0, lines: snapshot.lines }); } catch (err) { return next(err); } @@ -27862,6 +32751,12 @@ io.on("connection", async (socket) => { let accessSet = new Set(); try { user = email ? await findUserByEmail(email) : null; + if (!user || user.suspended) { + try { socket.disconnect(true); } catch { } + return; + } + email = String(user.email || email || "").trim().toLowerCase(); + trackActiveSocketForEmail(email, socket); isAdminUser = !!(user && user.admin); if (!isAdminUser && email) { const accessList = await getAccessListForEmail(email); @@ -27887,6 +32782,18 @@ io.on("connection", async (socket) => { const spamInterval = setInterval(() => { messageCount = 0; }, 60_000); + const suspensionInterval = setInterval(async () => { + try { + const latestUser = email ? await findUserByEmail(email) : null; + if (!latestUser || latestUser.suspended) { + try { socket.emit("account:suspended", { reason: "account-suspended" }); } catch { } + socket.disconnect(true); + } + } catch { + socket.disconnect(true); + } + }, 30_000); + suspensionInterval.unref?.(); function deny(room, msg = "Permission denied") { try { socket.emit("output", msg); } catch { } @@ -27907,32 +32814,47 @@ io.on("connection", async (socket) => { return accessSet.has(botName); } + // Mirrors resolveFsWriteMode in nodes.js for the Socket.IO local-mode path: + // returns { ok, mode } so the node enforces create-vs-overwrite atomically. + async function socketWriteMode(botName) { + if (isAdminUser) return { ok: true, mode: "" }; + if (!email) return { ok: false, mode: "" }; + const perms = await getEffectivePermsForUserOnServer(email, botName); + const canCreate = !!(perms && perms.files_create); + const canWrite = !!(perms && perms.files_write); + if (canCreate && canWrite) return { ok: true, mode: "" }; + if (canCreate) return { ok: true, mode: "create" }; + if (canWrite) return { ok: true, mode: "update" }; + return { ok: false, mode: "" }; + } + socket.on("join", async (botName) => { const name = String(botName || "").trim(); if (!name) return; if (!canAccessBot(name)) return deny(name, "[ADPanel] You don't have access to this server."); + const entry = await findServer(name); + if (isServerSuspended(entry)) return deny(name, "[ADPanel] This server is suspended."); const canReadConsole = await hasPerm(name, "console_read"); + if (!entry || !isRemoteEntry(entry)) { + _emitLine(name, "[ADPanel] This server is not attached to a node."); + return; + } + try { await socket.join(name); } catch { } if (canReadConsole) { try { await socket.join(getConsoleRoom(name)); } catch { } } panel(socket, name, "Connected"); - const entry = await findServer(name); - if (!entry || !isRemoteEntry(entry)) { - _emitLine(name, "[ADPanel] This server is not attached to a node."); - return; - } - const node = await findNodeByIdOrName(entry.nodeId); if (!node) return _emitLine(name, "[ADPanel] Node not found."); const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); if (!baseUrl) return _emitLine(name, "[ADPanel] Invalid node address."); - const headers = nodeAuthHeadersFor(node, true); - startRoomStatusWatcher(name, baseUrl, headers); - if (canReadConsole) tailLogsRemote(name, baseUrl, headers); + const headers = nodeAuthHeadersFor(node, true); + startRoomStatusWatcher(name, baseUrl, headers); + if (canReadConsole) tailLogsRemote(name, baseUrl, headers); }); socket.on("dashboard:watch", (payload) => { @@ -27979,9 +32901,34 @@ io.on("connection", async (socket) => { socket.leave('dashboard'); }); + // Admin-only live monitoring room for the /status page. Joining starts the + // intensive 1s sampling loop (driven by room occupancy); leaving stops it + // when the room empties, so the panel costs ~nothing when nobody is watching. + socket.on("monitor:subscribe", async () => { + if (!isAdminUser) { + try { socket.emit("monitor:error", { error: "admin required" }); } catch { } + return; + } + try { await socket.join("monitor"); } catch { } + try { + if (panelMetrics) { + panelMetrics.onRoomChange(); + const snapshot = await panelMetrics.getSnapshot(); + socket.emit("monitor:snapshot", snapshot); + } + } catch (_) { /* ignore */ } + }); + + socket.on("monitor:unsubscribe", () => { + try { socket.leave("monitor"); } catch { } + if (panelMetrics) panelMetrics.onRoomChange(); + }); + socket.on("resources:subscribe", async (payload) => { const serverName = String(payload?.server || payload || '').trim(); if (!serverName || !canAccessBot(serverName)) return; + const entry = await findServer(serverName); + if (isServerSuspended(entry)) return; const room = getResourceRoom(serverName); try { await socket.join(room); } catch { } startResourceStatsWatcher(serverName).catch(() => { }); @@ -27998,6 +32945,8 @@ io.on("connection", async (socket) => { for (const raw of servers) { const serverName = String(raw || '').trim(); if (!serverName || !canAccessBot(serverName)) continue; + const entry = await findServer(serverName); + if (isServerSuspended(entry)) continue; const room = getResourceRoom(serverName); try { await socket.join(room); } catch { continue; } startResourceStatsWatcher(serverName).catch(() => { }); @@ -28027,6 +32976,7 @@ io.on("connection", async (socket) => { socket.on("disconnect", () => { clearInterval(spamInterval); + clearInterval(suspensionInterval); try { for (const room of socket.rooms) { if (room && room !== socket.id && getRoomClientCount(room) === 0) stopRoomStatusWatcher(room); @@ -28039,19 +32989,22 @@ io.on("connection", async (socket) => { } } catch { } stopDashboardWatcher(socket); + if (panelMetrics) { try { setImmediate(() => panelMetrics.onRoomChange()); } catch { } } }); socket.on("readFile", async ({ bot, path: rel }) => { const name = String(bot || "").trim(); if (!name) return; if (!canAccessBot(name) || !(await hasPerm(name, "files_read"))) return deny(name, "[ADPanel] You are not allowed to read files on this server."); + const entry = await findServer(name); + if (isServerSuspended(entry)) return deny(name, "[ADPanel] This server is suspended."); const ctx = await resolveRemoteFsContext(name); if (!ctx.remote) return socket.emit("fileData", { path: rel, content: "/* ERROR: server not found on node */" }); try { const full = safeJoinUnix(ctx.baseDir, rel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, encoding: "utf8" }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, server: ctx.serverName, encoding: "utf8" }, 120000); if (status !== 200 || !json || !json.ok) throw new Error("node-read-failed"); socket.emit("fileData", { path: rel, content: typeof json.content === "string" ? json.content : "" }); } catch (e) { @@ -28063,14 +33016,20 @@ io.on("connection", async (socket) => { socket.on("writeFile", async ({ bot, path: rel, content }) => { const name = String(bot || "").trim(); if (!name) return; - if (!canAccessBot(name) || !(await hasPerm(name, "files_create"))) return deny(name, "[ADPanel] You are not allowed to edit files on this server."); + if (!canAccessBot(name)) return deny(name, "[ADPanel] You are not allowed to edit files on this server."); + const writeMode = await socketWriteMode(name); + if (!writeMode.ok) return deny(name, "[ADPanel] You are not allowed to edit files on this server."); + const entry = await findServer(name); + if (isServerSuspended(entry)) return deny(name, "[ADPanel] This server is suspended."); const ctx = await resolveRemoteFsContext(name); if (!ctx.remote) return io.to(name).emit("toast", { type: "error", msg: "Save failed: server not found on node" }); try { const full = safeJoinUnix(ctx.baseDir, rel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/write", { path: full, content: content ?? "", encoding: "utf8" }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/write", { path: full, server: ctx.serverName, content: content ?? "", encoding: "utf8", mode: writeMode.mode }, 120000); + if (status === 409) return deny(name, "[ADPanel] Overwriting existing files requires the 'Edit existing files' permission."); + if (status === 404 && json && json.existed === false) return deny(name, "[ADPanel] Creating new files requires the 'Create files/folders' permission."); if (status !== 200 || !json || !json.ok) throw new Error("node-write-failed"); io.to(name).emit("toast", { type: "success", msg: `Saved ${escapeHtml(rel)}` }); } catch (e) { @@ -28083,13 +33042,15 @@ io.on("connection", async (socket) => { const name = String(bot || "").trim(); if (!name) return; if (!canAccessBot(name) || !(await hasPerm(name, "files_delete"))) return deny(name, "[ADPanel] You are not allowed to delete files on this server."); + const entry = await findServer(name); + if (isServerSuspended(entry)) return deny(name, "[ADPanel] This server is suspended."); const ctx = await resolveRemoteFsContext(name); if (!ctx.remote) return io.to(name).emit("toast", { type: "error", msg: "Delete failed: server not found on node" }); try { const full = safeJoinUnix(ctx.baseDir, rel || ""); - const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/delete", { path: full, isDir: !!isDir }, 120000); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/delete", { path: full, server: ctx.serverName, isDir: !!isDir }, 120000); if (status !== 200 || !json || !json.ok) throw new Error("node-delete-failed"); io.to(name).emit("toast", { type: "success", msg: `Deleted ${escapeHtml(rel)}` }); } catch (e) { @@ -28105,12 +33066,13 @@ io.on("connection", async (socket) => { if (!canAccessBot(botName)) return deny(botName, "[ADPanel] You don't have access to this server."); const canReadConsole = await hasPerm(botName, "console_read"); + const entry = await findServer(botName); + if (isServerSuspended(entry)) return deny(botName, "[ADPanel] This server is suspended."); + if (!entry || !isRemoteEntry(entry)) return _emitLine(botName, "[ADPanel] This server is not attached to a node."); try { socket.join(botName); } catch { } if (canReadConsole) { try { socket.join(getConsoleRoom(botName)); } catch { } } - const entry = await findServer(botName); - if (!entry || !isRemoteEntry(entry)) return _emitLine(botName, "[ADPanel] This server is not attached to a node."); const node = await findNodeByIdOrName(entry.nodeId); if (!node) return _emitLine(botName, "[ADPanel] Node not found."); @@ -28120,15 +33082,15 @@ io.on("connection", async (socket) => { const headers = nodeAuthHeadersFor(node, true); - startRoomStatusWatcher(botName, baseUrl, headers); - if (canReadConsole) tailLogsRemote(botName, baseUrl, headers); + startRoomStatusWatcher(botName, baseUrl, headers); + if (canReadConsole) tailLogsRemote(botName, baseUrl, headers); if ((cmd === "stop" || cmd === "restart" || cmd === "kill") && !(await hasPerm(botName, "server_stop"))) return deny(botName); if (cmd === "run" && !(await hasPerm(botName, "server_start"))) return deny(botName); try { if (cmd === "run") { - resetConsoleHistoryState(botName); + await clearConsoleHistoryForServer(botName, { clearNode: true, emit: true }); panel(socket, botName, "Server starting"); const defaultPort = normalizeTemplateId(entry.template) === "minecraft" ? 25565 : 3001; @@ -28148,7 +33110,7 @@ io.on("connection", async (socket) => { } catch { } panel(socket, botName, "Start request accepted."); - if (canReadConsole) tailLogsRemote(botName, baseUrl, headers); + if (canReadConsole) tailLogsRemote(botName, baseUrl, headers, { force: true }); return; } @@ -28163,18 +33125,19 @@ io.on("connection", async (socket) => { } catch { } panel(socket, botName, "Server stopped"); + await clearConsoleHistoryForServer(botName, { clearNode: false, emit: true }); return; } if (cmd === "restart") { - resetConsoleHistoryState(botName); + await clearConsoleHistoryForServer(botName, { clearNode: true, emit: true }); emitPanel(botName, "Server restarting"); const r = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(botName)}/restart`, "POST", headers, null, 20_000); if (r.status !== 200 || !(r.json && r.json.ok)) throw new Error((r.json && (r.json.error || r.json.detail)) || `node status ${r.status}`); emitPanel(botName, "Server restarted"); - if (canReadConsole) tailLogsRemote(botName, baseUrl, headers); + if (canReadConsole) tailLogsRemote(botName, baseUrl, headers, { force: true }); return; } @@ -28185,6 +33148,7 @@ io.on("connection", async (socket) => { if (r.status !== 200 || !(r.json && r.json.ok)) throw new Error((r.json && (r.json.error || r.json.detail)) || `node status ${r.status}`); emitPanel(botName, "Server killed"); + await clearConsoleHistoryForServer(botName, { clearNode: false, emit: true }); return; } @@ -28221,9 +33185,19 @@ io.on("connection", async (socket) => { return; } + const entry = await findServer(botName); + if (isServerSuspended(entry)) { + deny(botName, "[ADPanel] This server is suspended."); + reply({ ok: false, error: "server suspended", code: "server-suspended" }); + return; + } + + const canReadConsole = await hasPerm(botName, "console_read"); + if (canReadConsole) { + try { socket.join(getConsoleRoom(botName)); } catch { } + } rememberConsoleCommand(botName, trimmed); - const entry = await findServer(botName); if (!entry || !isRemoteEntry(entry)) { _emitLine(botName, "[ADPanel] This server is not attached to a node."); reply({ ok: false, error: "not remote" }); @@ -28246,6 +33220,18 @@ io.on("connection", async (socket) => { const headers = nodeAuthHeadersFor(node, true); const body = requestId ? { command: trimmed, requestId } : { command: trimmed }; + if (canReadConsole) { + startRoomStatusWatcher(botName, baseUrl, headers); + // If the panel is not already tailing this server's logs, the very first + // command after a (re)start would race the SSE connection: the command + // output is produced on the node before our tail attaches with tail=0, + // so it never reaches consoleHistory and disappears on browser refresh. + // Attach with a small backfill tail on first attach to capture it. + const tailAlreadyRunning = !!remoteLogClients[botName]; + tailLogsRemote(botName, baseUrl, headers, tailAlreadyRunning + ? {} + : { force: true, tail: CONSOLE_COMMAND_BACKFILL_TAIL }); + } try { const r = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(botName)}/command`, "POST", headers, body, 20_000); @@ -28255,6 +33241,9 @@ io.on("connection", async (socket) => { reply({ ok: false, error: msg, status: r.status }); return; } + try { + recordActivity(botName, "console_command", { command: trimmed }, email || "unknown", getClientIP(socket.request || {})); + } catch { } reply({ ok: true }); } catch (e) { _emitLine(botName, "[ADPanel] command error: " + (e?.message || String(e))); @@ -28326,6 +33315,8 @@ function scheduleStartupMaturityNotice(delayMs = 1500) { } async function startServers() { + await prepareSessionBackendForStartup(); + try { await ensureMySqlRunning(); } catch (e) { @@ -28335,6 +33326,20 @@ async function startServers() { await db.ensureSchema(); await removeLegacyConsoleHistoryStorage(); + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'secret'`); + const secretColumn = Array.isArray(cols) ? cols[0] : null; + if (secretColumn && String(secretColumn.Null || "").toUpperCase() !== "YES") { + await db.query("ALTER TABLE users MODIFY COLUMN secret VARCHAR(255) NULL"); + console.log("[db] Made users.secret nullable for optional 2FA"); + } + await db.query("UPDATE users SET secret = NULL WHERE secret = ''"); + } catch (err) { + if (!err.message?.includes("Duplicate column")) { + console.debug("[db] users.secret nullable check:", err.message); + } + } + try { const [cols] = await db.pool.execute("SHOW COLUMNS FROM servers LIKE 'display_name'"); if (!cols || cols.length === 0) { @@ -28347,6 +33352,49 @@ async function startServers() { } } + try { + const [cols] = await db.pool.query("SHOW COLUMNS FROM servers LIKE 'suspended'"); + if (!cols || cols.length === 0) { + await db.query("ALTER TABLE servers ADD COLUMN suspended TINYINT(1) NOT NULL DEFAULT 0 AFTER status"); + console.log("[db] Added suspended column to servers table"); + } + } catch (err) { + if (!err.message?.includes("Duplicate column")) { + console.debug("[db] servers.suspended column check:", err.message); + } + } + + try { + const [cols] = await db.pool.query("SHOW COLUMNS FROM servers LIKE 'suspended_at'"); + if (!cols || cols.length === 0) { + await db.query("ALTER TABLE servers ADD COLUMN suspended_at BIGINT UNSIGNED DEFAULT NULL AFTER suspended"); + console.log("[db] Added suspended_at column to servers table"); + } + } catch (err) { + if (!err.message?.includes("Duplicate column")) { + console.debug("[db] servers.suspended_at column check:", err.message); + } + } + + try { + const [cols] = await db.pool.query("SHOW COLUMNS FROM servers LIKE 'suspended_by'"); + if (!cols || cols.length === 0) { + await db.query("ALTER TABLE servers ADD COLUMN suspended_by VARCHAR(255) DEFAULT NULL AFTER suspended_at"); + console.log("[db] Added suspended_by column to servers table"); + } + } catch (err) { + if (!err.message?.includes("Duplicate column")) { + console.debug("[db] servers.suspended_by column check:", err.message); + } + } + + try { + await initServerDeleteJobsTable(); + startServerDeleteWorker(); + } catch (err) { + console.warn("[startup] Server delete job worker disabled:", err?.message || err); + } + startStatusPolling(); // Migrate database tools nginx configs to internal-only proxy @@ -28406,6 +33454,42 @@ async function startServers() { } } + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'suspended'`); + if (!cols || cols.length === 0) { + await db.query("ALTER TABLE users ADD COLUMN suspended TINYINT(1) NOT NULL DEFAULT 0 AFTER admin"); + console.log('[db] Added suspended column to users table'); + } + } catch (err) { + if (!err.message?.includes('Duplicate column')) { + console.debug('[db] suspended column check:', err.message); + } + } + + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'suspended_at'`); + if (!cols || cols.length === 0) { + await db.query("ALTER TABLE users ADD COLUMN suspended_at BIGINT UNSIGNED DEFAULT NULL AFTER suspended"); + console.log('[db] Added suspended_at column to users table'); + } + } catch (err) { + if (!err.message?.includes('Duplicate column')) { + console.debug('[db] suspended_at column check:', err.message); + } + } + + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'suspended_by'`); + if (!cols || cols.length === 0) { + await db.query("ALTER TABLE users ADD COLUMN suspended_by VARCHAR(255) DEFAULT NULL AFTER suspended_at"); + console.log('[db] Added suspended_by column to users table'); + } + } catch (err) { + if (!err.message?.includes('Duplicate column')) { + console.debug('[db] suspended_by column check:', err.message); + } + } + try { const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'avatar_url'`); if (!cols || cols.length === 0) { diff --git a/initialize.sh b/initialize.sh index 1bc4c44..27afb50 100755 --- a/initialize.sh +++ b/initialize.sh @@ -86,9 +86,20 @@ if [ "$EUID" -ne 0 ]; then fi SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -if [ -n "$SCRIPT_DIR" ]; then - cd "$SCRIPT_DIR" || exit 1 +ADPANEL_PRODUCTION_ROOT="${ADPANEL_PRODUCTION_ROOT:-/var/www/adpanel}" +PANEL_ROOT="${ADPANEL_PANEL_ROOT:-${PANEL_DIR:-}}" +if [ -z "$PANEL_ROOT" ]; then + if [ -f "${ADPANEL_PRODUCTION_ROOT}/initialize.sh" ] && [ -f "${ADPANEL_PRODUCTION_ROOT}/index.js" ]; then + PANEL_ROOT="$ADPANEL_PRODUCTION_ROOT" + else + PANEL_ROOT="$SCRIPT_DIR" + fi fi +if ! PANEL_ROOT="$(cd "$PANEL_ROOT" 2>/dev/null && pwd)"; then + ui_error "Panel root not found: ${ADPANEL_PANEL_ROOT:-${PANEL_DIR:-$ADPANEL_PRODUCTION_ROOT}}" + exit 1 +fi +cd "$PANEL_ROOT" || exit 1 ui_banner ui_section "Choose an option:" @@ -98,7 +109,11 @@ ui_menu_item "3) Delete an user" ui_menu_item "4) Create User" CHOICE="${ADPANEL_INIT_CHOICE:-}" -if [ -z "$CHOICE" ] && [ "${1:-}" == "--choice" ]; then +if [ -z "$CHOICE" ] && { [ "${1:-}" == "--sshterm-only" ] || [ "${1:-}" == "--repair-sshterm" ]; }; then + CHOICE="5" +elif [ -z "$CHOICE" ] && [ "${1:-}" == "--repair-mysql" ]; then + CHOICE="6" +elif [ -z "$CHOICE" ] && [ "${1:-}" == "--choice" ]; then CHOICE="${2:-}" elif [ -z "$CHOICE" ] && [[ "${1:-}" == --choice=* ]]; then CHOICE="${1#--choice=}" @@ -109,16 +124,19 @@ if [ -n "$CHOICE" ]; then else read -p "$(ui_prompt "Enter choice (1, 2, 3 or 4): ")" CHOICE fi +ui_kv "Panel root:" "$PANEL_ROOT" CREATE_USER_SCRIPT="" -if [ -f "${SCRIPT_DIR}/scripts/create-user.js" ]; then - CREATE_USER_SCRIPT="${SCRIPT_DIR}/scripts/create-user.js" -elif [ -f "${SCRIPT_DIR}/create-user.js" ]; then - CREATE_USER_SCRIPT="${SCRIPT_DIR}/create-user.js" +if [ -f "${PANEL_ROOT}/scripts/create-user.js" ]; then + CREATE_USER_SCRIPT="${PANEL_ROOT}/scripts/create-user.js" +elif [ -f "${PANEL_ROOT}/create-user.js" ]; then + CREATE_USER_SCRIPT="${PANEL_ROOT}/create-user.js" fi OS_ID="unknown" OS_LIKE="" +OS_VERSION_ID="" +OS_MAJOR_ID="" PKG_MGR="unknown" INIT_SYSTEM="unknown" PKG_METADATA_READY="false" @@ -130,6 +148,7 @@ REDIS_CLI_CMD="redis-cli" NODE_MIN_MAJOR=18 GO_MIN_VERSION="1.24.0" GO_INSTALL_VERSION="1.24.11" +ADPANEL_SOURCE_RAW_BASE="${ADPANEL_SOURCE_RAW_BASE:-https://raw.githubusercontent.com/antonndev/ADPanel/main}" MYSQL_HOST="" MYSQL_PORT="" @@ -222,6 +241,8 @@ detect_platform() { . /etc/os-release OS_ID="${ID:-unknown}" OS_LIKE="${ID_LIKE:-}" + OS_VERSION_ID="${VERSION_ID:-}" + OS_MAJOR_ID="${OS_VERSION_ID%%.*}" fi if systemd_available; then @@ -473,11 +494,13 @@ enable_rhel_extra_repos() { ui_info "Checking optional RHEL-compatible repositories..." if [ "$PKG_MGR" = "dnf" ]; then + $SUDO dnf install -y --setopt=timeout=60 dnf-plugins-core >/dev/null 2>&1 || true $SUDO dnf install -y --setopt=timeout=60 epel-release >/dev/null 2>&1 || true - if cmd_exists dnf; then - $SUDO dnf config-manager --set-enabled crb >/dev/null 2>&1 || \ - $SUDO dnf config-manager --set-enabled powertools >/dev/null 2>&1 || true + if cmd_exists crb; then + $SUDO crb enable >/dev/null 2>&1 || true fi + $SUDO dnf config-manager --set-enabled crb >/dev/null 2>&1 || \ + $SUDO dnf config-manager --set-enabled powertools >/dev/null 2>&1 || true else $SUDO yum install -y epel-release >/dev/null 2>&1 || true if cmd_exists yum-config-manager; then @@ -490,6 +513,95 @@ enable_rhel_extra_repos() { return 0 } +enable_rhel_redis_module_if_available() { + case "$PKG_MGR" in + dnf|yum) ;; + *) return 0 ;; + esac + + local module_cmd="$PKG_MGR" + local tmp="" + tmp="$(mktemp /tmp/adpanel-redis-module.XXXXXX 2>/dev/null || echo "")" + [ -n "$tmp" ] || return 0 + + if ! $SUDO "$module_cmd" -q module list redis >"$tmp" 2>/dev/null; then + rm -f "$tmp" >/dev/null 2>&1 || true + return 0 + fi + + local stream="" + for candidate in 7 6 5; do + if grep -Eq "^[[:space:]]*redis[[:space:]]+${candidate}([[:space:]]|$|\\[)" "$tmp"; then + stream="$candidate" + break + fi + done + rm -f "$tmp" >/dev/null 2>&1 || true + + [ -n "$stream" ] || return 0 + ui_info "Enabling Redis module stream redis:${stream}..." + $SUDO "$module_cmd" -y module reset redis >/dev/null 2>&1 || true + $SUDO "$module_cmd" -y module enable "redis:${stream}" >/dev/null 2>&1 || true + PKG_METADATA_READY="false" + return 0 +} + +supports_official_redis_rpm_repo() { + case "$PKG_MGR" in + dnf|yum) ;; + *) return 1 ;; + esac + + case "$OS_MAJOR_ID" in + 8|9) ;; + *) return 1 ;; + esac + + case "$OS_ID" in + rocky|rockylinux|almalinux|alma|centos|rhel|ol|oracle) + return 0 + ;; + esac + + printf "%s" "$OS_LIKE" | grep -qiE '(^|[[:space:]])(rhel|fedora)([[:space:]]|$)' +} + +install_redis_from_official_rpm_repo() { + supports_official_redis_rpm_repo || return 1 + cmd_exists rpm || return 1 + + local repo_major="$OS_MAJOR_ID" + local repo_file="/etc/yum.repos.d/redis.repo" + local key_file="/tmp/adpanel-redis.key" + local baseurl="${ADPANEL_REDIS_RPM_REPO_BASEURL:-http://packages.redis.io/rpm/rockylinux${repo_major}}" + + ui_info "Trying official Redis RPM repository for RHEL-compatible ${repo_major}..." + if download_file "https://packages.redis.io/gpg" "$key_file" >/dev/null 2>&1; then + $SUDO rpm --import "$key_file" >/dev/null 2>&1 || true + rm -f "$key_file" >/dev/null 2>&1 || true + else + ui_warn "Could not download Redis GPG key; skipping official Redis RPM fallback." + return 1 + fi + + $SUDO mkdir -p /etc/yum.repos.d >/dev/null 2>&1 || true + cat </dev/null +[Redis] +name=Redis +baseurl=${baseurl} +enabled=1 +gpgcheck=1 +gpgkey=https://packages.redis.io/gpg +EOF + + $SUDO "$PKG_MGR" -y module reset redis >/dev/null 2>&1 || true + $SUDO "$PKG_MGR" -y module disable redis >/dev/null 2>&1 || true + PKG_METADATA_READY="false" + ensure_pkg_metadata >/dev/null 2>&1 || true + + pkg_install redis +} + pkg_install_try_sets() { local set for set in "$@"; do @@ -774,7 +886,7 @@ cpp_compiler_ready() { install_base_system_packages() { local need_base="false" - if ! cmd_exists curl || ! cmd_exists openssl || ! cmd_exists tar || ! cmd_exists xz || ! python_ready || ! cmd_exists make; then + if ! cmd_exists curl || ! cmd_exists openssl || ! cmd_exists tar || ! cmd_exists xz || ! python_ready || ! cmd_exists make || ! cmd_exists git; then need_base="true" fi if ! compiler_ready || ! cpp_compiler_ready; then @@ -796,19 +908,19 @@ install_base_system_packages() { case "$PKG_MGR" in apt) - pkg_install ca-certificates curl openssl tar xz-utils python3 make g++ + pkg_install ca-certificates curl git openssl tar xz-utils python3 make g++ ;; dnf|yum) - pkg_install ca-certificates curl openssl tar xz python3 make gcc gcc-c++ + pkg_install ca-certificates curl git openssl tar xz python3 make gcc gcc-c++ ;; apk) - pkg_install ca-certificates curl openssl tar xz python3 make g++ + pkg_install ca-certificates curl git openssl tar xz python3 make g++ ;; pacman) - pkg_install ca-certificates curl openssl tar xz python make gcc + pkg_install ca-certificates curl git openssl tar xz python make gcc ;; zypper) - pkg_install ca-certificates curl openssl tar xz python3 make gcc-c++ + pkg_install ca-certificates curl git openssl tar xz python3 make gcc-c++ ;; *) ui_error "Unsupported package manager for base system packages." @@ -821,7 +933,7 @@ install_base_system_packages() { fi ensure_python_binary_alias >/dev/null 2>&1 || true - if ! cmd_exists curl || ! cmd_exists openssl || ! cmd_exists tar || ! cmd_exists xz || ! python_ready || ! cmd_exists make; then + if ! cmd_exists curl || ! cmd_exists openssl || ! cmd_exists tar || ! cmd_exists xz || ! python_ready || ! cmd_exists make || ! cmd_exists git; then ui_error "Failed to install one or more required base system packages." return 1 fi @@ -1053,7 +1165,7 @@ ensure_go_runtime() { } project_extensions_ready() { - [ -d "${SCRIPT_DIR}/node_modules" ] || return 1 + [ -d "${PANEL_ROOT}/node_modules" ] || return 1 npm ls --omit=dev --depth=0 >/dev/null 2>&1 } @@ -1176,6 +1288,84 @@ service_reload() { esac } +ensure_panel_env_permissions() { + local panel_root="${1:-$PANEL_ROOT}" + local env_file="${panel_root}/.env" + [ -f "$env_file" ] || return 0 + + if id -u adpanel >/dev/null 2>&1; then + $SUDO chown adpanel:adpanel "$env_file" >/dev/null 2>&1 || true + $SUDO chmod 0640 "$env_file" >/dev/null 2>&1 || true + else + $SUDO chmod 0600 "$env_file" >/dev/null 2>&1 || true + fi +} + +is_rhel_like_platform() { + local id_like=" ${OS_LIKE:-} " + case "${OS_ID:-}" in + rocky|rhel|almalinux|centos|ol|fedora) + return 0 + ;; + esac + case "$id_like" in + *" rhel "*|*" fedora "*) + return 0 + ;; + esac + return 1 +} + +apply_adpanel_host_limits() { + local file_max="${ADPANEL_HOST_FILE_MAX:-1048576}" + local nr_open="${ADPANEL_HOST_NR_OPEN:-1048576}" + local inotify_watches="${ADPANEL_INOTIFY_MAX_USER_WATCHES:-1048576}" + local inotify_instances="${ADPANEL_INOTIFY_MAX_USER_INSTANCES:-2048}" + local sysctl_file="/etc/sysctl.d/99-adpanel-host-limits.conf" + local limits_file="/etc/security/limits.d/99-adpanel-nofile.conf" + + if ! printf "%s" "$file_max" | grep -qE '^[0-9]+$'; then file_max=1048576; fi + if ! printf "%s" "$nr_open" | grep -qE '^[0-9]+$'; then nr_open=1048576; fi + if ! printf "%s" "$inotify_watches" | grep -qE '^[0-9]+$'; then inotify_watches=1048576; fi + if ! printf "%s" "$inotify_instances" | grep -qE '^[0-9]+$'; then inotify_instances=2048; fi + + if [ "$file_max" -lt 1048576 ] 2>/dev/null; then file_max=1048576; fi + if [ "$nr_open" -lt 1048576 ] 2>/dev/null; then nr_open=1048576; fi + + if is_rhel_like_platform; then + ui_info "Applying Rocky/RHEL-safe host file limits for Docker game servers..." + else + ui_info "Applying ADPanel host file limits for Docker game servers..." + fi + + cat </dev/null +# Managed by ADPanel. Required for game servers that open many files/sockets. +fs.file-max = ${file_max} +fs.nr_open = ${nr_open} +fs.inotify.max_user_watches = ${inotify_watches} +fs.inotify.max_user_instances = ${inotify_instances} +EOF + + $SUDO sysctl -w "fs.file-max=${file_max}" >/dev/null 2>&1 || true + $SUDO sysctl -w "fs.nr_open=${nr_open}" >/dev/null 2>&1 || true + $SUDO sysctl -w "fs.inotify.max_user_watches=${inotify_watches}" >/dev/null 2>&1 || true + $SUDO sysctl -w "fs.inotify.max_user_instances=${inotify_instances}" >/dev/null 2>&1 || true + + cat </dev/null +# Managed by ADPanel. +* soft nofile ${nr_open} +* hard nofile ${nr_open} +root soft nofile ${nr_open} +root hard nofile ${nr_open} +adpanel soft nofile ${nr_open} +adpanel hard nofile ${nr_open} +adaemon soft nofile ${nr_open} +adaemon hard nofile ${nr_open} +EOF + + ui_success "Host file limits set to ${nr_open}." +} + detect_redis_commands() { if cmd_exists redis-server; then REDIS_SERVER_CMD="redis-server" @@ -1201,7 +1391,7 @@ detect_redis_commands setup_adpanel_systemd_service() { local service_name="adpanel" local service_file="/etc/systemd/system/${service_name}.service" - local panel_root="$SCRIPT_DIR" + local panel_root="$PANEL_ROOT" local runtime_script="${panel_root}/scripts/adpanel-runtime.sh" local monitor_script="${panel_root}/scripts/adpanel-autoscale-monitor.sh" local ecosystem_generator_script="${panel_root}/scripts/generate-ecosystem.sh" @@ -1288,7 +1478,8 @@ setup_adpanel_systemd_service() { cat </dev/null [Unit] Description=ADPanel PM2 Cluster Service -After=network.target +After=network.target adpanel-sshterm.service +Wants=adpanel-sshterm.service [Service] Type=simple @@ -1312,6 +1503,9 @@ LimitNOFILE=1048576 [Install] WantedBy=multi-user.target EOF + if cmd_exists restorecon; then + $SUDO restorecon "$service_file" >/dev/null 2>&1 || true + fi if ! $SUDO systemctl daemon-reload; then ui_error "Failed to reload systemd daemon after writing ${service_file}." @@ -1351,7 +1545,7 @@ EOF setup_adpanel_openrc_service() { local service_name="adpanel" local service_file="/etc/init.d/${service_name}" - local panel_root="$SCRIPT_DIR" + local panel_root="$PANEL_ROOT" local runtime_script="${panel_root}/scripts/adpanel-runtime.sh" local monitor_script="${panel_root}/scripts/adpanel-autoscale-monitor.sh" local ecosystem_generator_script="${panel_root}/scripts/generate-ecosystem.sh" @@ -1414,7 +1608,7 @@ export PM2_HOME="${pm2_home_dir}" depend() { need net - after mysql mariadb redis redis-server valkey nginx + after adpanel-sshterm mysql mariadb redis redis-server valkey nginx } EOF @@ -1436,7 +1630,7 @@ EOF setup_adpanel_sysv_service() { local service_name="adpanel" local service_file="/etc/init.d/${service_name}" - local panel_root="$SCRIPT_DIR" + local panel_root="$PANEL_ROOT" local runtime_script="${panel_root}/scripts/adpanel-runtime.sh" local monitor_script="${panel_root}/scripts/adpanel-autoscale-monitor.sh" local ecosystem_generator_script="${panel_root}/scripts/generate-ecosystem.sh" @@ -1484,6 +1678,7 @@ setup_adpanel_sysv_service() { ### BEGIN INIT INFO # Provides: ${service_name} # Required-Start: \$remote_fs \$network +# Should-Start: adpanel-sshterm # Required-Stop: \$remote_fs \$network # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 @@ -1606,13 +1801,394 @@ print_adpanel_service_commands() { esac } +read_env_file_value() { + local file="$1" + local key="$2" + [ -f "$file" ] || return 1 + grep -E "^[[:space:]]*${key}[[:space:]]*=" "$file" 2>/dev/null \ + | tail -n 1 \ + | sed -E "s/^[^=]*=[[:space:]]*//; s/^['\"]//; s/['\"]$//" +} + +resolve_sshterm_port() { + local panel_root="$1" + local port="${SSH_TERM_PORT:-}" + if [ -z "$port" ]; then + port="$(read_env_file_value "${panel_root}/.env" "SSH_TERM_PORT" || true)" + fi + normalize_port "$port" "9393" +} + +resolve_sshterm_bind() { + local panel_root="$1" + local port="$2" + local bind="${SSH_TERM_BIND:-}" + if [ -z "$bind" ]; then + bind="$(read_env_file_value "${panel_root}/.env" "SSH_TERM_BIND" || true)" + fi + if [ -z "$bind" ]; then + bind="127.0.0.1:${port}" + elif printf "%s" "$bind" | grep -qE '^[0-9]+$'; then + bind="127.0.0.1:${bind}" + fi + printf "%s" "$bind" +} + +sshterm_bind_host() { + local value + value="$(trim_ws "${1:-}")" + value="${value#http://}" + value="${value#https://}" + value="${value%%/*}" + + if printf "%s" "$value" | grep -qE '^\[[^]]+\](:[0-9]+)?$'; then + value="${value#\[}" + value="${value%%\]*}" + elif printf "%s" "$value" | grep -qE '^[^:]+:[0-9]+$'; then + value="${value%:*}" + elif printf "%s" "$value" | grep -qE '^:[0-9]+$'; then + value="" + fi + + printf "%s" "$value" +} + +sshterm_bind_is_loopback() { + local host + host="$(lower_trim "$(sshterm_bind_host "${1:-}")")" + case "$host" in + localhost|127.*|::1) + return 0 + ;; + esac + return 1 +} + +build_sshterm_health_url() { + local bind="$1" + local port="$2" + local host + host="$(sshterm_bind_host "$bind")" + case "$(lower_trim "$host")" in + ""|0.0.0.0|::|\*) + host="127.0.0.1" + ;; + esac + if printf "%s" "$host" | grep -q ':' && ! printf "%s" "$host" | grep -qE '^\[.*\]$'; then + host="[${host}]" + fi + printf "http://%s:%s/healthz" "$host" "$port" +} + +allow_tcp_firewall_port() { + local port="$1" + local label="${2:-service}" + [ -n "$port" ] || return 0 + + if cmd_exists ufw; then + preserve_ssh_firewall_access ufw + $SUDO ufw allow "${port}/tcp" >/dev/null 2>&1 || true + if $SUDO ufw status 2>/dev/null | grep -q "Status: active"; then + $SUDO ufw reload >/dev/null 2>&1 || true + fi + ui_success "Firewall allows ${label} on TCP port ${port} with ufw." + return 0 + fi + + if cmd_exists firewall-cmd; then + service_enable firewalld + service_start firewalld + preserve_ssh_firewall_access firewalld + $SUDO firewall-cmd --permanent --add-port="${port}/tcp" >/dev/null 2>&1 || true + $SUDO firewall-cmd --reload >/dev/null 2>&1 || true + ui_success "Firewall allows ${label} on TCP port ${port} with firewalld." + return 0 + fi + + if cmd_exists iptables; then + preserve_ssh_firewall_access iptables + $SUDO iptables -C INPUT -p tcp --dport "$port" -j ACCEPT >/dev/null 2>&1 || \ + $SUDO iptables -I INPUT -p tcp --dport "$port" -j ACCEPT >/dev/null 2>&1 || true + if cmd_exists netfilter-persistent; then + $SUDO netfilter-persistent save >/dev/null 2>&1 || true + elif [ -d /etc/iptables ] && cmd_exists iptables-save; then + $SUDO sh -c "iptables-save > /etc/iptables/rules.v4" >/dev/null 2>&1 || true + fi + ui_success "Firewall allows ${label} on TCP port ${port} with iptables." + return 0 + fi + + if cmd_exists nft && $SUDO nft list table inet filter >/dev/null 2>&1; then + preserve_ssh_firewall_access nftables + $SUDO nft add rule inet filter input tcp dport "$port" accept >/dev/null 2>&1 || true + ui_success "Firewall allows ${label} on TCP port ${port} with nftables." + return 0 + fi + + ui_warn "No supported firewall manager found; allow TCP port ${port} manually if ${label} is exposed publicly." + return 0 +} + +bind_host_is_loopback() { + local host + host="$(lower_trim "${1:-}")" + host="${host#http://}" + host="${host#https://}" + host="${host%%/*}" + host="${host%\]}" + host="${host#\[}" + if printf "%s" "$host" | grep -qE '^[^:]+:[0-9]+$'; then + host="${host%:*}" + fi + + case "$host" in + localhost|127.*|::1) + return 0 + ;; + esac + return 1 +} + +auto_open_firewall_enabled() { + local value + value="$(lower_trim "${ADPANEL_AUTO_OPEN_FIREWALL:-1}")" + case "$value" in + 0|false|no|off) + return 1 + ;; + esac + return 0 +} + +open_public_firewall_port() { + local port="$1" + local label="${2:-ADPanel}" + local bind_host="${3:-0.0.0.0}" + + [ -n "$port" ] || return 0 + if ! printf "%s" "$port" | grep -qE '^[0-9]+$'; then + return 0 + fi + if bind_host_is_loopback "$bind_host"; then + ui_info "${label} binds to ${bind_host}; no public firewall rule is needed." + return 0 + fi + if ! auto_open_firewall_enabled; then + ui_warn "Automatic firewall opening is disabled. Allow TCP port ${port} manually for ${label}." + return 0 + fi + + if cmd_exists firewall-cmd && $SUDO firewall-cmd --state >/dev/null 2>&1; then + preserve_ssh_firewall_access firewalld + $SUDO firewall-cmd --permanent --add-port="${port}/tcp" >/dev/null 2>&1 || true + $SUDO firewall-cmd --reload >/dev/null 2>&1 || true + ui_success "Firewall allows ${label} on TCP port ${port} with firewalld." + return 0 + fi + + if cmd_exists ufw && $SUDO ufw status 2>/dev/null | grep -q "Status: active"; then + preserve_ssh_firewall_access ufw + $SUDO ufw allow "${port}/tcp" >/dev/null 2>&1 || true + $SUDO ufw reload >/dev/null 2>&1 || true + ui_success "Firewall allows ${label} on TCP port ${port} with ufw." + return 0 + fi + + if cmd_exists iptables; then + preserve_ssh_firewall_access iptables + $SUDO iptables -C INPUT -p tcp --dport "$port" -j ACCEPT >/dev/null 2>&1 || \ + $SUDO iptables -I INPUT -p tcp --dport "$port" -j ACCEPT >/dev/null 2>&1 || true + if cmd_exists netfilter-persistent; then + $SUDO netfilter-persistent save >/dev/null 2>&1 || true + elif [ -d /etc/iptables ] && cmd_exists iptables-save; then + $SUDO sh -c "iptables-save > /etc/iptables/rules.v4" >/dev/null 2>&1 || true + fi + ui_success "Firewall allows ${label} on TCP port ${port} with iptables." + return 0 + fi + + ui_warn "No active supported firewall was detected. If this VPS filters traffic, allow TCP port ${port} for ${label}." + return 0 +} + +configure_panel_firewall() { + local nginx_enabled="${1:-false}" + local bind_host="${2:-0.0.0.0}" + local http_port="${3:-}" + local https_enabled="${4:-false}" + local https_port="${5:-}" + + if [ "$nginx_enabled" == "true" ]; then + bind_host="0.0.0.0" + fi + + open_public_firewall_port "$http_port" "ADPanel HTTP" "$bind_host" + if [ "$https_enabled" == "true" ]; then + open_public_firewall_port "$https_port" "ADPanel HTTPS" "$bind_host" + fi +} + +configure_sshterm_firewall() { + local port="$1" + local bind="$2" + + if sshterm_bind_is_loopback "$bind"; then + ui_info "SSH terminal binds to ${bind}; no public firewall rule is needed." + return 0 + fi + + allow_tcp_firewall_port "$port" "ADPanel SSH terminal" +} + +ensure_sshterm_source_available() { + local panel_root="${1:-$PANEL_ROOT}" + local raw_base="${ADPANEL_SOURCE_RAW_BASE%/}" + local missing=false + local rel="" + + for rel in go.mod go.sum cmd/sshterm/main.go; do + if [ ! -f "${panel_root}/${rel}" ]; then + missing=true + fi + done + + if [ "$missing" != "true" ]; then + return 0 + fi + + ui_warn "SSH terminal source files are missing; trying to recover them from ${raw_base}..." + for rel in go.mod go.sum cmd/sshterm/main.go; do + if [ -f "${panel_root}/${rel}" ]; then + continue + fi + + local dest="${panel_root}/${rel}" + local tmp="" + tmp="$(mktemp /tmp/adpanel-sshterm-src.XXXXXX 2>/dev/null || echo "")" + if [ -z "$tmp" ]; then + ui_warn "Could not create temp file while recovering ${rel}." + return 1 + fi + + if ! download_file "${raw_base}/${rel}" "$tmp" >/dev/null 2>&1; then + rm -f "$tmp" >/dev/null 2>&1 || true + ui_warn "Could not download ${rel}. Make sure the ADPanel release includes cmd/sshterm and go.mod/go.sum." + return 1 + fi + + $SUDO mkdir -p "$(dirname "$dest")" >/dev/null 2>&1 || true + if ! $SUDO mv "$tmp" "$dest"; then + rm -f "$tmp" >/dev/null 2>&1 || true + ui_warn "Could not install recovered ${rel} into ${dest}." + return 1 + fi + $SUDO chmod 0644 "$dest" >/dev/null 2>&1 || true + if id -u adpanel >/dev/null 2>&1; then + $SUDO chown adpanel:adpanel "$dest" >/dev/null 2>&1 || true + fi + done + + [ -f "${panel_root}/cmd/sshterm/main.go" ] && [ -f "${panel_root}/go.mod" ] && [ -f "${panel_root}/go.sum" ] +} + +prepare_adpanel_sshterm_runtime() { + local panel_root="$PANEL_ROOT" + local prep_script="${panel_root}/start.sh" + local sshterm_main="${panel_root}/cmd/sshterm/main.go" + local sshterm_bin="${panel_root}/.bin/adpanel-sshterm" + local sshterm_exec="/usr/local/bin/adpanel-sshterm" + local go_cache_dir="${panel_root}/.cache-go" + local go_modcache_dir="${panel_root}/.gomodcache" + local go_bin="" + local service_user="root" + local service_group="root" + + if ! cmd_exists go; then + ui_warn "Go runtime not found; skipping ADPanel SSH terminal service setup." + return 1 + fi + go_bin="$(command -v go 2>/dev/null || true)" + if [ -z "$go_bin" ]; then + ui_warn "Go runtime path could not be resolved; skipping ADPanel SSH terminal service setup." + return 1 + fi + + if ! ensure_sshterm_source_available "$panel_root"; then + ui_warn "SSH terminal source could not be recovered; skipping service setup." + return 1 + fi + + if [ ! -f "$sshterm_main" ]; then + ui_warn "SSH terminal source not found at ${sshterm_main}; skipping service setup." + return 1 + fi + + if [ -f "$prep_script" ]; then + ui_info "Preparing ADPanel runtime user and permissions for SSH terminal..." + if ! $SUDO bash "$prep_script"; then + ui_warn "Runtime preparation failed before SSH terminal service setup; continuing best effort." + fi + fi + + if id -u adpanel >/dev/null 2>&1; then + service_user="adpanel" + service_group="adpanel" + fi + + ensure_panel_env_permissions "$panel_root" + + $SUDO mkdir -p "$go_cache_dir" "$go_modcache_dir" "${panel_root}/.bin" >/dev/null 2>&1 || true + $SUDO chown -R "${service_user}:${service_group}" "$go_cache_dir" "$go_modcache_dir" "${panel_root}/.bin" >/dev/null 2>&1 || true + + ui_info "Building ADPanel SSH terminal binary..." + if ! $SUDO env \ + HOME="$panel_root" \ + GOCACHE="$go_cache_dir" \ + GOMODCACHE="$go_modcache_dir" \ + GOMAXPROCS=2 \ + "$go_bin" build -trimpath -buildvcs=false -ldflags="-s -w" -o "$sshterm_bin" ./cmd/sshterm; then + ui_warn "Failed to build ADPanel SSH terminal; service cannot be started." + return 1 + fi + + $SUDO chmod 0755 "$sshterm_bin" >/dev/null 2>&1 || true + $SUDO chown "${service_user}:${service_group}" "$sshterm_bin" >/dev/null 2>&1 || true + $SUDO mkdir -p "$(dirname "$sshterm_exec")" >/dev/null 2>&1 || true + if ! $SUDO install -m 0755 -o root -g root "$sshterm_bin" "$sshterm_exec"; then + ui_warn "Failed to install SSH terminal binary to ${sshterm_exec}; using project-local binary." + sshterm_exec="$sshterm_bin" + elif cmd_exists restorecon; then + $SUDO restorecon "$sshterm_exec" >/dev/null 2>&1 || true + fi + + SSHTERM_PANEL_ROOT="$panel_root" + SSHTERM_EXEC="$sshterm_exec" + SSHTERM_GO_CACHE_DIR="$go_cache_dir" + SSHTERM_GO_MODCACHE_DIR="$go_modcache_dir" + SSHTERM_SERVICE_USER="$service_user" + SSHTERM_SERVICE_GROUP="$service_group" + SSHTERM_PORT="$(resolve_sshterm_port "$panel_root")" + SSHTERM_BIND="$(resolve_sshterm_bind "$panel_root" "$SSHTERM_PORT")" + SSHTERM_HEALTH_URL="$(build_sshterm_health_url "$SSHTERM_BIND" "$SSHTERM_PORT")" + + configure_sshterm_firewall "$SSHTERM_PORT" "$SSHTERM_BIND" + return 0 +} + setup_adpanel_sshterm_systemd_service() { local service_name="adpanel-sshterm" local service_file="/etc/systemd/system/${service_name}.service" - local panel_root="$SCRIPT_DIR" + local panel_root="$PANEL_ROOT" + local prep_script="${panel_root}/start.sh" local sshterm_main="${panel_root}/cmd/sshterm/main.go" + local sshterm_bin="${panel_root}/.bin/adpanel-sshterm" + local sshterm_exec="/usr/local/bin/adpanel-sshterm" local go_cache_dir="${panel_root}/.cache-go" local go_modcache_dir="${panel_root}/.gomodcache" + local go_bin="" + local sshterm_port="" + local sshterm_bind="" + local sshterm_health_url="" local service_user="root" local service_group="root" @@ -1625,24 +2201,71 @@ setup_adpanel_sshterm_systemd_service() { ui_warn "Go runtime not found; skipping ${service_name} service setup." return 1 fi + go_bin="$(command -v go 2>/dev/null || true)" + if [ -z "$go_bin" ]; then + ui_warn "Go runtime path could not be resolved; skipping ${service_name} service setup." + return 1 + fi + + if ! ensure_sshterm_source_available "$panel_root"; then + ui_warn "SSH terminal source could not be recovered; skipping ${service_name} setup." + return 1 + fi if [ ! -f "$sshterm_main" ]; then ui_warn "SSH terminal source not found at ${sshterm_main}; skipping ${service_name} setup." return 1 fi + sshterm_port="$(resolve_sshterm_port "$panel_root")" + sshterm_bind="$(resolve_sshterm_bind "$panel_root" "$sshterm_port")" + sshterm_health_url="$(build_sshterm_health_url "$sshterm_bind" "$sshterm_port")" + + if [ -f "$prep_script" ]; then + ui_info "Preparing ADPanel runtime user and permissions for SSH terminal..." + if ! $SUDO bash "$prep_script"; then + ui_warn "Runtime preparation failed before ${service_name}; continuing with best-effort service setup." + fi + fi + if id -u adpanel >/dev/null 2>&1; then service_user="adpanel" service_group="adpanel" fi - $SUDO mkdir -p "$go_cache_dir" "$go_modcache_dir" >/dev/null 2>&1 || true - $SUDO chown -R "${service_user}:${service_group}" "$go_cache_dir" "$go_modcache_dir" >/dev/null 2>&1 || true + ensure_panel_env_permissions "$panel_root" + + $SUDO mkdir -p "$go_cache_dir" "$go_modcache_dir" "${panel_root}/.bin" >/dev/null 2>&1 || true + $SUDO chown -R "${service_user}:${service_group}" "$go_cache_dir" "$go_modcache_dir" "${panel_root}/.bin" >/dev/null 2>&1 || true + + ui_info "Building ADPanel SSH terminal binary..." + if ! $SUDO env \ + HOME="$panel_root" \ + GOCACHE="$go_cache_dir" \ + GOMODCACHE="$go_modcache_dir" \ + GOMAXPROCS=2 \ + "$go_bin" build -trimpath -buildvcs=false -ldflags="-s -w" -o "$sshterm_bin" ./cmd/sshterm; then + ui_warn "Failed to build ${service_name}; SSH terminal service cannot be started." + return 1 + fi + $SUDO chmod 0755 "$sshterm_bin" >/dev/null 2>&1 || true + $SUDO chown "${service_user}:${service_group}" "$sshterm_bin" >/dev/null 2>&1 || true + $SUDO mkdir -p "$(dirname "$sshterm_exec")" >/dev/null 2>&1 || true + if ! $SUDO install -m 0755 -o root -g root "$sshterm_bin" "$sshterm_exec"; then + ui_warn "Failed to install ${service_name} binary to ${sshterm_exec}; using project-local binary." + sshterm_exec="$sshterm_bin" + elif cmd_exists restorecon; then + $SUDO restorecon "$sshterm_exec" >/dev/null 2>&1 || true + fi + configure_sshterm_firewall "$sshterm_port" "$sshterm_bind" cat </dev/null [Unit] Description=ADPanel SSH Terminal Service -After=network.target +After=network-online.target +Wants=network-online.target +Before=adpanel.service +PartOf=adpanel.service [Service] Type=simple @@ -1651,13 +2274,16 @@ User=${service_user} Group=${service_group} EnvironmentFile=-${panel_root}/.env Environment=SSH_TERM_PANEL_ROOT=${panel_root} -Environment=SSH_TERM_BIND=0.0.0.0:9393 +Environment=SSH_TERM_BIND=${sshterm_bind} +Environment=SSH_TERM_PORT=${sshterm_port} +Environment=ENABLE_HTTPS=false Environment=HOME=${panel_root} Environment=GOCACHE=${go_cache_dir} Environment=GOMODCACHE=${go_modcache_dir} Environment=GOMAXPROCS=1 -Environment=GOMEMLIMIT=10MiB -ExecStart=/usr/bin/env bash -lc 'cd "${panel_root}" && exec go run ./cmd/sshterm/main.go' +Environment=GOMEMLIMIT=128MiB +Environment=PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin +ExecStart=${sshterm_exec} NoNewPrivileges=true PrivateTmp=true ProtectKernelTunables=true @@ -1670,6 +2296,9 @@ LimitNOFILE=65535 [Install] WantedBy=multi-user.target EOF + if cmd_exists restorecon; then + $SUDO restorecon "$service_file" >/dev/null 2>&1 || true + fi if ! $SUDO systemctl daemon-reload; then ui_warn "Failed to reload systemd daemon for ${service_name}." @@ -1684,15 +2313,215 @@ EOF fi if $SUDO systemctl is-active --quiet "$service_name"; then + if cmd_exists curl; then + local health_ok=false + local i + for i in 1 2 3 4 5; do + if curl -fsS --max-time 5 "$sshterm_health_url" >/dev/null 2>&1; then + health_ok=true + break + fi + sleep 1 + done + if [ "$health_ok" != "true" ]; then + ui_warn "${service_name}.service is active but its local health check failed." + ui_warn "Health check URL: ${sshterm_health_url}" + ui_warn "Check logs with: journalctl -u ${service_name} -n 80 --no-pager" + $SUDO journalctl -u "$service_name" -n 20 --no-pager 2>/dev/null || true + return 1 + fi + fi ui_success "${service_name}.service is active and enabled." else ui_warn "${service_name}.service was created but is not active." ui_warn "Check status with: systemctl status ${service_name}" + $SUDO systemctl status "$service_name" --no-pager -l 2>/dev/null || true fi return 0 } +setup_adpanel_sshterm_openrc_service() { + local service_name="adpanel-sshterm" + local service_file="/etc/init.d/${service_name}" + + if ! cmd_exists rc-service || ! cmd_exists rc-update; then + ui_warn "OpenRC tools not found; skipping ${service_name} setup." + return 1 + fi + + if ! prepare_adpanel_sshterm_runtime; then + return 1 + fi + + cat </dev/null +#!/sbin/openrc-run +name="ADPanel SSH Terminal" +description="ADPanel SSH Terminal Service" +directory="${SSHTERM_PANEL_ROOT}" +command="${SSHTERM_EXEC}" +command_user="${SSHTERM_SERVICE_USER}:${SSHTERM_SERVICE_GROUP}" +command_background=true +supervisor=supervise-daemon +pidfile="/run/${service_name}.pid" +output_log="/var/log/${service_name}.log" +error_log="/var/log/${service_name}.log" + +export SSH_TERM_PANEL_ROOT="${SSHTERM_PANEL_ROOT}" +export SSH_TERM_BIND="${SSHTERM_BIND}" +export SSH_TERM_PORT="${SSHTERM_PORT}" +export ENABLE_HTTPS="false" +export HOME="${SSHTERM_PANEL_ROOT}" +export GOCACHE="${SSHTERM_GO_CACHE_DIR}" +export GOMODCACHE="${SSHTERM_GO_MODCACHE_DIR}" +export GOMAXPROCS="1" +export GOMEMLIMIT="128MiB" +export PATH="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" + +depend() { + need net + before adpanel +} +EOF + + $SUDO chmod +x "$service_file" >/dev/null 2>&1 || true + service_enable "$service_name" + service_restart "$service_name" + service_start "$service_name" + + if $SUDO rc-service "$service_name" status >/dev/null 2>&1; then + if cmd_exists curl && ! curl -fsS --max-time 5 "$SSHTERM_HEALTH_URL" >/dev/null 2>&1; then + ui_warn "${service_name} OpenRC service is active but its local health check failed." + ui_warn "Health check URL: ${SSHTERM_HEALTH_URL}" + return 1 + fi + ui_success "${service_name} OpenRC service is active and enabled." + return 0 + fi + + ui_warn "${service_name} OpenRC service was created but is not active." + ui_warn "Check status with: rc-service ${service_name} status" + return 1 +} + +setup_adpanel_sshterm_sysv_service() { + local service_name="adpanel-sshterm" + local service_file="/etc/init.d/${service_name}" + + if ! cmd_exists service; then + ui_warn "SysV service command not found; skipping ${service_name} setup." + return 1 + fi + + if ! prepare_adpanel_sshterm_runtime; then + return 1 + fi + + cat </dev/null +#!/bin/sh +### BEGIN INIT INFO +# Provides: ${service_name} +# Required-Start: \$remote_fs \$network +# Required-Stop: \$remote_fs \$network +# Default-Start: 2 3 4 5 +# Default-Stop: 0 1 6 +# Short-Description: ADPanel SSH Terminal Service +### END INIT INFO + +NAME="${service_name}" +PANEL_DIR="${SSHTERM_PANEL_ROOT}" +DAEMON="${SSHTERM_EXEC}" +PIDFILE="/var/run/${service_name}.pid" +LOGFILE="/var/log/${service_name}.log" +SERVICE_USER="${SSHTERM_SERVICE_USER}" + +start() { + if [ -f "\$PIDFILE" ] && kill -0 "\$(cat "\$PIDFILE")" 2>/dev/null; then + echo "\$NAME is already running" + return 0 + fi + echo "Starting \$NAME" + if command -v start-stop-daemon >/dev/null 2>&1; then + if [ "\$SERVICE_USER" = "root" ]; then + start-stop-daemon --start --background --make-pidfile --pidfile "\$PIDFILE" --chdir "\$PANEL_DIR" --startas /bin/sh -- -c "SSH_TERM_PANEL_ROOT='${SSHTERM_PANEL_ROOT}' SSH_TERM_BIND='${SSHTERM_BIND}' SSH_TERM_PORT='${SSHTERM_PORT}' ENABLE_HTTPS=false HOME='${SSHTERM_PANEL_ROOT}' GOCACHE='${SSHTERM_GO_CACHE_DIR}' GOMODCACHE='${SSHTERM_GO_MODCACHE_DIR}' GOMAXPROCS=1 GOMEMLIMIT=128MiB PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin exec '\$DAEMON' >>'\$LOGFILE' 2>&1" + else + start-stop-daemon --start --background --make-pidfile --pidfile "\$PIDFILE" --chuid "\$SERVICE_USER" --chdir "\$PANEL_DIR" --startas /bin/sh -- -c "SSH_TERM_PANEL_ROOT='${SSHTERM_PANEL_ROOT}' SSH_TERM_BIND='${SSHTERM_BIND}' SSH_TERM_PORT='${SSHTERM_PORT}' ENABLE_HTTPS=false HOME='${SSHTERM_PANEL_ROOT}' GOCACHE='${SSHTERM_GO_CACHE_DIR}' GOMODCACHE='${SSHTERM_GO_MODCACHE_DIR}' GOMAXPROCS=1 GOMEMLIMIT=128MiB PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin exec '\$DAEMON' >>'\$LOGFILE' 2>&1" + fi + else + if [ "\$SERVICE_USER" != "root" ] && command -v su >/dev/null 2>&1; then + su -s /bin/sh -c "cd '\$PANEL_DIR' && SSH_TERM_PANEL_ROOT='${SSHTERM_PANEL_ROOT}' SSH_TERM_BIND='${SSHTERM_BIND}' SSH_TERM_PORT='${SSHTERM_PORT}' ENABLE_HTTPS=false HOME='${SSHTERM_PANEL_ROOT}' GOCACHE='${SSHTERM_GO_CACHE_DIR}' GOMODCACHE='${SSHTERM_GO_MODCACHE_DIR}' GOMAXPROCS=1 GOMEMLIMIT=128MiB PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin nohup '\$DAEMON' >>'\$LOGFILE' 2>&1 & echo \\\$! > '\$PIDFILE'" "\$SERVICE_USER" + else + (cd "\$PANEL_DIR" && SSH_TERM_PANEL_ROOT="${SSHTERM_PANEL_ROOT}" SSH_TERM_BIND="${SSHTERM_BIND}" SSH_TERM_PORT="${SSHTERM_PORT}" ENABLE_HTTPS=false HOME="${SSHTERM_PANEL_ROOT}" GOCACHE="${SSHTERM_GO_CACHE_DIR}" GOMODCACHE="${SSHTERM_GO_MODCACHE_DIR}" GOMAXPROCS=1 GOMEMLIMIT=128MiB PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin nohup "\$DAEMON" >>"\$LOGFILE" 2>&1 & echo \$! > "\$PIDFILE") + fi + fi +} + +stop() { + echo "Stopping \$NAME" + if command -v start-stop-daemon >/dev/null 2>&1; then + start-stop-daemon --stop --pidfile "\$PIDFILE" --retry TERM/8/KILL/3 >/dev/null 2>&1 || true + elif [ -f "\$PIDFILE" ]; then + kill "\$(cat "\$PIDFILE")" >/dev/null 2>&1 || true + fi + rm -f "\$PIDFILE" +} + +status() { + if [ -f "\$PIDFILE" ] && kill -0 "\$(cat "\$PIDFILE")" 2>/dev/null; then + echo "\$NAME is running" + return 0 + fi + echo "\$NAME is not running" + return 3 +} + +case "\$1" in + start) start ;; + stop) stop ;; + restart) stop; start ;; + status) status ;; + *) echo "Usage: \$0 {start|stop|restart|status}"; exit 2 ;; +esac +EOF + + $SUDO chmod +x "$service_file" >/dev/null 2>&1 || true + service_enable "$service_name" + service_restart "$service_name" + service_start "$service_name" + + if $SUDO service "$service_name" status >/dev/null 2>&1; then + if cmd_exists curl && ! curl -fsS --max-time 5 "$SSHTERM_HEALTH_URL" >/dev/null 2>&1; then + ui_warn "${service_name} SysV service is active but its local health check failed." + ui_warn "Health check URL: ${SSHTERM_HEALTH_URL}" + return 1 + fi + ui_success "${service_name} SysV service is active and enabled." + return 0 + fi + + ui_warn "${service_name} SysV service was created but is not active." + ui_warn "Check status with: service ${service_name} status" + return 1 +} + +setup_adpanel_sshterm_service() { + case "$INIT_SYSTEM" in + systemd) + setup_adpanel_sshterm_systemd_service + ;; + openrc) + setup_adpanel_sshterm_openrc_service + ;; + sysv) + setup_adpanel_sshterm_sysv_service + ;; + *) + ui_warn "SSH terminal service setup skipped because init system is unsupported: ${INIT_SYSTEM}." + return 1 + ;; + esac +} + install_certbot() { ui_info "Installing certbot..." if command -v certbot >/dev/null 2>&1; then @@ -2078,6 +2907,70 @@ BINDEOF return 0 } +detect_ssh_ports() { + local found="" + local file + for file in /etc/ssh/sshd_config /etc/ssh/sshd_config.d/*.conf; do + [ -f "$file" ] || continue + found="$found +$(awk 'BEGIN{IGNORECASE=1} /^[[:space:]]*Port[[:space:]]+[0-9]+/ {print $2}' "$file" 2>/dev/null || true)" + done + found="$(printf "%s\n" "$found" | awk '/^[0-9]+$/ && $1 > 0 && $1 <= 65535 {print $1}' | sort -n -u)" + if [ -n "$found" ]; then + printf "%s\n" "$found" + else + printf "22\n" + fi +} + +preserve_ssh_firewall_access() { + local backend="${1:-}" + local port + [ -n "$backend" ] || return 0 + + case "$backend" in + ufw) + while IFS= read -r port; do + [ -n "$port" ] || continue + $SUDO ufw allow "${port}/tcp" >/dev/null 2>&1 || true + done </dev/null 2>&1 || true + service_start firewalld >/dev/null 2>&1 || true + $SUDO firewall-cmd --permanent --add-service=ssh >/dev/null 2>&1 || true + while IFS= read -r port; do + [ -n "$port" ] || continue + $SUDO firewall-cmd --permanent --add-port="${port}/tcp" >/dev/null 2>&1 || true + done </dev/null 2>&1 || \ + $SUDO iptables -I INPUT 1 -p tcp --dport "$port" -j ACCEPT >/dev/null 2>&1 || true + done </dev/null 2>&1; then + while IFS= read -r port; do + [ -n "$port" ] || continue + $SUDO nft add rule inet filter input tcp dport "$port" accept >/dev/null 2>&1 || true + done </dev/null 2>&1 || true $SUDO ufw deny 445/udp >/dev/null 2>&1 || true ui_success "Port 445 (SMB) blocked." @@ -2122,6 +3016,7 @@ harden_firewall() { firewalld) service_enable firewalld service_start firewalld + preserve_ssh_firewall_access firewalld $SUDO firewall-cmd --permanent --add-rich-rule='rule family="ipv4" port port="445" protocol="tcp" reject' >/dev/null 2>&1 || true $SUDO firewall-cmd --permanent --add-rich-rule='rule family="ipv4" port port="445" protocol="udp" reject' >/dev/null 2>&1 || true ui_success "Port 445 (SMB) blocked." @@ -2135,6 +3030,7 @@ harden_firewall() { ;; *) if command -v iptables >/dev/null 2>&1; then + preserve_ssh_firewall_access iptables $SUDO iptables -C INPUT -p tcp --dport 445 -j DROP >/dev/null 2>&1 || \ $SUDO iptables -A INPUT -p tcp --dport 445 -j DROP >/dev/null 2>&1 || true $SUDO iptables -C INPUT -p udp --dport 445 -j DROP >/dev/null 2>&1 || \ @@ -2165,6 +3061,91 @@ harden_firewall() { return 1 } +is_debian_like_platform() { + local id_like=" ${OS_LIKE:-} " + case "${OS_ID:-}" in + debian|ubuntu|linuxmint|pop|raspbian) + return 0 + ;; + esac + case "$id_like" in + *" debian "*) + return 0 + ;; + esac + return 1 +} + +sshd_binary_path() { + if cmd_exists sshd; then + command -v sshd + return 0 + fi + if [ -x /usr/sbin/sshd ]; then + printf "%s\n" "/usr/sbin/sshd" + return 0 + fi + if [ -x /usr/local/sbin/sshd ]; then + printf "%s\n" "/usr/local/sbin/sshd" + return 0 + fi + return 1 +} + +sshd_config_is_valid() { + local sshd_bin + sshd_bin="$(sshd_binary_path 2>/dev/null || true)" + [ -n "$sshd_bin" ] || return 0 + $SUDO "$sshd_bin" -t >/dev/null 2>&1 +} + +reload_sshd_safely() { + if ! sshd_config_is_valid; then + ui_warn "OpenSSH config is not valid; not reloading SSH. Existing SSH sessions were left untouched." + return 1 + fi + + if systemd_available; then + $SUDO systemctl reload sshd 2>/dev/null || \ + $SUDO systemctl reload ssh 2>/dev/null || \ + service_reload sshd 2>/dev/null || \ + service_reload ssh 2>/dev/null || true + else + service_reload sshd 2>/dev/null || service_reload ssh 2>/dev/null || true + fi + return 0 +} + +repair_openssh_cross_distro_config() { + local changed=false + local file + + # DebianBanner is a Debian/Ubuntu OpenSSH patch. RHEL/Rocky/OpenSSH Portable + # treats it as a fatal config error, so never write it and repair old ADPanel + # installs that did. + if is_debian_like_platform; then + return 0 + fi + + for file in /etc/ssh/sshd_config /etc/ssh/sshd_config.d/*.conf; do + [ -f "$file" ] || continue + if grep -qE '^[[:space:]]*DebianBanner([[:space:]]|$)' "$file" 2>/dev/null; then + $SUDO cp -a "$file" "${file}.adpanel-bak.$(date +%Y%m%d%H%M%S)" >/dev/null 2>&1 || true + $SUDO sed -i -E '/^[[:space:]]*DebianBanner([[:space:]]|$)/ s/^/# ADPanel disabled non-portable OpenSSH option: /' "$file" + changed=true + ui_warn "Disabled unsupported DebianBanner in ${file}; Rocky/RHEL sshd rejects this option." + fi + done + + if [ "$changed" = true ]; then + if reload_sshd_safely; then + ui_success "OpenSSH config repaired and reloaded safely." + else + ui_warn "OpenSSH config was repaired, but sshd -t still fails; inspect /etc/ssh/sshd_config before restarting SSH." + fi + fi +} + mask_service_versions() { ui_info "Masking service version fingerprints..." @@ -2213,31 +3194,7 @@ MYSQLEOF fi fi - # --- OpenSSH: minimize banner exposure --- - local sshd_conf="/etc/ssh/sshd_config" - if [ -f "$sshd_conf" ]; then - # Disable Debian/Ubuntu-specific banner that leaks OS info - if ! grep -qE "^DebianBanner[[:space:]]+no" "$sshd_conf" 2>/dev/null; then - if grep -q "^#\?DebianBanner" "$sshd_conf" 2>/dev/null; then - $SUDO sed -i 's/^#\?DebianBanner.*/DebianBanner no/' "$sshd_conf" - else - echo "DebianBanner no" | $SUDO tee -a "$sshd_conf" >/dev/null - fi - fi - # Disable custom banner file - if grep -qE "^Banner[[:space:]]" "$sshd_conf" 2>/dev/null; then - $SUDO sed -i 's/^Banner[[:space:]].*/Banner none/' "$sshd_conf" - elif ! grep -qE "^Banner[[:space:]]+none" "$sshd_conf" 2>/dev/null; then - echo "Banner none" | $SUDO tee -a "$sshd_conf" >/dev/null - fi - # Restart sshd to apply - if systemd_available; then - $SUDO systemctl restart sshd 2>/dev/null || $SUDO systemctl restart ssh 2>/dev/null || true - else - service_restart sshd 2>/dev/null || service_restart ssh 2>/dev/null || true - fi - ui_success "OpenSSH banner exposure minimized." - fi + repair_openssh_cross_distro_config # --- PHP: hide version from HTTP headers (for phpMyAdmin) --- local php_ini_paths=( @@ -2472,6 +3429,8 @@ CREATE DATABASE IF NOT EXISTS \`$esc_db\` CHARACTER SET utf8mb4 COLLATE utf8mb4_ CREATE USER IF NOT EXISTS '$esc_user'@'localhost' IDENTIFIED BY '$esc_pass'; CREATE USER IF NOT EXISTS '$esc_user'@'127.0.0.1' IDENTIFIED BY '$esc_pass'; +ALTER USER '$esc_user'@'localhost' IDENTIFIED BY '$esc_pass'; +ALTER USER '$esc_user'@'127.0.0.1' IDENTIFIED BY '$esc_pass'; -- Schema permissions kept local-only; REFERENCES is needed for foreign keys. GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, ALTER, INDEX, DROP, REFERENCES @@ -2505,7 +3464,7 @@ EOF local encoded_pass encoded_pass=$(node -e "console.log(encodeURIComponent(process.argv[1] || ''))" "$MYSQL_PASSWORD") - MYSQL_URL="mysql://${MYSQL_USER}:${encoded_pass}@127.0.0.1:${MYSQL_PORT}/${MYSQL_DATABASE}" + MYSQL_URL="mysql://${MYSQL_USER}:${encoded_pass}@${MYSQL_HOST}:${MYSQL_PORT}/${MYSQL_DATABASE}" return 0 } @@ -2572,7 +3531,7 @@ bootstrap_db_and_create_admin() { local script_path="$CREATE_USER_SCRIPT" if [ -z "$script_path" ]; then - ui_warn "create-user.js not found (expected ${SCRIPT_DIR}/scripts/create-user.js); skipping automatic admin DB seeding." + ui_warn "create-user.js not found (expected ${PANEL_ROOT}/scripts/create-user.js); skipping automatic admin DB seeding." return 0 fi @@ -2588,7 +3547,7 @@ bootstrap_db_and_create_admin() { pid=$! fi - if ! wait_for_mysql_table "$MYSQL_DATABASE" "users" "127.0.0.1" "$MYSQL_PORT" "$MYSQL_USER" "$MYSQL_PASSWORD"; then + if ! wait_for_mysql_table "$MYSQL_DATABASE" "users" "$MYSQL_HOST" "$MYSQL_PORT" "$MYSQL_USER" "$MYSQL_PASSWORD"; then ui_warn "users table did not appear. Check bootstrap log: ${boot_log}" fi @@ -2635,10 +3594,23 @@ install_redis() { "valkey valkey-tools" \ "valkey-server valkey-tools" || return 1 ;; - dnf|yum|zypper) + dnf|yum) + enable_rhel_redis_module_if_available + ensure_pkg_metadata >/dev/null 2>&1 || true + if ! pkg_install_try_sets \ + "redis" \ + "redis6" \ + "redis7" \ + "redis-server" \ + "valkey" \ + "valkey valkey-compat" \ + "valkey-redis-compat"; then + install_redis_from_official_rpm_repo || return 1 + fi + ;; + zypper) pkg_install_try_sets \ "redis" \ - "redis-server redis" \ "valkey" \ "valkey-redis-compat" || return 1 ;; @@ -2668,9 +3640,11 @@ install_redis() { detect_redis_conf() { local candidates=( "/etc/redis/redis.conf" + "/etc/redis/default.conf" "/etc/redis.conf" "/usr/local/etc/redis/redis.conf" "/etc/valkey/valkey.conf" + "/etc/valkey/default.conf" "/etc/valkey.conf" ) for f in "${candidates[@]}"; do @@ -2783,6 +3757,9 @@ configure_redis_auth() { $SUDO sed -i '/^[[:space:]]*supervised[[:space:]]/d' "$conf" 2>/dev/null || true $SUDO sed -i '/^[[:space:]]*save[[:space:]]/d' "$conf" 2>/dev/null || true $SUDO sed -i '/^[[:space:]]*appendonly[[:space:]]/d' "$conf" 2>/dev/null || true + $SUDO sed -i '/^[[:space:]]*appendfsync[[:space:]]/d' "$conf" 2>/dev/null || true + $SUDO sed -i '/^[[:space:]]*no-appendfsync-on-rewrite[[:space:]]/d' "$conf" 2>/dev/null || true + $SUDO sed -i '/^[[:space:]]*aof-use-rdb-preamble[[:space:]]/d' "$conf" 2>/dev/null || true $SUDO sed -i '/^[[:space:]]*maxmemory[[:space:]]/d' "$conf" 2>/dev/null || true $SUDO sed -i '/^[[:space:]]*maxmemory-policy[[:space:]]/d' "$conf" 2>/dev/null || true $SUDO sed -i '/^[[:space:]]*lazyfree-lazy-eviction[[:space:]]/d' "$conf" 2>/dev/null || true @@ -2811,8 +3788,11 @@ supervised ${supervised_val} requirepass ${password} -save "" -appendonly no +save 900 1 300 10 60 10000 +appendonly yes +appendfsync everysec +no-appendfsync-on-rewrite no +aof-use-rdb-preamble yes maxmemory ${maxmemory} maxmemory-policy noeviction @@ -2862,14 +3842,20 @@ restart_redis_service() { if [ "$INIT_SYSTEM" == "systemd" ]; then $SUDO systemctl daemon-reload >/dev/null 2>&1 || true - if systemctl list-unit-files 2>/dev/null | grep -q "^redis-server.service"; then + local unit_files="" + unit_files="$(systemctl list-unit-files 2>/dev/null || true)" + if printf "%s\n" "$unit_files" | grep -q "^redis-server.service"; then svc="redis-server" - elif systemctl list-unit-files 2>/dev/null | grep -q "^redis.service"; then + elif printf "%s\n" "$unit_files" | grep -q "^redis.service"; then svc="redis" - elif systemctl list-unit-files 2>/dev/null | grep -q "^valkey.service"; then + elif printf "%s\n" "$unit_files" | grep -q "^redis@.service"; then + svc="redis@default" + elif printf "%s\n" "$unit_files" | grep -q "^valkey.service"; then svc="valkey" - elif systemctl list-unit-files 2>/dev/null | grep -q "^valkey-server.service"; then + elif printf "%s\n" "$unit_files" | grep -q "^valkey-server.service"; then svc="valkey-server" + elif printf "%s\n" "$unit_files" | grep -q "^valkey@.service"; then + svc="valkey@default" fi if [ -n "$svc" ]; then @@ -2880,7 +3866,7 @@ restart_redis_service() { fi fi - for svc in redis-server redis valkey valkey-server; do + for svc in redis-server redis redis@default valkey valkey-server valkey@default; do service_restart "$svc" done @@ -3175,8 +4161,7 @@ write_nginx_config() { local upstream_host="${APP_HOST}" local upstream_port="${APP_PORT}" - local panel_root - panel_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + local panel_root="$PANEL_ROOT" local static_root="${panel_root}/public" local layout @@ -3260,7 +4245,7 @@ EOF gzip on; gzip_vary on; gzip_min_length 256; - gzip_comp_level 2; + gzip_comp_level 5; gzip_proxied any; gzip_types text/plain text/css application/javascript application/json application/xml application/rss+xml image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype; @@ -3268,7 +4253,7 @@ EOF if [ "$nginx_has_brotli" == "true" ]; then cat </dev/null brotli on; - brotli_comp_level 4; + brotli_comp_level 5; brotli_min_length 256; brotli_types text/plain text/css application/javascript application/json application/xml application/rss+xml image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype; @@ -3558,7 +4543,7 @@ server { gzip on; gzip_vary on; gzip_min_length 256; - gzip_comp_level 2; + gzip_comp_level 5; gzip_proxied any; gzip_types text/plain text/css application/javascript application/json application/xml application/rss+xml image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype; @@ -3566,7 +4551,7 @@ EOF if [ "$nginx_has_brotli" == "true" ]; then cat </dev/null brotli on; - brotli_comp_level 4; + brotli_comp_level 5; brotli_min_length 256; brotli_types text/plain text/css application/javascript application/json application/xml application/rss+xml image/svg+xml application/vnd.ms-fontobject application/x-font-ttf font/opentype; @@ -3899,28 +4884,10 @@ apply_nginx_performance_profile() { cat <<'EOF' | $SUDO tee "$perf_conf" >/dev/null # ADPanel nginx performance profile (managed by initialize.sh) -# This file is included from nginx.conf inside the http {} context. - -tcp_nodelay on; -keepalive_timeout 20; -keepalive_requests 10000; -send_timeout 30; -reset_timedout_connection on; - -open_file_cache max=200000 inactive=30s; -open_file_cache_valid 60s; -open_file_cache_min_uses 2; -open_file_cache_errors on; - -proxy_headers_hash_max_size 2048; -proxy_headers_hash_bucket_size 128; - -client_body_timeout 15s; -client_header_timeout 15s; -client_body_buffer_size 128k; - -gzip_comp_level 2; -gzip_vary on; +# Kept intentionally directive-free because this file is included in the +# nginx http {} context, where many distro defaults already define +# keepalive/gzip/client timeout directives. Duplicating them breaks nginx -t +# on Rocky/Alma/CentOS and other RHEL-compatible layouts. EOF } @@ -4002,6 +4969,8 @@ delete_user() { initialize_panel() { ui_section "=== Panel Initialization ===" + repair_openssh_cross_distro_config || true + apply_adpanel_host_limits || true read -p "$(ui_prompt "Enter admin email: ")" EMAIL read -s -p "$(ui_prompt "Enter admin password: ")" PASSWORD @@ -4182,7 +5151,7 @@ EOF ui_warn "Skipping automatic firewall hardening. You can configure firewall rules manually later." fi mask_service_versions - ensure_stealth_config "$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + ensure_stealth_config "$PANEL_ROOT" if install_nginx; then service_enable nginx @@ -4261,21 +5230,7 @@ EOF fi PANEL_PUBLIC_URL="$(build_public_url "$public_scheme" "$PANEL_PUBLIC_HOST" "$public_port")" - APP_PORT_LINE="" - if [ "$NGINX_ENABLED" == "true" ] && [ "$APP_PORT" != "3001" ]; then - APP_PORT_LINE="APP_PORT=$APP_PORT" - fi - - SSH_TERM_SCHEME="http" - if [ "$ENABLE_HTTPS" == "true" ]; then - SSH_TERM_SCHEME="https" - fi - SSH_TERM_HOST="$HOST" - if [ -n "$PANEL_PUBLIC_URL" ]; then - SSH_TERM_HOST="$(printf '%s' "$PANEL_PUBLIC_URL" | sed -E 's#^[A-Za-z]+://##; s#/.*$##')" - SSH_TERM_HOST="${SSH_TERM_HOST%%:*}" - fi - SSH_TERM_PUBLIC_URL_VALUE="${SSH_TERM_SCHEME}://${SSH_TERM_HOST}:9393" + configure_panel_firewall "$NGINX_ENABLED" "$HOST" "$HTTP_PORT" "$ENABLE_HTTPS" "$HTTPS_PORT" cat < .env HOST=$HOST @@ -4291,7 +5246,7 @@ SESSION_COOKIE_SECURE=$SESSION_COOKIE_SECURE SESSION_STORE=$SESSION_STORE NGINX_ENABLED=$NGINX_ENABLED APP_HOST=$APP_HOST -${APP_PORT_LINE} +APP_PORT=$APP_PORT STEALTH_MODE=true STEALTH_COOKIE_TTL_DAYS=30 STEALTH_RESPONSE_FLOOR_MS=90 @@ -4317,10 +5272,14 @@ SESSION_SECRET="$SESSION_SECRET" DUMMY_HASH="$DUMMY_HASH" BROTLI_QUALITY=4 SSH_TERM_PORT=9393 -SSH_TERM_PUBLIC_URL=$SSH_TERM_PUBLIC_URL_VALUE +SSH_TERM_BIND=127.0.0.1:9393 +SSH_TERM_INTERNAL_URL=http://127.0.0.1:9393 +SSH_TERM_PUBLIC_URL= +SSH_TERM_WS_PUBLIC_URL= EOF ui_success ".env file created with network and security settings." + ensure_panel_env_permissions "$PANEL_ROOT" if bootstrap_db_and_create_admin "$EMAIL" "$HASH" "$SECRET"; then ui_success "Admin account created in database." @@ -4328,26 +5287,69 @@ EOF ui_warn "Panel setup completed, but admin account creation in database failed." fi ui_warn "Panel setup complete!" + if [ "$NGINX_ENABLED" == "true" ]; then + ui_kv "Panel URL:" "$PANEL_PUBLIC_URL" + else + ui_warn "nginx reverse proxy is disabled; use the direct panel URL below." + ui_kv "Panel URL:" "$PANEL_PUBLIC_URL" + fi + + if [ "$INIT_SYSTEM" != "unknown" ]; then + ui_info "Configuring and starting service: adpanel-sshterm..." + if ensure_go_runtime && setup_adpanel_sshterm_service; then + case "$INIT_SYSTEM" in + systemd) ui_kv " SSH Terminal status:" "systemctl status adpanel-sshterm" ;; + openrc) ui_kv " SSH Terminal status:" "rc-service adpanel-sshterm status" ;; + sysv) ui_kv " SSH Terminal status:" "service adpanel-sshterm status" ;; + esac + else + ui_warn "SSH terminal service setup skipped." + fi + else + ui_warn "SSH terminal service setup skipped because init system is unsupported: ${INIT_SYSTEM}." + fi + ui_info "Configuring and starting service: adpanel..." if ! setup_adpanel_service; then ui_error "Failed to configure/start adpanel service. Exiting." return 1 fi print_adpanel_service_commands - if [ "$INIT_SYSTEM" == "systemd" ]; then - ui_info "Configuring and starting systemd service: adpanel-sshterm..." - if ensure_go_runtime && setup_adpanel_sshterm_systemd_service; then - ui_kv " SSH Terminal status:" "systemctl status adpanel-sshterm" - else - ui_warn "SSH terminal service setup skipped." - fi - else - ui_warn "SSH terminal service setup currently requires systemd and was skipped on ${INIT_SYSTEM}." +} + +repair_sshterm_service() { + ui_section "Repair SSH terminal service" + log_platform_summary + + if [ ! -f "${PANEL_ROOT}/.env" ]; then + ui_warn ".env was not found. The SSH terminal needs SESSION_SECRET from an initialized panel." + ui_warn "Run option 1 first if this is a new ADPanel install." fi + + if ensure_go_runtime && setup_adpanel_sshterm_service; then + case "$INIT_SYSTEM" in + systemd) + ui_success "SSH terminal service repaired." + ui_kv " Status:" "systemctl status adpanel-sshterm" + ;; + openrc) + ui_success "SSH terminal service repaired." + ui_kv " Status:" "rc-service adpanel-sshterm status" + ;; + sysv) + ui_success "SSH terminal service repaired." + ui_kv " Status:" "service adpanel-sshterm status" + ;; + esac + return 0 + fi + + ui_error "Failed to repair SSH terminal service." + return 1 } load_mysql_env() { - if [ ! -f "${SCRIPT_DIR}/.env" ]; then + if [ ! -f "${PANEL_ROOT}/.env" ]; then ui_error ".env not found. Run 'Initialize Panel' first." return 1 fi @@ -4379,7 +5381,14 @@ EOF return 1 fi - IFS=$'\n' read -r MYSQL_URL MYSQL_HOST MYSQL_PORT MYSQL_USER MYSQL_PASSWORD MYSQL_DATABASE <<< "$values" + local env_values=() + mapfile -t env_values <<< "$values" + MYSQL_URL="${env_values[0]:-}" + MYSQL_HOST="${env_values[1]:-}" + MYSQL_PORT="${env_values[2]:-}" + MYSQL_USER="${env_values[3]:-}" + MYSQL_PASSWORD="${env_values[4]:-}" + MYSQL_DATABASE="${env_values[5]:-}" if [ -z "$MYSQL_URL" ] && { [ -z "$MYSQL_HOST" ] || [ -z "$MYSQL_DATABASE" ]; }; then ui_error "MySQL is not configured in .env. Set MYSQL_URL or MYSQL_HOST/MYSQL_DATABASE." @@ -4389,6 +5398,85 @@ EOF return 0 } +mysql_configured_user_can_connect() { + local cli + cli="$(mysql_detect_cli)" + [ -n "$MYSQL_DATABASE" ] && [ -n "$MYSQL_USER" ] && [ -n "$MYSQL_HOST" ] && [ -n "$MYSQL_PORT" ] || return 1 + cmd_exists "$cli" || return 1 + + MYSQL_PWD="$MYSQL_PASSWORD" "$cli" \ + -h "$MYSQL_HOST" \ + -P "$MYSQL_PORT" \ + -u "$MYSQL_USER" \ + -e "SELECT 1;" "$MYSQL_DATABASE" >/dev/null 2>&1 +} + +repair_mysql_credentials_from_env() { + ui_section "Repair MySQL credentials" + if ! load_mysql_env; then + return 1 + fi + + if mysql_configured_user_can_connect; then + ui_success "MySQL credentials from .env are already valid." + return 0 + fi + + if [ -z "$MYSQL_DATABASE" ] || [ -z "$MYSQL_USER" ] || [ -z "$MYSQL_PASSWORD" ]; then + ui_error "MYSQL_DATABASE, MYSQL_USER or MYSQL_PASSWORD is missing from .env." + return 1 + fi + + local esc_user esc_pass esc_db + esc_user="$(mysql_sql_escape "$MYSQL_USER")" + esc_pass="$(mysql_sql_escape "$MYSQL_PASSWORD")" + esc_db="$(printf "%s" "$MYSQL_DATABASE" | sed "s/\`//g")" + + if ! printf "%s" "$esc_user" | grep -qE '^[A-Za-z0-9_@.-]+$'; then + ui_error "MySQL username contains unsupported characters; cannot repair automatically." + return 1 + fi + if ! printf "%s" "$esc_db" | grep -qE '^[A-Za-z0-9_]+$'; then + ui_error "MySQL database name contains unsupported characters; cannot repair automatically." + return 1 + fi + + local sql + sql=$(cat < primary-only. + Disks []NodeDisk `json:"disks,omitempty"` +} + +// NodeDisk describes a storage location available to this node. The primary disk +// is synthetic (ID="primary", MountPath=a.dataRoot) and is never persisted here +// nor deletable; only additional disks live in NodeInformation.Disks. +type NodeDisk struct { + ID string `json:"id"` + MountPath string `json:"mountPath"` + LimitGb int64 `json:"limitGb"` + Primary bool `json:"primary,omitempty"` + CreatedAt string `json:"createdAt,omitempty"` +} + +type nodeUpdateFilePayload struct { + Path string `json:"path"` + ContentBase64 string `json:"contentBase64"` +} + +type nodeUpdateInstallRequest struct { + Version string `json:"version"` + Files []nodeUpdateFilePayload `json:"files"` +} + +type nodeUpdateAutoRequest struct { + Enabled bool `json:"enabled"` +} + +func (c Config) Bool(path ...string) bool { + v := c.Any(path...) + b, _ := v.(bool) + return b +} +func (c Config) String(path ...string) string { + v := c.Any(path...) + switch x := v.(type) { + case string: + return x + default: + return "" + } +} +func (c Config) Int(path ...string) int { + v := c.Any(path...) + switch x := v.(type) { + case int: + return x + case int64: + return int(x) + case float64: + return int(x) + case string: + n, _ := strconv.Atoi(strings.TrimSpace(x)) + return n + default: + return 0 + } +} +func (c Config) Any(path ...string) any { + cur := any(c.Raw) + for _, k := range path { + m, ok := cur.(map[string]any) + if !ok { + return nil + } + cur = m[k] + } + return cur +} + +func parseYAMLSubset(src string) (map[string]any, error) { + lines := strings.Split(strings.ReplaceAll(src, "\r\n", "\n"), "\n") + root := map[string]any{} + type frame struct { + indent int + obj map[string]any + } + stack := []frame{{indent: -1, obj: root}} + + for lineNum, raw := range lines { + line := strings.ReplaceAll(raw, "\t", " ") + trim := strings.TrimSpace(line) + if trim == "" || strings.HasPrefix(trim, "#") { + continue + } + indent := len(line) - len(strings.TrimLeft(line, " ")) + for len(stack) > 0 && indent <= stack[len(stack)-1].indent { + stack = stack[:len(stack)-1] + } + if len(stack) == 0 { + return nil, fmt.Errorf("yaml parse: invalid indent at line %d", lineNum+1) + } + cur := stack[len(stack)-1].obj + + parts := strings.SplitN(strings.TrimSpace(line), ":", 2) + if len(parts) != 2 { + fmt.Fprintf(os.Stderr, "[warn] yaml parse: malformed line %d (missing colon): %s\n", lineNum+1, trim) + continue + } + key := strings.TrimSpace(parts[0]) + valRaw := strings.TrimSpace(parts[1]) + + if valRaw == "" { + obj := map[string]any{} + cur[key] = obj + stack = append(stack, frame{indent: indent, obj: obj}) + continue + } + + val := any(valRaw) + if (strings.HasPrefix(valRaw, `"`) && strings.HasSuffix(valRaw, `"`)) || + (strings.HasPrefix(valRaw, `'`) && strings.HasSuffix(valRaw, `'`)) { + val = valRaw[1 : len(valRaw)-1] + } else if strings.EqualFold(valRaw, "true") || strings.EqualFold(valRaw, "false") { + val = strings.EqualFold(valRaw, "true") + } else if n, err := strconv.ParseInt(valRaw, 10, 64); err == nil { + val = int(n) + } else if f, err := strconv.ParseFloat(valRaw, 64); err == nil { + val = f + } + cur[key] = val + } + return root, nil +} + +func mustReadFile(p string) []byte { + b, err := os.ReadFile(p) + if err != nil { + fmt.Fprintf(os.Stderr, "[fatal] read %s: %v\n", p, err) + os.Exit(1) + } + return b +} + +func ensureDir(p string) error { + return os.MkdirAll(p, 0o755) +} + +func anyToInt(v any) int { + switch x := v.(type) { + case int: + return x + case int64: + return int(x) + case float64: + return int(x) + case float32: + return int(x) + case string: + n, _ := strconv.Atoi(strings.TrimSpace(x)) + return n + default: + return 0 + } +} + +func anyToInt64(v any) int64 { + switch x := v.(type) { + case int: + return int64(x) + case int64: + return x + case int32: + return int64(x) + case float64: + return int64(x) + case float32: + return int64(x) + case string: + n, _ := strconv.ParseInt(strings.TrimSpace(x), 10, 64) + return n + default: + return 0 + } +} + +func anyToFloat64(v any) float64 { + switch x := v.(type) { + case float64: + return x + case float32: + return float64(x) + case int: + return float64(x) + case int64: + return float64(x) + case string: + n, _ := strconv.ParseFloat(strings.TrimSpace(x), 64) + return n + default: + return 0 + } +} + +func openWriteNoFollow(path string, perm os.FileMode) (*os.File, error) { + f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|syscall.O_NOFOLLOW, perm) + if err != nil { + if errors.Is(err, syscall.ELOOP) { + return nil, fmt.Errorf("refusing to write through symlink: %s", path) + } + return nil, err + } + return f, nil +} + +func writeFileNoFollow(path string, data []byte, perm os.FileMode) error { + f, err := openWriteNoFollow(path, perm) + if err != nil { + return err + } + _, werr := f.Write(data) + cerr := f.Close() + if werr != nil { + return werr + } + return cerr +} + +func normalizeNodeVersionTag(version string) string { + clean := strings.TrimSpace(version) + if clean == "" { + return "v" + NodeVersion + } + if strings.HasPrefix(strings.ToLower(clean), "v") { + return "v" + strings.TrimPrefix(strings.TrimPrefix(clean, "v"), "V") + } + return "v" + clean +} + +func validNodeUpdateVersion(version string) bool { + return regexp.MustCompile(`^v?\d+\.\d+\.\d+([\-+][A-Za-z0-9_.-]+)?$`).MatchString(strings.TrimSpace(version)) +} + +func allowedNodeUpdateFile(rel string) bool { + raw := strings.TrimSpace(rel) + if strings.Contains(raw, "/") || strings.Contains(raw, "\\") { + return false + } + clean := filepath.Clean(raw) + if clean == "." || clean == "" || strings.Contains(clean, "/") || strings.Contains(clean, string(filepath.Separator)) { + return false + } + if clean == "go.mod" || clean == "go.sum" { + return true + } + return regexp.MustCompile(`^[A-Za-z0-9_.-]+\.go$`).MatchString(clean) +} + +func validateNodeUpdateFileContent(rel string, data []byte) error { + if len(data) == 0 { + return fmt.Errorf("%s is empty", rel) + } + if len(data) > 8*1024*1024 { + return fmt.Errorf("%s is too large", rel) + } + if strings.HasSuffix(rel, ".go") && !bytes.HasPrefix(bytes.TrimSpace(data), []byte("package main")) { + return fmt.Errorf("%s is not a package main Go file", rel) + } + if rel == "go.mod" && !bytes.HasPrefix(bytes.TrimSpace(data), []byte("module ")) { + return fmt.Errorf("go.mod is invalid") + } + return nil +} + +func copyRegularFile(src, dst string) error { + in, err := os.Open(src) + if err != nil { + return err + } + defer in.Close() + st, err := in.Stat() + if err != nil { + return err + } + if !st.Mode().IsRegular() { + return nil + } + if err := ensureDir(filepath.Dir(dst)); err != nil { + return err + } + out, err := openWriteNoFollow(dst, st.Mode().Perm()) + if err != nil { + return err + } + _, copyErr := io.Copy(out, in) + closeErr := out.Close() + if copyErr != nil { + return copyErr + } + return closeErr +} + +func sanitizeName(raw string) string { + s := strings.TrimSpace(raw) + s = regexp.MustCompile(`\s+`).ReplaceAllString(s, "-") + s = regexp.MustCompile(`[^\w\-_.]+`).ReplaceAllString(s, "") + s = strings.Trim(s, "-_.") + for len(s) > 0 && !((s[0] >= 'a' && s[0] <= 'z') || (s[0] >= 'A' && s[0] <= 'Z') || (s[0] >= '0' && s[0] <= '9')) { + s = s[1:] + } + if len(s) > 120 { + s = s[:120] + } + return s +} + +func isValidContainerName(name string) bool { + if name == "" || len(name) > 120 { + return false + } + if !((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z') || (name[0] >= '0' && name[0] <= '9')) { + return false + } + for _, c := range name { + if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '-') { + return false + } + } + return true +} + +func isDockerNativeContainerName(name string) bool { + if name == "" || len(name) > 128 { + return false + } + if len(name) < 2 { + return false + } + if !((name[0] >= 'a' && name[0] <= 'z') || (name[0] >= 'A' && name[0] <= 'Z') || (name[0] >= '0' && name[0] <= '9')) { + return false + } + for _, c := range name { + if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '.' || c == '-') { + return false + } + } + return true +} + +func dockerContainerName(name string) string { + clean := strings.TrimSpace(name) + if isDockerNativeContainerName(clean) { + return clean + } + safe := sanitizeName(clean) + if safe == "" { + return clean + } + sum := sha256.Sum256([]byte(clean)) + hash := hex.EncodeToString(sum[:])[:12] + if len(safe) > 64 { + safe = safe[:64] + } + return "adpanel-" + hash + "-" + safe +} + +func dockerContainerSpecName(spec string) string { + if left, right, ok := strings.Cut(spec, ":"); ok && left != "" && !strings.Contains(left, "/") { + return dockerContainerName(left) + ":" + right + } + return spec +} + +func rewriteDockerCLIArgs(args []string) []string { + if len(args) == 0 { + return args + } + out := append([]string(nil), args...) + rewriteLast := func() { + if len(out) > 1 { + out[len(out)-1] = dockerContainerName(out[len(out)-1]) + } + } + + switch out[0] { + case "logs", "diff", "stop", "kill", "restart", "stats", "update": + rewriteLast() + case "inspect": + rewriteLast() + case "rm": + for i := 1; i < len(out); i++ { + if strings.HasPrefix(out[i], "-") { + continue + } + out[i] = dockerContainerName(out[i]) + } + case "exec": + for i := 1; i < len(out); i++ { + if strings.HasPrefix(out[i], "-") { + continue + } + out[i] = dockerContainerName(out[i]) + break + } + case "cp": + for i := 1; i < len(out); i++ { + out[i] = dockerContainerSpecName(out[i]) + } + case "run": + for i := 1; i < len(out)-1; i++ { + if out[i] == "--name" { + out[i+1] = dockerContainerName(out[i+1]) + i++ + } + } + } + return out +} + +func safeJoin(base, rel string) (string, bool) { + r := strings.TrimSpace(rel) + if r == "" { + return filepath.Clean(base), true + } + if filepath.IsAbs(r) { + r = strings.TrimLeft(r, string(os.PathSeparator)) + } + target := filepath.Join(base, r) + baseC := filepath.Clean(base) + targetC := filepath.Clean(target) + + relToBase, err := filepath.Rel(baseC, targetC) + if err != nil { + return "", false + } + if relToBase == "." { + return targetC, true + } + if strings.HasPrefix(relToBase, ".."+string(os.PathSeparator)) || relToBase == ".." || filepath.IsAbs(relToBase) { + return "", false + } + return targetC, true +} + +func isUnder(base, target string) bool { + baseC := filepath.Clean(base) + targetC := filepath.Clean(target) + rel, err := filepath.Rel(baseC, targetC) + if err != nil { + return false + } + return rel == "." || (!strings.HasPrefix(rel, ".."+string(os.PathSeparator)) && rel != ".." && !filepath.IsAbs(rel)) +} + +func ensureResolvedUnder(base, p string) error { + resolved, err := filepath.EvalSymlinks(p) + if err != nil { + return err + } + baseC := filepath.Clean(base) + if !isUnder(baseC, resolved) && baseC != resolved { + return fmt.Errorf("symlink escape blocked") + } + return nil +} + +func panelSafeCaps() []string { + return []string{ + "--cap-add=CHOWN", + "--cap-add=DAC_OVERRIDE", + "--cap-add=FOWNER", + "--cap-add=SETUID", + "--cap-add=SETGID", + "--cap-add=KILL", + "--cap-add=NET_BIND_SERVICE", + "--cap-add=NET_RAW", + "--cap-add=SYS_CHROOT", + "--cap-add=AUDIT_WRITE", + } +} + +func containerSecurityArgs(uid, gid int, readOnly bool) []string { + args := []string{"--cap-drop=ALL"} + args = append(args, panelSafeCaps()...) + args = append(args, + "--security-opt=no-new-privileges", + "--pids-limit=512", + fmt.Sprintf("--user=%d:%d", uid, gid), + ) + if readOnly { + args = append(args, + "--read-only", + "--tmpfs", "/tmp:rw,noexec,nosuid,size=256m", + "--tmpfs", "/var/tmp:rw,noexec,nosuid,size=64m", + "--tmpfs", "/run:rw,noexec,nosuid,size=32m", + ) + } + return args +} + +func timingSafeEq(a, b string) bool { + return subtle.ConstantTimeCompare([]byte(a), []byte(b)) == 1 +} + +func jsonWrite(w http.ResponseWriter, status int, v any) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + _ = json.NewEncoder(w).Encode(v) +} + +func readJSON(w http.ResponseWriter, r *http.Request, limitBytes int64, dst any) error { + r.Body = http.MaxBytesReader(w, r.Body, limitBytes) + defer r.Body.Close() + dec := json.NewDecoder(r.Body) + dec.DisallowUnknownFields() + return dec.Decode(dst) +} + +type Docker struct { + debug bool +} + +func (d Docker) runCollect(ctx context.Context, args ...string) (string, string, int, error) { + args = rewriteDockerCLIArgs(args) + cmd := exec.CommandContext(ctx, "docker", args...) + var out, errb bytes.Buffer + cmd.Stdout = &out + cmd.Stderr = &errb + err := cmd.Run() + exit := 0 + if err != nil { + var ee *exec.ExitError + if errors.As(err, &ee) { + exit = ee.ExitCode() + } else { + exit = -1 + } + return out.String(), errb.String(), exit, err + } + return out.String(), errb.String(), 0, nil +} + +func (d Docker) containerExists(ctx context.Context, name string) bool { + _, _, _, err := d.runCollect(ctx, "inspect", name) + return err == nil +} + +func (d Docker) containerState(ctx context.Context, name string) string { + out, _, _, err := d.runCollect(ctx, "inspect", "-f", "{{.State.Status}}", name) + if err != nil { + return "" + } + return strings.ToLower(strings.TrimSpace(out)) +} + +func (d Docker) kill(ctx context.Context, name string) { + _, _, _, _ = d.runCollect(ctx, "kill", name) +} + +func (d Docker) rmForce(ctx context.Context, name string) { + d.kill(ctx, name) + _, _, _, _ = d.runCollect(ctx, "rm", "-f", "-v", name) +} + +func (d Docker) brutalRemoveContainer(ctx context.Context, name string) error { + dockerName := dockerContainerName(name) + if dockerName == "" { + return fmt.Errorf("missing container name") + } + + runAPIStep := func(timeout time.Duration, fn func(context.Context) error) error { + if ctx.Err() != nil { + return ctx.Err() + } + stepCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + return fn(stepCtx) + } + + var lastErr error + if err := runAPIStep(2*time.Second, func(stepCtx context.Context) error { + return d.updateRestartNoAPI(stepCtx, dockerName) + }); err != nil { + lastErr = err + } + if err := runAPIStep(2*time.Second, func(stepCtx context.Context) error { + return d.killContainerAPI(stepCtx, dockerName) + }); err != nil { + lastErr = err + } + if err := runAPIStep(5*time.Second, func(stepCtx context.Context) error { + return d.removeContainerAPI(stepCtx, dockerName, true) + }); err == nil { + return nil + } else { + lastErr = err + } + + cliCtx, cancel := context.WithTimeout(ctx, 4*time.Second) + _, errText, code, err := d.runCollect(cliCtx, "rm", "-f", "-v", dockerName) + cancel() + if err == nil && code == 0 { + return nil + } + if strings.TrimSpace(errText) != "" { + lastErr = errors.New(strings.TrimSpace(errText)) + } else if err != nil { + lastErr = err + } + + checkCtx, checkCancel := context.WithTimeout(context.Background(), 1500*time.Millisecond) + exists, inspectErr := d.containerExistsAPI(checkCtx, dockerName) + checkCancel() + if inspectErr == nil { + if !exists { + return nil + } + } else { + cliCheckCtx, cliCheckCancel := context.WithTimeout(context.Background(), 1500*time.Millisecond) + _, cliInspectText, _, cliInspectErr := d.runCollect(cliCheckCtx, "inspect", dockerName) + cliTimedOut := cliCheckCtx.Err() != nil + cliCheckCancel() + if cliInspectErr != nil && !cliTimedOut { + msg := strings.ToLower(cliInspectText) + if strings.Contains(msg, "no such object") || strings.Contains(msg, "no such container") || strings.Contains(msg, "not found") { + return nil + } + } + if lastErr == nil { + if cliTimedOut { + lastErr = cliCheckCtx.Err() + } else { + lastErr = inspectErr + } + } + } + if lastErr != nil { + return lastErr + } + return fmt.Errorf("container still exists after force removal") +} + +func (d Docker) pull(ctx context.Context, ref string) { + if err := d.pullImageAPI(ctx, ref); err != nil { + _, _, _, _ = d.runCollect(ctx, "pull", ref) + } +} + +func (d Docker) imageExistsLocally(ctx context.Context, ref string) bool { + _, _, exitCode, _ := d.runCollect(ctx, "image", "inspect", ref) + return exitCode == 0 +} + +type imageConfig struct { + Volumes []string + Workdir string + User string + Env map[string]string + Entrypoint []string + Cmd []string +} + +func (d Docker) inspectImageConfig(ctx context.Context, ref string) imageConfig { + if apiCfg, err := d.inspectImageConfigAPI(ctx, ref); err == nil { + return apiCfg + } + + cfg := imageConfig{Env: map[string]string{}} + + out, _, code, err := d.runCollect(ctx, "inspect", "--format", + `{{json .Config.Volumes}}||{{.Config.WorkingDir}}||{{.Config.User}}||{{json .Config.Env}}||{{json .Config.Entrypoint}}||{{json .Config.Cmd}}`, ref) + if err != nil || code != 0 { + return cfg + } + + parts := strings.SplitN(strings.TrimSpace(out), "||", 6) + if len(parts) < 3 { + return cfg + } + + volJson := strings.TrimSpace(parts[0]) + if volJson != "" && volJson != "null" && volJson != "{}" { + var vols map[string]any + if jsonErr := json.Unmarshal([]byte(volJson), &vols); jsonErr == nil { + for p := range vols { + p = strings.TrimSpace(p) + if p != "" && p != "/" { + cfg.Volumes = append(cfg.Volumes, p) + } + } + } + } + + cfg.Workdir = strings.TrimSpace(parts[1]) + cfg.User = strings.TrimSpace(parts[2]) + + if len(parts) >= 4 { + envJson := strings.TrimSpace(parts[3]) + if envJson != "" && envJson != "null" { + var envArr []string + if jsonErr := json.Unmarshal([]byte(envJson), &envArr); jsonErr == nil { + for _, kv := range envArr { + if k, v, ok := strings.Cut(kv, "="); ok { + cfg.Env[k] = v + } + } + } + } + } + + if len(parts) >= 5 { + cfg.Entrypoint = parseImageConfigStringList(parts[4]) + } + + if len(parts) >= 6 { + cfg.Cmd = parseImageConfigStringList(parts[5]) + } + + return cfg +} + +func parseImageConfigStringList(raw string) []string { + trimmed := strings.TrimSpace(raw) + if trimmed == "" || trimmed == "null" { + return nil + } + var list []string + if err := json.Unmarshal([]byte(trimmed), &list); err != nil { + return nil + } + out := make([]string, 0, len(list)) + for _, item := range list { + clean := strings.TrimSpace(item) + if clean != "" { + out = append(out, clean) + } + } + return out +} + +func runtimeArgNeedsQuoting(arg string) bool { + if arg == "" { + return true + } + for _, r := range arg { + switch r { + case ' ', '\t', '\n', '\r', '"', '\\': + return true + } + } + return false +} + +func quoteRuntimeArg(arg string) string { + if !runtimeArgNeedsQuoting(arg) { + return arg + } + var b strings.Builder + b.WriteByte('"') + for _, r := range arg { + if r == '"' || r == '\\' { + b.WriteByte('\\') + } + b.WriteRune(r) + } + b.WriteByte('"') + return b.String() +} + +func runtimeCommandFromArgs(args []string) string { + if len(args) == 0 { + return "" + } + encoded := make([]string, 0, len(args)) + for _, arg := range args { + clean := strings.TrimSpace(arg) + if clean == "" { + continue + } + encoded = append(encoded, quoteRuntimeArg(clean)) + } + return strings.TrimSpace(strings.Join(encoded, " ")) +} + +func trimRuntimeProcessArgs(args []string) []string { + out := make([]string, 0, len(args)) + for _, arg := range args { + clean := strings.TrimSpace(arg) + if clean != "" { + out = append(out, clean) + } + } + return out +} + +func isRuntimeShellName(value string) bool { + switch strings.ToLower(strings.TrimSpace(value)) { + case "sh", "bash", "ash", "dash", "zsh", "ksh": + return true + default: + return false + } +} + +func shellEntrypointInfo(entrypoint []string) (bool, int) { + if len(entrypoint) < 2 { + return false, 0 + } + + execIndex := 0 + flagIndex := 1 + cmdIndex := 2 + execName := strings.ToLower(strings.TrimSpace(filepath.Base(entrypoint[execIndex]))) + + if execName == "env" && len(entrypoint) >= 3 { + execIndex = 1 + flagIndex = 2 + cmdIndex = 3 + execName = strings.ToLower(strings.TrimSpace(filepath.Base(entrypoint[execIndex]))) + } + + if !isRuntimeShellName(execName) || len(entrypoint) <= flagIndex { + return false, 0 + } + + flags := strings.TrimSpace(entrypoint[flagIndex]) + if !strings.HasPrefix(flags, "-") || !strings.Contains(flags, "c") { + return false, 0 + } + + return true, cmdIndex +} + +func runtimeCommandFromImageConfig(cfg imageConfig) string { + entrypoint := trimRuntimeProcessArgs(cfg.Entrypoint) + cmd := trimRuntimeProcessArgs(cfg.Cmd) + + if isShell, cmdIndex := shellEntrypointInfo(entrypoint); isShell { + if len(cmd) > 0 { + // Docker treats Cmd as a single shell command string when Entrypoint is a shell wrapper. + return strings.TrimSpace(strings.Join(cmd, " ")) + } + if len(entrypoint) > cmdIndex { + return strings.TrimSpace(strings.Join(entrypoint[cmdIndex:], " ")) + } + return "" + } + + args := make([]string, 0, len(entrypoint)+len(cmd)) + args = append(args, entrypoint...) + args = append(args, cmd...) + return runtimeCommandFromArgs(args) +} + +func getDataPathsFromEnv(env map[string]string) []string { + dataKeys := []string{ + "SERVER_DIR", "SERVERDIR", "SRV_DIR", "GAME_DIR", "GAMEDIR", + "DATA_DIR", "DATADIR", "INSTALL_DIR", "INSTALLDIR", + "STEAMAPPDIR", "HOMEDIR", "HOME_DIR", + "APP_DIR", "APPDIR", "WORKDIR", "WORK_DIR", + } + seen := map[string]bool{} + var paths []string + for _, key := range dataKeys { + if val, ok := env[key]; ok { + val = strings.TrimSpace(val) + if val != "" && val != "/" && strings.HasPrefix(val, "/") && !seen[val] { + paths = append(paths, val) + seen[val] = true + } + } + } + return paths +} + +func (d Docker) getImageVolumePaths(ctx context.Context, ref string) []string { + return d.inspectImageConfig(ctx, ref).Volumes +} + +func ensureVolumeWritable(serverDir string) { + if err := os.Chmod(serverDir, 0777); err != nil { + fmt.Printf("[volumes] warning: chmod 0777 %s failed: %v\n", serverDir, err) + } + _ = filepath.Walk(serverDir, func(child string, info os.FileInfo, err error) error { + if err != nil || child == serverDir || info == nil { + return nil + } + if info.IsDir() { + _ = os.Chmod(child, 0777) + return nil + } + mode := os.FileMode(0666) + if info.Mode().Perm()&0111 != 0 { + mode = 0777 + } + _ = os.Chmod(child, mode) + return nil + }) +} + +func (a *Agent) recoverMisplacedFiles(name, serverDir string) { + for _, waitTime := range []time.Duration{15 * time.Second, 45 * time.Second} { + time.Sleep(waitTime) + + entries, err := os.ReadDir(serverDir) + if err != nil { + return + } + realFileCount := 0 + realRegularFiles := 0 + for _, e := range entries { + if e.Name() == ".adpanel" || e.Name() == ".adpanel_meta" { + continue + } + realFileCount++ + if !e.IsDir() { + realRegularFiles++ + } + } + if realRegularFiles > 0 || realFileCount > 1 { + fmt.Printf("[file-recovery] %s: server directory has %d entries (%d regular files), volume mount is working\n", name, realFileCount, realRegularFiles) + return + } + if realFileCount > 0 && waitTime < 45*time.Second { + fmt.Printf("[file-recovery] %s: server directory has only %d directory(ies) and no regular files — waiting longer before recovery\n", name, realFileCount) + continue + } + } + + fmt.Printf("[file-recovery] %s: server directory is EMPTY after 60s — attempting file recovery\n", name) + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + statusOut, _, _, _ := a.docker.runCollect(ctx, "inspect", "--format", "{{.State.Running}}", name) + if strings.TrimSpace(statusOut) != "true" { + fmt.Printf("[file-recovery] %s: container not running, skipping recovery\n", name) + return + } + + diffOut, _, _, diffErr := a.docker.runCollect(ctx, "diff", name) + if diffErr != nil || strings.TrimSpace(diffOut) == "" { + fmt.Printf("[file-recovery] %s: docker diff returned no changes\n", name) + return + } + + dataRoots := map[string]int{} + for _, line := range strings.Split(diffOut, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + parts := strings.SplitN(line, " ", 2) + if len(parts) != 2 { + continue + } + action := parts[0] + filePath := parts[1] + + if action != "A" { + continue + } + + skipPrefixes := []string{"/tmp/", "/var/", "/proc/", "/sys/", + "/dev/", "/etc/", "/root/", "/run/", "/opt/", "/usr/", "/home/"} + skip := false + for _, prefix := range skipPrefixes { + if strings.HasPrefix(filePath, prefix) { + skip = true + break + } + } + if skip { + continue + } + + clean := filepath.Clean(filePath) + segments := strings.Split(strings.TrimPrefix(clean, "/"), "/") + if len(segments) == 0 { + continue + } + + root := "/" + segments[0] + if len(segments) >= 2 { + root = "/" + segments[0] + "/" + segments[1] + } + dataRoots[root]++ + } + + if len(dataRoots) == 0 { + fmt.Printf("[file-recovery] %s: no significant file changes found in container\n", name) + return + } + + bestRoot := "" + bestCount := 0 + for root, count := range dataRoots { + if count > bestCount { + bestRoot = root + bestCount = count + } + } + + fmt.Printf("[file-recovery] %s: detected data root '%s' with %d new files — copying to server directory\n", name, bestRoot, bestCount) + + cpCtx, cpCancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cpCancel() + + srcPath := name + ":" + bestRoot + "/." + _, cpErr, cpCode, cpGoErr := a.docker.runCollect(cpCtx, "cp", srcPath, serverDir+"/") + if cpGoErr != nil || cpCode != 0 { + srcPath = name + ":" + bestRoot + _, cpErr, cpCode, cpGoErr = a.docker.runCollect(cpCtx, "cp", srcPath, serverDir+"/") + if cpGoErr != nil || cpCode != 0 { + fmt.Printf("[file-recovery] %s: docker cp failed: %s\n", name, cpErr) + return + } + } + + ensureVolumeWritable(serverDir) + + correctVolume := fmt.Sprintf("%s:%s", serverDir, bestRoot) + _ = a.modifyMeta(serverDir, func(meta map[string]any) { + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + runtimeObj = make(map[string]any) + } + + runtimeObj["volumes"] = []any{correctVolume} + meta["runtime"] = runtimeObj + + if sc, ok := meta["startupCommand"].(string); ok && sc != "" { + fmt.Printf("[file-recovery] %s: startup command exists, runtime volumes updated to %s\n", name, correctVolume) + } + }) + + fmt.Printf("[file-recovery] %s: recovered %d files from container path '%s' — volume config updated for future starts\n", name, bestCount, bestRoot) + + newEntries, _ := os.ReadDir(serverDir) + newCount := 0 + for _, e := range newEntries { + if e.Name() != ".adpanel" && e.Name() != ".adpanel_meta" { + newCount++ + } + } + fmt.Printf("[file-recovery] %s: server directory now has %d files\n", name, newCount) +} + +func (d Docker) extractImageFiles(ctx context.Context, imageRef, destDir, extractPath string) error { + if extractPath == "" { + extractPath = "/" + } + + extractPath = strings.TrimSuffix(extractPath, "/") + if extractPath == "" { + extractPath = "/" + } + + tempName := "adpanel-extract-" + fmt.Sprintf("%d", time.Now().UnixNano()) + + _, errStr, code, err := d.runCollect(ctx, "create", "--name", tempName, imageRef, "true") + if err != nil || code != 0 { + return fmt.Errorf("failed to create temp container: %s", strings.TrimSpace(errStr)) + } + + defer func() { + cleanupCtx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + d.rmForce(cleanupCtx, tempName) + }() + + srcPath := tempName + ":" + extractPath + if extractPath != "/" { + srcPath = srcPath + "/." + } + + _, errStr, code, err = d.runCollect(ctx, "cp", srcPath, destDir+"/") + if err != nil || code != 0 { + srcPath = tempName + ":" + extractPath + _, errStr, code, err = d.runCollect(ctx, "cp", srcPath, destDir+"/") + if err != nil || code != 0 { + return fmt.Errorf("failed to copy files from container: %s", strings.TrimSpace(errStr)) + } + } + + if d.debug { + fmt.Printf("[docker] extracted files from %s:%s to %s\n", imageRef, extractPath, destDir) + } + + return nil +} + +func (d Docker) updateRestartNo(ctx context.Context, name string) { + _, _, _, _ = d.runCollect(ctx, "update", "--restart=no", name) +} + +func (d Docker) updateRestartPolicy(ctx context.Context, name, policy string) { + clean := strings.ToLower(strings.TrimSpace(policy)) + switch clean { + case "", "no", "always", "unless-stopped", "on-failure": + default: + clean = "unless-stopped" + } + if clean == "" { + clean = "no" + } + _, _, _, _ = d.runCollect(ctx, "update", "--restart="+clean, name) +} + +func (d Docker) getImageDigest(ctx context.Context, imageRef string) string { + out, _, code, err := d.runCollect(ctx, "inspect", "--format", "{{.Id}}", imageRef) + if err != nil || code != 0 { + return "" + } + return strings.TrimSpace(out) +} + +func (a *Agent) syncNewFilesToServer(ctx context.Context, imageRef, serverDir string, containerPaths []string) error { + tmpDir, err := os.MkdirTemp("", "adpanel-sync-*") + if err != nil { + return fmt.Errorf("failed to create temp dir: %w", err) + } + defer os.RemoveAll(tmpDir) + + extracted := false + for _, containerPath := range containerPaths { + if err := a.docker.extractImageFiles(ctx, imageRef, tmpDir, containerPath); err == nil { + extracted = true + break + } + } + + if !extracted { + commonPaths := []string{"/app", "/data", "/config", "/opt", "/srv"} + for _, p := range commonPaths { + if err := a.docker.extractImageFiles(ctx, imageRef, tmpDir, p); err == nil { + extracted = true + break + } + } + } + + if !extracted { + return fmt.Errorf("could not extract files from image") + } + + newFiles := 0 + err = filepath.Walk(tmpDir, func(path string, info os.FileInfo, walkErr error) error { + if walkErr != nil || info.IsDir() { + return walkErr + } + + if info.Mode()&os.ModeSymlink != 0 { + return nil + } + if !info.Mode().IsRegular() { + return nil + } + + rel, err := filepath.Rel(tmpDir, path) + if err != nil { + return nil + } + + destPath := filepath.Join(serverDir, rel) + + destParent := filepath.Dir(destPath) + if rp, rpErr := filepath.EvalSymlinks(destParent); rpErr == nil && !isUnder(serverDir, rp) { + return nil + } + if di, diErr := os.Lstat(destPath); diErr == nil && di.Mode()&os.ModeSymlink != 0 { + return nil + } + if _, err := os.Stat(destPath); os.IsNotExist(err) { + if err := ensureDir(filepath.Dir(destPath)); err != nil { + return nil + } + + data, err := os.ReadFile(path) + if err != nil { + return nil + } + + if err := writeFileNoFollow(destPath, data, info.Mode()); err == nil { + newFiles++ + if a.debug { + fmt.Printf("[sync] added new file: %s\n", rel) + } + } + } + + return nil + }) + + if newFiles > 0 { + fmt.Printf("[sync] added %d new files from image update\n", newFiles) + } + + return err +} + +func serverDirVisibleFileCount(serverDir string) int { + entries, err := os.ReadDir(serverDir) + if err != nil { + return 0 + } + count := 0 + for _, entry := range entries { + name := entry.Name() + if name == ".adpanel" || name == ".adpanel_meta" || name == "adpanel.json" || strings.HasPrefix(name, ".adpanel_") { + continue + } + count++ + } + return count +} + +func appendUniqueContainerPath(paths []string, seen map[string]struct{}, raw string) []string { + clean := path.Clean(strings.TrimSpace(raw)) + if clean == "" || clean == "." || clean == "/" || !strings.HasPrefix(clean, "/") { + return paths + } + if _, ok := seen[clean]; ok { + return paths + } + seen[clean] = struct{}{} + return append(paths, clean) +} + +func commandReferencedContainerPaths(command, workdir, dataDir string) []string { + args := parseShellArgs(command) + if len(args) == 0 { + return nil + } + paths := []string{} + seen := map[string]struct{}{} + for _, arg := range args[1:] { + token := strings.TrimSpace(arg) + if token == "" || strings.HasPrefix(token, "-") { + continue + } + lower := strings.ToLower(token) + if strings.HasPrefix(token, "/") { + paths = appendUniqueContainerPath(paths, seen, path.Dir(token)) + continue + } + if strings.Contains(token, "/") || strings.HasSuffix(lower, ".sh") || strings.HasSuffix(lower, ".py") || strings.HasSuffix(lower, ".js") { + base := strings.TrimSpace(workdir) + if base == "" { + base = dataDir + } + if base != "" { + paths = appendUniqueContainerPath(paths, seen, path.Dir(path.Join(base, token))) + } + } + } + return paths +} + +func (a *Agent) prepareServerDirFromImage(ctx context.Context, imageRef, serverDir string, imgCfg imageConfig, paths []string) string { + if serverDirVisibleFileCount(serverDir) > 0 { + return "" + } + + seen := map[string]struct{}{} + candidates := []string{} + for _, p := range paths { + candidates = appendUniqueContainerPath(candidates, seen, p) + } + for _, p := range imgCfg.Volumes { + candidates = appendUniqueContainerPath(candidates, seen, p) + } + for _, p := range getDataPathsFromEnv(imgCfg.Env) { + candidates = appendUniqueContainerPath(candidates, seen, p) + } + candidates = appendUniqueContainerPath(candidates, seen, imgCfg.Workdir) + for _, p := range []string{"/app", "/data", "/config", "/srv", "/opt"} { + candidates = appendUniqueContainerPath(candidates, seen, p) + } + + for _, p := range candidates { + extractCtx, cancel := context.WithTimeout(ctx, 90*time.Second) + err := a.docker.extractImageFiles(extractCtx, imageRef, serverDir, p) + cancel() + if err != nil { + continue + } + if serverDirVisibleFileCount(serverDir) > 0 { + _ = sanitizeExtractedTree(serverDir) + ensureVolumeWritable(serverDir) + fmt.Printf("[docker] prepared server directory from image %s:%s\n", imageRef, p) + return p + } + } + return "" +} + +func (d Docker) stop(ctx context.Context, name string) { + _, _, _, _ = d.runCollect(ctx, "stop", "-t", "15", name) +} + +func (d Docker) clearContainerLogs(ctx context.Context, name string) error { + dockerName := dockerContainerName(name) + if dockerName == "" { + return fmt.Errorf("missing container name") + } + + out, errText, _, err := d.runCollect(ctx, "inspect", "-f", "{{.LogPath}}", dockerName) + if err != nil { + lower := strings.ToLower(errText) + if strings.Contains(lower, "no such object") || strings.Contains(lower, "no such container") || strings.Contains(lower, "not found") { + return nil + } + if strings.TrimSpace(errText) != "" { + return errors.New(strings.TrimSpace(errText)) + } + return err + } + + logPath := strings.TrimSpace(out) + if logPath == "" || logPath == "" { + return nil + } + cleanPath := filepath.Clean(logPath) + if !filepath.IsAbs(cleanPath) || cleanPath == string(filepath.Separator) { + return fmt.Errorf("unsafe docker log path") + } + info, statErr := os.Lstat(cleanPath) + if statErr != nil { + if os.IsNotExist(statErr) { + return nil + } + return statErr + } + if info.Mode()&os.ModeSymlink != 0 || !info.Mode().IsRegular() { + return fmt.Errorf("refusing to truncate non-regular docker log path") + } + return os.Truncate(cleanPath, 0) +} + +const ( + stdinMaxContainers = 100 + stdinIdleTimeout = 10 * time.Minute + stdinWriteTimeout = 5 * time.Second + stdinCommandMaxLen = 4096 + stdinBufferSize = 256 + + consoleCommandDuplicateWindow = 1200 * time.Millisecond + consoleCommandRequestIDWindow = 30 * time.Second + consoleCommandRequestIDMaxLen = 128 + consoleCommandRecentMaxServers = 1000 +) + +type recentConsoleCommand struct { + command string + requestID string + at time.Time +} + +type stdinConn struct { + name string + stdin io.WriteCloser + cmd *exec.Cmd + lastUsed time.Time + tty bool + transport string + mu sync.Mutex + closed bool +} + +type stdinManager struct { + mu sync.RWMutex + conns map[string]*stdinConn + docker *Docker + debug bool + stopCh chan struct{} + stopOnce sync.Once +} + +func preferDockerCLIConsoleTransport() bool { + override := strings.ToLower(strings.TrimSpace(os.Getenv("ADPANEL_DOCKER_STREAM_TRANSPORT"))) + switch override { + case "cli", "docker-cli", "docker": + return true + case "api", "docker-api", "hijack": + return false + } + return false +} + +func isEnterpriseLinuxOSRelease(raw string) bool { + osInfo := strings.ToLower(raw) + for _, line := range strings.Split(osInfo, "\n") { + key, val, ok := strings.Cut(line, "=") + if !ok { + continue + } + key = strings.ToLower(strings.TrimSpace(key)) + val = strings.Trim(strings.TrimSpace(val), `"'`) + if key != "id" && key != "id_like" { + continue + } + for _, distro := range []string{"rocky", "rhel", "centos", "almalinux", "ol", "fedora"} { + if val == distro || strings.Contains(val, distro) { + return true + } + } + } + return false +} + +func preferDockerCLIPTYStdinTransport() bool { + override := strings.ToLower(strings.TrimSpace(os.Getenv("ADPANEL_DOCKER_STDIN_TRANSPORT"))) + switch override { + case "pty", "cli-pty", "docker-pty", "script": + return true + case "api", "docker-api", "hijack": + return false + } + return true +} + +func containerTTYForHost() bool { + return true +} + +func dockerRunInteractiveArgs() []string { + return []string{"run", "-d", "-i", "-t"} +} + +func dockerRunInteractivePrefix() string { + return "docker run -d -i -t" +} + +func newStdinManager(docker *Docker, debug bool) *stdinManager { + sm := &stdinManager{ + conns: make(map[string]*stdinConn), + docker: docker, + debug: debug, + stopCh: make(chan struct{}), + } + go sm.cleanupLoop() + return sm +} + +func (sm *stdinManager) cleanupLoop() { + ticker := time.NewTicker(30 * time.Second) + defer ticker.Stop() + for { + select { + case <-sm.stopCh: + return + case <-ticker.C: + sm.cleanupIdle() + } + } +} + +func extractTarSafeRouted(tr *tar.Reader, serverDir string, backupsDir string, metaDir ...string) error { + var totalSize int64 + var fileCount int + + const backupsPrefix = ".adpanel_backups/" + const metaPrefix = ".adpanel_meta/" + + for { + h, err := tr.Next() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + + fileCount++ + if fileCount > maxExtractFiles { + return fmt.Errorf("too many files in tar: %d (max %d)", fileCount, maxExtractFiles) + } + if h.Size > maxSingleFile { + return fmt.Errorf("file too large in tar: %s (%d bytes, max %d)", h.Name, h.Size, maxSingleFile) + } + + cleaned := filepath.Clean(h.Name) + cleaned = strings.TrimPrefix(cleaned, "/") + if cleaned == "." || cleaned == "" { + continue + } + + destRoot := serverDir + rel := cleaned + if cleaned == strings.TrimSuffix(backupsPrefix, "/") { + continue + } + if cleaned == strings.TrimSuffix(metaPrefix, "/") { + continue + } + if strings.HasPrefix(cleaned, metaPrefix) { + if len(metaDir) > 0 && metaDir[0] != "" { + destRoot = metaDir[0] + rel = strings.TrimPrefix(cleaned, metaPrefix) + if rel == "" || rel == "." { + continue + } + } else { + continue + } + } else if strings.HasPrefix(cleaned, backupsPrefix) { + destRoot = backupsDir + rel = strings.TrimPrefix(cleaned, backupsPrefix) + if rel == "" || rel == "." { + continue + } + } + + target := filepath.Join(destRoot, rel) + if !isUnder(destRoot, target) { + return fmt.Errorf("tar-slip blocked: %s", h.Name) + } + baseName := filepath.Base(rel) + if baseName == "." || baseName == ".." { + continue + } + + switch h.Typeflag { + case tar.TypeDir: + if err := os.MkdirAll(target, 0o755); err != nil { + return err + } + resolvedDir, rdErr := filepath.EvalSymlinks(target) + if rdErr == nil && !isUnder(destRoot, resolvedDir) { + return fmt.Errorf("symlink escape blocked during tar extract: %s", h.Name) + } + case tar.TypeReg, tar.TypeRegA: + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + resolvedParent, rpErr := filepath.EvalSymlinks(filepath.Dir(target)) + if rpErr == nil && !isUnder(destRoot, resolvedParent) { + return fmt.Errorf("symlink escape blocked during tar extract: %s", h.Name) + } + if ei, eiErr := os.Lstat(target); eiErr == nil && ei.Mode()&os.ModeSymlink != 0 { + continue + } + out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644) + if err != nil { + return err + } + lw := &limitedWriter{w: out, limit: maxExtractSize - totalSize} + n, err := io.Copy(lw, tr) + out.Close() + if err != nil { + return err + } + totalSize += n + case tar.TypeLink: + return fmt.Errorf("hardlinks not allowed for security: %s", h.Name) + case tar.TypeSymlink: + continue + default: + continue + } + } +} + +func (sm *stdinManager) cleanupIdle() { + sm.mu.Lock() + defer sm.mu.Unlock() + + now := time.Now() + for name, conn := range sm.conns { + conn.mu.Lock() + idle := now.Sub(conn.lastUsed) > stdinIdleTimeout + conn.mu.Unlock() + + if idle { + if sm.debug { + fmt.Printf("[stdin-manager] closing idle connection for %s\n", name) + } + conn.close() + delete(sm.conns, name) + } + } +} + +func (sm *stdinManager) stop() { + sm.stopOnce.Do(func() { + close(sm.stopCh) + sm.mu.Lock() + defer sm.mu.Unlock() + for name, conn := range sm.conns { + conn.close() + delete(sm.conns, name) + } + }) +} + +func (sm *stdinManager) getOrCreate(ctx context.Context, containerName string) (*stdinConn, error) { + name := dockerContainerName(containerName) + if name == "" { + return nil, fmt.Errorf("empty container name") + } + + if !sm.docker.containerExists(ctx, name) { + return nil, fmt.Errorf("container-not-running") + } + + sm.mu.Lock() + defer sm.mu.Unlock() + + if conn, ok := sm.conns[name]; ok { + conn.mu.Lock() + if !conn.closed { + conn.lastUsed = time.Now() + conn.mu.Unlock() + return conn, nil + } + conn.mu.Unlock() + delete(sm.conns, name) + } + + if len(sm.conns) >= stdinMaxContainers { + var oldestName string + var oldestTime time.Time + for n, c := range sm.conns { + c.mu.Lock() + if oldestName == "" || c.lastUsed.Before(oldestTime) { + oldestName = n + oldestTime = c.lastUsed + } + c.mu.Unlock() + } + if oldestName != "" { + if sm.debug { + fmt.Printf("[stdin-manager] evicting oldest connection %s\n", oldestName) + } + sm.conns[oldestName].close() + delete(sm.conns, oldestName) + } + } + + conn, err := sm.createStdinConn(ctx, name) + if err != nil { + return nil, err + } + sm.conns[name] = conn + return conn, nil +} + +func (sm *stdinManager) createStdinConn(ctx context.Context, name string) (*stdinConn, error) { + tty := sm.docker.containerTTY(ctx, name) + preferCLI := preferDockerCLIConsoleTransport() && !tty + preferCLIPTY := tty && preferDockerCLIPTYStdinTransport() + if preferCLIPTY { + conn, err := sm.createDockerCLIPTYStdinConn(ctx, name) + if err == nil { + return conn, nil + } + if sm.debug { + fmt.Printf("[stdin-manager] Docker CLI PTY stdin attach failed for %s: %v\n", name, err) + } + } + if preferCLI { + conn, err := sm.createDockerCLIStdinConn(ctx, name) + if err == nil { + return conn, nil + } + if sm.debug { + fmt.Printf("[stdin-manager] Docker CLI stdin attach failed for %s: %v\n", name, err) + } + } + + attachCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + + stdin, err := sm.docker.attachContainerAPI(attachCtx, name, dockerAttachOptions{Stdin: true}) + if err != nil { + if tty && !preferCLIPTY { + conn, ptyErr := sm.createDockerCLIPTYStdinConn(ctx, name) + if ptyErr == nil { + return conn, nil + } + return nil, fmt.Errorf("failed to attach container stdin: Docker API: %v; Docker CLI PTY: %w", err, ptyErr) + } + if !preferCLI && !tty { + conn, cliErr := sm.createDockerCLIStdinConn(ctx, name) + if cliErr == nil { + return conn, nil + } + return nil, fmt.Errorf("failed to attach container stdin: Docker API: %v; Docker CLI: %w", err, cliErr) + } + return nil, fmt.Errorf("failed to attach container stdin: %w", err) + } + + conn := &stdinConn{ + name: name, + stdin: stdin, + lastUsed: time.Now(), + tty: tty, + transport: "docker-api", + } + + if sm.debug { + fmt.Printf("[stdin-manager] created Docker API stdin connection for %s (tty=%t)\n", name, conn.tty) + } + + return conn, nil +} + +func (sm *stdinManager) createDockerCLIPTYStdinConn(ctx context.Context, name string) (*stdinConn, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if strings.TrimSpace(name) == "" { + return nil, fmt.Errorf("empty container name") + } + + cmd := exec.Command("docker", "attach", "--sig-proxy=false", "--detach-keys=ctrl-@", name) + ptmx, err := pty.StartWithSize(cmd, &pty.Winsize{Rows: 30, Cols: 120}) + if err != nil { + return nil, err + } + + conn := &stdinConn{ + name: name, + stdin: ptmx, + cmd: cmd, + lastUsed: time.Now(), + tty: true, + transport: "docker-cli-pty", + } + go func() { + _, _ = io.Copy(io.Discard, ptmx) + }() + go func() { + _ = cmd.Wait() + conn.mu.Lock() + conn.closed = true + conn.mu.Unlock() + }() + + if sm.debug { + fmt.Printf("[stdin-manager] created Docker CLI PTY stdin connection for %s\n", name) + } + return conn, nil +} + +func (sm *stdinManager) createDockerCLIStdinConn(ctx context.Context, name string) (*stdinConn, error) { + if err := ctx.Err(); err != nil { + return nil, err + } + if strings.TrimSpace(name) == "" { + return nil, fmt.Errorf("empty container name") + } + + cmd := exec.Command("docker", "attach", "--sig-proxy=false", name) + stdin, err := cmd.StdinPipe() + if err != nil { + return nil, err + } + cmd.Stdout = io.Discard + cmd.Stderr = io.Discard + if err := cmd.Start(); err != nil { + _ = stdin.Close() + return nil, err + } + + conn := &stdinConn{ + name: name, + stdin: stdin, + cmd: cmd, + lastUsed: time.Now(), + tty: sm.docker.containerTTY(ctx, name), + transport: "docker-cli", + } + go func() { + _ = cmd.Wait() + conn.mu.Lock() + conn.closed = true + conn.mu.Unlock() + }() + + if sm.debug { + fmt.Printf("[stdin-manager] created Docker CLI stdin connection for %s (tty=%t)\n", name, conn.tty) + } + return conn, nil +} + +func (c *stdinConn) close() { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return + } + c.closed = true + if c.stdin != nil { + c.stdin.Close() + } + if c.cmd != nil && c.cmd.Process != nil { + _ = c.cmd.Process.Kill() + } +} + +func (c *stdinConn) sendCommand(cmd string) error { + c.mu.Lock() + defer c.mu.Unlock() + if c.closed { + return fmt.Errorf("connection closed") + } + c.lastUsed = time.Now() + line := strings.TrimRight(cmd, "\r\n") + "\n" + if deadlineWriter, ok := c.stdin.(interface{ SetWriteDeadline(time.Time) error }); ok { + _ = deadlineWriter.SetWriteDeadline(time.Now().Add(stdinWriteTimeout)) + defer deadlineWriter.SetWriteDeadline(time.Time{}) + } + if _, err := io.WriteString(c.stdin, line); err != nil { + c.closed = true + if c.stdin != nil { + _ = c.stdin.Close() + } + if c.cmd != nil && c.cmd.Process != nil { + _ = c.cmd.Process.Kill() + } + return fmt.Errorf("stdin write failed: %w", err) + } + return nil +} + +func (sm *stdinManager) remove(name string) { + name = dockerContainerName(name) + sm.mu.Lock() + defer sm.mu.Unlock() + if conn, ok := sm.conns[name]; ok { + conn.close() + delete(sm.conns, name) + } +} + +func exitCodeFromErr(err error) int { + if err == nil { + return 0 + } + var ee *exec.ExitError + if errors.As(err, &ee) { + return ee.ExitCode() + } + return -1 +} + +func (d Docker) writeToContainerProcessStdin(ctx context.Context, containerName, command string) error { + name := dockerContainerName(containerName) + cmd := strings.TrimSpace(command) + if name == "" || cmd == "" { + return fmt.Errorf("missing-params") + } + shells := []string{"sh", "/bin/sh", "bash", "/bin/bash"} + for idx, shellPath := range shells { + script := "fd=$(readlink /proc/1/fd/0 2>/dev/null || true); case \"$fd\" in /dev/null*) exit 45 ;; esac; cat > /proc/1/fd/0" + pipeCmd := exec.CommandContext(ctx, "docker", "exec", "-i", name, shellPath, "-lc", script) + pipeCmd.Stdin = strings.NewReader(cmd + "\n") + pipeCmd.Stdout = io.Discard + var stderr bytes.Buffer + pipeCmd.Stderr = &stderr + if err := pipeCmd.Run(); err == nil { + return nil + } else { + exitCode := exitCodeFromErr(err) + if exitCode == 45 { + return fmt.Errorf("process stdin is not open; restart the server so the container is recreated with interactive stdin") + } + if isMissingExecShell(stderr.String(), shellPath, exitCode) && idx < len(shells)-1 { + continue + } + detail := strings.TrimSpace(stderr.String()) + if detail == "" { + detail = err.Error() + } + return fmt.Errorf("process stdin write failed: %s", detail) + } + } + return fmt.Errorf("process stdin write failed: no supported shell found in container") +} + +func (d Docker) containerTTY(ctx context.Context, containerName string) bool { + name := dockerContainerName(containerName) + if name == "" { + return false + } + inspectCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + out, _, _, err := d.runCollect(inspectCtx, "inspect", "-f", "{{.Config.Tty}}", name) + return err == nil && strings.EqualFold(strings.TrimSpace(out), "true") +} + +func (d Docker) containerOpenStdin(ctx context.Context, containerName string) bool { + name := dockerContainerName(containerName) + if name == "" { + return false + } + inspectCtx, cancel := context.WithTimeout(ctx, 3*time.Second) + defer cancel() + out, _, _, err := d.runCollect(inspectCtx, "inspect", "-f", "{{.Config.OpenStdin}} {{.Config.AttachStdin}}", name) + if err != nil { + return false + } + fields := strings.Fields(strings.ToLower(strings.TrimSpace(out))) + return len(fields) >= 1 && fields[0] == "true" +} + +func (d Docker) writeToMinecraftProcessStdin(ctx context.Context, containerName, command string) error { + name := dockerContainerName(containerName) + cmd := strings.TrimSpace(command) + if name == "" || cmd == "" { + return fmt.Errorf("missing-params") + } + script := "pid=$(pgrep -n java || pgrep -n bedrock_server || echo 1); fd=$(readlink \"/proc/$pid/fd/0\" 2>/dev/null || true); case \"$fd\" in /dev/null*) exit 45 ;; esac; cat > \"/proc/$pid/fd/0\"" + shells := []string{"sh", "/bin/sh", "bash", "/bin/bash"} + for idx, shellPath := range shells { + pipeCmd := exec.CommandContext(ctx, "docker", "exec", "-i", name, shellPath, "-lc", script) + pipeCmd.Stdin = strings.NewReader(cmd + "\n") + pipeCmd.Stdout = io.Discard + var stderr bytes.Buffer + pipeCmd.Stderr = &stderr + if err := pipeCmd.Run(); err == nil { + return nil + } else { + exitCode := exitCodeFromErr(err) + if exitCode == 45 { + return fmt.Errorf("minecraft stdin is not open; restart the server so the container is recreated with interactive stdin") + } + if isMissingExecShell(stderr.String(), shellPath, exitCode) && idx < len(shells)-1 { + continue + } + detail := strings.TrimSpace(stderr.String()) + if detail == "" { + detail = err.Error() + } + return fmt.Errorf("minecraft stdin write failed: %s", detail) + } + } + return fmt.Errorf("minecraft stdin write failed: no supported shell found in container") +} + +func (d Docker) writeToTargetProcessStdin(ctx context.Context, containerName, command string, targets []string) error { + name := dockerContainerName(containerName) + cmd := strings.TrimSpace(command) + targets = sanitizeConsoleProcessTargets(targets) + if name == "" || cmd == "" { + return fmt.Errorf("missing-params") + } + if len(targets) == 0 { + return fmt.Errorf("no console target processes configured") + } + + script := strings.Join([]string{ + "pid=''", + "self=$$", + "for pattern in \"$@\"; do", + " [ -n \"$pattern\" ] || continue", + " pid=$(pgrep -n -x -- \"$pattern\" 2>/dev/null || true)", + " if [ -z \"$pid\" ]; then", + " for candidate in $(pgrep -f -- \"$pattern\" 2>/dev/null || true); do", + " [ \"$candidate\" = \"$self\" ] && continue", + " cmdline=$(tr '\\000' ' ' < \"/proc/$candidate/cmdline\" 2>/dev/null || true)", + " case \"$cmdline\" in *adpanel-console*) continue ;; esac", + " pid=$candidate", + " done", + " fi", + " [ -n \"$pid\" ] && break", + "done", + "[ -n \"$pid\" ] || exit 44", + "fd=$(readlink \"/proc/$pid/fd/0\" 2>/dev/null || true)", + "case \"$fd\" in /dev/null*) exit 45 ;; esac", + "cat > \"/proc/$pid/fd/0\"", + }, "\n") + + shells := []string{"sh", "/bin/sh", "bash", "/bin/bash"} + for idx, shellPath := range shells { + args := []string{"exec", "-i", name, shellPath, "-c", script, "adpanel-console"} + args = append(args, targets...) + pipeCmd := exec.CommandContext(ctx, "docker", args...) + pipeCmd.Stdin = strings.NewReader(cmd + "\n") + pipeCmd.Stdout = io.Discard + var stderr bytes.Buffer + pipeCmd.Stderr = &stderr + if err := pipeCmd.Run(); err == nil { + if d.debug { + fmt.Printf("[docker] command sent to target process stdin: %s\n", strings.Join(targets, ",")) + } + return nil + } else { + exitCode := exitCodeFromErr(err) + if exitCode == 44 { + return fmt.Errorf("target process not found: %s", strings.Join(targets, ", ")) + } + if exitCode == 45 { + return fmt.Errorf("target process stdin is not open; restart the server so the container is recreated with interactive stdin") + } + if isMissingExecShell(stderr.String(), shellPath, exitCode) && idx < len(shells)-1 { + continue + } + detail := strings.TrimSpace(stderr.String()) + if detail == "" { + detail = err.Error() + } + return fmt.Errorf("target process stdin write failed: %s", detail) + } + } + return fmt.Errorf("target process stdin write failed: no supported shell found in container") +} + +func (d Docker) sendViaAttachedStdin(ctx context.Context, stdinMgr *stdinManager, containerName, command string) error { + name := dockerContainerName(containerName) + cmd := strings.TrimSpace(command) + if name == "" || cmd == "" { + return fmt.Errorf("missing-params") + } + if stdinMgr == nil { + return fmt.Errorf("stdin manager unavailable") + } + + var lastErr error + for attempt := 0; attempt < 2; attempt++ { + if err := ctx.Err(); err != nil { + return err + } + conn, err := stdinMgr.getOrCreate(ctx, name) + if err == nil { + if err := conn.sendCommand(cmd); err == nil { + if d.debug { + fmt.Printf("[docker] command sent via attached container stdin\n") + } + return nil + } else { + lastErr = err + stdinMgr.remove(name) + continue + } + } + lastErr = err + stdinMgr.remove(name) + } + if lastErr == nil { + lastErr = fmt.Errorf("stdin channel unavailable") + } + return lastErr +} + +func (d Docker) sendCommand(ctx context.Context, stdinMgr *stdinManager, containerName, command string, targetProcesses []string) error { + name := dockerContainerName(containerName) + cmd := strings.TrimSpace(command) + if name == "" || cmd == "" { + return fmt.Errorf("missing-params") + } + + if len(cmd) > stdinCommandMaxLen { + return fmt.Errorf("command too long (max %d)", stdinCommandMaxLen) + } + + if err := validateCommandInput(cmd); err != nil { + return err + } + + if state := d.containerState(ctx, name); state != "running" { + return fmt.Errorf("container-not-running") + } + + openStdin := d.containerOpenStdin(ctx, name) + if !openStdin { + if stdinMgr != nil { + stdinMgr.remove(name) + } + return fmt.Errorf("container stdin is not open; restart the server so the container is recreated with interactive stdin") + } + + tty := d.containerTTY(ctx, name) + + var targetErr error + var attachedErr error + if stdinMgr != nil { + if err := d.sendViaAttachedStdin(ctx, stdinMgr, name, cmd); err == nil { + return nil + } else { + attachedErr = err + if d.debug { + fmt.Printf("[docker] attached stdin failed for %s: %v\n", name, err) + } + } + } + + if tty { + if attachedErr != nil { + return fmt.Errorf("failed-to-send: attached TTY stdin failed: %w", attachedErr) + } + return fmt.Errorf("failed-to-send: TTY stdin channel unavailable") + } + + if len(targetProcesses) > 0 { + if err := d.writeToTargetProcessStdin(ctx, name, cmd, targetProcesses); err == nil { + return nil + } else { + targetErr = err + if d.debug { + fmt.Printf("[docker] target process stdin failed for %s: %v\n", name, err) + } + } + } + + if err := d.writeToContainerProcessStdin(ctx, name, cmd); err == nil { + if d.debug { + fmt.Printf("[docker] command sent via /proc/1/fd/0\n") + } + return nil + } else if err != nil { + if attachedErr != nil { + if targetErr != nil { + return fmt.Errorf("failed-to-send: target process stdin failed: %v; attached stdin failed: %v; process stdin fallback failed: %w", targetErr, attachedErr, err) + } + return fmt.Errorf("failed-to-send: attached stdin failed: %v; process stdin fallback failed: %w", attachedErr, err) + } + if targetErr != nil { + return fmt.Errorf("failed-to-send: target process stdin failed: %v; process stdin fallback failed: %w", targetErr, err) + } + return fmt.Errorf("failed-to-send: %w", err) + } + return fmt.Errorf("failed-to-send: stdin channel unavailable") +} + +func validateCommandInput(cmd string) error { + if strings.ContainsRune(cmd, '\x00') { + return fmt.Errorf("invalid command: contains null byte") + } + for _, r := range cmd { + if r < 32 && r != '\t' && r != '\n' && r != '\r' { + return fmt.Errorf("invalid command: contains control character") + } + } + return nil +} + +type Downloader struct { + headerTimeout time.Duration + maxBytes int64 +} + +func (dl Downloader) safeURL(raw string) (*url.URL, error) { + u, err := url.Parse(strings.TrimSpace(raw)) + if err != nil { + return nil, err + } + if u.Scheme != "http" && u.Scheme != "https" { + return nil, fmt.Errorf("invalid scheme") + } + if u.User != nil && u.User.String() != "" { + return nil, fmt.Errorf("credentials not allowed") + } + host := u.Hostname() + if host == "" { + return nil, fmt.Errorf("missing host") + } + if isBlockedOutboundHostname(host) { + return nil, fmt.Errorf("blocked host") + } + + ips, err := net.LookupIP(host) + if err != nil { + return nil, fmt.Errorf("dns failed: %w", err) + } + checkedIP := false + for _, ip := range ips { + addr, ok := netip.AddrFromSlice(ip) + if !ok { + continue + } + checkedIP = true + if isBlockedOutboundAddr(addr) { + return nil, fmt.Errorf("blocked host ip: %s", addr.String()) + } + } + if !checkedIP { + return nil, fmt.Errorf("dns returned no usable ip") + } + return u, nil +} + +func isBlockedOutboundHostname(host string) bool { + h := strings.TrimSuffix(strings.ToLower(strings.TrimSpace(host)), ".") + return h == "localhost" || strings.HasSuffix(h, ".localhost") || strings.HasSuffix(h, ".local") +} + +func isBlockedOutboundAddr(addr netip.Addr) bool { + if addr.Is4In6() { + addr = addr.Unmap() + } + return !addr.IsGlobalUnicast() || + addr.IsPrivate() || + addr.IsLoopback() || + addr.IsLinkLocalUnicast() || + addr.IsLinkLocalMulticast() || + addr.IsMulticast() || + addr.IsUnspecified() +} + +func isPrivateIP(ip net.IP) bool { + addr, ok := netip.AddrFromSlice(ip) + if !ok { + return true + } + return isBlockedOutboundAddr(addr) +} + +func (dl Downloader) client() *http.Client { + return dl.clientWithProxy(http.ProxyFromEnvironment) +} + +func (dl Downloader) clientNoProxy() *http.Client { + return dl.clientWithProxy(nil) +} + +func (dl Downloader) clientWithProxy(proxy func(*http.Request) (*url.URL, error)) *http.Client { + safeDialer := &net.Dialer{ + Timeout: 10 * time.Second, + KeepAlive: 30 * time.Second, + } + + transport := &http.Transport{ + Proxy: proxy, + DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) { + host, port, err := net.SplitHostPort(addr) + if err != nil { + return nil, fmt.Errorf("invalid address: %w", err) + } + + ips, err := net.LookupIP(host) + if err != nil { + return nil, fmt.Errorf("dns lookup failed: %w", err) + } + + for _, ip := range ips { + if isPrivateIP(ip) { + continue + } + dialAddr := net.JoinHostPort(ip.String(), port) + return safeDialer.DialContext(ctx, network, dialAddr) + } + + return nil, fmt.Errorf("all resolved IPs are blocked (private/internal)") + }, + TLSHandshakeTimeout: 10 * time.Second, + ResponseHeaderTimeout: dl.headerTimeout, + IdleConnTimeout: 60 * time.Second, + MaxIdleConns: 50, + MaxIdleConnsPerHost: 10, + } + return &http.Client{ + Transport: transport, + CheckRedirect: func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return fmt.Errorf("too many redirects") + } + _, err := dl.safeURL(req.URL.String()) + return err + }, + } +} + +func (dl Downloader) getJSON(ctx context.Context, raw string, dst any) error { + u, err := dl.safeURL(raw) + if err != nil { + return err + } + req, _ := http.NewRequestWithContext(ctx, "GET", u.String(), nil) + resp, err := dl.client().Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + io.Copy(io.Discard, resp.Body) + return fmt.Errorf("http %d", resp.StatusCode) + } + body, err := io.ReadAll(io.LimitReader(resp.Body, 8<<20)) + if err != nil { + return err + } + return json.Unmarshal(body, dst) +} + +func (dl Downloader) downloadToFile(ctx context.Context, rawURL, destPath string) error { + u, err := dl.safeURL(rawURL) + if err != nil { + return err + } + if err := ensureDir(filepath.Dir(destPath)); err != nil { + return err + } + + req, _ := http.NewRequestWithContext(ctx, "GET", u.String(), nil) + resp, err := dl.client().Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + if resp.StatusCode != 200 { + io.Copy(io.Discard, resp.Body) + return fmt.Errorf("http %d", resp.StatusCode) + } + + tmp := destPath + ".tmp" + _ = os.Remove(tmp) + f, err := os.OpenFile(tmp, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644) + if err != nil { + return err + } + defer f.Close() + + var r io.Reader = resp.Body + if dl.maxBytes > 0 { + r = io.LimitReader(resp.Body, dl.maxBytes) + } + if _, err := io.Copy(f, r); err != nil { + _ = os.Remove(tmp) + return err + } + if err := f.Close(); err != nil { + _ = os.Remove(tmp) + return err + } + return os.Rename(tmp, destPath) +} + +func writeMinecraftScaffold(serverDir, name, fork, version string) { + _ = os.WriteFile(filepath.Join(serverDir, "eula.txt"), []byte("eula=true\n"), 0o644) + props := strings.Join([]string{ + "motd=" + name, + "max-players=20", + "enforce-secure-profile=false", + "server-port=25565", + "server-ip=", + "", + }, "\n") + _ = os.WriteFile(filepath.Join(serverDir, "server.properties"), []byte(props), 0o644) +} + +func enforceServerProps(serverDir string) { + p := filepath.Join(serverDir, "server.properties") + txt := "" + if b, err := os.ReadFile(p); err == nil { + txt = string(b) + } + if txt == "" { + txt = "server-port=25565\nserver-ip=\n" + } else { + rePort := regexp.MustCompile(`(?m)^server-port=.*$`) + reIP := regexp.MustCompile(`(?m)^server-ip=.*$`) + if rePort.MatchString(txt) { + txt = rePort.ReplaceAllString(txt, "server-port=25565") + } else { + txt += "\nserver-port=25565\n" + } + if reIP.MatchString(txt) { + txt = reIP.ReplaceAllString(txt, "server-ip=") + } else { + txt += "server-ip=\n" + } + } + _ = os.WriteFile(p, []byte(txt), 0o644) +} + +func fixedJarUrlFor1218(fork string) string { + f := strings.ToLower(strings.TrimSpace(fork)) + switch f { + case "paper": + return "https://fill-data.papermc.io/v1/objects/8de7c52c3b02403503d16fac58003f1efef7dd7a0256786843927fa92ee57f1e/paper-1.21.8-60.jar" + case "pufferfish": + return "https://ci.pufferfish.host/job/Pufferfish-1.21/33/artifact/pufferfish-server/build/libs/pufferfish-paperclip-1.21.8-R0.1-SNAPSHOT-mojmap.jar" + case "vanilla": + return "https://piston-data.mojang.com/v1/objects/95495a7f485eedd84ce928cef5e223b757d2f764/server.jar" + default: + return "https://api.purpurmc.org/v2/purpur/1.21.8/2497/download" + } +} + +func getMinecraftJarURL(ctx context.Context, dl Downloader, fork, version string, debug bool) string { + v := strings.TrimSpace(version) + f := strings.ToLower(strings.TrimSpace(fork)) + if v == "1.21.8" { + return fixedJarUrlFor1218(f) + } + + defer func() { + _ = recover() + }() + + if f == "purpur" { + return fmt.Sprintf("https://api.purpurmc.org/v2/purpur/%s/latest/download", v) + } + + if f == "paper" || f == "pufferfish" { + var builds struct { + Builds []struct { + Build int `json:"build"` + Downloads struct { + Application struct { + Name string `json:"name"` + } `json:"application"` + } `json:"downloads"` + } `json:"builds"` + } + u := fmt.Sprintf("https://api.papermc.io/v2/projects/paper/versions/%s/builds", v) + if err := dl.getJSON(ctx, u, &builds); err == nil && len(builds.Builds) > 0 { + last := builds.Builds[len(builds.Builds)-1] + jarName := last.Downloads.Application.Name + if jarName == "" { + jarName = fmt.Sprintf("paper-%s-%d.jar", v, last.Build) + } + return fmt.Sprintf("https://api.papermc.io/v2/projects/paper/versions/%s/builds/%d/downloads/%s", v, last.Build, jarName) + } + } + + if f == "vanilla" { + var manifest struct { + Versions []struct { + ID string `json:"id"` + URL string `json:"url"` + } `json:"versions"` + } + if err := dl.getJSON(ctx, "https://piston-meta.mojang.com/mc/game/version_manifest_v2.json", &manifest); err == nil { + for _, ver := range manifest.Versions { + if ver.ID == v && ver.URL != "" { + var det struct { + Downloads struct { + Server struct { + URL string `json:"url"` + } `json:"server"` + } `json:"downloads"` + } + if err := dl.getJSON(ctx, ver.URL, &det); err == nil && det.Downloads.Server.URL != "" { + return det.Downloads.Server.URL + } + } + } + } + } + + return fmt.Sprintf("https://api.purpurmc.org/v2/purpur/%s/latest/download", v) +} + +const legacyPythonMainTemplate = `def greet(name="World"): + return f"Hello, {name}!" + +if __name__ == "__main__": + print("--- Starting main.py execution ---") + + user_name = "ADPanel" + message_1 = greet(user_name) + print(f"Message 1: {message_1}") + + message_2 = greet() + print(f"Message 2: {message_2}") + + print("--- Execution finished ---") +` + +const pythonMainTemplate = `from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +import os + + +class Handler(BaseHTTPRequestHandler): + def do_GET(self): + body = b"ADPanel Python server is running.\n" + self.send_response(200) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, fmt, *args): + print("%s - %s" % (self.address_string(), fmt % args), flush=True) + + +if __name__ == "__main__": + port = int(os.environ.get("PORT", "8000")) + server = ThreadingHTTPServer(("0.0.0.0", port), Handler) + print(f"ADPanel Python server listening on 0.0.0.0:{port}", flush=True) + server.serve_forever() +` + +func clampPort(p any, fallback int) int { + if n, ok := parseStrictPortValue(p); ok { + return n + } + return fallback +} + +func isStrictNumericPortString(s string) bool { + if s == "" { + return false + } + if s[0] < '1' || s[0] > '9' { + return false + } + for i := 1; i < len(s); i++ { + if s[i] < '0' || s[i] > '9' { + return false + } + } + return true +} + +func parseStrictPortValue(v any) (int, bool) { + switch x := v.(type) { + case int: + if x < 1 || x > 65535 { + return 0, false + } + return x, true + case int64: + if x < 1 || x > 65535 { + return 0, false + } + return int(x), true + case float64: + if x < 1 || x > 65535 || x != float64(int(x)) { + return 0, false + } + return int(x), true + case float32: + if x < 1 || x > 65535 || x != float32(int(x)) { + return 0, false + } + return int(x), true + case string: + s := strings.TrimSpace(x) + if !isStrictNumericPortString(s) { + return 0, false + } + n, err := strconv.Atoi(s) + if err != nil || n < 1 || n > 65535 { + return 0, false + } + return n, true + default: + return 0, false + } +} + +func normalizePortProtocolName(v any) string { + protocol := strings.ToLower(strings.TrimSpace(fmt.Sprint(v))) + switch protocol { + case "tcp", "udp", "sctp": + return protocol + default: + return "" + } +} + +func normalizePortProtocolSlice(v any) []string { + var raw []any + switch x := v.(type) { + case []string: + raw = make([]any, 0, len(x)) + for _, item := range x { + raw = append(raw, item) + } + case []any: + raw = x + case string: + raw = []any{x} + default: + return nil + } + + out := make([]string, 0, len(raw)) + seen := map[string]struct{}{} + for _, item := range raw { + protocol := normalizePortProtocolName(item) + if protocol == "" { + continue + } + if _, ok := seen[protocol]; ok { + continue + } + seen[protocol] = struct{}{} + out = append(out, protocol) + } + return out +} + +func runtimePortProtocolMap(raw any) map[int][]string { + out := map[int][]string{} + switch x := raw.(type) { + case map[string][]string: + for key, protocolsRaw := range x { + port, ok := parseStrictPortValue(key) + if !ok { + continue + } + protocols := normalizePortProtocolSlice(protocolsRaw) + if len(protocols) > 0 { + out[port] = protocols + } + } + case map[string]any: + for key, protocolsRaw := range x { + port, ok := parseStrictPortValue(key) + if !ok { + continue + } + protocols := normalizePortProtocolSlice(protocolsRaw) + if len(protocols) > 0 { + out[port] = protocols + } + } + case map[int][]string: + for port, protocolsRaw := range x { + if _, ok := parseStrictPortValue(port); !ok { + continue + } + protocols := normalizePortProtocolSlice(protocolsRaw) + if len(protocols) > 0 { + out[port] = protocols + } + } + } + if len(out) == 0 { + return nil + } + return out +} + +func portProtocolsFor(protocolsByPort map[int][]string, port int) []string { + if port > 0 { + if protocols := protocolsByPort[port]; len(protocols) > 0 { + return protocols + } + } + return []string{"tcp"} +} + +func mergePortProtocols(a, b []string) []string { + out := make([]string, 0, len(a)+len(b)) + seen := map[string]struct{}{} + for _, source := range [][]string{a, b} { + for _, raw := range source { + protocol := normalizePortProtocolName(raw) + if protocol == "" { + continue + } + if _, ok := seen[protocol]; ok { + continue + } + seen[protocol] = struct{}{} + out = append(out, protocol) + } + } + return out +} + +func sanitizeDockerPortProtocols(raw map[string][]string, ports []int) map[string][]string { + if len(raw) == 0 { + return nil + } + allowedPorts := map[int]struct{}{} + for _, port := range ports { + if _, ok := parseStrictPortValue(port); ok { + allowedPorts[port] = struct{}{} + } + } + + out := map[string][]string{} + for rawPort, protocolsRaw := range raw { + port, ok := parseStrictPortValue(rawPort) + if !ok { + continue + } + if len(allowedPorts) > 0 { + if _, ok := allowedPorts[port]; !ok { + continue + } + } + protocols := normalizePortProtocolSlice(protocolsRaw) + if len(protocols) > 0 { + out[strconv.Itoa(port)] = protocols + } + } + if len(out) == 0 { + return nil + } + return out +} + +func (a *Agent) dockerHostPortOwner(ctx context.Context, port int, excludeName string) string { + if a == nil || port <= 0 { + return "" + } + out, _, code, err := a.docker.runCollect(ctx, "ps", "--format", "{{.Names}}\t{{.Ports}}") + if err != nil || code != 0 { + return "" + } + needle := ":" + strconv.Itoa(port) + "->" + excluded := strings.ToLower(strings.TrimSpace(excludeName)) + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + parts := strings.SplitN(line, "\t", 2) + if len(parts) != 2 { + continue + } + name := strings.TrimSpace(parts[0]) + if excluded != "" && strings.ToLower(name) == excluded { + continue + } + if strings.Contains(parts[1], needle) { + return name + } + } + return "" +} + +func tcpHostPortBindable(port int) bool { + if port <= 0 { + return true + } + ln, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port)) + if err != nil { + return false + } + _ = ln.Close() + return true +} + +func udpHostPortBindable(port int) bool { + if port <= 0 { + return true + } + ln, err := net.ListenPacket("udp", fmt.Sprintf("0.0.0.0:%d", port)) + if err != nil { + return false + } + _ = ln.Close() + return true +} + +func hostPortBindableForProtocols(port int, protocols []string) bool { + if port <= 0 { + return true + } + cleanProtocols := normalizePortProtocolSlice(protocols) + if len(cleanProtocols) == 0 { + cleanProtocols = []string{"tcp"} + } + for _, protocol := range cleanProtocols { + switch protocol { + case "udp": + if !udpHostPortBindable(port) { + return false + } + case "tcp", "sctp": + if !tcpHostPortBindable(port) { + return false + } + } + } + return true +} + +func (a *Agent) hostPortAvailability(ctx context.Context, port int, excludeName string) (bool, string, string) { + return a.hostPortAvailabilityForProtocols(ctx, port, []string{"tcp"}, excludeName) +} + +func (a *Agent) hostPortAvailabilityForProtocols(ctx context.Context, port int, protocols []string, excludeName string) (bool, string, string) { + if port <= 0 { + return true, "", "" + } + if owner := a.dockerHostPortOwner(ctx, port, excludeName); owner != "" { + return false, owner, "docker" + } + if !hostPortBindableForProtocols(port, protocols) { + return false, "", "socket" + } + return true, "", "" +} + +var dockerRunFlagsWithValue = map[string]bool{ + "-e": true, "--env": true, "-v": true, "--volume": true, + "-p": true, "--publish": true, "-w": true, "--workdir": true, + "--name": true, "-m": true, "--memory": true, "--cpus": true, + "--memory-swap": true, "--memory-reservation": true, "--cpu-period": true, "--cpu-quota": true, + "-u": true, "--user": true, "-h": true, "--hostname": true, + "--network": true, "--net": true, "--restart": true, + "-l": true, "--label": true, "--entrypoint": true, + "--mount": true, "--tmpfs": true, "--device": true, + "--pid": true, "--ipc": true, "--userns": true, "--uts": true, "--cgroupns": true, + "--shm-size": true, "--ulimit": true, "--dns": true, "--dns-search": true, + "--add-host": true, "--log-driver": true, "--log-opt": true, + "--stop-signal": true, "--stop-timeout": true, "--health-cmd": true, + "--health-interval": true, "--health-retries": true, "--health-timeout": true, + "--runtime": true, "--platform": true, "--pull": true, + "--ip": true, "--ip6": true, "--mac-address": true, + "--expose": true, "--link": true, "--cidfile": true, +} + +var dockerRunSafeStandaloneFlags = map[string]bool{ + "-d": true, "--detach": true, "-i": true, "--interactive": true, + "-t": true, "--tty": true, "--rm": true, "--init": true, "--read-only": true, +} + +var dockerRunBlockedFlags = map[string]bool{ + "--privileged": true, + "--cap-add": true, + "--cap-drop": true, + "--security-opt": true, + "--volumes-from": true, + "--env-file": true, + "--device": true, + "--device-cgroup-rule": true, + "--sysctl": true, + "--oom-kill-disable": true, + "--oom-score-adj": true, +} + +var dockerRunHostNamespaceFlags = map[string]bool{ + "--network": true, "--net": true, "--pid": true, "--userns": true, + "--ipc": true, "--uts": true, "--cgroupns": true, +} + +func isSafeShortDockerFlagCluster(flag string) bool { + if len(flag) < 2 || flag[0] != '-' || strings.HasPrefix(flag, "--") { + return false + } + for i := 1; i < len(flag); i++ { + switch flag[i] { + case 'd', 'D', 'i', 'I', 't', 'T': + default: + return false + } + } + return true +} + +func parseDockerFlagToken(token string) (string, string) { + trimmed := strings.TrimSpace(token) + lower := strings.ToLower(trimmed) + if eqIdx := strings.Index(lower, "="); eqIdx > 0 { + return lower[:eqIdx], strings.TrimSpace(trimmed[eqIdx+1:]) + } + return lower, "" +} + +func readDockerFlagValue(args []string, index int, inlineValue string) (string, int) { + if strings.TrimSpace(inlineValue) != "" { + return inlineValue, index + } + if index+1 >= len(args) { + return "", index + } + return args[index+1], index + 1 +} + +func validateDockerRunCommandSafety(command string, allowedHostPorts []int, reservedHostPorts []int, expectedImageRef string) string { + cmd := strings.TrimSpace(command) + if cmd == "" { + return "" + } + if !strings.HasPrefix(strings.ToLower(cmd), "docker run") { + return "Startup command must start with 'docker run'." + } + for _, r := range cmd { + if r < 0x20 && r != '\t' && r != '\n' && r != '\r' { + return "Startup command contains unsupported control characters." + } + } + + allowedSet := make(map[int]bool, len(allowedHostPorts)) + for _, p := range allowedHostPorts { + if port, ok := parseStrictPortValue(p); ok { + allowedSet[port] = true + } + } + reservedSet := make(map[int]bool, len(reservedHostPorts)) + for _, p := range reservedHostPorts { + if port, ok := parseStrictPortValue(p); ok { + reservedSet[port] = true + } + } + + args := parseShellArgs(strings.TrimSpace(cmd[len("docker run"):])) + for i := 0; i < len(args); i++ { + token := strings.TrimSpace(args[i]) + if token == "" { + continue + } + tokenLower := strings.ToLower(token) + if !strings.HasPrefix(tokenLower, "-") { + if strings.TrimSpace(expectedImageRef) != "" { + normalizedExpected := normalizeDockerImage(expectedImageRef) + normalizedCommand := normalizeDockerImage(token) + if normalizedExpected != "" && normalizedCommand != "" && normalizedExpected != normalizedCommand { + return fmt.Sprintf("The Docker image in the startup command (%s) does not match the configured image (%s).", token, expectedImageRef) + } + } + return "" + } + + flagName, inlineValue := parseDockerFlagToken(token) + + if dockerRunBlockedFlags[flagName] { + return fmt.Sprintf("Blocked dangerous Docker flag: %s", flagName) + } + + if flagName == "--mount" { + value, nextIndex := readDockerFlagValue(args, i, inlineValue) + mountValue := strings.ToLower(strings.TrimSpace(value)) + if mountValue == "" { + return "Docker flag --mount requires a value." + } + if strings.Contains(mountValue, "type=bind") { + return "Blocked dangerous Docker flag: --mount with bind" + } + i = nextIndex + continue + } + + if flagName == "--tmpfs" { + value, nextIndex := readDockerFlagValue(args, i, inlineValue) + tmpfsValue := strings.ToLower(strings.TrimSpace(value)) + if tmpfsValue == "" { + return "Docker flag --tmpfs requires a value." + } + if strings.Contains(tmpfsValue, "exec") { + return "Blocked dangerous Docker flag: --tmpfs with exec" + } + i = nextIndex + continue + } + + if dockerRunHostNamespaceFlags[flagName] { + value, nextIndex := readDockerFlagValue(args, i, inlineValue) + nsMode := strings.ToLower(strings.TrimSpace(value)) + if nsMode == "" { + return fmt.Sprintf("Docker flag %s requires a value.", flagName) + } + if nsMode == "host" { + return fmt.Sprintf("Blocked dangerous Docker flag: %s=host", flagName) + } + i = nextIndex + continue + } + + if flagName == "-p" || flagName == "--publish" { + value, nextIndex := readDockerFlagValue(args, i, inlineValue) + mapping := strings.TrimSpace(value) + if mapping == "" { + return "Docker publish flag is missing a port mapping." + } + if !strings.Contains(mapping, "{PORT}") { + hostPort := extractHostPortFromMapping(mapping) + if hostPort == 0 { + return fmt.Sprintf("Invalid Docker port mapping: %s", mapping) + } + if !allowedSet[hostPort] { + return "Port config through docker edit command is not allowed. Add or remove a port through Port Management." + } + if reservedSet[hostPort] { + return fmt.Sprintf("Port %d in the Docker command conflicts with a port forwarding rule.", hostPort) + } + } + i = nextIndex + continue + } + + if isSafeShortDockerFlagCluster(flagName) || dockerRunSafeStandaloneFlags[flagName] { + continue + } + + if dockerRunFlagsWithValue[flagName] { + value, nextIndex := readDockerFlagValue(args, i, inlineValue) + if strings.TrimSpace(value) == "" { + return fmt.Sprintf("Docker flag %s requires a value.", flagName) + } + i = nextIndex + continue + } + + return fmt.Sprintf("Unsupported Docker flag in startup command: %s", flagName) + } + + return "Startup command must include a Docker image." +} + +func buildNodeIndexTemplate(port int) string { + p := port + if p < 1 || p > 65535 { + p = 3001 + } + return fmt.Sprintf(`const http = require("http"); + +const PORT = Number(process.env.PORT || %d); + +const server = http.createServer((req, res) => { + const body = "ADPanel Node.js server is running.\n"; + res.writeHead(200, { + "Content-Type": "text/plain; charset=utf-8", + "Content-Length": Buffer.byteLength(body) + }); + res.end(body); +}); + +server.listen(PORT, "0.0.0.0", () => { + console.log(`+"`"+`ADPanel Node.js server listening on 0.0.0.0:${PORT}`+"`"+`); +}); +`, p) +} + +func writeGeneratedRuntimeFile(path string, content []byte, isReplaceableLegacy func([]byte) bool) { + if strings.TrimSpace(path) == "" { + return + } + if existing, err := os.ReadFile(path); err == nil { + if isReplaceableLegacy != nil && isReplaceableLegacy(existing) { + _ = os.WriteFile(path, content, 0o644) + } + return + } + _ = ensureDir(filepath.Dir(path)) + _ = os.WriteFile(path, content, 0o644) +} + +func isLegacyPythonScaffold(content []byte) bool { + return strings.TrimSpace(string(content)) == strings.TrimSpace(legacyPythonMainTemplate) +} + +func isLegacyNodeScaffold(content []byte) bool { + s := string(content) + return strings.Contains(s, `const express = require("express");`) && + strings.Contains(s, "Hello World from ADPanel!") +} + +func scaffoldPython(serverDir, startFile string) { + sf := strings.TrimSpace(startFile) + if sf == "" { + sf = "main.py" + } + sf = filepath.Base(sf) + if sf == "." || sf == ".." || sf == "" { + sf = "main.py" + } + writeGeneratedRuntimeFile(filepath.Join(serverDir, sf), []byte(pythonMainTemplate), isLegacyPythonScaffold) +} + +func scaffoldNode(serverDir, startFile string, port int) { + sf := strings.TrimSpace(startFile) + if sf == "" { + sf = "index.js" + } + sf = filepath.Base(sf) + if sf == "." || sf == ".." || sf == "" { + sf = "index.js" + } + writeGeneratedRuntimeFile(filepath.Join(serverDir, sf), []byte(buildNodeIndexTemplate(port)), isLegacyNodeScaffold) + + pkgPath := filepath.Join(serverDir, "package.json") + if _, err := os.Stat(pkgPath); err == nil { + return + } + + pkg := map[string]any{ + "name": filepath.Base(serverDir), + "private": true, + "version": "1.0.0", + "main": "index.js", + "scripts": map[string]string{"start": "node index.js"}, + "dependencies": map[string]string{}, + } + b, _ := json.MarshalIndent(pkg, "", " ") + _ = os.WriteFile(pkgPath, b, 0o644) +} + +var ansiSGRRE = regexp.MustCompile(`\x1b\[[0-9;:]*m`) +var mcHexRE = regexp.MustCompile(`§x(?:§[0-9A-Fa-f]){6}`) +var mcRE = regexp.MustCompile(`§[0-9A-FK-ORa-fk-or]`) +var promptArtifactRE = regexp.MustCompile(`(?m)^\s*>\.{2,}\s*`) +var ttyOnlyLineRE = regexp.MustCompile(`^[\s>.=…-]+$`) + +func stripDockerStreamFraming(s string) string { + buf := []byte(s) + if len(buf) < 8 { + return s + } + out := make([]byte, 0, len(buf)) + usedFrames := false + for i := 0; i < len(buf); { + if len(buf)-i >= 8 && buf[i] >= 1 && buf[i] <= 3 && buf[i+1] == 0 && buf[i+2] == 0 && buf[i+3] == 0 { + frameLen := int(binary.BigEndian.Uint32(buf[i+4 : i+8])) + if frameLen == 0 { + usedFrames = true + i += 8 + continue + } + if frameLen > 0 && len(buf)-i-8 >= frameLen { + out = append(out, buf[i+8:i+8+frameLen]...) + i += 8 + frameLen + usedFrames = true + continue + } + } + out = append(out, buf[i]) + i++ + } + if usedFrames { + return string(out) + } + return s +} + +func consumeAnsiCSISequence(s string, idx int) (next int, keep bool) { + i := idx + for i < len(s) { + c := s[i] + if c >= 0x40 && c <= 0x7e { + return i + 1, c == 'm' + } + i++ + } + return len(s), false +} + +func skipAnsiOSCSequence(s string, idx int) int { + i := idx + for i < len(s) { + if s[i] == 0x07 { + return i + 1 + } + if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { + return i + 2 + } + i++ + } + return len(s) +} + +func skipAnsiEscTerminatedSequence(s string, idx int) int { + i := idx + for i < len(s) { + if s[i] == 0x1b && i+1 < len(s) && s[i+1] == '\\' { + return i + 2 + } + i++ + } + return len(s) +} + +func sanitizeAnsiForConsole(s string) string { + if s == "" { + return s + } + var out strings.Builder + out.Grow(len(s)) + for i := 0; i < len(s); { + switch s[i] { + case 0x9b: + next, keep := consumeAnsiCSISequence(s, i+1) + if keep { + out.WriteString(s[i:next]) + } + i = next + continue + case 0x1b: + if i+1 >= len(s) { + i++ + continue + } + nextByte := s[i+1] + switch nextByte { + case '[': + next, keep := consumeAnsiCSISequence(s, i+2) + if keep { + out.WriteString(s[i:next]) + } + i = next + continue + case ']': + i = skipAnsiOSCSequence(s, i+2) + continue + case 'P', 'X', '^', '_': + i = skipAnsiEscTerminatedSequence(s, i+2) + continue + default: + if nextByte >= 0x40 && nextByte <= 0x5f { + i += 2 + continue + } + i++ + continue + } + default: + if (s[i] < 32 || s[i] == 127) && s[i] != '\n' && s[i] != '\r' && s[i] != '\t' { + i++ + continue + } + out.WriteByte(s[i]) + i++ + } + } + return out.String() +} + +func cleanLogLine(s string) string { + if s == "" { + return s + } + s = strings.ReplaceAll(s, "\r\n", "\n") + s = strings.ReplaceAll(s, "\r", "\n") + s = stripDockerStreamFraming(s) + s = sanitizeAnsiForConsole(s) + s = mcHexRE.ReplaceAllString(s, "") + s = mcRE.ReplaceAllString(s, "") + s = promptArtifactRE.ReplaceAllString(s, "") + lines := strings.Split(s, "\n") + out := make([]string, 0, len(lines)) + for _, line := range lines { + line = strings.ReplaceAll(line, "…", "") + line = strings.TrimRight(line, " \t") + line = strings.TrimLeft(line, ">=. ") + plain := strings.TrimSpace(ansiSGRRE.ReplaceAllString(line, "")) + if plain == "" || ttyOnlyLineRE.MatchString(plain) { + continue + } + out = append(out, line) + } + return strings.Join(out, "\n") +} + +func normalizeConsoleMode(raw any) string { + switch v := raw.(type) { + case string: + mode := strings.ToLower(strings.TrimSpace(v)) + switch mode { + case "stdin", "exec", "exec-shell", "shell": + return mode + } + case map[string]any: + if mode := normalizeConsoleMode(v["mode"]); mode != "" { + return mode + } + if mode := normalizeConsoleMode(v["type"]); mode != "" { + return mode + } + } + return "" +} + +func consoleProcessTargetsFromRaw(raw any) []string { + switch v := raw.(type) { + case string: + return sanitizeConsoleProcessTargets([]string{v}) + case []string: + return sanitizeConsoleProcessTargets(v) + case []any: + out := make([]string, 0, len(v)) + for _, item := range v { + out = append(out, fmt.Sprint(item)) + } + return sanitizeConsoleProcessTargets(out) + case map[string]any: + for _, key := range []string{"targetProcesses", "target_processes", "processes", "processNames", "process_names"} { + if targets := consoleProcessTargetsFromRaw(v[key]); len(targets) > 0 { + return targets + } + } + for _, key := range []string{"targetProcess", "target_process", "process", "target"} { + if targets := consoleProcessTargetsFromRaw(v[key]); len(targets) > 0 { + return targets + } + } + } + return nil +} + +func sanitizeConsoleProcessTargets(values []string) []string { + out := make([]string, 0, len(values)) + seen := make(map[string]struct{}, len(values)) + for _, value := range values { + target := strings.TrimSpace(value) + target = strings.Trim(target, "'\"") + if target == "" || target == "" || strings.ContainsAny(target, "\x00\r\n") { + continue + } + if len(target) > 120 { + target = target[:120] + } + if _, ok := seen[target]; ok { + continue + } + seen[target] = struct{}{} + out = append(out, target) + if len(out) >= 12 { + break + } + } + return out +} + +func normalizeTemplateID(raw any) string { + id := strings.ToLower(strings.TrimSpace(fmt.Sprint(raw))) + id = strings.ReplaceAll(id, "_", "-") + id = strings.ReplaceAll(id, " ", "-") + for strings.Contains(id, "--") { + id = strings.ReplaceAll(id, "--", "-") + } + id = strings.Trim(id, "-") + if id == "" { + return "" + } + return id +} + +func isKnownStdinConsoleTemplate(id string) bool { + switch normalizeTemplateID(id) { + case "7-days-to-die", "7dtd", "sdtd", + "ark", "ark-survival-evolved", + "assetto-corsa", + "csgo", "cs2", "counter-strike-2", + "dayz", + "fivem", "five-m", + "hytale", + "minecraft", + "palworld", + "project-zomboid", "zomboid", + "ragemp", "rage-mp", + "redm", + "rust", + "valheim": + return true + default: + return false + } +} + +func defaultConsoleProcessTargetsForTemplate(id string) []string { + switch normalizeTemplateID(id) { + case "7-days-to-die", "7dtd", "sdtd": + return []string{"7DaysToDieServer", "7DaysToDieServer.x86_64"} + case "ark", "ark-survival-evolved": + return []string{"ShooterGameServer"} + case "assetto-corsa": + return []string{"server-manager", "acServer"} + case "csgo", "cs2", "counter-strike-2": + return []string{"cs2", "srcds_linux"} + case "dayz": + return []string{"DayZServer", "DayZServer_x64", "dayzserver"} + case "fivem", "five-m": + return []string{"FXServer", "fxserver"} + case "hytale": + return []string{"hytale-server", "java"} + case "minecraft": + return []string{"java", "bedrock_server"} + case "palworld": + return []string{"PalServer-Linux-Test", "PalServer"} + case "project-zomboid", "zomboid": + return []string{"ProjectZomboid64", "ProjectZomboid32", "java"} + case "ragemp", "rage-mp": + return []string{"ragemp-server", "ragemp"} + case "redm": + return []string{"FXServer", "fxserver"} + case "rust": + return []string{"RustDedicated"} + case "valheim": + return []string{"valheim_server", "valheim_server.x86_64"} + default: + return nil + } +} + +func defaultConsoleProcessTargetsForImage(image string) []string { + imageLower := strings.ToLower(strings.TrimSpace(image)) + switch { + case strings.Contains(imageLower, "hytale"): + return defaultConsoleProcessTargetsForTemplate("hytale") + case strings.Contains(imageLower, "redm"): + return defaultConsoleProcessTargetsForTemplate("redm") + case strings.Contains(imageLower, "fivem"): + return defaultConsoleProcessTargetsForTemplate("fivem") + case strings.Contains(imageLower, "dayz") || strings.Contains(imageLower, "day-z"): + return defaultConsoleProcessTargetsForTemplate("dayz") + case strings.Contains(imageLower, "zomboid"): + return defaultConsoleProcessTargetsForTemplate("project-zomboid") + case strings.Contains(imageLower, "palworld"): + return defaultConsoleProcessTargetsForTemplate("palworld") + case strings.Contains(imageLower, "valheim"): + return defaultConsoleProcessTargetsForTemplate("valheim") + case strings.Contains(imageLower, "rust"): + return defaultConsoleProcessTargetsForTemplate("rust") + case strings.Contains(imageLower, "ragemp"): + return defaultConsoleProcessTargetsForTemplate("ragemp") + case strings.Contains(imageLower, "ark"): + return defaultConsoleProcessTargetsForTemplate("ark-survival-evolved") + case strings.Contains(imageLower, "7dtd") || strings.Contains(imageLower, "7daystodie") || strings.Contains(imageLower, "7-days-to-die") || strings.Contains(imageLower, "sdtd"): + return defaultConsoleProcessTargetsForTemplate("7-days-to-die") + case strings.Contains(imageLower, "assetto"): + return defaultConsoleProcessTargetsForTemplate("assetto-corsa") + case strings.Contains(imageLower, "cs2") || strings.Contains(imageLower, "csgo"): + return defaultConsoleProcessTargetsForTemplate("cs2") + default: + return nil + } +} + +func consoleProcessTargetsForServer(meta map[string]any) []string { + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj != nil { + if targets := consoleProcessTargetsFromRaw(runtimeObj["console"]); len(targets) > 0 { + return targets + } + } + for _, key := range []string{"template", "type"} { + if targets := defaultConsoleProcessTargetsForTemplate(fmt.Sprint(meta[key])); len(targets) > 0 { + return targets + } + } + if runtimeObj != nil { + if targets := defaultConsoleProcessTargetsForTemplate(fmt.Sprint(runtimeObj["providerId"])); len(targets) > 0 { + return targets + } + if targets := defaultConsoleProcessTargetsForImage(fmt.Sprint(runtimeObj["image"])); len(targets) > 0 { + return targets + } + } + return nil +} + +func inferredConsoleModeForServer(meta map[string]any) string { + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj != nil { + if mode := normalizeConsoleMode(runtimeObj["console"]); mode != "" { + return mode + } + if len(consoleProcessTargetsFromRaw(runtimeObj["console"])) > 0 { + return "stdin" + } + } + + for _, key := range []string{"template", "type"} { + if isKnownStdinConsoleTemplate(fmt.Sprint(meta[key])) { + return "stdin" + } + } + if runtimeObj != nil { + if isKnownStdinConsoleTemplate(fmt.Sprint(runtimeObj["providerId"])) { + return "stdin" + } + image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + if image != "" && image != "" && isGameServerDockerImage(image) { + return "stdin" + } + startupDisplay := strings.TrimSpace(fmt.Sprint(runtimeObj["startupDisplay"])) + if startupDisplay != "" && startupDisplay != "" { + return "stdin" + } + } + return "" +} + +const ( + maxExtractSize = 10 << 30 + maxExtractFiles = 100000 + maxSingleFile = 2 << 30 +) + +type limitedWriter struct { + w io.Writer + written int64 + limit int64 +} + +func (lw *limitedWriter) Write(p []byte) (int, error) { + if lw.written+int64(len(p)) > lw.limit { + return 0, fmt.Errorf("extraction size limit exceeded (%d bytes)", lw.limit) + } + n, err := lw.w.Write(p) + lw.written += int64(n) + return n, err +} + +func sanitizeFileMode(mode os.FileMode, isDir bool) os.FileMode { + mode &^= os.ModeSetuid | os.ModeSetgid | os.ModeSticky + if isDir { + mode = mode.Perm() & 0o755 + } else { + mode = mode.Perm() & 0o644 + } + return mode +} + +func sanitizeExtractedTree(dest string) error { + return filepath.Walk(dest, func(path string, info os.FileInfo, err error) error { + if err != nil { + return nil + } + if info.Mode()&os.ModeSymlink != 0 { + return nil + } + if !info.Mode().IsRegular() && !info.IsDir() { + return nil + } + safe := sanitizeFileMode(info.Mode(), info.IsDir()) + if info.Mode().Perm() != safe { + _ = os.Chmod(path, safe) + } + return nil + }) +} + +func extractZipSafe(src, dest string) error { + r, err := zip.OpenReader(src) + if err != nil { + return err + } + defer r.Close() + + if len(r.File) > maxExtractFiles { + return fmt.Errorf("too many files in archive: %d (max %d)", len(r.File), maxExtractFiles) + } + + var totalSize int64 + var fileCount int + + for _, f := range r.File { + name := f.Name + name = filepath.FromSlash(name) + target := filepath.Join(dest, name) + if !isUnder(dest, target) { + return fmt.Errorf("zip-slip blocked: %s", f.Name) + } + + if f.UncompressedSize64 > maxSingleFile { + return fmt.Errorf("file too large: %s (%d bytes, max %d)", f.Name, f.UncompressedSize64, maxSingleFile) + } + + baseName := filepath.Base(name) + if baseName == "." || baseName == ".." { + continue + } + + if f.FileInfo().IsDir() { + if err := os.MkdirAll(target, 0o755); err != nil { + return err + } + resolvedDir, rdErr := filepath.EvalSymlinks(target) + if rdErr == nil && !isUnder(dest, resolvedDir) { + return fmt.Errorf("symlink escape blocked during zip extract: %s", f.Name) + } + continue + } + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + resolvedParent, rpErr := filepath.EvalSymlinks(filepath.Dir(target)) + if rpErr == nil && !isUnder(dest, resolvedParent) { + return fmt.Errorf("symlink escape blocked during zip extract: %s", f.Name) + } + if ei, eiErr := os.Lstat(target); eiErr == nil && ei.Mode()&os.ModeSymlink != 0 { + continue + } + + if err := func() error { + rc, err := f.Open() + if err != nil { + return err + } + defer rc.Close() + + out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644) + if err != nil { + return err + } + defer out.Close() + + lw := &limitedWriter{w: out, limit: maxExtractSize - totalSize} + n, err := io.Copy(lw, rc) + if err != nil { + return err + } + totalSize += n + fileCount++ + + if fileCount > maxExtractFiles { + return fmt.Errorf("too many files extracted: %d (max %d)", fileCount, maxExtractFiles) + } + + return nil + }(); err != nil { + return err + } + } + return nil +} + +func extractTarSafe(tr *tar.Reader, dest string) error { + var totalSize int64 + var fileCount int + + for { + h, err := tr.Next() + if err == io.EOF { + return nil + } + if err != nil { + return err + } + + fileCount++ + if fileCount > maxExtractFiles { + return fmt.Errorf("too many files in tar: %d (max %d)", fileCount, maxExtractFiles) + } + + if h.Size > maxSingleFile { + return fmt.Errorf("file too large in tar: %s (%d bytes, max %d)", h.Name, h.Size, maxSingleFile) + } + + name := filepath.Clean(h.Name) + baseName := filepath.Base(name) + if baseName == "." || baseName == ".." { + continue + } + target := filepath.Join(dest, name) + if !isUnder(dest, target) { + return fmt.Errorf("tar-slip blocked: %s", h.Name) + } + switch h.Typeflag { + case tar.TypeDir: + if err := os.MkdirAll(target, 0o755); err != nil { + return err + } + resolvedDir, rdErr := filepath.EvalSymlinks(target) + if rdErr == nil && !isUnder(dest, resolvedDir) { + return fmt.Errorf("symlink escape blocked during tar extract: %s", h.Name) + } + case tar.TypeReg, tar.TypeRegA: + if err := os.MkdirAll(filepath.Dir(target), 0o755); err != nil { + return err + } + resolvedParent, rpErr := filepath.EvalSymlinks(filepath.Dir(target)) + if rpErr == nil && !isUnder(dest, resolvedParent) { + return fmt.Errorf("symlink escape blocked during tar extract: %s", h.Name) + } + if ei, eiErr := os.Lstat(target); eiErr == nil && ei.Mode()&os.ModeSymlink != 0 { + continue + } + out, err := os.OpenFile(target, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644) + if err != nil { + return err + } + + lw := &limitedWriter{w: out, limit: maxExtractSize - totalSize} + n, err := io.Copy(lw, tr) + out.Close() + if err != nil { + return err + } + totalSize += n + + case tar.TypeLink: + return fmt.Errorf("hardlinks not allowed for security: %s", h.Name) + + case tar.TypeSymlink: + continue + + default: + continue + } + } +} + +func detectArchiveType(p string) string { + l := strings.ToLower(p) + switch { + case strings.HasSuffix(l, ".zip"): + return "zip" + case strings.HasSuffix(l, ".tar"): + return "tar" + case strings.HasSuffix(l, ".tar.gz") || strings.HasSuffix(l, ".tgz"): + return "targz" + case strings.HasSuffix(l, ".tar.bz2") || strings.HasSuffix(l, ".tbz2"): + return "tarbz2" + case strings.HasSuffix(l, ".tar.xz") || strings.HasSuffix(l, ".txz"): + return "tarxz" + case strings.HasSuffix(l, ".7z"): + return "7z" + case strings.HasSuffix(l, ".rar"): + return "rar" + default: + return "" + } +} + +type AuditLogger struct { + enabled bool + mu sync.Mutex +} + +func sanitizeLogField(s string) string { + return strings.NewReplacer( + "\n", "\\n", + "\r", "\\r", + "\t", "\\t", + ).Replace(s) +} + +func (al *AuditLogger) Log(event, clientIP, user, resource, action, result string, details map[string]any) { + if !al.enabled { + return + } + al.mu.Lock() + defer al.mu.Unlock() + + entry := map[string]any{ + "timestamp": time.Now().UTC().Format(time.RFC3339), + "event": sanitizeLogField(event), + "clientIP": sanitizeLogField(clientIP), + "user": sanitizeLogField(user), + "resource": sanitizeLogField(resource), + "action": sanitizeLogField(action), + "result": sanitizeLogField(result), + } + if details != nil { + entry["details"] = details + } + b, _ := json.Marshal(entry) + fmt.Printf("[AUDIT] %s\n", string(b)) +} + +var auditLog = &AuditLogger{enabled: true} + +type Agent struct { + cfg Config + debug bool + token string + tokenID string + uuid string + apiHost string + apiPort int + uploadLimit int64 + dataRoot string + volumesDir string + + panelHMAC string + + stopGrace time.Duration + + docker Docker + dl Downloader + + logs *logManager + stdinMgr *stdinManager + + resourceStats *serverResourceStatsCache + + stopMu sync.Mutex + stoppingNow map[string]time.Time + + commandMu sync.Mutex + recentCommands map[string]recentConsoleCommand + + importProgressMu sync.RWMutex + importProgress map[string]*ImportProgress + + importSem chan struct{} + + wsMu sync.Mutex + wsSubscribers map[*wsSubscriber]struct{} + + metaLocks sync.Map + + serverOpLocks sync.Map + + // adpanel:multidisk:fields (anchor) - per-server disk routing cache. Empty by + // default => single-disk behavior preserved. + disksMu sync.RWMutex + serverDiskCache map[string]string +} + +const ( + serverResourceStatsDefaultTTL = 2500 * time.Millisecond + serverResourceStatsDiskTTL = 15 * time.Second + serverResourceStatsMaxIdle = 10 * time.Minute +) + +type serverResourceStatsCache struct { + ttl time.Duration + diskTTL time.Duration + mu sync.Mutex + entries map[string]*serverResourceStatsCacheEntry +} + +// deepCopyJSONValue returns a deep copy of a value composed of the dynamic +// types produced by JSON-style payloads (map[string]any, []any and scalars). +// It is used to hand out cached payloads safely: callers may freely mutate or +// JSON-encode the returned value without racing against other goroutines that +// share the same cached map. Without this, two concurrent requests for the +// same server would mutate/encode the same cached map and trigger the runtime +// "fatal error: concurrent map writes". +func deepCopyJSONValue(v any) any { + switch val := v.(type) { + case map[string]any: + if val == nil { + return map[string]any(nil) + } + cp := make(map[string]any, len(val)) + for k, item := range val { + cp[k] = deepCopyJSONValue(item) + } + return cp + case []any: + if val == nil { + return []any(nil) + } + cp := make([]any, len(val)) + for i, item := range val { + cp[i] = deepCopyJSONValue(item) + } + return cp + case map[string]string: + cp := make(map[string]string, len(val)) + for k, item := range val { + cp[k] = item + } + return cp + default: + // Scalars (string, numbers, bool, nil) and other immutable values are + // safe to share by value. + return val + } +} + +// deepCopyPayload deep-copies a top-level payload map. Returns nil for a nil +// input so callers can preserve the "not found"/empty semantics. +func deepCopyPayload(payload map[string]any) map[string]any { + if payload == nil { + return nil + } + cp, _ := deepCopyJSONValue(payload).(map[string]any) + return cp +} + +type serverResourceStatsCacheEntry struct { + mu sync.Mutex + + payload map[string]any + expiresAt time.Time + touchedAt time.Time + + diskBytes int64 + diskExpiresAt time.Time + + // adpanel:backup-storage - backups live in a separate directory outside the + // server dir, so they are tracked (and cached) separately and then folded + // into the reported/enforced "used" total. + backupsBytes int64 + backupsExpiresAt time.Time + + containerID string + seenNetwork bool + lastRawRx uint64 + lastRawTx uint64 + totalRx uint64 + totalTx uint64 + + networkWindowStartedAt time.Time + networkWindowRx uint64 + networkWindowTx uint64 +} + +func newServerResourceStatsCache(ttl, diskTTL time.Duration) *serverResourceStatsCache { + if ttl <= 0 { + ttl = serverResourceStatsDefaultTTL + } + if diskTTL <= 0 { + diskTTL = serverResourceStatsDiskTTL + } + return &serverResourceStatsCache{ + ttl: ttl, + diskTTL: diskTTL, + entries: make(map[string]*serverResourceStatsCacheEntry), + } +} + +func (c *serverResourceStatsCache) get(name string) *serverResourceStatsCacheEntry { + c.mu.Lock() + defer c.mu.Unlock() + entry := c.entries[name] + if entry == nil { + entry = &serverResourceStatsCacheEntry{} + c.entries[name] = entry + } + return entry +} + +func (c *serverResourceStatsCache) cleanup(maxIdle time.Duration) { + if c == nil || maxIdle <= 0 { + return + } + cutoff := time.Now().Add(-maxIdle) + c.mu.Lock() + defer c.mu.Unlock() + for name, entry := range c.entries { + entry.mu.Lock() + idle := !entry.touchedAt.IsZero() && entry.touchedAt.Before(cutoff) + entry.mu.Unlock() + if idle { + delete(c.entries, name) + } + } +} + +func (e *serverResourceStatsCacheEntry) cachedDiskUsage(a *Agent, serverDir string, now time.Time, ttl time.Duration) int64 { + if now.Before(e.diskExpiresAt) { + return e.diskBytes + } + e.diskBytes = a.getServerDiskUsage(serverDir) + e.diskExpiresAt = now.Add(ttl) + return e.diskBytes +} + +// cachedBackupsUsage returns the cached on-disk size of a server's backups +// directory, refreshing it when the TTL elapses. adpanel:backup-storage - kept +// on the same TTL as the disk scan so a stats request triggers at most one walk +// of each tree. +func (e *serverResourceStatsCacheEntry) cachedBackupsUsage(a *Agent, serverName string, now time.Time, ttl time.Duration) int64 { + if now.Before(e.backupsExpiresAt) { + return e.backupsBytes + } + e.backupsBytes = a.getServerBackupsUsage(serverName) + e.backupsExpiresAt = now.Add(ttl) + return e.backupsBytes +} + +func addUint64Saturating(a, b uint64) uint64 { + if ^uint64(0)-a < b { + return ^uint64(0) + } + return a + b +} + +func (e *serverResourceStatsCacheEntry) updateNetworkCounters(containerID string, rawRx, rawTx uint64, now time.Time, resetEvery time.Duration) (uint64, uint64, uint64, uint64, time.Time) { + if e.seenNetwork && containerID != "" && e.containerID != "" && containerID != e.containerID { + e.lastRawRx = 0 + e.lastRawTx = 0 + } + + var rxDelta, txDelta uint64 + if !e.seenNetwork { + e.totalRx = rawRx + e.totalTx = rawTx + rxDelta = rawRx + txDelta = rawTx + } else { + if rawRx >= e.lastRawRx { + rxDelta = rawRx - e.lastRawRx + } else { + rxDelta = rawRx + } + if rawTx >= e.lastRawTx { + txDelta = rawTx - e.lastRawTx + } else { + txDelta = rawTx + } + e.totalRx = addUint64Saturating(e.totalRx, rxDelta) + e.totalTx = addUint64Saturating(e.totalTx, txDelta) + } + + if resetEvery > 0 { + if e.networkWindowStartedAt.IsZero() || now.Sub(e.networkWindowStartedAt) >= resetEvery || now.Before(e.networkWindowStartedAt) { + e.networkWindowStartedAt = now + e.networkWindowRx = 0 + e.networkWindowTx = 0 + } + e.networkWindowRx = addUint64Saturating(e.networkWindowRx, rxDelta) + e.networkWindowTx = addUint64Saturating(e.networkWindowTx, txDelta) + } + + e.lastRawRx = rawRx + e.lastRawTx = rawTx + e.containerID = containerID + e.seenNetwork = true + return e.totalRx, e.totalTx, e.networkWindowRx, e.networkWindowTx, e.networkWindowStartedAt +} + +type ImportProgress struct { + Status string `json:"status"` + Percent int `json:"percent"` + Downloaded int64 `json:"downloaded"` + Total int64 `json:"total"` + Error string `json:"error,omitempty"` +} + +func (a *Agent) logf(format string, args ...any) { + if a.debug { + fmt.Printf(format+"\n", args...) + } +} + +func (a *Agent) authOK(r *http.Request) bool { + h := r.Header.Get("x-node-token") + if h == "" { + h = r.Header.Get("authorization") + } + t := strings.TrimSpace(h) + if strings.HasPrefix(strings.ToLower(t), "bearer ") { + t = strings.TrimSpace(t[7:]) + } + if a.token == "" || t == "" { + return false + } + return timingSafeEq(t, a.token) +} + +func (a *Agent) verifyPanelSignature(r *http.Request, name string, providerId, versionId, u string, bodyTS any) (bool, string) { + if a.panelHMAC == "" { + return false, "hmac-not-configured" + } + ts := r.Header.Get("x-panel-ts") + sig := r.Header.Get("x-panel-sign") + if ts == "" || sig == "" { + return false, "missing-signature" + } + tsNum, err := strconv.ParseInt(ts, 10, 64) + if err != nil { + return false, "expired" + } + now := time.Now().UnixMilli() + drift := now - tsNum + if drift < 0 { + drift = -drift + } + if drift > 5*60*1000 { + return false, "expired" + } + base := fmt.Sprintf("%s|%s|%s|%s|%s", strings.TrimSpace(name), providerId, versionId, u, ts) + m := hmac.New(sha256.New, []byte(a.panelHMAC)) + _, _ = m.Write([]byte(base)) + expect := hex.EncodeToString(m.Sum(nil)) + if !timingSafeEq(strings.TrimSpace(sig), expect) { + return false, "bad-signature" + } + _ = bodyTS + return true, "" +} + +func (a *Agent) verifyReinstallAdminRequest(r *http.Request, name, template string) (bool, string) { + role := strings.ToLower(strings.TrimSpace(r.Header.Get("x-panel-role"))) + if role != "admin" { + return false, "admin-required" + } + + secret := strings.TrimSpace(a.panelHMAC) + if secret == "" { + secret = strings.TrimSpace(a.token) + } + if secret == "" { + return false, "hmac-not-configured" + } + + ts := r.Header.Get("x-panel-ts") + sig := r.Header.Get("x-panel-sign") + if ts == "" || sig == "" { + return false, "missing-signature" + } + + tsNum, err := strconv.ParseInt(strings.TrimSpace(ts), 10, 64) + if err != nil { + return false, "expired" + } + now := time.Now().UnixMilli() + drift := now - tsNum + if drift < 0 { + drift = -drift + } + if drift > 5*60*1000 { + return false, "expired" + } + + base := fmt.Sprintf("%s|%s|%s|%s|%s", strings.TrimSpace(name), "reinstall", template, role, ts) + m := hmac.New(sha256.New, []byte(secret)) + _, _ = m.Write([]byte(base)) + expect := hex.EncodeToString(m.Sum(nil)) + if !timingSafeEq(strings.TrimSpace(sig), expect) { + return false, "bad-signature" + } + return true, "" +} + +func (a *Agent) nodeInformationPath() string { + return filepath.Join(a.dataRoot, NodeInfoFileName) +} + +func (a *Agent) defaultNodeInformation() NodeInformation { + return NodeInformation{ + NodeVersion: normalizeNodeVersionTag(NodeVersion), + NodeArchitecture: runtime.GOOS + "/" + runtime.GOARCH, + NodeAutoUpdate: false, + } +} + +func (a *Agent) readNodeInformation() NodeInformation { + info := a.defaultNodeInformation() + b, err := os.ReadFile(a.nodeInformationPath()) + if err != nil || len(bytes.TrimSpace(b)) == 0 { + return info + } + + var arr []NodeInformation + if err := json.Unmarshal(b, &arr); err == nil && len(arr) > 0 { + if arr[0].NodeVersion != "" { + info.NodeVersion = normalizeNodeVersionTag(arr[0].NodeVersion) + } + if arr[0].NodeArchitecture != "" { + info.NodeArchitecture = arr[0].NodeArchitecture + } + info.NodeAutoUpdate = arr[0].NodeAutoUpdate + info.UpdatedAt = arr[0].UpdatedAt + info.Disks = arr[0].Disks + return info + } + + var obj NodeInformation + if err := json.Unmarshal(b, &obj); err == nil { + if obj.NodeVersion != "" { + info.NodeVersion = normalizeNodeVersionTag(obj.NodeVersion) + } + if obj.NodeArchitecture != "" { + info.NodeArchitecture = obj.NodeArchitecture + } + info.NodeAutoUpdate = obj.NodeAutoUpdate + info.UpdatedAt = obj.UpdatedAt + info.Disks = obj.Disks + } + return info +} + +func (a *Agent) writeNodeInformation(info NodeInformation) error { + if err := ensureDir(a.dataRoot); err != nil { + return err + } + if info.NodeVersion == "" { + info.NodeVersion = normalizeNodeVersionTag(NodeVersion) + } else { + info.NodeVersion = normalizeNodeVersionTag(info.NodeVersion) + } + if info.NodeArchitecture == "" { + info.NodeArchitecture = runtime.GOOS + "/" + runtime.GOARCH + } + info.UpdatedAt = time.Now().UTC().Format(time.RFC3339) + b, err := json.MarshalIndent([]NodeInformation{info}, "", " ") + if err != nil { + return err + } + b = append(b, '\n') + return writeFileNoFollow(a.nodeInformationPath(), b, 0o644) +} + +func (a *Agent) ensureNodeInformationFile() NodeInformation { + info := a.readNodeInformation() + if _, err := os.Stat(a.nodeInformationPath()); err != nil { + if writeErr := a.writeNodeInformation(info); writeErr != nil { + fmt.Fprintf(os.Stderr, "[node-update] failed to initialize %s: %v\n", NodeInfoFileName, writeErr) + } + } + return info +} + +func (a *Agent) verifyNodeAdminRequest(r *http.Request, action, subject string) (bool, string) { + role := strings.ToLower(strings.TrimSpace(r.Header.Get("x-panel-role"))) + if role != "admin" { + return false, "admin-required" + } + + secret := strings.TrimSpace(a.panelHMAC) + if secret == "" { + secret = strings.TrimSpace(a.token) + } + if secret == "" { + return false, "hmac-not-configured" + } + + ts := r.Header.Get("x-panel-ts") + sig := r.Header.Get("x-panel-sign") + if ts == "" || sig == "" { + return false, "missing-signature" + } + + tsNum, err := strconv.ParseInt(strings.TrimSpace(ts), 10, 64) + if err != nil { + return false, "expired" + } + now := time.Now().UnixMilli() + drift := now - tsNum + if drift < 0 { + drift = -drift + } + if drift > 5*60*1000 { + return false, "expired" + } + + base := fmt.Sprintf("%s|%s|%s|%s|%s", strings.TrimSpace(a.uuid), strings.TrimSpace(action), strings.TrimSpace(subject), role, ts) + m := hmac.New(sha256.New, []byte(secret)) + _, _ = m.Write([]byte(base)) + expect := hex.EncodeToString(m.Sum(nil)) + if !timingSafeEq(strings.TrimSpace(sig), expect) { + return false, "bad-signature" + } + return true, "" +} + +func (a *Agent) writeNodeUpdateFile(rel string, data []byte, backupDir string) error { + if !allowedNodeUpdateFile(rel) { + return fmt.Errorf("file is not allowed: %s", rel) + } + if err := validateNodeUpdateFileContent(rel, data); err != nil { + return err + } + if err := ensureDir(a.dataRoot); err != nil { + return err + } + + target := filepath.Join(a.dataRoot, rel) + resolvedRoot, err := filepath.Abs(a.dataRoot) + if err != nil { + return err + } + resolvedTarget, err := filepath.Abs(target) + if err != nil { + return err + } + if resolvedTarget != resolvedRoot && !strings.HasPrefix(resolvedTarget, resolvedRoot+string(filepath.Separator)) { + return fmt.Errorf("refusing path outside node root: %s", rel) + } + + if st, err := os.Lstat(target); err == nil && st.Mode().IsRegular() && backupDir != "" { + if err := copyRegularFile(target, filepath.Join(backupDir, rel)); err != nil { + return fmt.Errorf("backup failed for %s: %w", rel, err) + } + } + + tmp := filepath.Join(a.dataRoot, fmt.Sprintf(".%s.tmp.%d", rel, time.Now().UnixNano())) + if err := writeFileNoFollow(tmp, data, 0o644); err != nil { + return err + } + if err := os.Rename(tmp, target); err != nil { + _ = os.Remove(tmp) + return err + } + return nil +} + +func (a *Agent) runGoClean() error { + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, "go", "clean") + cmd.Dir = a.dataRoot + out, err := cmd.CombinedOutput() + if ctx.Err() == context.DeadlineExceeded { + return fmt.Errorf("go clean timed out") + } + if err != nil { + msg := strings.TrimSpace(string(out)) + if len(msg) > 400 { + msg = msg[:400] + } + if msg == "" { + msg = err.Error() + } + return fmt.Errorf("go clean failed: %s", msg) + } + return nil +} + +func (a *Agent) scheduleAdaemonRestart() { + go func() { + time.Sleep(900 * time.Millisecond) + cmd := exec.Command("systemctl", "restart", "adaemon") + out, err := cmd.CombinedOutput() + if err != nil { + msg := strings.TrimSpace(string(out)) + if len(msg) > 400 { + msg = msg[:400] + } + fmt.Fprintf(os.Stderr, "[node-update] systemctl restart adaemon failed: %v %s\n", err, msg) + return + } + fmt.Println("[node-update] systemctl restart adaemon executed") + }() +} + +func (a *Agent) handleNodeUpdateInfo(w http.ResponseWriter, r *http.Request) { + info := a.ensureNodeInformationFile() + jsonWrite(w, 200, map[string]any{ + "ok": true, + "version": info.NodeVersion, + "architecture": info.NodeArchitecture, + "autoUpdateEnabled": info.NodeAutoUpdate, + "nodeId": a.uuid, + }) +} + +func (a *Agent) handleNodeUpdateAuto(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, 1024*1024) + var payload nodeUpdateAutoRequest + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil && !errors.Is(err, io.EOF) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid request body"}) + return + } + subject := "off" + if payload.Enabled { + subject = "on" + } + if ok, reason := a.verifyNodeAdminRequest(r, "node-update-auto", subject); !ok { + jsonWrite(w, 403, map[string]any{"ok": false, "error": reason}) + return + } + info := a.readNodeInformation() + info.NodeAutoUpdate = payload.Enabled + if err := a.writeNodeInformation(info); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to save node information"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true, "autoUpdateEnabled": payload.Enabled}) +} + +func (a *Agent) handleNodeUpdateInstall(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, NodeUpdateMaxBody) + var payload nodeUpdateInstallRequest + if err := json.NewDecoder(r.Body).Decode(&payload); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid request body"}) + return + } + + version := normalizeNodeVersionTag(payload.Version) + if !validNodeUpdateVersion(version) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid version"}) + return + } + if ok, reason := a.verifyNodeAdminRequest(r, "node-update-install", version); !ok { + jsonWrite(w, 403, map[string]any{"ok": false, "error": reason}) + return + } + if len(payload.Files) == 0 || len(payload.Files) > 32 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid update file set"}) + return + } + + seenMain := false + totalBytes := 0 + decoded := make(map[string][]byte, len(payload.Files)) + for _, file := range payload.Files { + rel := strings.TrimSpace(file.Path) + if !allowedNodeUpdateFile(rel) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "update contains an unsupported file"}) + return + } + if _, exists := decoded[rel]; exists { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "duplicate update file"}) + return + } + data, err := base64.StdEncoding.DecodeString(strings.TrimSpace(file.ContentBase64)) + if err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid update file encoding"}) + return + } + if err := validateNodeUpdateFileContent(rel, data); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": err.Error()}) + return + } + totalBytes += len(data) + if totalBytes > NodeUpdateMaxBody { + jsonWrite(w, 413, map[string]any{"ok": false, "error": "update payload too large"}) + return + } + if rel == "main.go" { + seenMain = true + } + decoded[rel] = data + } + if !seenMain { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "main.go is required"}) + return + } + + backupDir := filepath.Join(a.dataRoot, ".update-backups", time.Now().UTC().Format("20060102-150405")) + filesUpdated := 0 + for rel, data := range decoded { + if err := a.writeNodeUpdateFile(rel, data, backupDir); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write update file"}) + return + } + filesUpdated++ + } + + info := a.readNodeInformation() + info.NodeVersion = version + info.NodeArchitecture = runtime.GOOS + "/" + runtime.GOARCH + if err := a.writeNodeInformation(info); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to save node information"}) + return + } + + if err := a.runGoClean(); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": err.Error(), "filesUpdated": filesUpdated}) + return + } + + a.scheduleAdaemonRestart() + jsonWrite(w, 200, map[string]any{ + "ok": true, + "version": version, + "filesUpdated": filesUpdated, + "restartCommand": "systemctl restart adaemon", + "message": "Node update installed. go clean completed and adaemon restart was scheduled.", + }) +} + +const ( + wsMaxSubscribers = 5 + wsStatusIntervalSec = 10 + wsWriteTimeout = 5 * time.Second + wsReadTimeout = 60 * time.Second +) + +type wsSubscriber struct { + msgs chan []byte + done chan struct{} +} + +// enumerateServerNames returns the unique set of server directory names across +// every registered disk's volumes root (primary first), preserving discovery +// order. adpanel:multidisk - this is the single source of truth for "which +// servers exist on this node". Reading only a.volumesDir would silently drop +// every server that lives on a secondary disk, which is why status/stats and the +// server listing previously reported secondary-disk servers as missing (no live +// metrics, power state stuck at "idle"/unknown). +func (a *Agent) enumerateServerNames() []string { + var names []string + seen := map[string]struct{}{} + for _, root := range a.allDiskVolumeRoots() { + entries, err := os.ReadDir(root) + if err != nil { + // A secondary disk may be temporarily unmounted/unreadable. Skip it + // rather than failing the whole enumeration so the remaining disks + // (including the primary) still report correctly. + continue + } + for _, e := range entries { + if !e.IsDir() || strings.HasPrefix(e.Name(), ".") { + continue + } + name := e.Name() + if _, dup := seen[name]; dup { + continue + } + seen[name] = struct{}{} + names = append(names, name) + } + } + return names +} + +func (a *Agent) collectServerStatuses() map[string]any { + names := a.enumerateServerNames() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + var servers []ServerStatus + for _, name := range names { + serverDir := a.serverDir(name) + + ss := ServerStatus{Name: name, Status: "stopped"} + + meta := a.loadMeta(serverDir) + cpuCoresConfig := metaCpuCores(meta) + _, cpuLimit := computeCpuLimit(cpuCoresConfig) + ss.CpuLimit = &cpuLimit + + if a.docker.containerExists(ctx, name) { + out, _, _, err := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", name) + if err == nil && strings.TrimSpace(out) == "true" { + ss.Status = "running" + + startedAt, _, _, startErr := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.StartedAt}}", name) + if startErr == nil && strings.TrimSpace(startedAt) != "" { + startTime, parseErr := time.Parse(time.RFC3339Nano, strings.TrimSpace(startedAt)) + if parseErr == nil { + uptime := int64(time.Since(startTime).Seconds()) + ss.Uptime = &uptime + } + } + + statsOut, _, _, statsErr := a.docker.runCollect(ctx, "stats", "--no-stream", "--format", + "{{.CPUPerc}}|{{.MemUsage}}", name) + if statsErr == nil && strings.TrimSpace(statsOut) != "" { + parts := strings.Split(strings.TrimSpace(statsOut), "|") + if len(parts) >= 2 { + cpuStr := strings.TrimSuffix(strings.TrimSpace(parts[0]), "%") + if cpu, err := strconv.ParseFloat(cpuStr, 64); err == nil { + if cpu > cpuLimit { + cpu = cpuLimit + } + ss.CPU = &cpu + } + memParts := strings.Split(parts[1], "/") + if len(memParts) >= 1 { + memMb := parseMemoryString(strings.TrimSpace(memParts[0])) + if memMb > 0 { + ss.Memory = &memMb + } + } + } + } + } + } + + diskBytes := a.getServerTotalUsage(serverDir) + if diskBytes > 0 { + diskMb := float64(diskBytes) / (1024 * 1024) + ss.Disk = &diskMb + } + + servers = append(servers, ss) + } + + return map[string]any{ + "type": "status", + "ok": true, + "nodeId": a.uuid, + "timestamp": time.Now().UnixMilli(), + "servers": servers, + "resources": map[string]any{ + "cpuCount": runtime.NumCPU(), + }, + } +} + +func (a *Agent) handleWebSocket(w http.ResponseWriter, r *http.Request) { + conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{}) + if err != nil { + if a.debug { + fmt.Printf("[ws] accept error: %v\n", err) + } + return + } + + sub := &wsSubscriber{ + msgs: make(chan []byte, 4), + done: make(chan struct{}), + } + + a.wsMu.Lock() + if a.wsSubscribers == nil { + a.wsSubscribers = make(map[*wsSubscriber]struct{}) + } + if len(a.wsSubscribers) >= wsMaxSubscribers { + a.wsMu.Unlock() + conn.Close(websocket.StatusTryAgainLater, "too many connections") + return + } + a.wsSubscribers[sub] = struct{}{} + a.wsMu.Unlock() + + defer func() { + conn.Close(websocket.StatusNormalClosure, "closing") + a.wsMu.Lock() + delete(a.wsSubscribers, sub) + a.wsMu.Unlock() + close(sub.done) + }() + + fmt.Printf("[ws] panel connected (subscribers: %d)\n", func() int { + a.wsMu.Lock() + defer a.wsMu.Unlock() + return len(a.wsSubscribers) + }()) + + snapshot := a.collectServerStatuses() + ctx, cancel := context.WithTimeout(r.Context(), wsWriteTimeout) + _ = wsjson.Write(ctx, conn, snapshot) + cancel() + + go func() { + for { + _, _, err := conn.Read(r.Context()) + if err != nil { + return + } + } + }() + + ticker := time.NewTicker(wsStatusIntervalSec * time.Second) + defer ticker.Stop() + + for { + select { + case <-r.Context().Done(): + fmt.Printf("[ws] panel disconnected\n") + return + case <-ticker.C: + status := a.collectServerStatuses() + data, err := json.Marshal(status) + if err != nil { + continue + } + writeCtx, writeCancel := context.WithTimeout(r.Context(), wsWriteTimeout) + err = conn.Write(writeCtx, websocket.MessageText, data) + writeCancel() + if err != nil { + if a.debug { + fmt.Printf("[ws] write error: %v\n", err) + } + return + } + case msg := <-sub.msgs: + writeCtx, writeCancel := context.WithTimeout(r.Context(), wsWriteTimeout) + err := conn.Write(writeCtx, websocket.MessageText, msg) + writeCancel() + if err != nil { + if a.debug { + fmt.Printf("[ws] write error: %v\n", err) + } + return + } + } + } +} + +func (a *Agent) broadcastContainerEvent(name, status string) { + a.wsMu.Lock() + subs := make([]*wsSubscriber, 0, len(a.wsSubscribers)) + for s := range a.wsSubscribers { + subs = append(subs, s) + } + a.wsMu.Unlock() + + if len(subs) == 0 { + return + } + + evt := map[string]any{ + "type": "event", + "nodeId": a.uuid, + "timestamp": time.Now().UnixMilli(), + "server": name, + "status": status, + } + data, err := json.Marshal(evt) + if err != nil { + return + } + + for _, s := range subs { + select { + case s.msgs <- data: + default: + } + } +} + +func statUIDGID(p string) (uid, gid int) { + uid, gid = 1000, 1000 + st, err := os.Stat(p) + if err != nil { + return + } + sys, ok := st.Sys().(*syscall.Stat_t) + if !ok { + return + } + return int(sys.Uid), int(sys.Gid) +} + +const ( + cpuPeriod = 100000 + defaultPidsLimit = 512 + minIoWeight = 10 + maxIoWeight = 1000 + minCpuWeight = 1 + maxCpuWeight = 1000 + minPidsLimit = 64 + maxPidsLimit = 4096 + minFileLimit = 1024 + maxFileLimit = 1048576 + + minNetworkLimitMb int64 = 1 + maxNetworkLimitMb int64 = 1073741824 + defaultNetworkResetMins = 1440 + minNetworkResetMins = 1 + maxNetworkResetMins = 43200 +) + +func dockerCpuSharesFromWeight(weight int) int64 { + if weight <= 0 { + return 0 + } + if weight < minCpuWeight { + weight = minCpuWeight + } + if weight > maxCpuWeight { + weight = maxCpuWeight + } + shares := int64((weight * 2048) / maxCpuWeight) + if shares < 2 { + return 2 + } + return shares +} + +func runtimeNeedsHighFileLimit(tpl, imageRef string) bool { + tpl = strings.ToLower(strings.TrimSpace(tpl)) + imageRef = strings.ToLower(strings.TrimSpace(imageRef)) + if tpl == "rust" { + return true + } + return strings.Contains(imageRef, "pterodactyl/games:rust") || + strings.Contains(imageRef, "parkervcp/games:rust") || + strings.Contains(imageRef, "didstopia/rust-server") +} + +func withRuntimeDefaultFileLimit(resources *resourceLimits, tpl, imageRef string) *resourceLimits { + if !runtimeNeedsHighFileLimit(tpl, imageRef) { + return resources + } + if resources != nil && resources.FileLimit != nil { + return resources + } + + limit := maxFileLimit + if resources == nil { + return &resourceLimits{FileLimit: &limit} + } + copy := *resources + copy.FileLimit = &limit + return © +} + +const rustPterodactylStartup = `./RustDedicated -batchmode -nographics -logfile "{{LOG_FILE}}" +server.ip 0.0.0.0 +server.port {{SERVER_PORT}} +server.queryport {{QUERY_PORT}} +server.identity "{{SERVER_IDENTITY}}" +server.level "{{SERVER_LEVEL}}" +server.seed {{SERVER_SEED}} +server.worldsize {{WORLD_SIZE}} +server.hostname "{{SERVER_NAME}}" +server.description "{{SERVER_DESCRIPTION}}" +server.maxplayers {{MAX_PLAYERS}} +server.secure {{SERVER_SECURE}} +rcon.ip 0.0.0.0 +rcon.web {{RCON_WEB}} +rcon.port {{RCON_PORT}} +rcon.password "{{RCON_PASS}}" +app.port {{RUST_PLUS_PORT}} +server.saveinterval {{SAVE_INTERVAL}} {{ADDITIONAL_ARGS}}` + +func normalizeRustRuntimeForPterodactyl(meta map[string]any) bool { + if meta == nil { + return false + } + template := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) + if template == "" || template == "" { + template = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) + } + runtimeObj, _ := meta["runtime"].(map[string]any) + image := "" + tag := "" + if runtimeObj != nil { + image = strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["image"]))) + tag = strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["tag"]))) + } + imageRef := image + ":" + tag + isRust := template == "rust" || + strings.Contains(imageRef, "didstopia/rust-server") || + strings.Contains(imageRef, "pterodactyl/games:rust") || + strings.Contains(imageRef, "parkervcp/games:rust") + if !isRust { + return false + } + if runtimeObj == nil { + runtimeObj = map[string]any{} + } + + changed := false + set := func(key string, value any) { + if !reflect.DeepEqual(runtimeObj[key], value) { + runtimeObj[key] = value + changed = true + } + } + set("image", "ghcr.io/pterodactyl/games") + set("tag", "rust") + set("volumes", []any{"{BOT_DIR}:/home/container"}) + set("workdir", "/home/container") + set("command", "") + set("adpanelStartup", "") + set("startupDisplay", "/bin/bash /entrypoint.sh") + set("ports", []any{28015, 28016, 28082}) + set("portProtocols", map[string]any{ + "28015": []any{"udp"}, + "28016": []any{"tcp", "udp"}, + "28082": []any{"tcp", "udp"}, + }) + set("console", map[string]any{ + "type": "stdin", + "targetProcesses": []any{"RustDedicated"}, + }) + + env := runtimeEnvMap(runtimeObj["env"]) + if env == nil { + env = map[string]string{} + } + copyEnv := func(dst, src string) { + if strings.TrimSpace(env[dst]) == "" && strings.TrimSpace(env[src]) != "" { + env[dst] = env[src] + changed = true + } + } + copyEnv("SERVER_IDENTITY", "RUST_SERVER_IDENTITY") + copyEnv("SERVER_PORT", "RUST_SERVER_PORT") + copyEnv("QUERY_PORT", "RUST_SERVER_QUERYPORT") + copyEnv("SERVER_SEED", "RUST_SERVER_SEED") + copyEnv("WORLD_SIZE", "RUST_SERVER_WORLDSIZE") + copyEnv("SERVER_NAME", "RUST_SERVER_NAME") + copyEnv("SERVER_DESCRIPTION", "RUST_SERVER_DESCRIPTION") + copyEnv("MAX_PLAYERS", "RUST_SERVER_MAXPLAYERS") + copyEnv("RCON_PORT", "RUST_RCON_PORT") + copyEnv("RCON_PASS", "RUST_RCON_PASSWORD") + copyEnv("RUST_PLUS_PORT", "RUST_APP_PORT") + + envDefaults := map[string]string{ + "STARTUP": rustPterodactylStartup, + "AUTO_UPDATE": "0", + "FRAMEWORK": "", + "OXIDE": "0", + "LD_LIBRARY_PATH": "/home/container/RustDedicated_Data/Plugins/x86_64:/home/container", + "LOG_FILE": "/home/container/logs/rust.log", + "SERVER_PORT": "28015", + "QUERY_PORT": "28016", + "RCON_PORT": "28016", + "RUST_PLUS_PORT": "28082", + "SERVER_IDENTITY": "adpanel", + "SERVER_LEVEL": "Procedural Map", + "SERVER_SEED": "12345", + "WORLD_SIZE": "3500", + "SERVER_NAME": "ADPanel Rust Server", + "SERVER_DESCRIPTION": "Rust server hosted with ADPanel", + "MAX_PLAYERS": "100", + "SERVER_SECURE": "1", + "RCON_WEB": "true", + "RCON_PASS": "change-me", + "RCON_PASSWORD": "change-me", + "RCON_IP": "127.0.0.1", + "SAVE_INTERVAL": "300", + "ADDITIONAL_ARGS": "", + "TZ": "Etc/UTC", + } + for key, value := range envDefaults { + if _, ok := env[key]; !ok { + env[key] = value + changed = true + } + } + if env["RCON_PASSWORD"] != env["RCON_PASS"] { + env["RCON_PASSWORD"] = env["RCON_PASS"] + changed = true + } + if !reflect.DeepEqual(runtimeObj["env"], env) { + runtimeObj["env"] = env + changed = true + } + + if meta["type"] != "rust" { + meta["type"] = "rust" + changed = true + } + if meta["template"] != "rust" { + meta["template"] = "rust" + changed = true + } + if !reflect.DeepEqual(meta["runtime"], runtimeObj) { + meta["runtime"] = runtimeObj + changed = true + } + return changed +} + +func validateResourcePerformanceLimits(resources *resourceLimits) string { + if resources == nil { + return "" + } + if resources.IoWeight != nil && (*resources.IoWeight < minIoWeight || *resources.IoWeight > maxIoWeight) { + return fmt.Sprintf("I/O Priority must be between %d and %d.", minIoWeight, maxIoWeight) + } + if resources.CpuWeight != nil && (*resources.CpuWeight < minCpuWeight || *resources.CpuWeight > maxCpuWeight) { + return fmt.Sprintf("CPU Priority must be between %d and %d.", minCpuWeight, maxCpuWeight) + } + if resources.PidsLimit != nil && (*resources.PidsLimit < minPidsLimit || *resources.PidsLimit > maxPidsLimit) { + return fmt.Sprintf("Process Limit must be between %d and %d.", minPidsLimit, maxPidsLimit) + } + if resources.FileLimit != nil && (*resources.FileLimit < minFileLimit || *resources.FileLimit > maxFileLimit) { + return fmt.Sprintf("File Limit must be between %d and %d.", minFileLimit, maxFileLimit) + } + if resources.NetworkInboundLimitMb != nil && *resources.NetworkInboundLimitMb != 0 && (*resources.NetworkInboundLimitMb < minNetworkLimitMb || *resources.NetworkInboundLimitMb > maxNetworkLimitMb) { + return fmt.Sprintf("Inbound Limit must be between %d and %d.", minNetworkLimitMb, maxNetworkLimitMb) + } + if resources.NetworkOutboundLimitMb != nil && *resources.NetworkOutboundLimitMb != 0 && (*resources.NetworkOutboundLimitMb < minNetworkLimitMb || *resources.NetworkOutboundLimitMb > maxNetworkLimitMb) { + return fmt.Sprintf("Outbound Limit must be between %d and %d.", minNetworkLimitMb, maxNetworkLimitMb) + } + if resources.NetworkResetMinutes != nil && *resources.NetworkResetMinutes != 0 && (*resources.NetworkResetMinutes < minNetworkResetMins || *resources.NetworkResetMinutes > maxNetworkResetMins) { + return fmt.Sprintf("Reset Time must be between %d and %d.", minNetworkResetMins, maxNetworkResetMins) + } + return "" +} + +func computeCpuLimit(allocatedCores float64) (effectiveCores, maxPercent float64) { + hostCores := float64(runtime.NumCPU()) + if hostCores <= 0 { + hostCores = 1 + } + effectiveCores = hostCores + if allocatedCores > 0 { + effectiveCores = allocatedCores + if effectiveCores > hostCores { + effectiveCores = hostCores + } + } + maxPercent = effectiveCores * 100 + return +} + +func metaCpuCores(meta map[string]any) float64 { + if meta == nil { + return 0 + } + res, ok := meta["resources"].(map[string]any) + if !ok { + return 0 + } + switch v := res["cpuCores"].(type) { + case float64: + return v + case int: + return float64(v) + case int64: + return float64(v) + } + return 0 +} + +const ( + defaultMinecraftProcessImage = "eclipse-temurin" + defaultMinecraftProcessTag = "21-jre" + defaultMinecraftProcessCommand = "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui" + maxRuntimeCommandLen = 4000 +) + +var ( + fallbackMinecraftJavaVersions = []string{"8", "11", "17", "21", "22", "23", "24", "25", "26"} + minecraftJavaVersionsCache []string + minecraftJavaVersionsCacheExpireAt time.Time + minecraftJavaVersionsMu sync.Mutex +) + +const ( + minecraftJavaMinVersion = 8 + minecraftJavaMaxVersion = 99 + minecraftJavaDiscoveryURL = "https://hub.docker.com/v2/repositories/library/eclipse-temurin/tags?page_size=100&name=-jre" + minecraftJavaDiscoveryTimeout = 4500 * time.Millisecond + minecraftJavaDiscoveryTTL = 6 * time.Hour + minecraftJavaDiscoveryFailTTL = 5 * time.Minute +) + +type dockerHubTagsResponse struct { + Next string `json:"next"` + Results []struct { + Name string `json:"name"` + } `json:"results"` +} + +func normalizeMinecraftJavaVersion(raw any) string { + value := strings.TrimSpace(strings.ToLower(fmt.Sprint(raw))) + if value == "" || value == "" { + return "" + } + var digits strings.Builder + for _, r := range value { + if r < '0' || r > '9' { + break + } + digits.WriteRune(r) + } + version := digits.String() + if version == "" { + return "" + } + parsed, err := strconv.Atoi(version) + if err != nil || parsed < minecraftJavaMinVersion || parsed > minecraftJavaMaxVersion { + return "" + } + return fmt.Sprint(parsed) +} + +func minecraftJavaTag(version any) string { + clean := normalizeMinecraftJavaVersion(version) + if clean == "" { + return defaultMinecraftProcessTag + } + return clean + "-jre" +} + +func minecraftJavaVersionFromTag(raw any) string { + tag := strings.TrimSpace(strings.ToLower(fmt.Sprint(raw))) + if tag == "" || tag == "" { + return "" + } + if idx := strings.LastIndex(tag, ":"); idx >= 0 && idx+1 < len(tag) { + tag = tag[idx+1:] + } + return normalizeMinecraftJavaVersion(tag) +} + +func cloneStringSlice(values []string) []string { + if len(values) == 0 { + return nil + } + out := make([]string, len(values)) + copy(out, values) + return out +} + +func mergeMinecraftJavaVersions(discovered []string) []string { + seen := make(map[int]struct{}) + for _, raw := range fallbackMinecraftJavaVersions { + if clean := normalizeMinecraftJavaVersion(raw); clean != "" { + if n, err := strconv.Atoi(clean); err == nil { + seen[n] = struct{}{} + } + } + } + for _, raw := range discovered { + if clean := normalizeMinecraftJavaVersion(raw); clean != "" { + if n, err := strconv.Atoi(clean); err == nil { + seen[n] = struct{}{} + } + } + } + nums := make([]int, 0, len(seen)) + for n := range seen { + nums = append(nums, n) + } + sort.Ints(nums) + out := make([]string, 0, len(nums)) + for _, n := range nums { + out = append(out, fmt.Sprint(n)) + } + return out +} + +func extractMinecraftJavaVersionsFromDockerHubPayload(payload dockerHubTagsResponse) []string { + versions := []string{} + for _, result := range payload.Results { + name := strings.TrimSpace(strings.ToLower(result.Name)) + if !strings.HasSuffix(name, "-jre") { + continue + } + prefix := strings.TrimSuffix(name, "-jre") + if prefix == "" || strings.ContainsAny(prefix, ".-_") { + continue + } + if version := normalizeMinecraftJavaVersion(prefix); version != "" { + versions = append(versions, version) + } + } + return versions +} + +func discoverMinecraftJavaVersions(ctx context.Context) ([]string, bool) { + discovered := []string{} + nextURL := minecraftJavaDiscoveryURL + client := &http.Client{Timeout: minecraftJavaDiscoveryTimeout} + ok := false + for page := 0; page < 5 && nextURL != ""; page++ { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, nextURL, nil) + if err != nil { + break + } + req.Header.Set("Accept", "application/json") + resp, err := client.Do(req) + if err != nil { + break + } + func() { + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + nextURL = "" + return + } + ok = true + var payload dockerHubTagsResponse + if err := json.NewDecoder(io.LimitReader(resp.Body, 2*1024*1024)).Decode(&payload); err != nil { + nextURL = "" + return + } + discovered = append(discovered, extractMinecraftJavaVersionsFromDockerHubPayload(payload)...) + next := strings.TrimSpace(payload.Next) + if next == "" || !strings.HasPrefix(next, "https://hub.docker.com/v2/repositories/library/eclipse-temurin/tags") { + nextURL = "" + return + } + nextURL = next + }() + } + return mergeMinecraftJavaVersions(discovered), ok +} + +func minecraftJavaVersions() []string { + now := time.Now() + minecraftJavaVersionsMu.Lock() + if len(minecraftJavaVersionsCache) > 0 && now.Before(minecraftJavaVersionsCacheExpireAt) { + cached := cloneStringSlice(minecraftJavaVersionsCache) + minecraftJavaVersionsMu.Unlock() + return cached + } + minecraftJavaVersionsMu.Unlock() + + ctx, cancel := context.WithTimeout(context.Background(), minecraftJavaDiscoveryTimeout) + discovered, ok := discoverMinecraftJavaVersions(ctx) + cancel() + if len(discovered) == 0 { + discovered = mergeMinecraftJavaVersions(nil) + } + + minecraftJavaVersionsMu.Lock() + minecraftJavaVersionsCache = cloneStringSlice(discovered) + if ok { + minecraftJavaVersionsCacheExpireAt = time.Now().Add(minecraftJavaDiscoveryTTL) + } else { + minecraftJavaVersionsCacheExpireAt = time.Now().Add(minecraftJavaDiscoveryFailTTL) + } + out := cloneStringSlice(minecraftJavaVersionsCache) + minecraftJavaVersionsMu.Unlock() + return out +} + +func minecraftJavaOptionsPayload(selected string) map[string]any { + selected = normalizeMinecraftJavaVersion(selected) + if selected == "" { + selected = minecraftJavaVersionFromTag(defaultMinecraftProcessTag) + } + if selected == "" { + selected = "21" + } + versions := minecraftJavaVersions() + hasSelected := false + for _, version := range versions { + if version == selected { + hasSelected = true + break + } + } + if !hasSelected { + versions = mergeMinecraftJavaVersions(append(versions, selected)) + } + options := make([]map[string]string, 0, len(versions)) + for _, version := range versions { + options = append(options, map[string]string{ + "version": version, + "tag": minecraftJavaTag(version), + "label": "Java " + version, + }) + } + return map[string]any{ + "selected": selected, + "image": defaultMinecraftProcessImage, + "tag": minecraftJavaTag(selected), + "options": options, + } +} + +func sanitizeRuntimeCommand(raw any) string { + s := strings.ReplaceAll(fmt.Sprint(raw), "\r\n", "\n") + s = strings.ReplaceAll(s, "\r", "\n") + s = strings.TrimSpace(s) + if len(s) > maxRuntimeCommandLen { + s = s[:maxRuntimeCommandLen] + } + if s == "" { + return "" + } + return s +} + +func stripLegacyStartupCommandFields(meta map[string]any) bool { + if meta == nil { + return false + } + changed := false + if _, ok := meta["startupCommand"]; ok { + delete(meta, "startupCommand") + changed = true + } + if runtimeObj, ok := meta["runtime"].(map[string]any); ok { + if _, ok := runtimeObj["startupCommand"]; ok { + delete(runtimeObj, "startupCommand") + meta["runtime"] = runtimeObj + changed = true + } + } + return changed +} + +func defaultStartFileForType(tpl string) string { + switch strings.ToLower(strings.TrimSpace(tpl)) { + case "minecraft": + return "server.jar" + case "python": + return "main.py" + case "nodejs", "discord-bot": + return "index.js" + default: + return "" + } +} + +func defaultDataDirForType(tpl string) string { + switch strings.ToLower(strings.TrimSpace(tpl)) { + case "python", "nodejs", "discord-bot", "runtime": + return "/app" + case "fivem", "five-m", "redm": + return cfxRuntimeServerDir + default: + return "/data" + } +} + +func hasManagedRuntimeDefaults(tpl string) bool { + switch strings.ToLower(strings.TrimSpace(tpl)) { + case "minecraft", "python", "nodejs", "discord-bot", "runtime": + return true + default: + return false + } +} + +func isManagedProcessRuntime(tpl string) bool { + switch strings.ToLower(strings.TrimSpace(tpl)) { + case "python", "nodejs", "discord-bot", "runtime": + return true + default: + return false + } +} + +func defaultRuntimeCommandForType(tpl, startFile, dataDir string) string { + switch strings.ToLower(strings.TrimSpace(tpl)) { + case "minecraft": + return defaultMinecraftProcessCommand + case "python": + if startFile == "" { + startFile = "main.py" + } + return fmt.Sprintf("python %s/%s", strings.TrimRight(dataDir, "/"), startFile) + case "nodejs", "discord-bot": + if startFile == "" { + startFile = "index.js" + } + return fmt.Sprintf("node %s/%s", strings.TrimRight(dataDir, "/"), startFile) + default: + return "" + } +} + +func (a *Agent) inferRuntimeProcessCommandFromImage(ctx context.Context, tpl, imageRef, startFile, dataDir, fallbackCommand string) (string, string, imageConfig, error) { + cleanTemplate := strings.ToLower(strings.TrimSpace(tpl)) + cleanImageRef := strings.TrimSpace(imageRef) + cleanStartFile := strings.TrimSpace(startFile) + providedDataDir := strings.TrimSpace(dataDir) != "" + cleanDataDir := strings.TrimSpace(dataDir) + if cleanStartFile == "" { + cleanStartFile = defaultStartFileForType(cleanTemplate) + } + if cleanDataDir == "" { + cleanDataDir = defaultDataDirForType(cleanTemplate) + } + + fallback := sanitizeRuntimeCommand(fallbackCommand) + if fallback == "" { + fallback = defaultRuntimeCommandForType(cleanTemplate, cleanStartFile, cleanDataDir) + } + inspected := imageConfig{Env: map[string]string{}} + + if cleanImageRef != "" { + if !a.docker.imageExistsLocally(ctx, cleanImageRef) { + a.docker.pull(ctx, cleanImageRef) + } + + imgCfg := a.docker.inspectImageConfig(ctx, cleanImageRef) + inspected = imgCfg + if !providedDataDir { + if wd := strings.TrimSpace(imgCfg.Workdir); wd != "" { + cleanDataDir = wd + } + } + + candidate := runtimeCommandFromImageConfig(imgCfg) + if candidate != "" { + candidate = normalizeLegacyRuntimeProcessCommand(cleanTemplate, candidate, cleanStartFile, cleanDataDir) + if shouldPreferImageDefaultRuntimeCommand(candidate, imgCfg) { + return candidate, "image-default", inspected, nil + } + if reason := validateRuntimeProcessCommand(candidate); reason == "" { + return candidate, "image-inspect", inspected, nil + } + } + } + + fallback = normalizeLegacyRuntimeProcessCommand(cleanTemplate, fallback, cleanStartFile, cleanDataDir) + if reason := validateRuntimeProcessCommand(fallback); reason != "" { + return "", "", inspected, fmt.Errorf("%s", reason) + } + if fallback != "" { + return fallback, "template-default", inspected, nil + } + + return "", "", inspected, fmt.Errorf("no startup command could be inferred") +} + +func metaIntValue(meta map[string]any, key string, fallback int) int { + if meta == nil { + return fallback + } + resources, _ := meta["resources"].(map[string]any) + if resources == nil { + return fallback + } + switch v := resources[key].(type) { + case float64: + return int(v) + case int: + return v + case int64: + return int(v) + case string: + if parsed, err := strconv.Atoi(strings.TrimSpace(v)); err == nil { + return parsed + } + } + return fallback +} + +func metaFloatValue(meta map[string]any, key string, fallback float64) float64 { + if meta == nil { + return fallback + } + resources, _ := meta["resources"].(map[string]any) + if resources == nil { + return fallback + } + switch v := resources[key].(type) { + case float64: + return v + case int: + return float64(v) + case int64: + return float64(v) + case string: + if parsed, err := strconv.ParseFloat(strings.TrimSpace(v), 64); err == nil { + return parsed + } + } + return fallback +} + +func effectiveRamMb(resources *resourceLimits, meta map[string]any, fallback int) int { + if resources != nil && resources.RamMb != nil && *resources.RamMb > 0 { + return *resources.RamMb + } + return metaIntValue(meta, "ramMb", fallback) +} + +func effectiveCpuCores(resources *resourceLimits, meta map[string]any, fallback float64) float64 { + if resources != nil && resources.CpuCores != nil && *resources.CpuCores > 0 { + return *resources.CpuCores + } + return metaFloatValue(meta, "cpuCores", fallback) +} + +func resourceLimitsFromMeta(meta map[string]any) *resourceLimits { + rm, ok := meta["resources"].(map[string]any) + if !ok || rm == nil { + return nil + } + resources := &resourceLimits{} + if v := anyToInt(rm["ramMb"]); v > 0 { + i := v + resources.RamMb = &i + } + if v := anyToFloat64(rm["cpuCores"]); v > 0 { + resources.CpuCores = &v + } + if v := anyToInt(rm["storageMb"]); v > 0 { + i := v + resources.StorageMb = &i + } else if v := anyToInt(rm["storageGb"]); v > 0 { + i := v * 1024 + resources.StorageMb = &i + } + if _, ok := rm["swapMb"]; ok { + i := anyToInt(rm["swapMb"]) + resources.SwapMb = &i + } + if v := anyToInt(rm["backupsMax"]); v > 0 { + i := v + resources.BackupsMax = &i + } + if v := anyToInt(rm["maxSchedules"]); v > 0 { + i := v + resources.MaxSchedules = &i + } + if v := anyToInt(rm["ioWeight"]); v > 0 { + i := v + resources.IoWeight = &i + } + if v := anyToInt(rm["cpuWeight"]); v > 0 { + i := v + resources.CpuWeight = &i + } + if v := anyToInt(rm["pidsLimit"]); v > 0 { + i := v + resources.PidsLimit = &i + } + if v := anyToInt(rm["fileLimit"]); v > 0 { + i := v + resources.FileLimit = &i + } + if v := anyToInt64(rm["networkInboundLimitMb"]); v > 0 { + i := v + resources.NetworkInboundLimitMb = &i + } + if v := anyToInt64(rm["networkOutboundLimitMb"]); v > 0 { + i := v + resources.NetworkOutboundLimitMb = &i + } + if v := anyToInt(rm["networkResetMinutes"]); v > 0 { + i := v + resources.NetworkResetMinutes = &i + } + return resources +} + +func renderRuntimeCommandTemplate(command, dataDir, startFile, imageRef string, hostPort int, resources *resourceLimits, meta map[string]any) string { + cmd := sanitizeRuntimeCommand(command) + if cmd == "" { + return "" + } + ramMb := effectiveRamMb(resources, meta, 2048) + cpuCores := effectiveCpuCores(resources, meta, 1) + values := map[string]string{ + "PORT": fmt.Sprint(hostPort), + "SERVER_PORT": fmt.Sprint(hostPort), + "DATA_DIR": dataDir, + "START_FILE": startFile, + "RAM_MB": fmt.Sprint(ramMb), + "SERVER_MEMORY": fmt.Sprint(ramMb), + "CPU_CORES": strconv.FormatFloat(cpuCores, 'f', -1, 64), + "IMAGE": imageRef, + } + if meta != nil { + if runtimeObj, ok := meta["runtime"].(map[string]any); ok { + for key, value := range runtimeEnvMap(runtimeObj["env"]) { + envKey := strings.TrimSpace(key) + if envKey != "" { + values[envKey] = value + } + } + } + } + replacer := strings.NewReplacer( + "{PORT}", values["PORT"], + "{SERVER_PORT}", values["SERVER_PORT"], + "{DATA_DIR}", values["DATA_DIR"], + "{START_FILE}", values["START_FILE"], + "{RAM_MB}", values["RAM_MB"], + "{SERVER_MEMORY}", values["SERVER_MEMORY"], + "{CPU_CORES}", values["CPU_CORES"], + "{IMAGE}", values["IMAGE"], + ) + rendered := replacer.Replace(cmd) + doubleBraceReplacer := regexp.MustCompile(`\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}`) + rendered = doubleBraceReplacer.ReplaceAllStringFunc(rendered, func(token string) string { + match := doubleBraceReplacer.FindStringSubmatch(token) + if len(match) != 2 { + return token + } + key := strings.TrimSpace(match[1]) + if key == "server.build.default.port" { + if hostPort > 0 { + return fmt.Sprint(hostPort) + } + return token + } + if strings.HasPrefix(key, "env.") { + key = strings.TrimPrefix(key, "env.") + } + if value, ok := values[key]; ok { + return value + } + return token + }) + return strings.TrimSpace(rendered) +} + +func isPythonRuntimeExecutable(execName string) bool { + execName = strings.ToLower(strings.TrimSpace(execName)) + return execName == "python" || strings.HasPrefix(execName, "python3") || strings.HasPrefix(execName, "python2") +} + +func isNodeRuntimeExecutable(execName string) bool { + execName = strings.ToLower(strings.TrimSpace(execName)) + return execName == "node" || execName == "nodejs" +} + +func firstRuntimeCommandFileTarget(args []string, startIndex int, extensions map[string]bool) string { + for i := startIndex + 1; i < len(args); i++ { + token := strings.TrimSpace(args[i]) + if token == "" || token == "--" { + continue + } + if strings.HasPrefix(token, "-") { + continue + } + ext := strings.ToLower(path.Ext(strings.SplitN(token, "?", 2)[0])) + if extensions[ext] { + return token + } + } + return "" +} + +func containerPathToServerPath(serverDir, dataDir, workdir, rawPath string) string { + clean := strings.TrimSpace(rawPath) + if clean == "" || strings.Contains(clean, "\x00") { + return "" + } + clean = strings.ReplaceAll(clean, "\\", "/") + + var rel string + if path.IsAbs(clean) { + for _, root := range []string{dataDir, workdir} { + root = path.Clean(strings.TrimSpace(root)) + if root == "" || root == "." || root == "/" { + continue + } + if clean == root { + return "" + } + prefix := strings.TrimRight(root, "/") + "/" + if strings.HasPrefix(clean, prefix) { + rel = strings.TrimPrefix(clean, prefix) + break + } + } + if rel == "" { + return "" + } + } else { + rel = clean + } + + rel = path.Clean("/" + rel) + rel = strings.TrimPrefix(rel, "/") + if rel == "" || rel == "." || rel == ".." || strings.HasPrefix(rel, "../") { + return "" + } + return filepath.Join(serverDir, filepath.FromSlash(rel)) +} + +func ensureRuntimeEntrypointScaffold(serverDir, tpl, commandTemplate, dataDir, workdir, startFile string, hostPort int) { + command := sanitizeRuntimeCommand(commandTemplate) + if command == "" { + return + } + args := parseShellArgs(command) + execName, execIndex := resolveRuntimeProcessExecutable(args) + if execIndex < 0 { + return + } + + if isPythonRuntimeExecutable(execName) { + target := firstRuntimeCommandFileTarget(args, execIndex, map[string]bool{".py": true}) + if target == "" && strings.EqualFold(strings.TrimSpace(tpl), "python") { + if startFile == "" { + startFile = "main.py" + } + target = path.Join(strings.TrimRight(dataDir, "/"), startFile) + } + hostPath := containerPathToServerPath(serverDir, dataDir, workdir, target) + if hostPath != "" { + writeGeneratedRuntimeFile(hostPath, []byte(pythonMainTemplate), isLegacyPythonScaffold) + } + return + } + + if isNodeRuntimeExecutable(execName) { + target := firstRuntimeCommandFileTarget(args, execIndex, map[string]bool{".js": true, ".mjs": true, ".cjs": true}) + normalizedTpl := strings.ToLower(strings.TrimSpace(tpl)) + if target == "" && (normalizedTpl == "nodejs" || normalizedTpl == "discord-bot") { + if startFile == "" { + startFile = "index.js" + } + target = path.Join(strings.TrimRight(dataDir, "/"), startFile) + } + hostPath := containerPathToServerPath(serverDir, dataDir, workdir, target) + if hostPath != "" { + writeGeneratedRuntimeFile(hostPath, []byte(buildNodeIndexTemplate(hostPort)), isLegacyNodeScaffold) + } + } +} + +func parseVolumeSpecContainerPath(spec string) string { + parts := strings.Split(spec, ":") + if len(parts) < 2 { + return "" + } + containerPath := strings.TrimSpace(parts[1]) + if idx := strings.LastIndex(containerPath, ":"); idx > 0 { + containerPath = containerPath[:idx] + } + return strings.TrimSpace(containerPath) +} + +func replaceVolumeSpecContainerPath(spec, containerPath string) string { + cleanTarget := strings.TrimSpace(containerPath) + if cleanTarget == "" { + return spec + } + parts := strings.Split(spec, ":") + if len(parts) < 2 { + return spec + } + parts[1] = cleanTarget + return strings.Join(parts, ":") +} + +func imageConfigHasRuntimeDefault(cfg imageConfig) bool { + return len(trimRuntimeProcessArgs(cfg.Entrypoint)) > 0 || len(trimRuntimeProcessArgs(cfg.Cmd)) > 0 +} + +func imageConfigDeclaresVolume(cfg imageConfig, containerPath string) bool { + cleanPath := path.Clean(strings.TrimSpace(containerPath)) + if cleanPath == "." || cleanPath == "/" || cleanPath == "" { + return false + } + for _, volumePath := range cfg.Volumes { + if path.Clean(strings.TrimSpace(volumePath)) == cleanPath { + return true + } + } + return false +} + +func imageUsesPterodactylContainerWorkdir(imageRef string, imgCfg imageConfig) bool { + workdir := path.Clean(strings.TrimSpace(imgCfg.Workdir)) + if workdir != "/home/container" { + return false + } + imageLower := strings.ToLower(strings.TrimSpace(imageRef)) + return strings.Contains(imageLower, "ghcr.io/pterodactyl/") || + strings.Contains(imageLower, "ghcr.io/ptero-eggs/") || + strings.Contains(imageLower, "ghcr.io/parkervcp/") || + strings.Contains(imageLower, "pterodactyl/") +} + +func (a *Agent) inspectRuntimeImageConfig(ctx context.Context, imageRef string) imageConfig { + cleanImageRef := strings.TrimSpace(imageRef) + if cleanImageRef == "" { + return imageConfig{Env: map[string]string{}} + } + if !a.docker.imageExistsLocally(ctx, cleanImageRef) { + a.docker.pull(ctx, cleanImageRef) + } + return a.docker.inspectImageConfig(ctx, cleanImageRef) +} + +func sanitizeCustomImageDefaultBinds(imageRef string, imgCfg imageConfig, binds []string, dataDir string) ([]string, string) { + workdir := path.Clean(strings.TrimSpace(imgCfg.Workdir)) + if workdir == "" || workdir == "." || workdir == "/" || !imageConfigHasRuntimeDefault(imgCfg) || imageConfigDeclaresVolume(imgCfg, workdir) { + return binds, dataDir + } + if imageUsesPterodactylContainerWorkdir(imageRef, imgCfg) { + return binds, dataDir + } + + gameDataPath := "" + if isGameServerDockerImage(imageRef) { + gameDataPath = path.Clean(getGameServerDataPath(imageRef)) + } + if gameDataPath == workdir { + return binds, dataDir + } + if gameDataPath == "." || gameDataPath == "/" { + gameDataPath = "" + } + + changed := false + out := make([]string, 0, len(binds)) + for _, bind := range binds { + containerPath := path.Clean(parseVolumeSpecContainerPath(bind)) + if containerPath == workdir { + if gameDataPath != "" { + out = append(out, replaceVolumeSpecContainerPath(bind, gameDataPath)) + if path.Clean(strings.TrimSpace(dataDir)) == workdir { + dataDir = gameDataPath + } + changed = true + fmt.Printf("[docker] remapped volume away from image workdir for %s: %s -> %s\n", imageRef, workdir, gameDataPath) + continue + } + changed = true + fmt.Printf("[docker] skipped volume that would hide image workdir for %s: %s\n", imageRef, bind) + continue + } + out = append(out, bind) + } + + if !changed { + return binds, dataDir + } + if len(out) == 0 { + return nil, "" + } + return out, dataDir +} + +func runtimeStringSlice(raw any) []string { + switch v := raw.(type) { + case []string: + out := make([]string, 0, len(v)) + for _, entry := range v { + clean := strings.TrimSpace(entry) + if clean != "" && clean != "" { + out = append(out, clean) + } + } + return out + case []any: + out := make([]string, 0, len(v)) + for _, entry := range v { + clean := strings.TrimSpace(fmt.Sprint(entry)) + if clean != "" && clean != "" { + out = append(out, clean) + } + } + return out + default: + return nil + } +} + +func runtimeIntSlice(raw any) []int { + switch v := raw.(type) { + case []int: + out := make([]int, 0, len(v)) + for _, entry := range v { + if port, ok := parseStrictPortValue(entry); ok { + out = append(out, port) + } + } + return out + case []float64: + out := make([]int, 0, len(v)) + for _, entry := range v { + if port, ok := parseStrictPortValue(entry); ok { + out = append(out, port) + } + } + return out + case []string: + out := make([]int, 0, len(v)) + for _, entry := range v { + if port, ok := parseStrictPortValue(entry); ok { + out = append(out, port) + } + } + return out + case []any: + out := make([]int, 0, len(v)) + for _, entry := range v { + if port, ok := parseStrictPortValue(entry); ok { + out = append(out, port) + } + } + return out + default: + return nil + } +} + +func runtimeBool(raw any) bool { + switch v := raw.(type) { + case bool: + return v + case string: + clean := strings.ToLower(strings.TrimSpace(v)) + return clean == "1" || clean == "true" || clean == "yes" || clean == "on" + case float64: + return v != 0 + case int: + return v != 0 + default: + return false + } +} + +func runtimeEnvMap(raw any) map[string]string { + out := map[string]string{} + switch v := raw.(type) { + case map[string]string: + for key, value := range v { + envKey := strings.TrimSpace(key) + if envKey != "" { + out[envKey] = value + } + } + case map[string]any: + for key, value := range v { + envKey := strings.TrimSpace(key) + if envKey != "" { + out[envKey] = fmt.Sprint(value) + } + } + } + if len(out) == 0 { + return nil + } + return out +} + +func primaryPortEnvKeysForTemplate(tpl string) []string { + switch strings.ToLower(strings.TrimSpace(tpl)) { + case "ark-survival-evolved", "ark": + return []string{"GAME_CLIENT_PORT"} + case "cs2", "dayz", "rust", "valheim": + return []string{"SERVER_PORT"} + case "fivem", "redm": + return []string{"SERVER_PORT", "PORT", "ADPANEL_GAME_PORT"} + case "palworld": + return []string{"PORT"} + case "project-zomboid": + return []string{"DEFAULT_PORT"} + case "ragemp": + return []string{"RAGEMP_PORT"} + default: + return nil + } +} + +func applyRuntimeHostPortEnv(tpl string, env map[string]string, hostPort int) { + if env == nil || hostPort <= 0 { + return + } + portValue := fmt.Sprint(hostPort) + env["PORT"] = portValue + env["SERVER_PORT"] = portValue + for _, key := range primaryPortEnvKeysForTemplate(tpl) { + env[key] = portValue + } +} + +func renderRuntimeEnvTemplates(tpl string, env map[string]string, hostPort int) { + if env == nil { + return + } + for key, value := range env { + if !strings.Contains(value, "{{") && !strings.Contains(value, "{PORT}") && !strings.Contains(value, "{SERVER_PORT}") { + continue + } + rendered := renderADPanelStartupTemplate(value, env, hostPort) + if hostPort > 0 { + rendered = strings.ReplaceAll(rendered, "{SERVER_PORT}", fmt.Sprint(hostPort)) + rendered = strings.ReplaceAll(rendered, "{PORT}", fmt.Sprint(hostPort)) + } + env[key] = rendered + } +} + +func runtimeUsesHostPortInsideContainer(tpl string, runtimeObj map[string]any, env map[string]string) bool { + normalized := strings.ToLower(strings.TrimSpace(tpl)) + switch normalized { + case "ark-survival-evolved", "ark", "cs2", "dayz", "fivem", "redm", "palworld", "project-zomboid", "ragemp", "rust", "valheim": + return true + } + for _, key := range primaryPortEnvKeysForTemplate(normalized) { + if _, ok := env[key]; ok { + return true + } + } + startup := strings.TrimSpace(env["STARTUP"]) + if startup == "" { + startup = startupTemplateFromRuntime(runtimeObj) + } + return strings.Contains(startup, "{{SERVER_PORT}}") || + strings.Contains(startup, "{{PORT}}") || + strings.Contains(startup, "{SERVER_PORT}") || + strings.Contains(startup, "{PORT}") +} + +const cfxRuntimeServerDir = "/serverdata/serverfiles" + +func isCfxTemplate(tpl string) bool { + switch strings.ToLower(strings.TrimSpace(tpl)) { + case "fivem", "five-m", "redm": + return true + default: + return false + } +} + +func migrateNestedCfxServerFiles(serverDir string) { + nested := filepath.Join(serverDir, "serverfiles") + info, err := os.Stat(nested) + if err != nil || !info.IsDir() { + return + } + entries, err := os.ReadDir(nested) + if err != nil { + return + } + for _, entry := range entries { + src := filepath.Join(nested, entry.Name()) + dst := filepath.Join(serverDir, entry.Name()) + if pathExists(dst) { + continue + } + if err := os.Rename(src, dst); err != nil { + fmt.Printf("[cfx-layout] could not move %s to %s: %v\n", src, dst, err) + } + } + _ = os.Remove(nested) +} + +func normalizeCfxRuntimeLayout(tpl string, runtimeObj map[string]any, serverDir string) bool { + if runtimeObj == nil || !isCfxTemplate(tpl) { + return false + } + changed := false + migrateNestedCfxServerFiles(serverDir) + desiredVolume := "{BOT_DIR}:" + cfxRuntimeServerDir + volumes := runtimeStringSlice(runtimeObj["volumes"]) + if len(volumes) != 1 || strings.TrimSpace(volumes[0]) != desiredVolume { + runtimeObj["volumes"] = []any{desiredVolume} + changed = true + } + if normalizeContainerWorkdir(runtimeObj["workdir"]) != cfxRuntimeServerDir { + runtimeObj["workdir"] = cfxRuntimeServerDir + changed = true + } + env := runtimeEnvMap(runtimeObj["env"]) + if env == nil { + env = map[string]string{} + } + for key, value := range map[string]string{ + "DATA_DIR": cfxRuntimeServerDir, + "SERVER_DIR": cfxRuntimeServerDir, + "GAME_CONFIG": "server.cfg", + "HOME": cfxRuntimeServerDir, + "DATA_PERM": "777", + } { + if env[key] != value { + env[key] = value + changed = true + } + } + runtimeObj["env"] = env + if runtimeObj["runAsRoot"] != true { + runtimeObj["runAsRoot"] = true + changed = true + } + if rawInstall, ok := runtimeObj["install"]; ok && rawInstall != nil { + switch install := rawInstall.(type) { + case map[string]any: + if normalizeContainerWorkdir(install["runtimePath"]) != cfxRuntimeServerDir { + install["runtimePath"] = cfxRuntimeServerDir + changed = true + } + if normalizeContainerWorkdir(install["mountPath"]) == "" && normalizeContainerWorkdir(install["containerPath"]) == "" { + install["mountPath"] = "/mnt/server" + changed = true + } + case *templateInstallConfig: + if normalizeContainerWorkdir(install.RuntimePath) != cfxRuntimeServerDir { + install.RuntimePath = cfxRuntimeServerDir + changed = true + } + if normalizeContainerWorkdir(install.MountPath) == "" && normalizeContainerWorkdir(install.ContainerPath) == "" { + install.MountPath = "/mnt/server" + changed = true + } + } + } + return changed +} + +func (a *Agent) resolveStructuredBinds(tpl string, runtimeObj map[string]any, serverDir string) ([]string, string) { + defaultDir := defaultDataDirForType(tpl) + binds := []string{} + primaryDir := defaultDir + + if volumes := runtimeStringSlice(runtimeObj["volumes"]); len(volumes) > 0 { + // adpanel:multidisk - validate host bind paths against the volume root that + // actually OWNS this server (primary or a secondary disk), not the primary + // volumes dir. Using a.volumesDir here caused every secondary-disk bind to + // be dropped, so those containers started without their data volume and + // Docker reported no usable metrics / a non-running state. + serverVolRoot := a.volumeRootFor(serverDir) + for _, s := range volumes { + s = strings.ReplaceAll(s, "{BOT_DIR}", serverDir) + s = strings.ReplaceAll(s, "{SERVER_DIR}", serverDir) + s = strings.ReplaceAll(s, "{DATA_DIR}", serverDir) + + parts := strings.SplitN(s, ":", 2) + if len(parts) >= 2 { + hostPath := filepath.Clean(parts[0]) + if err := ensureResolvedUnder(serverVolRoot, hostPath); err != nil { + fmt.Printf("[security] blocked volume mount outside volumes dir: %s\n", s) + continue + } + containerPath := parseVolumeSpecContainerPath(s) + if containerPath != "" && primaryDir == defaultDir { + primaryDir = containerPath + } + } + binds = append(binds, s) + } + } + + if len(binds) == 0 { + binds = []string{fmt.Sprintf("%s:%s", serverDir, defaultDir)} + primaryDir = defaultDir + } + return binds, primaryDir +} + +func addPortBinding(portBindings map[string][]dockerPortBinding, exposed map[string]struct{}, hostPort, containerPort int, protocols []string) { + if hostPort <= 0 || containerPort <= 0 { + return + } + cleanProtocols := normalizePortProtocolSlice(protocols) + if len(cleanProtocols) == 0 { + cleanProtocols = []string{"tcp"} + } + for _, protocol := range cleanProtocols { + key := fmt.Sprintf("%d/%s", containerPort, protocol) + exposed[key] = struct{}{} + duplicate := false + for _, binding := range portBindings[key] { + if binding.HostPort == fmt.Sprint(hostPort) { + duplicate = true + break + } + } + if duplicate { + continue + } + portBindings[key] = append(portBindings[key], dockerPortBinding{ + HostIP: "0.0.0.0", + HostPort: fmt.Sprint(hostPort), + }) + } +} + +func (a *Agent) buildStructuredPortBindings(serverDir string, meta map[string]any, hostPort, mainContainerPort int) (map[string][]dockerPortBinding, map[string]struct{}) { + portBindings := make(map[string][]dockerPortBinding) + exposed := make(map[string]struct{}) + runtimeObj, _ := meta["runtime"].(map[string]any) + protocolsByPort := runtimePortProtocolMap(runtimeObj["portProtocols"]) + addPortBinding(portBindings, exposed, hostPort, mainContainerPort, portProtocolsFor(protocolsByPort, mainContainerPort)) + + if metaRes, ok := meta["resources"].(map[string]any); ok { + for _, ap := range runtimeIntSlice(metaRes["ports"]) { + if ap > 0 && ap != hostPort { + addPortBinding(portBindings, exposed, ap, ap, portProtocolsFor(protocolsByPort, ap)) + fmt.Printf("[port-manage] exposing additional port %d:%d\n", ap, ap) + } + } + } + + for _, pf := range a.loadPortForwards(serverDir) { + targetPort := pf.Internal + if hostPort > 0 && pf.Internal == hostPort && mainContainerPort > 0 { + targetPort = mainContainerPort + } + addPortBinding(portBindings, exposed, pf.Public, targetPort, portProtocolsFor(protocolsByPort, targetPort)) + } + return portBindings, exposed +} + +func dockerRestartPolicyFromName(name string) dockerRestartPolicy { + clean := strings.ToLower(strings.TrimSpace(name)) + switch clean { + case "no", "": + return dockerRestartPolicy{Name: "no"} + case "always": + return dockerRestartPolicy{Name: "always"} + case "on-failure": + return dockerRestartPolicy{Name: "on-failure"} + default: + return dockerRestartPolicy{Name: "unless-stopped"} + } +} + +func buildStructuredHostConfig(binds []string, portBindings map[string][]dockerPortBinding, resources *resourceLimits, restart string, readOnly bool) dockerHostConfig { + pidsLimit := int64(defaultPidsLimit) + if resources != nil && resources.PidsLimit != nil && *resources.PidsLimit >= minPidsLimit && *resources.PidsLimit <= maxPidsLimit { + pidsLimit = int64(*resources.PidsLimit) + } + + hostConfig := dockerHostConfig{ + Binds: binds, + PortBindings: portBindings, + RestartPolicy: dockerRestartPolicyFromName(restart), + CapDrop: []string{"ALL"}, + CapAdd: []string{ + "CHOWN", + "DAC_OVERRIDE", + "FOWNER", + "SETUID", + "SETGID", + "KILL", + "NET_BIND_SERVICE", + "NET_RAW", + "SYS_CHROOT", + "AUDIT_WRITE", + }, + SecurityOpt: []string{"no-new-privileges"}, + PidsLimit: pidsLimit, + } + + if readOnly { + hostConfig.ReadonlyRootfs = true + hostConfig.Tmpfs = map[string]string{ + "/tmp": "rw,noexec,nosuid,size=256m", + "/var/tmp": "rw,noexec,nosuid,size=64m", + "/run": "rw,noexec,nosuid,size=32m", + } + } + + if resources != nil { + if resources.RamMb != nil && *resources.RamMb > 0 { + hostConfig.Memory = int64(*resources.RamMb) * 1024 * 1024 + hostConfig.MemoryReservation = int64(*resources.RamMb*90/100) * 1024 * 1024 + if resources.SwapMb == nil { + hostConfig.MemorySwap = int64(*resources.RamMb) * 1024 * 1024 + } else { + swapVal := *resources.SwapMb + if swapVal == -1 { + hostConfig.MemorySwap = int64(*resources.RamMb) * 1024 * 1024 + } else if swapVal == 0 { + hostConfig.MemorySwap = -1 + } else { + hostConfig.MemorySwap = int64(*resources.RamMb+swapVal) * 1024 * 1024 + } + } + } + + if resources.CpuCores != nil && *resources.CpuCores > 0 { + effCores, _ := computeCpuLimit(*resources.CpuCores) + hostConfig.CpuPeriod = cpuPeriod + hostConfig.CpuQuota = int64(float64(cpuPeriod) * effCores) + } + if resources.CpuWeight != nil && *resources.CpuWeight >= minCpuWeight && *resources.CpuWeight <= maxCpuWeight { + hostConfig.CpuShares = dockerCpuSharesFromWeight(*resources.CpuWeight) + } + if resources.IoWeight != nil && *resources.IoWeight >= minIoWeight && *resources.IoWeight <= maxIoWeight { + hostConfig.BlkioWeight = int64(*resources.IoWeight) + } + if resources.FileLimit != nil && *resources.FileLimit >= minFileLimit && *resources.FileLimit <= maxFileLimit { + limit := int64(*resources.FileLimit) + hostConfig.Ulimits = append(hostConfig.Ulimits, dockerUlimit{Name: "nofile", Soft: limit, Hard: limit}) + } + } + + return hostConfig +} + +func envMapToList(env map[string]string) []string { + if len(env) == 0 { + return nil + } + out := make([]string, 0, len(env)) + for k, v := range env { + k = strings.TrimSpace(k) + if k == "" { + continue + } + out = append(out, fmt.Sprintf("%s=%s", k, v)) + } + return out +} + +func isBlockedRuntimeShellExecutable(arg string) bool { + switch runtimeProcessBaseExecutable(arg) { + case "sh", "bash", "ash", "dash", "zsh", "ksh": + return true + default: + return false + } +} + +func isRuntimeShellWrapperArgs(args []string, execIndex int) bool { + if execIndex < 0 || execIndex >= len(args) { + return false + } + if !isBlockedRuntimeShellExecutable(args[execIndex]) { + return false + } + if execIndex+1 >= len(args) { + return false + } + flags := strings.ToLower(strings.TrimSpace(args[execIndex+1])) + return strings.HasPrefix(flags, "-") && strings.Contains(flags, "c") +} + +func isBlockedRuntimeShellToken(arg string) bool { + switch strings.TrimSpace(arg) { + case "&&", "||", "|", ";", "&", ">", ">>", "<", "<<", "2>", "2>>", "2>&1", "|&": + return true + default: + return false + } +} + +func runtimeProcessBaseExecutable(arg string) string { + clean := strings.TrimSpace(arg) + if clean == "" { + return "" + } + if strings.IndexFunc(clean, func(r rune) bool { return r == ' ' || r == '\t' || r == '\n' || r == '\r' }) >= 0 { + if nested := parseShellArgs(clean); len(nested) > 0 { + clean = strings.TrimSpace(nested[0]) + } + } + clean = strings.ToLower(strings.ReplaceAll(clean, "\\", "/")) + if slash := strings.LastIndex(clean, "/"); slash >= 0 && slash+1 < len(clean) { + return clean[slash+1:] + } + return clean +} + +func isRuntimeEnvAssignmentToken(arg string) bool { + token := strings.TrimSpace(arg) + if token == "" || strings.HasPrefix(token, "-") { + return false + } + eqIdx := strings.Index(token, "=") + if eqIdx <= 0 { + return false + } + key := token[:eqIdx] + for i, r := range key { + isLetter := (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') + isDigit := r >= '0' && r <= '9' + if i == 0 { + if r != '_' && !isLetter { + return false + } + continue + } + if r != '_' && !isLetter && !isDigit { + return false + } + } + return true +} + +func resolveRuntimeProcessExecutable(args []string) (string, int) { + if len(args) == 0 { + return "", -1 + } + for index := 0; index < len(args); index++ { + token := strings.TrimSpace(args[index]) + if token == "" { + continue + } + execName := runtimeProcessBaseExecutable(token) + if execName == "env" { + index++ + for index < len(args) { + envToken := strings.TrimSpace(args[index]) + if envToken == "" { + index++ + continue + } + if envToken == "--" { + index++ + break + } + if strings.HasPrefix(envToken, "-") || isRuntimeEnvAssignmentToken(envToken) { + index++ + continue + } + break + } + index-- + continue + } + return execName, index + } + return "", -1 +} + +func isBlockedContainerRuntimeExecutable(arg string) bool { + switch strings.TrimSpace(arg) { + case "docker", "docker-compose", "podman", "podman-compose", "nerdctl", "ctr": + return true + default: + return false + } +} + +func unwrapRuntimeShellWrapper(cmd string) (string, bool) { + args := parseShellArgs(cmd) + if len(args) < 3 { + return "", false + } + if !isBlockedRuntimeShellExecutable(args[0]) { + return "", false + } + flags := strings.TrimSpace(args[1]) + if !strings.HasPrefix(flags, "-") || !strings.Contains(flags, "c") { + return "", false + } + inner := sanitizeRuntimeCommand(args[2]) + if inner == "" { + return "", false + } + return inner, true +} + +func normalizeLegacyRuntimeProcessCommand(tpl, command, startFile, dataDir string) string { + clean := sanitizeRuntimeCommand(command) + if clean == "" { + return "" + } + for i := 0; i < 2; i++ { + inner, ok := unwrapRuntimeShellWrapper(clean) + if !ok { + break + } + clean = sanitizeRuntimeCommand(inner) + } + switch strings.ToLower(strings.TrimSpace(tpl)) { + case "nodejs", "discord-bot": + lower := strings.ToLower(clean) + nodeIdx := strings.LastIndex(lower, "node ") + if nodeIdx >= 0 && (strings.Contains(lower, "&&") || strings.HasPrefix(lower, "npm ") || strings.HasPrefix(lower, "cd ")) { + clean = sanitizeRuntimeCommand(clean[nodeIdx:]) + } + } + return clean +} + +func looksLikePathOnlyScriptRuntimeCommand(command string) bool { + args := parseShellArgs(command) + if len(args) != 1 { + return false + } + token := strings.ToLower(strings.TrimSpace(args[0])) + if !strings.HasPrefix(token, "/") { + return false + } + return strings.Contains(token, "entrypoint") || strings.HasSuffix(token, ".sh") || strings.HasSuffix(token, ".bash") +} + +func looksLikeImageDefaultWrapperRuntimeCommand(command string, imgCfg imageConfig) bool { + clean := strings.ToLower(strings.TrimSpace(command)) + if clean == "" { + return false + } + if looksLikePathOnlyScriptRuntimeCommand(command) { + return true + } + entrypoint := trimRuntimeProcessArgs(imgCfg.Entrypoint) + cmd := trimRuntimeProcessArgs(imgCfg.Cmd) + if len(entrypoint) == 2 && isRuntimeShellName(entrypoint[0]) { + script := strings.ToLower(strings.TrimSpace(entrypoint[1])) + if strings.HasPrefix(script, "/") && (strings.Contains(script, "entrypoint") || strings.HasSuffix(script, ".sh") || strings.HasSuffix(script, ".bash")) { + return true + } + } + if len(cmd) == 1 { + script := strings.ToLower(strings.TrimSpace(cmd[0])) + if strings.HasPrefix(script, "/") && (strings.Contains(script, "entrypoint") || strings.HasSuffix(script, ".sh") || strings.HasSuffix(script, ".bash")) { + return true + } + } + if strings.Contains(clean, "entrypoint") && strings.Contains(clean, "/") { + return true + } + return false +} + +func shouldPreferImageDefaultRuntimeCommand(command string, imgCfg imageConfig) bool { + if !imageConfigHasRuntimeDefault(imgCfg) { + return false + } + return looksLikeImageDefaultWrapperRuntimeCommand(command, imgCfg) +} + +func validateRuntimeProcessCommand(command string) string { + clean := sanitizeRuntimeCommand(command) + if clean == "" { + return "" + } + if len(clean) > 4000 { + return "process command is too long" + } + if strings.Contains(clean, "\n") { + return "process command must be a single line" + } + if strings.Contains(clean, "`") || strings.Contains(clean, "$(") { + return "shell expansions are not allowed in process commands" + } + args := parseShellArgs(clean) + if len(args) == 0 { + return "process command is empty" + } + execName, execIndex := resolveRuntimeProcessExecutable(args) + if isBlockedContainerRuntimeExecutable(execName) { + return `container runtime CLI commands like "docker run" are not allowed; configure image, ports, volumes, env, and the in-container process separately` + } + if isBlockedRuntimeShellExecutable(execName) && isRuntimeShellWrapperArgs(args, execIndex) { + return "shell wrappers like sh -c or bash -lc are not allowed; provide the executable and arguments directly" + } + for _, arg := range args { + if isBlockedRuntimeShellToken(arg) { + return fmt.Sprintf("shell control operator %q is not allowed in process commands", strings.TrimSpace(arg)) + } + } + return "" +} + +func buildProcessCommandArgs(command string) ([]string, error) { + clean := sanitizeRuntimeCommand(command) + if clean == "" { + return nil, nil + } + if reason := validateRuntimeProcessCommand(clean); reason != "" { + return nil, fmt.Errorf("%s", reason) + } + args := parseShellArgs(clean) + if len(args) == 0 { + return nil, fmt.Errorf("process command is empty") + } + return args, nil +} + +func normalizeContainerWorkdir(value any) string { + workdir := strings.TrimSpace(fmt.Sprint(value)) + if workdir == "" || workdir == "" { + return "" + } + workdir = strings.ReplaceAll(workdir, "\\", "/") + if !strings.HasPrefix(workdir, "/") { + return "" + } + workdir = path.Clean(workdir) + if workdir == "" || workdir == "." { + return "" + } + if !strings.HasPrefix(workdir, "/") { + workdir = "/" + workdir + } + return workdir +} + +func buildRenderedRuntimeProcessArgs(tpl, command, dataDir, startFile, imageRef string, hostPort int, resources *resourceLimits, meta map[string]any) ([]string, error) { + rendered := renderRuntimeCommandTemplate(command, dataDir, startFile, imageRef, hostPort, resources, meta) + rendered = normalizeLegacyRuntimeProcessCommand(tpl, rendered, startFile, dataDir) + return buildProcessCommandArgs(rendered) +} + +func (a *Agent) recentContainerLogs(ctx context.Context, name string, tail int) string { + tailN := tail + if tailN <= 0 { + tailN = 50 + } + out, _, _, _ := a.docker.runCollect(ctx, "logs", "--tail", fmt.Sprint(tailN), name) + return out +} + +func isImmediateStartupPermissionIssue(logs string) bool { + lower := strings.ToLower(strings.TrimSpace(logs)) + if lower == "" { + return false + } + + hasPermissionFailure := strings.Contains(lower, "permission denied") || + strings.Contains(lower, "operation not permitted") || + strings.Contains(lower, "cannot execute") + if !hasPermissionFailure { + return false + } + + startupHints := []string{ + "start.sh", + "entrypoint", + "docker-entrypoint", + "/opt/", + "/bin/bash", + "/bin/sh", + "/usr/local/bin", + "exec /", + } + for _, hint := range startupHints { + if strings.Contains(lower, hint) { + return true + } + } + + return true +} + +func isMissingRuntimeExecutableStartError(err error) bool { + if err == nil { + return false + } + lower := strings.ToLower(err.Error()) + if !strings.Contains(lower, "exec:") { + return false + } + return strings.Contains(lower, "no such file or directory") || + strings.Contains(lower, "executable file not found") || + strings.Contains(lower, "stat ") || + strings.Contains(lower, "not found") +} + +func (a *Agent) preferredStructuredContainerUser(ctx context.Context, imageRef string, uid, gid int) string { + if uid < 0 || gid < 0 { + return "" + } + + cleanImageRef := strings.TrimSpace(imageRef) + if cleanImageRef != "" { + if !a.docker.imageExistsLocally(ctx, cleanImageRef) { + a.docker.pull(ctx, cleanImageRef) + } + imgCfg := a.docker.inspectImageConfig(ctx, cleanImageRef) + if strings.TrimSpace(imgCfg.User) != "" { + if a.debug { + fmt.Printf("[docker] honoring image-defined user %q for %s\n", imgCfg.User, cleanImageRef) + } + return "" + } + } + + return fmt.Sprintf("%d:%d", uid, gid) +} + +func runtimeRequestsRootUser(runtimeObj map[string]any) bool { + if runtimeObj == nil { + return false + } + return runtimeBool(runtimeObj["runAsRoot"]) || runtimeBool(runtimeObj["run_as_root"]) +} + +func (a *Agent) structuredContainerUser(ctx context.Context, imageRef string, uid, gid int, runtimeObj map[string]any) string { + if runtimeRequestsRootUser(runtimeObj) { + if a.debug { + fmt.Printf("[docker] template requested root entrypoint for %s\n", imageRef) + } + return "" + } + return a.preferredStructuredContainerUser(ctx, imageRef, uid, gid) +} + +func hostConfigMemoryLimitMb(cfg dockerHostConfig) float64 { + if cfg.Memory <= 0 { + return 0 + } + return float64(cfg.Memory) / (1024 * 1024) +} + +func hostConfigCpuLimitPercent(cfg dockerHostConfig) float64 { + if cfg.CpuPeriod <= 0 || cfg.CpuQuota <= 0 { + return 0 + } + return (float64(cfg.CpuQuota) / float64(cfg.CpuPeriod)) * 100 +} + +func almostEqualFloat64(a, b, tolerance float64) bool { + diff := a - b + if diff < 0 { + diff = -diff + } + return diff <= tolerance +} + +func (a *Agent) inspectContainerHostConfig(ctx context.Context, name string) (dockerHostConfig, error) { + inspected, err := a.docker.inspectContainerAPI(ctx, dockerContainerName(name)) + if err != nil { + return dockerHostConfig{}, err + } + return inspected.HostConfig, nil +} + +func (a *Agent) inspectContainerAppliedLimits(ctx context.Context, name string) (memoryLimitMb float64, cpuLimitPercent float64, err error) { + hostConfig, err := a.inspectContainerHostConfig(ctx, name) + if err != nil { + return 0, 0, err + } + return hostConfigMemoryLimitMb(hostConfig), hostConfigCpuLimitPercent(hostConfig), nil +} + +type dockerContainerStateForStats struct { + Status string `json:"Status"` + Running bool `json:"Running"` + StartedAt string `json:"StartedAt"` +} + +type dockerContainerInspectForStats struct { + ID string `json:"Id"` + Name string `json:"Name"` + State dockerContainerStateForStats `json:"State"` + HostConfig dockerHostConfig `json:"HostConfig"` +} + +type dockerStatsCPUUsage struct { + TotalUsage uint64 `json:"total_usage"` + PercpuUsage []uint64 `json:"percpu_usage"` +} + +type dockerStatsCPU struct { + CPUUsage dockerStatsCPUUsage `json:"cpu_usage"` + SystemCPUUsage uint64 `json:"system_cpu_usage"` + OnlineCPUs uint32 `json:"online_cpus"` +} + +type dockerStatsMemory struct { + Usage uint64 `json:"usage"` + Limit uint64 `json:"limit"` + Stats map[string]uint64 `json:"stats"` +} + +type dockerStatsNetwork struct { + RxBytes uint64 `json:"rx_bytes"` + TxBytes uint64 `json:"tx_bytes"` +} + +type dockerContainerStatsResponse struct { + CPUStats dockerStatsCPU `json:"cpu_stats"` + PreCPUStats dockerStatsCPU `json:"precpu_stats"` + MemoryStats dockerStatsMemory `json:"memory_stats"` + Networks map[string]dockerStatsNetwork `json:"networks"` +} + +func (a *Agent) inspectContainerForStats(ctx context.Context, name string) (dockerContainerInspectForStats, bool, error) { + dockerName := dockerContainerName(name) + body, status, err := a.docker.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(dockerName)+"/json", nil, nil) + if err != nil { + return dockerContainerInspectForStats{}, false, err + } + if status == http.StatusNotFound { + return dockerContainerInspectForStats{}, false, nil + } + if status < 200 || status >= 300 { + return dockerContainerInspectForStats{}, false, fmt.Errorf("failed to inspect container %s: %s", name, decodeDockerAPIError(body)) + } + + var payload dockerContainerInspectForStats + if err := json.Unmarshal(body, &payload); err != nil { + return dockerContainerInspectForStats{}, false, err + } + if strings.TrimPrefix(payload.Name, "/") != dockerName { + return dockerContainerInspectForStats{}, false, fmt.Errorf("container name mismatch") + } + return payload, true, nil +} + +func (a *Agent) readContainerStatsForServer(ctx context.Context, name string) (dockerContainerStatsResponse, error) { + query := url.Values{} + query.Set("stream", "false") + dockerName := dockerContainerName(name) + body, status, err := a.docker.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(dockerName)+"/stats", query, nil) + if err != nil { + return dockerContainerStatsResponse{}, err + } + if status < 200 || status >= 300 { + return dockerContainerStatsResponse{}, fmt.Errorf("failed to read container stats %s: %s", name, decodeDockerAPIError(body)) + } + var payload dockerContainerStatsResponse + if err := json.Unmarshal(body, &payload); err != nil { + return dockerContainerStatsResponse{}, err + } + return payload, nil +} + +func dockerCPUPercent(stats dockerContainerStatsResponse) float64 { + cpuTotal := stats.CPUStats.CPUUsage.TotalUsage + preCPUTime := stats.PreCPUStats.CPUUsage.TotalUsage + systemTotal := stats.CPUStats.SystemCPUUsage + preSystemTotal := stats.PreCPUStats.SystemCPUUsage + if cpuTotal <= preCPUTime || systemTotal <= preSystemTotal { + return 0 + } + + cpuDelta := float64(cpuTotal - preCPUTime) + systemDelta := float64(systemTotal - preSystemTotal) + if cpuDelta <= 0 || systemDelta <= 0 { + return 0 + } + + onlineCPUs := float64(stats.CPUStats.OnlineCPUs) + if onlineCPUs <= 0 { + onlineCPUs = float64(len(stats.CPUStats.CPUUsage.PercpuUsage)) + } + if onlineCPUs <= 0 { + onlineCPUs = 1 + } + return (cpuDelta / systemDelta) * onlineCPUs * 100 +} + +func dockerMemoryUsedBytes(mem dockerStatsMemory) uint64 { + usage := mem.Usage + if usage == 0 { + return 0 + } + if inactiveFile, ok := mem.Stats["inactive_file"]; ok && inactiveFile < usage { + return usage - inactiveFile + } + if cache, ok := mem.Stats["cache"]; ok && cache < usage { + return usage - cache + } + return usage +} + +func sumDockerNetworkBytes(networks map[string]dockerStatsNetwork) (uint64, uint64) { + var rx, tx uint64 + for _, counters := range networks { + rx = addUint64Saturating(rx, counters.RxBytes) + tx = addUint64Saturating(tx, counters.TxBytes) + } + return rx, tx +} + +func (a *Agent) verifyContainerResourceLimitsApplied(ctx context.Context, name string, expected dockerHostConfig) error { + actual, err := a.inspectContainerHostConfig(ctx, name) + if err != nil { + return fmt.Errorf("failed to verify container resource limits: %w", err) + } + + if expected.Memory > 0 && actual.Memory != expected.Memory { + return fmt.Errorf( + "container memory limit mismatch: expected %d MB, got %.0f MB", + expected.Memory/(1024*1024), + hostConfigMemoryLimitMb(actual), + ) + } + + if expected.CpuPeriod > 0 && expected.CpuQuota > 0 { + expectedPercent := hostConfigCpuLimitPercent(expected) + actualPercent := hostConfigCpuLimitPercent(actual) + if !almostEqualFloat64(actualPercent, expectedPercent, 0.05) { + return fmt.Errorf( + "container cpu limit mismatch: expected %.2f cores, got %.2f cores", + expectedPercent/100.0, + actualPercent/100.0, + ) + } + } + + return nil +} + +func (a *Agent) runStructuredContainerWithCompatUser(ctx context.Context, name string, req dockerContainerCreateRequest) error { + dockerName := dockerContainerName(name) + cleanupFailedContainer := func(err error) error { + return err + } + + if err := a.docker.runContainerAPI(ctx, dockerName, req); err != nil { + if len(req.Cmd) > 0 && isMissingRuntimeExecutableStartError(err) { + imgCfg := a.inspectRuntimeImageConfig(ctx, req.Image) + if imageConfigHasRuntimeDefault(imgCfg) { + fmt.Printf("[docker] startup command failed for %s (%v); retrying with image default entrypoint/cmd\n", name, err) + retryReq := req + retryReq.Cmd = nil + retryReq.Entrypoint = nil + if workdir := normalizeContainerWorkdir(imgCfg.Workdir); workdir != "" { + retryReq.WorkingDir = workdir + } + if retryErr := a.docker.runContainerAPI(ctx, dockerName, retryReq); retryErr != nil { + return retryErr + } + if healthErr := a.verifyContainerHealthyAfterStart(ctx, name); healthErr != nil { + return cleanupFailedContainer(healthErr) + } + if limitErr := a.verifyContainerResourceLimitsApplied(ctx, name, retryReq.HostConfig); limitErr != nil { + return limitErr + } + return nil + } + } + return err + } + if err := a.verifyContainerHealthyAfterStart(ctx, name); err != nil { + forcedUser := strings.TrimSpace(req.User) + if forcedUser == "" { + return cleanupFailedContainer(err) + } + + logCtx, logCancel := context.WithTimeout(context.Background(), 5*time.Second) + logsOut := a.recentContainerLogs(logCtx, name, 80) + logCancel() + if !isImmediateStartupPermissionIssue(logsOut) { + return cleanupFailedContainer(err) + } + + fmt.Printf("[docker] startup failed under forced user %s for %s; retrying with image default user\n", forcedUser, name) + a.docker.rmForce(ctx, name) + + retryReq := req + retryReq.User = "" + if err := a.docker.runContainerAPI(ctx, dockerName, retryReq); err != nil { + return err + } + if err := a.verifyContainerHealthyAfterStart(ctx, name); err != nil { + return cleanupFailedContainer(err) + } + if err := a.verifyContainerResourceLimitsApplied(ctx, name, retryReq.HostConfig); err != nil { + return err + } + return nil + } + if err := a.verifyContainerResourceLimitsApplied(ctx, name, req.HostConfig); err != nil { + return err + } + return nil +} + +func (a *Agent) verifyContainerHealthyAfterStart(ctx context.Context, name string) error { + deadline := time.Now().Add(4 * time.Second) + for { + time.Sleep(500 * time.Millisecond) + + statusOut, _, _, _ := a.docker.runCollect(ctx, "inspect", "--format", "{{.State.Status}} {{.State.ExitCode}}", name) + statusParts := strings.Fields(strings.TrimSpace(statusOut)) + if len(statusParts) == 0 { + if time.Now().Before(deadline) { + continue + } + return nil + } + + status := statusParts[0] + exitStr := "0" + if len(statusParts) >= 2 { + exitStr = statusParts[1] + } + + switch status { + case "running": + return nil + case "created": + if time.Now().Before(deadline) { + continue + } + return nil + case "restarting": + logsOut := a.recentContainerLogs(ctx, name, 50) + fmt.Printf("[docker] container %s is restarting after startup; leaving restart policy active and not blocking start. Last logs:\n%s\n", name, logsOut) + return nil + case "exited", "dead": + logsOut := a.recentContainerLogs(ctx, name, 50) + fmt.Printf("[docker] container exited after startup. Last logs:\n%s\n", logsOut) + logSummary := strings.TrimSpace(logsOut) + if len(logSummary) > 1800 { + logSummary = logSummary[len(logSummary)-1800:] + } + if logSummary != "" { + logSummary = "; last logs: " + logSummary + } + return fmt.Errorf("container exited immediately with code %s%s", exitStr, logSummary) + default: + if time.Now().Before(deadline) { + continue + } + return nil + } + } +} + +func customBootstrapFailureReason(logs string) string { + lower := strings.ToLower(strings.TrimSpace(logs)) + if lower == "" { + return "" + } + + if strings.Contains(lower, "state is 0x202 after update job") && + (strings.Contains(lower, "srcds_run: no such file or directory") || + strings.Contains(lower, "tar:") || + strings.Contains(lower, "server.cfg: no such file or directory")) { + return "SteamCMD/app install failed and the expected server files are missing" + } + + fatalPatterns := []string{ + "executable file not found", + "error during container init", + "stat ", + "no such file or directory", + "permission denied", + "error is not recoverable", + "cannot open: no such file or directory", + "is not a directory", + "srcds_run: no such file or directory", + "server.cfg: no such file or directory", + } + score := 0 + primary := "" + for _, line := range strings.Split(lower, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + for _, pattern := range fatalPatterns { + if strings.Contains(line, pattern) { + score++ + if primary == "" { + primary = strings.TrimSpace(line) + } + break + } + } + } + if score >= 4 { + if primary != "" { + return primary + } + return "repeated fatal startup errors detected" + } + return "" +} + +func logsSuggestBootstrapInProgress(logs string) bool { + lower := strings.ToLower(strings.TrimSpace(logs)) + if lower == "" { + return false + } + patterns := []string{ + "downloading update", + "installing update", + "extracting package", + "steam console client", + "steamcmd", + "app_update", + "installing", + "extracting", + "downloading", + "npm install", + "pip install", + "apt-get", + "apk add", + "composer install", + } + for _, pattern := range patterns { + if strings.Contains(lower, pattern) { + return true + } + } + return false +} + +func summarizeStartupLogs(logs string, maxLen int) string { + clean := strings.TrimSpace(logs) + if clean == "" { + return "" + } + if maxLen <= 0 { + maxLen = 1800 + } + if len(clean) > maxLen { + clean = clean[len(clean)-maxLen:] + } + return clean +} + +type boundedLogWriter struct { + mu sync.Mutex + buf []byte + max int +} + +func newBoundedLogWriter(max int) *boundedLogWriter { + if max <= 0 { + max = 64 * 1024 + } + return &boundedLogWriter{max: max} +} + +func (w *boundedLogWriter) Write(p []byte) (int, error) { + w.mu.Lock() + defer w.mu.Unlock() + w.buf = append(w.buf, p...) + if len(w.buf) > w.max { + w.buf = append([]byte(nil), w.buf[len(w.buf)-w.max:]...) + } + return len(p), nil +} + +func (w *boundedLogWriter) String() string { + w.mu.Lock() + defer w.mu.Unlock() + return string(append([]byte(nil), w.buf...)) +} + +type setupConsoleWriter struct { + agent *Agent + name string + prefix string + mu sync.Mutex + partial string +} + +func newSetupConsoleWriter(agent *Agent, name, prefix string) *setupConsoleWriter { + prefix = strings.TrimSuffix(strings.TrimSpace(prefix), ":") + if prefix != "stderr" { + prefix = "stdout" + } + return &setupConsoleWriter{agent: agent, name: name, prefix: prefix} +} + +func (w *setupConsoleWriter) Write(p []byte) (int, error) { + if w == nil || w.agent == nil || w.name == "" { + return len(p), nil + } + w.mu.Lock() + defer w.mu.Unlock() + + data := w.partial + string(p) + data = strings.ReplaceAll(data, "\r\n", "\n") + data = strings.ReplaceAll(data, "\r", "\n") + parts := strings.Split(data, "\n") + if strings.HasSuffix(data, "\n") { + w.partial = "" + } else { + w.partial = parts[len(parts)-1] + parts = parts[:len(parts)-1] + } + for _, line := range parts { + w.agent.emitSetupLog(w.name, w.prefix, line) + } + return len(p), nil +} + +func (w *setupConsoleWriter) Flush() { + if w == nil || w.agent == nil || w.name == "" { + return + } + w.mu.Lock() + line := w.partial + w.partial = "" + w.mu.Unlock() + if strings.TrimSpace(line) != "" { + w.agent.emitSetupLog(w.name, w.prefix, line) + } +} + +func normalizeTemplateInstallConfig(raw *templateInstallConfig) *templateInstallConfig { + if raw == nil { + return nil + } + script := strings.TrimSpace(strings.ReplaceAll(raw.Script, "\r\n", "\n")) + script = strings.ReplaceAll(script, "\r", "\n") + if script == "" { + return nil + } + if len(script) > 262144 { + script = script[:262144] + } + + image := strings.TrimSpace(raw.Image) + if image == "" { + image = strings.TrimSpace(raw.Container) + } + if image == "" { + image = "ghcr.io/pterodactyl/installers:debian" + } + if strings.ContainsAny(image, " \t\r\n\x00") { + return nil + } + + mountPath := normalizeContainerWorkdir(raw.MountPath) + if mountPath == "" { + mountPath = normalizeContainerWorkdir(raw.ContainerPath) + } + if mountPath == "" { + mountPath = "/mnt/server" + } + runtimePath := normalizeContainerWorkdir(raw.RuntimePath) + if runtimePath == "" { + runtimePath = "/home/container" + } + minimumStorageMb := raw.MinimumStorageMb + if minimumStorageMb < 0 { + minimumStorageMb = 0 + } + timeoutSeconds := raw.TimeoutSeconds + if timeoutSeconds <= 0 { + timeoutSeconds = 1800 + } + if timeoutSeconds < 60 { + timeoutSeconds = 60 + } + if timeoutSeconds > 7200 { + timeoutSeconds = 7200 + } + + env := map[string]string{} + for key, value := range raw.Env { + envKey := strings.TrimSpace(key) + if envKey == "" || strings.ContainsAny(envKey, "\x00=\r\n") { + continue + } + env[envKey] = value + } + + clean := &templateInstallConfig{ + Image: image, + Script: script, + MountPath: mountPath, + RuntimePath: runtimePath, + TimeoutSeconds: timeoutSeconds, + MinimumStorageMb: minimumStorageMb, + AllowEmpty: raw.AllowEmpty || raw.AllowEmptyResult, + } + if len(env) > 0 { + clean.Env = env + } + return clean +} + +func dockerTemplateInstall(cfg *dockerTemplateConfig) *templateInstallConfig { + if cfg == nil { + return nil + } + if install := normalizeTemplateInstallConfig(cfg.Install); install != nil { + return install + } + return normalizeTemplateInstallConfig(cfg.Installation) +} + +func installConfigFromRuntime(runtimeObj map[string]any) *templateInstallConfig { + if runtimeObj == nil { + return nil + } + raw, ok := runtimeObj["install"] + if !ok || raw == nil { + return nil + } + if install, ok := raw.(*templateInstallConfig); ok { + return normalizeTemplateInstallConfig(install) + } + b, err := json.Marshal(raw) + if err != nil { + return nil + } + var install templateInstallConfig + if err := json.Unmarshal(b, &install); err != nil { + return nil + } + return normalizeTemplateInstallConfig(&install) +} + +func runtimeImageRef(runtimeObj map[string]any) string { + if runtimeObj == nil { + return "" + } + image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + if image == "" || image == "" { + return "" + } + tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) + if tag == "" || tag == "" { + tag = "latest" + } + return image + ":" + tag +} + +func safeInstallerContainerName(serverName string) string { + base := sanitizeName(serverName) + if base == "" { + base = "server" + } + suffix := strconv.FormatInt(time.Now().UnixNano(), 36) + name := "adpanel-install-" + base + "-" + suffix + if len(name) > 120 { + name = name[:120] + } + return name +} + +func adpanelStartupDefaultEnv(name string, hostPort int, resources *resourceLimits, startup string) map[string]string { + env := map[string]string{ + "TZ": "Etc/UTC", + "SERVER_IP": "0.0.0.0", + "P_SERVER_LOCATION": "ADPanel", + "P_SERVER_ALLOCATION_LIMIT": "0", + "P_SERVER_UUID": name, + "P_SERVER_UUID_SHORT": name, + } + if hostPort > 0 { + env["SERVER_PORT"] = fmt.Sprint(hostPort) + env["PORT"] = fmt.Sprint(hostPort) + } + if resources != nil && resources.RamMb != nil && *resources.RamMb > 0 { + env["SERVER_MEMORY"] = fmt.Sprint(*resources.RamMb) + } + if strings.TrimSpace(startup) != "" { + env["STARTUP"] = startup + } + return env +} + +func mergeStringEnv(dst map[string]string, src map[string]string) map[string]string { + if dst == nil { + dst = map[string]string{} + } + for key, value := range src { + envKey := strings.TrimSpace(key) + if envKey == "" || strings.ContainsAny(envKey, "\x00=\r\n") { + continue + } + dst[envKey] = value + } + return dst +} + +func startupTemplateFromRuntime(runtimeObj map[string]any) string { + if runtimeObj == nil { + return "" + } + for _, key := range []string{"adpanelStartup", "adpanel_startup", "pterodactylStartup", "pterodactyl_startup"} { + value := strings.TrimSpace(fmt.Sprint(runtimeObj[key])) + if value != "" && value != "" { + return value + } + } + return "" +} + +func startupTemplateFromDockerConfig(cfg *dockerTemplateConfig) string { + if cfg == nil { + return "" + } + if startup := strings.TrimSpace(cfg.ADPanelStartup); startup != "" { + return startup + } + if startup := strings.TrimSpace(cfg.ADPanelStartupSnake); startup != "" { + return startup + } + if startup := strings.TrimSpace(cfg.LegacyStartup); startup != "" { + return startup + } + return strings.TrimSpace(cfg.LegacyStartupSnake) +} + +func startupDisplayFromDockerConfig(cfg *dockerTemplateConfig) string { + if cfg == nil { + return "" + } + for _, value := range []string{ + cfg.StartupDisplay, + cfg.StartupDisplaySnake, + cfg.StartupPreview, + cfg.StartupPreviewSnake, + cfg.ImageDefaultStartup, + cfg.ImageDefaultStartupSnake, + } { + if display := strings.TrimSpace(value); display != "" { + return display + } + } + return "" +} + +func javaVersionFromDockerConfig(cfg *dockerTemplateConfig) string { + if cfg == nil { + return "" + } + if version := strings.TrimSpace(cfg.JavaVersion); version != "" { + return version + } + return strings.TrimSpace(cfg.Java) +} + +func freeDiskMb(path string) int64 { + var stat syscall.Statfs_t + if err := syscall.Statfs(path, &stat); err != nil { + return 0 + } + return int64(stat.Bavail) * int64(stat.Bsize) / (1024 * 1024) +} + +func renderADPanelStartupTemplate(startup string, env map[string]string, hostPort int) string { + rendered := strings.TrimSpace(startup) + if rendered == "" { + return "" + } + values := map[string]string{} + for key, value := range env { + values[strings.TrimSpace(key)] = value + } + if hostPort > 0 { + values["SERVER_PORT"] = fmt.Sprint(hostPort) + values["PORT"] = fmt.Sprint(hostPort) + } + + replacer := regexp.MustCompile(`\{\{\s*([A-Za-z0-9_.-]+)\s*\}\}`) + rendered = replacer.ReplaceAllStringFunc(rendered, func(token string) string { + match := replacer.FindStringSubmatch(token) + if len(match) != 2 { + return token + } + key := strings.TrimSpace(match[1]) + switch key { + case "server.build.default.port": + if hostPort > 0 { + return fmt.Sprint(hostPort) + } + return token + } + if strings.HasPrefix(key, "env.") { + key = strings.TrimPrefix(key, "env.") + } + if value, ok := values[key]; ok { + return value + } + return token + }) + return rendered +} + +func (a *Agent) emitSetupLog(name, prefix, message string) { + if a == nil || a.logs == nil { + return + } + name = sanitizeName(name) + if name == "" { + return + } + prefix = strings.TrimSuffix(strings.TrimSpace(prefix), ":") + if prefix != "stderr" { + prefix = "stdout" + } + message = strings.ReplaceAll(message, "\r\n", "\n") + message = strings.ReplaceAll(message, "\r", "\n") + t := a.logs.getOrCreate(name) + for _, line := range strings.Split(message, "\n") { + line = strings.TrimRight(line, " \t") + plain := strings.TrimSpace(ansiSGRRE.ReplaceAllString(line, "")) + if plain == "" { + continue + } + a.logs.sendToClients(t, prefix+":[ADPanel Setup] "+line) + } +} + +func (a *Agent) checkTemplateInstallPreflight(name, serverDir string, install *templateInstallConfig) error { + install = normalizeTemplateInstallConfig(install) + if install == nil { + return nil + } + if err := ensureDir(serverDir); err != nil { + return err + } + ensureVolumeWritable(serverDir) + if install.MinimumStorageMb > 0 { + freeMb := freeDiskMb(serverDir) + if freeMb > 0 && freeMb < int64(install.MinimumStorageMb) { + return fmt.Errorf("not enough free disk for installer: template requires at least %d MB, host has %d MB free", install.MinimumStorageMb, freeMb) + } + } + return nil +} + +func (a *Agent) pullSetupImage(name, serverDir, imageRef, label string, timeout time.Duration) error { + imageRef = strings.TrimSpace(imageRef) + if imageRef == "" { + return nil + } + label = strings.TrimSpace(label) + if label == "" { + label = "Docker" + } + if timeout <= 0 { + timeout = 10 * time.Minute + } + a.updateSetupState(name, serverDir, "pulling", fmt.Sprintf("Pulling %s image %s", label, imageRef)) + ctx, cancel := context.WithTimeout(context.Background(), timeout) + err := a.docker.ensureImageAvailableAPI(ctx, imageRef) + cancel() + if err != nil { + return fmt.Errorf("%s image pull failed: %w", label, err) + } + a.emitSetupLog(name, "stdout", fmt.Sprintf("%s image ready: %s", label, imageRef)) + return nil +} + +func installerScriptPreferredShell(script string) string { + clean := strings.TrimSpace(strings.ReplaceAll(script, "\r\n", "\n")) + if clean == "" { + return "sh" + } + + if strings.HasPrefix(clean, "#!") { + firstLine := strings.TrimSpace(strings.SplitN(clean, "\n", 2)[0]) + firstLine = strings.TrimSpace(strings.TrimPrefix(firstLine, "#!")) + for _, token := range strings.Fields(firstLine) { + base := strings.ToLower(path.Base(strings.TrimSpace(token))) + switch base { + case "bash", "zsh", "ksh": + return base + case "sh", "ash", "dash": + return "sh" + } + } + } + + lower := strings.ToLower(clean) + if strings.Contains(lower, "[[") || + strings.Contains(lower, "function ") || + strings.Contains(lower, "source ") || + strings.Contains(lower, "set -o pipefail") { + return "bash" + } + return "sh" +} + +func installerShellCommandFlag(shell string) string { + switch strings.ToLower(path.Base(strings.TrimSpace(shell))) { + case "bash", "zsh", "ksh": + return "-lc" + default: + return "-c" + } +} + +func installerDefaultCommandArgs(entrypoint []string, script string) []string { + ep := trimRuntimeProcessArgs(entrypoint) + if len(ep) == 0 { + shell := installerScriptPreferredShell(script) + return []string{shell, installerShellCommandFlag(shell), script} + } + execIndex := 0 + if strings.EqualFold(path.Base(ep[0]), "env") && len(ep) > 1 { + execIndex = 1 + } + base := strings.ToLower(path.Base(ep[execIndex])) + if base == "bash" || base == "zsh" || base == "ksh" || base == "sh" || base == "ash" || base == "dash" { + if len(ep) > execIndex+1 && strings.HasPrefix(ep[execIndex+1], "-") && strings.Contains(ep[execIndex+1], "c") { + return []string{script} + } + return []string{installerShellCommandFlag(base), script} + } + return []string{script} +} + +func (a *Agent) runTemplateInstall(name, serverDir string, install *templateInstallConfig, runtimeObj map[string]any, hostPort int, resources *resourceLimits) error { + install = normalizeTemplateInstallConfig(install) + if install == nil { + return nil + } + if err := ensureDir(serverDir); err != nil { + return err + } + ensureVolumeWritable(serverDir) + + startup := startupTemplateFromRuntime(runtimeObj) + env := adpanelStartupDefaultEnv(name, hostPort, resources, startup) + env = mergeStringEnv(env, runtimeEnvMap(runtimeObj["env"])) + env = mergeStringEnv(env, install.Env) + tpl := strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["providerId"]))) + applyRuntimeHostPortEnv(tpl, env, hostPort) + renderRuntimeEnvTemplates(tpl, env, hostPort) + if startup != "" { + env["STARTUP"] = renderADPanelStartupTemplate(startup, env, hostPort) + } + if err := a.checkTemplateInstallPreflight(name, serverDir, install); err != nil { + return err + } + + ctx, cancel := context.WithTimeout(context.Background(), time.Duration(install.TimeoutSeconds)*time.Second) + defer cancel() + + a.emitSetupLog(name, "stdout", "Preparing template installer") + if err := a.docker.ensureImageAvailableAPI(ctx, install.Image); err != nil { + return fmt.Errorf("installer image pull failed: %w", err) + } + a.emitSetupLog(name, "stdout", "Running template installer in "+install.Image) + imgCfg := a.inspectRuntimeImageConfig(ctx, install.Image) + installerCmdArgs := installerDefaultCommandArgs(imgCfg.Entrypoint, install.Script) + + containerName := safeInstallerContainerName(name) + defer a.docker.rmForce(context.Background(), containerName) + + args := []string{ + "run", "--rm", + "--name", containerName, + "-v", fmt.Sprintf("%s:%s", serverDir, install.MountPath), + "-w", install.MountPath, + } + for key, value := range env { + args = append(args, "-e", fmt.Sprintf("%s=%s", key, value)) + } + args = append(args, install.Image) + args = append(args, installerCmdArgs...) + + logs := newBoundedLogWriter(96 * 1024) + stdoutLog := newSetupConsoleWriter(a, name, "stdout") + stderrLog := newSetupConsoleWriter(a, name, "stderr") + cmd := exec.CommandContext(ctx, "docker", args...) + cmd.Stdout = io.MultiWriter(logs, stdoutLog) + cmd.Stderr = io.MultiWriter(logs, stderrLog) + err := cmd.Run() + stdoutLog.Flush() + stderrLog.Flush() + if err != nil { + if ctx.Err() == context.DeadlineExceeded { + return fmt.Errorf("template installer timed out after %ds; last logs: %s", install.TimeoutSeconds, summarizeStartupLogs(logs.String(), 2400)) + } + return fmt.Errorf("template installer failed: %w; last logs: %s", err, summarizeStartupLogs(logs.String(), 2400)) + } + + ensureVolumeWritable(serverDir) + if count := serverDirVisibleFileCount(serverDir); count == 0 && !install.AllowEmpty { + return fmt.Errorf("template installer completed but did not create any visible server files in %s; last logs: %s", install.MountPath, summarizeStartupLogs(logs.String(), 2400)) + } else if count == 0 { + a.emitSetupLog(name, "stdout", "Installer completed without visible files; continuing because allowEmpty is enabled") + } + a.emitSetupLog(name, "stdout", "Template installer completed") + fmt.Printf("[installer] template install completed for %s using %s into %s\n", name, install.Image, install.MountPath) + return nil +} + +func (a *Agent) updateSetupState(name, serverDir, status, message string) { + meta := a.loadMeta(serverDir) + if meta == nil { + meta = map[string]any{} + } + status = strings.TrimSpace(status) + message = strings.TrimSpace(message) + if status == "" { + delete(meta, "setupStatus") + } else { + meta["setupStatus"] = status + } + if message == "" { + delete(meta, "setupMessage") + } else { + meta["setupMessage"] = message + } + meta["setupUpdatedAt"] = time.Now().UnixMilli() + if err := a.saveMeta(serverDir, meta); err != nil { + fmt.Printf("[setup] failed to update setup state for %s: %v\n", name, err) + } + if status != "" { + line := status + if message != "" { + line += ": " + message + } + prefix := "stdout" + if strings.EqualFold(status, "failed") { + prefix = "stderr" + } + a.emitSetupLog(name, prefix, line) + } +} + +func (a *Agent) prepareMinecraftCreateSetup(req createReq, name, serverDir string, meta map[string]any) bool { + runtimeObj, _ := meta["runtime"].(map[string]any) + imageRef := runtimeImageRef(runtimeObj) + if imageRef != "" { + if err := a.pullSetupImage(name, serverDir, imageRef, "runtime", 10*time.Minute); err != nil { + a.updateSetupState(name, serverDir, "failed", err.Error()) + fmt.Printf("[setup] Minecraft runtime image pull failed for %s: %v\n", name, err) + return false + } + } + a.updateSetupState(name, serverDir, "queued", "Docker image ready; Minecraft setup will continue in the background") + return true +} + +func (a *Agent) prepareCustomCreateSetup(req createReq, name, serverDir string, meta map[string]any) bool { + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + runtimeObj = map[string]any{} + } + a.updateSetupState(name, serverDir, "preparing", "Preparing Docker template") + if install := installConfigFromRuntime(runtimeObj); install != nil { + if err := a.checkTemplateInstallPreflight(name, serverDir, install); err != nil { + a.updateSetupState(name, serverDir, "failed", err.Error()) + fmt.Printf("[setup] Template preflight failed for %s: %v\n", name, err) + return false + } + if err := a.pullSetupImage(name, serverDir, install.Image, "installer", 10*time.Minute); err != nil { + a.updateSetupState(name, serverDir, "failed", err.Error()) + fmt.Printf("[setup] Template installer image pull failed for %s: %v\n", name, err) + return false + } + } + if imageRef := runtimeImageRef(runtimeObj); imageRef != "" { + if err := a.pullSetupImage(name, serverDir, imageRef, "runtime", 10*time.Minute); err != nil { + a.updateSetupState(name, serverDir, "failed", err.Error()) + fmt.Printf("[setup] Runtime image pull failed for %s: %v\n", name, err) + return false + } + } + a.updateSetupState(name, serverDir, "queued", "Docker images ready; setup will continue in the background") + return true +} + +func (a *Agent) finishMinecraftCreateSetup(req createReq, name, serverDir string, meta map[string]any, hostPort int) { + fork := strings.TrimSpace(req.MCFork) + if fork == "" { + fork = "paper" + } + ver := strings.TrimSpace(req.MCVersion) + if ver == "" { + ver = "1.21.8" + } + + a.updateSetupState(name, serverDir, "downloading", "Downloading Minecraft server files") + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + jarURL := getMinecraftJarURL(ctx, a.dl, fork, ver, a.debug) + cancel() + + ctxD, cancelD := context.WithTimeout(context.Background(), 30*time.Minute) + if err := a.dl.downloadToFile(ctxD, jarURL, filepath.Join(serverDir, "server.jar")); err != nil { + cancelD() + a.updateSetupState(name, serverDir, "failed", err.Error()) + fmt.Printf("[setup] Minecraft download failed for %s: %v\n", name, err) + return + } + cancelD() + + enforceServerProps(serverDir) + + if req.ImportUrl != "" { + a.updateSetupState(name, serverDir, "importing", "Importing archive") + if err := a.downloadAndExtractArchiveSync(name, serverDir, req.ImportUrl); err != nil { + a.updateSetupState(name, serverDir, "failed", "archive import failed: "+err.Error()) + fmt.Printf("[setup] Minecraft archive import failed for %s: %v\n", name, err) + return + } + } + + if req.AutoStart { + a.updateSetupState(name, serverDir, "starting", "Starting container") + ctxStart, cancelStart := context.WithTimeout(context.Background(), 240*time.Second) + err := a.startMinecraftContainer(ctxStart, name, serverDir, hostPort, req.Resources, nil) + cancelStart() + if err != nil { + a.updateSetupState(name, serverDir, "failed", err.Error()) + fmt.Printf("[setup] Minecraft startup failed for %s: %v\n", name, err) + return + } + a.ensureLiveLogs(name) + } + + a.updateSetupState(name, serverDir, "ready", "Server setup complete") + auditLog.Log("server_setup", "127.0.0.1", "", name, "setup", "success", map[string]any{"template": req.Template}) +} + +func (a *Agent) finishCustomCreateSetup(req createReq, name, serverDir string, meta map[string]any, hostPort int) { + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + runtimeObj = map[string]any{} + } + if install := installConfigFromRuntime(runtimeObj); install != nil { + a.updateSetupState(name, serverDir, "installing", "Installing server files") + if err := a.runTemplateInstall(name, serverDir, install, runtimeObj, hostPort, req.Resources); err != nil { + a.updateSetupState(name, serverDir, "failed", err.Error()) + fmt.Printf("[setup] Template install failed for %s: %v\n", name, err) + return + } + } + + if req.ImportUrl != "" { + a.updateSetupState(name, serverDir, "importing", "Importing archive") + if err := a.downloadAndExtractArchiveSync(name, serverDir, req.ImportUrl); err != nil { + a.updateSetupState(name, serverDir, "failed", "archive import failed: "+err.Error()) + fmt.Printf("[setup] Archive import failed for %s: %v\n", name, err) + return + } + } + + template := strings.ToLower(strings.TrimSpace(req.Template)) + switch template { + case "python": + scaffoldPython(serverDir, defaultStartFileForType(template)) + case "nodejs", "discord-bot": + scaffoldNode(serverDir, defaultStartFileForType(template), hostPort) + } + + hasImage := req.Docker != nil && strings.TrimSpace(req.Docker.Image) != "" + if req.AutoStart && hasImage { + a.updateSetupState(name, serverDir, "starting", "Starting container") + ctxStart, cancelStart := context.WithTimeout(context.Background(), 240*time.Second) + var err error + if isManagedProcessRuntime(template) { + err = a.startRuntimeContainer(ctxStart, name, serverDir, meta, hostPort, req.Resources, nil) + } else { + err = a.startCustomDockerContainer(ctxStart, name, serverDir, meta, hostPort, req.Resources) + } + cancelStart() + if err != nil { + a.updateSetupState(name, serverDir, "failed", err.Error()) + fmt.Printf("[setup] Container startup failed for %s: %v\n", name, err) + return + } + a.ensureLiveLogs(name) + } + + a.updateSetupState(name, serverDir, "ready", "Server setup complete") + auditLog.Log("server_setup", "127.0.0.1", "", name, "setup", "success", map[string]any{"template": req.Template}) +} + +func (a *Agent) monitorCustomContainerBootstrap(ctx context.Context, name, imageRef string) error { + started := time.Now() + defaultWindow := 18 * time.Second + bootstrapWindow := 115 * time.Second + if isGameServerDockerImage(imageRef) { + bootstrapWindow = 150 * time.Second + } + + seenBootstrap := false + ticker := time.NewTicker(2 * time.Second) + defer ticker.Stop() + + for { + select { + case <-ctx.Done(): + logCtx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + logsOut := a.recentContainerLogs(logCtx, name, 160) + cancel() + return fmt.Errorf("container bootstrap did not become stable before timeout; last logs: %s", summarizeStartupLogs(logsOut, 1800)) + case <-ticker.C: + } + + statusOut, _, _, _ := a.docker.runCollect(ctx, "inspect", "--format", "{{.State.Status}} {{.State.ExitCode}}", name) + statusParts := strings.Fields(strings.TrimSpace(statusOut)) + status := "" + exitStr := "0" + if len(statusParts) > 0 { + status = statusParts[0] + } + if len(statusParts) > 1 { + exitStr = statusParts[1] + } + + logsOut := a.recentContainerLogs(ctx, name, 160) + if logsSuggestBootstrapInProgress(logsOut) { + seenBootstrap = true + } + if reason := customBootstrapFailureReason(logsOut); reason != "" { + return fmt.Errorf("container bootstrap failed: %s; last logs: %s", reason, summarizeStartupLogs(logsOut, 1800)) + } + + switch status { + case "restarting": + if time.Since(started) >= defaultWindow { + fmt.Printf("[docker] %s is restarting during bootstrap; not blocking startup.\n", name) + return nil + } + continue + case "exited", "dead": + if status == "" { + status = "unknown" + } + return fmt.Errorf("container stopped during bootstrap (%s, exit code %s); last logs: %s", status, exitStr, summarizeStartupLogs(logsOut, 1800)) + case "running": + elapsed := time.Since(started) + if seenBootstrap { + if elapsed >= bootstrapWindow { + return nil + } + continue + } + if elapsed >= defaultWindow { + return nil + } + case "created", "": + if time.Since(started) > defaultWindow { + return nil + } + default: + if time.Since(started) > defaultWindow { + return nil + } + } + } +} + +func (a *Agent) startMinecraftContainer(ctx context.Context, name, serverDir string, hostPort int, resources *resourceLimits, extraEnv map[string]string) error { + a.docker.rmForce(ctx, name) + meta := a.loadMeta(serverDir) + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + runtimeObj = make(map[string]any) + } + + ensureVolumeWritable(serverDir) + uid, gid := statUIDGID(serverDir) + + commandTemplate := sanitizeRuntimeCommand(runtimeObj["command"]) + image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) + rawJavaVersion := strings.TrimSpace(fmt.Sprint(runtimeObj["javaVersion"])) + selectedJavaVersion := normalizeMinecraftJavaVersion(rawJavaVersion) + if rawJavaVersion != "" && rawJavaVersion != "" && selectedJavaVersion == "" { + return fmt.Errorf("unsupported minecraft java version: %s", rawJavaVersion) + } + if selectedJavaVersion != "" { + image = defaultMinecraftProcessImage + tag = minecraftJavaTag(selectedJavaVersion) + runtimeObj["image"] = image + runtimeObj["tag"] = tag + runtimeObj["javaVersion"] = selectedJavaVersion + } + useLegacyImageMode := false + + if image == "" || image == "" { + if commandTemplate == "" { + image = "itzg/minecraft-server" + tag = "latest" + useLegacyImageMode = true + } else { + image = defaultMinecraftProcessImage + tag = defaultMinecraftProcessTag + } + } + if tag == "" || tag == "" { + if strings.EqualFold(image, "itzg/minecraft-server") && commandTemplate == "" { + tag = "latest" + useLegacyImageMode = true + } else { + tag = defaultMinecraftProcessTag + } + } + if strings.EqualFold(image, "itzg/minecraft-server") && commandTemplate == "" { + useLegacyImageMode = true + } + + imageRef := image + ":" + tag + binds, dataDir := a.resolveStructuredBinds("minecraft", runtimeObj, serverDir) + workdir := normalizeContainerWorkdir(runtimeObj["workdir"]) + if workdir == "" { + workdir = dataDir + } + startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) + if startFile == "" || startFile == "" { + startFile = "server.jar" + } + + env := runtimeEnvMap(runtimeObj["env"]) + if env == nil { + env = map[string]string{} + } + for k, v := range extraEnv { + env[strings.TrimSpace(k)] = v + } + + req := dockerContainerCreateRequest{ + Image: imageRef, + Tty: containerTTYForHost(), + OpenStdin: true, + AttachStdin: true, + AttachStdout: true, + AttachStderr: true, + WorkingDir: workdir, + } + + if useLegacyImageMode { + if _, ok := env["EULA"]; !ok { + env["EULA"] = "TRUE" + } + if _, ok := env["TYPE"]; !ok { + env["TYPE"] = "CUSTOM" + } + if _, ok := env["CUSTOM_SERVER"]; !ok { + env["CUSTOM_SERVER"] = "/data/server.jar" + } + if _, ok := env["ENABLE_RCON"]; !ok { + env["ENABLE_RCON"] = "false" + } + if _, ok := env["CREATE_CONSOLE_IN_PIPE"]; !ok { + env["CREATE_CONSOLE_IN_PIPE"] = "true" + } + if _, ok := env["UID"]; !ok { + env["UID"] = fmt.Sprint(uid) + } + if _, ok := env["GID"]; !ok { + env["GID"] = fmt.Sprint(gid) + } + } else { + if commandTemplate == "" { + commandTemplate = defaultRuntimeCommandForType("minecraft", startFile, dataDir) + } + cmdArgs, err := buildRenderedRuntimeProcessArgs("minecraft", commandTemplate, dataDir, startFile, imageRef, hostPort, resources, meta) + if err != nil { + return err + } + req.User = a.structuredContainerUser(ctx, imageRef, uid, gid, runtimeObj) + req.Cmd = cmdArgs + } + + portBindings, exposedPorts := a.buildStructuredPortBindings(serverDir, meta, hostPort, 25565) + req.ExposedPorts = exposedPorts + req.HostConfig = buildStructuredHostConfig( + binds, + portBindings, + resources, + strings.TrimSpace(fmt.Sprint(runtimeObj["restart"])), + false, + ) + req.Env = envMapToList(env) + + if err := a.runStructuredContainerWithCompatUser(ctx, name, req); err != nil { + return err + } + return nil +} + +func (a *Agent) startRuntimeContainer(ctx context.Context, name, serverDir string, meta map[string]any, hostPort int, resources *resourceLimits, extraEnv map[string]string) error { + a.docker.rmForce(ctx, name) + + runtimeObj, _ := meta["runtime"].(map[string]any) + tpl := strings.ToLower(fmt.Sprint(meta["type"])) + if tpl == "" { + tpl = strings.ToLower(fmt.Sprint(runtimeObj["providerId"])) + } + isPython := tpl == "python" + + image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) + if image == "" { + if isPython { + image = "python" + } else { + image = "node" + } + } + if tag == "" { + if isPython { + tag = "3.12-slim" + } else { + tag = "20-alpine" + } + } + imageRef := image + if tag != "" { + imageRef = image + ":" + tag + } + ensureVolumeWritable(serverDir) + + effectivePort := 0 + if hostPort > 0 { + effectivePort = hostPort + } + + binds, dataDir := a.resolveStructuredBinds(tpl, runtimeObj, serverDir) + workdir := normalizeContainerWorkdir(runtimeObj["workdir"]) + if workdir == "" { + workdir = dataDir + } + + env := runtimeEnvMap(runtimeObj["env"]) + if env == nil { + env = map[string]string{} + } + for k, v := range extraEnv { + env[strings.TrimSpace(k)] = v + } + if effectivePort > 0 { + applyRuntimeHostPortEnv(tpl, env, effectivePort) + renderRuntimeEnvTemplates(tpl, env, effectivePort) + } + + startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) + if startFile == "" || startFile == "" { + startFile = defaultStartFileForType(tpl) + } + + commandTemplate := sanitizeRuntimeCommand(runtimeObj["command"]) + if commandTemplate == "" { + commandTemplate = defaultRuntimeCommandForType(tpl, startFile, dataDir) + } + ensureRuntimeEntrypointScaffold(serverDir, tpl, commandTemplate, dataDir, workdir, startFile, effectivePort) + cmdArgs, err := buildRenderedRuntimeProcessArgs(tpl, commandTemplate, dataDir, startFile, imageRef, effectivePort, resources, meta) + if err != nil { + return err + } + uid, gid := statUIDGID(serverDir) + req := dockerContainerCreateRequest{ + Image: imageRef, + Env: envMapToList(env), + Cmd: cmdArgs, + WorkingDir: workdir, + User: a.structuredContainerUser(ctx, imageRef, uid, gid, runtimeObj), + Tty: containerTTYForHost(), + OpenStdin: true, + AttachStdin: true, + AttachStdout: true, + AttachStderr: true, + } + portBindings, exposedPorts := a.buildStructuredPortBindings(serverDir, meta, effectivePort, effectivePort) + req.ExposedPorts = exposedPorts + req.HostConfig = buildStructuredHostConfig( + binds, + portBindings, + resources, + strings.TrimSpace(fmt.Sprint(runtimeObj["restart"])), + false, + ) + + if err := a.runStructuredContainerWithCompatUser(ctx, name, req); err != nil { + return err + } + return nil +} + +func matchesBlockedFlag(flag string, denylist map[string]bool) (bool, string) { + if !strings.HasPrefix(flag, "--") || len(flag) <= 2 { + return false, "" + } + for blocked := range denylist { + if strings.HasPrefix(blocked, flag) { + return true, blocked + } + } + return false, "" +} + +var legacyRawDockerStartupCommandsDisabled = true + +func (a *Agent) executeStartupCommand(ctx context.Context, name, serverDir string, hostPort int, startupCmd string, resources *resourceLimits, meta map[string]any) error { + if legacyRawDockerStartupCommandsDisabled { + fmt.Printf("[security] blocked legacy raw docker startup command path for %s\n", name) + return fmt.Errorf("raw docker startup commands are disabled; configure image, ports, volumes, env, and the in-container process separately") + } + if a.debug { + fmt.Printf("[docker] executeStartupCommand called for %s\n", name) + fmt.Printf("[docker] serverDir: %s\n", serverDir) + } + + a.docker.rmForce(ctx, name) + + cmd := startupCmd + cmd = strings.ReplaceAll(cmd, "{SERVER_NAME}", name) + cmd = strings.ReplaceAll(cmd, "{PORT}", fmt.Sprint(hostPort)) + cmd = strings.ReplaceAll(cmd, "{DATA_DIR}", serverDir) + cmd = strings.ReplaceAll(cmd, "{BOT_DIR}", serverDir) + cmd = strings.ReplaceAll(cmd, "{SERVER_DIR}", serverDir) + + ramMb := 0 + cpuCores := float64(0) + if resources != nil { + if resources.RamMb != nil { + ramMb = *resources.RamMb + } + if resources.CpuCores != nil { + cpuCores = *resources.CpuCores + } + } + cmd = strings.ReplaceAll(cmd, "{RAM_MB}", fmt.Sprint(ramMb)) + cmd = strings.ReplaceAll(cmd, "{CPU_CORES}", fmt.Sprintf("%.1f", cpuCores)) + + runtimeObj, _ := meta["runtime"].(map[string]any) + image := "" + if v := runtimeObj["image"]; v != nil { + image = strings.TrimSpace(fmt.Sprint(v)) + if image == "" { + image = "" + } + } + tag := "" + if v := runtimeObj["tag"]; v != nil { + tag = strings.TrimSpace(fmt.Sprint(v)) + if tag == "" { + tag = "" + } + } + if tag == "" { + tag = "latest" + } + imageRef := image + ":" + tag + cmd = strings.ReplaceAll(cmd, "{IMAGE}", imageRef) + + allowedHostPorts := make([]int, 0, 8) + if port, ok := parseStrictPortValue(hostPort); ok { + allowedHostPorts = append(allowedHostPorts, port) + } + if metaRes, ok := meta["resources"].(map[string]any); ok { + for _, port := range runtimeIntSlice(metaRes["ports"]) { + if port > 0 { + allowedHostPorts = append(allowedHostPorts, port) + } + } + } + reservedHostPorts := make([]int, 0, 4) + for _, pf := range a.loadPortForwards(serverDir) { + if port, ok := parseStrictPortValue(pf.Public); ok { + reservedHostPorts = append(reservedHostPorts, port) + } + } + expectedImageRef := "" + if image != "" { + expectedImageRef = imageRef + } + + cmd = strings.TrimSpace(cmd) + if safetyViolation := validateDockerRunCommandSafety(cmd, allowedHostPorts, reservedHostPorts, expectedImageRef); safetyViolation != "" { + return errors.New(safetyViolation) + } + cmdLower := strings.ToLower(cmd) + if !strings.HasPrefix(cmdLower, "docker run") { + return fmt.Errorf("startup command must start with 'docker run'") + } + + argsStr := cmd[len("docker run"):] + argsStr = strings.TrimSpace(argsStr) + + args := parseShellArgs(argsStr) + + dockerImage := "" + skipNext := false + flagsWithValue := map[string]bool{ + "-e": true, "--env": true, "-v": true, "--volume": true, + "-p": true, "--publish": true, "-w": true, "--workdir": true, + "--name": true, "-m": true, "--memory": true, "--cpus": true, + "--memory-swap": true, "--memory-reservation": true, "--cpu-period": true, "--cpu-quota": true, + "-u": true, "--user": true, "-h": true, "--hostname": true, + "--network": true, "--net": true, "--restart": true, + "-l": true, "--label": true, "--entrypoint": true, + "--mount": true, "--tmpfs": true, "--device": true, + "--pid": true, "--ipc": true, "--userns": true, "--uts": true, "--cgroupns": true, + "--shm-size": true, "--ulimit": true, "--dns": true, "--dns-search": true, + "--add-host": true, "--log-driver": true, "--log-opt": true, + "--stop-signal": true, "--stop-timeout": true, "--health-cmd": true, + "--health-interval": true, "--health-retries": true, "--health-timeout": true, + "--runtime": true, "--platform": true, "--pull": true, + "--ip": true, "--ip6": true, "--mac-address": true, + "--expose": true, "--link": true, "--cidfile": true, + } + + blockedFlags := map[string]bool{ + "--privileged": true, + "--cap-add": true, + "--cap-drop": true, + "--security-opt": true, + "--volumes-from": true, + "--env-file": true, + "--device": true, + "--device-cgroup-rule": true, + "--sysctl": true, + "--oom-kill-disable": true, + "--oom-score-adj": true, + } + + namespaceFlagsBlockHost := map[string]bool{ + "--network": true, + "--net": true, + "--pid": true, + "--userns": true, + "--ipc": true, + "--uts": true, + "--cgroupns": true, + } + + for i := 0; i < len(args); i++ { + arg := args[i] + if skipNext { + skipNext = false + continue + } + argLower := strings.ToLower(strings.TrimSpace(arg)) + flagName := argLower + flagValue := "" + if strings.HasPrefix(argLower, "--") { + if k, v, ok := strings.Cut(argLower, "="); ok { + flagName = k + flagValue = strings.TrimSpace(v) + } + } + + if strings.HasPrefix(argLower, "-") { + if blocked, match := matchesBlockedFlag(flagName, blockedFlags); blocked { + fmt.Printf("[security] blocked dangerous docker flag: %s (matches %s)\n", flagName, match) + return fmt.Errorf("blocked dangerous docker flag: %s", match) + } + } + + if matched, _ := matchesBlockedFlag(flagName, map[string]bool{"--mount": true}); matched || flagName == "--mount" { + mountVal := flagValue + if mountVal == "" && i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") { + mountVal = strings.ToLower(strings.TrimSpace(args[i+1])) + skipNext = true + } + mountVal = strings.ToLower(mountVal) + if strings.Contains(mountVal, "type=bind") { + fmt.Printf("[security] blocked --mount bind mount: %s\n", mountVal) + return fmt.Errorf("blocked dangerous docker flag: --mount with bind") + } + } + + if matched, _ := matchesBlockedFlag(flagName, map[string]bool{"--tmpfs": true}); matched || flagName == "--tmpfs" { + tmpfsVal := flagValue + if tmpfsVal == "" && i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") { + tmpfsVal = strings.ToLower(strings.TrimSpace(args[i+1])) + skipNext = true + } + if strings.Contains(strings.ToLower(tmpfsVal), "exec") { + fmt.Printf("[security] blocked --tmpfs with exec: %s\n", tmpfsVal) + return fmt.Errorf("blocked dangerous docker flag: --tmpfs with exec") + } + } + + if blocked, _ := matchesBlockedFlag(flagName, namespaceFlagsBlockHost); blocked { + nsMode := flagValue + if nsMode == "" && i+1 < len(args) && !strings.HasPrefix(args[i+1], "-") { + nsMode = strings.ToLower(strings.TrimSpace(args[i+1])) + skipNext = true + } + if nsMode == "host" { + fmt.Printf("[security] blocked namespace escape: %s=host\n", flagName) + return fmt.Errorf("blocked dangerous docker flag: %s=host", flagName) + } + } + + if strings.HasPrefix(argLower, "-") { + if strings.Contains(argLower, "=") { + continue + } + if flagsWithValue[flagName] { + skipNext = true + } + continue + } + dockerImage = arg + break + } + + if dockerImage == "" { + fmt.Printf("[docker] ERROR: could not find docker image in args: %v\n", args) + return fmt.Errorf("could not find docker image in startup command") + } + + if image != "" { + normalizedConfigured := normalizeDockerImage(imageRef) + normalizedCommand := normalizeDockerImage(dockerImage) + if normalizedConfigured != normalizedCommand { + fmt.Printf("[security] BLOCKED docker image mismatch at execution for %s: configured=%q command=%q\n", name, imageRef, dockerImage) + return fmt.Errorf("docker image mismatch: the startup command image does not match the server's configured image") + } + } + + if !a.docker.imageExistsLocally(ctx, dockerImage) { + fmt.Printf("[docker] pulling image: %s\n", dockerImage) + a.docker.pull(ctx, dockerImage) + } else { + fmt.Printf("[docker] image already available locally, skipping pull: %s\n", dockerImage) + } + + ensureVolumeWritable(serverDir) + + volumeContainerPaths := []string{} + for i, arg := range args { + if (arg == "-v" || arg == "--volume") && i+1 < len(args) { + volSpec := args[i+1] + parts := strings.Split(volSpec, ":") + if len(parts) >= 2 { + containerPath := parts[1] + if idx := strings.Index(containerPath, ":"); idx > 0 { + containerPath = containerPath[:idx] + } + volumeContainerPaths = append(volumeContainerPaths, containerPath) + } + } else if strings.HasPrefix(arg, "-v=") || strings.HasPrefix(arg, "--volume=") { + volSpec := strings.SplitN(arg, "=", 2)[1] + parts := strings.Split(volSpec, ":") + if len(parts) >= 2 { + containerPath := parts[1] + if idx := strings.Index(containerPath, ":"); idx > 0 { + containerPath = containerPath[:idx] + } + volumeContainerPaths = append(volumeContainerPaths, containerPath) + } + } + } + + fmt.Printf("[docker] found volume container paths: %v\n", volumeContainerPaths) + + isGameServer := isGameServerDockerImage(dockerImage) + + shouldExtract := !isGameServer + if shouldExtract { + entries, err := os.ReadDir(serverDir) + if err == nil { + fileCount := 0 + for _, e := range entries { + if e.Name() != ".adpanel" { + fileCount++ + } + } + if fileCount > 0 { + fmt.Printf("[docker] server directory already has %d files, skipping extraction to preserve user changes\n", fileCount) + shouldExtract = false + } + } + } else { + fmt.Printf("[docker] game server image detected (%s), skipping file extraction — container will download files\n", dockerImage) + } + + extracted := false + if shouldExtract { + for _, containerPath := range volumeContainerPaths { + err := a.docker.extractImageFiles(ctx, dockerImage, serverDir, containerPath) + if err == nil { + fmt.Printf("[docker] extracted files from %s:%s to server directory\n", dockerImage, containerPath) + extracted = true + break + } + } + + if !extracted { + imgCfg := a.docker.inspectImageConfig(ctx, dockerImage) + for _, p := range imgCfg.Volumes { + err := a.docker.extractImageFiles(ctx, dockerImage, serverDir, p) + if err == nil { + fmt.Printf("[docker] extracted files from %s:%s (image VOLUME) to server directory\n", dockerImage, p) + extracted = true + break + } + } + if !extracted { + for _, ep := range getDataPathsFromEnv(imgCfg.Env) { + err := a.docker.extractImageFiles(ctx, dockerImage, serverDir, ep) + if err == nil { + fmt.Printf("[docker] extracted files from %s:%s (image ENV) to server directory\n", dockerImage, ep) + extracted = true + break + } + } + } + if !extracted && imgCfg.Workdir != "" && imgCfg.Workdir != "/" { + err := a.docker.extractImageFiles(ctx, dockerImage, serverDir, imgCfg.Workdir) + if err == nil { + fmt.Printf("[docker] extracted files from %s:%s (image WORKDIR) to server directory\n", dockerImage, imgCfg.Workdir) + extracted = true + } + } + } + + if !extracted { + commonPaths := []string{"/app", "/data", "/config", "/srv"} + for _, extractPath := range commonPaths { + err := a.docker.extractImageFiles(ctx, dockerImage, serverDir, extractPath) + if err == nil { + fmt.Printf("[docker] extracted files from %s:%s to server directory\n", dockerImage, extractPath) + extracted = true + break + } + } + } + + if !extracted { + fmt.Printf("[docker] note: could not extract files from image (image may use runtime-only setup)\n") + } + } + + firstContainerPort := 0 + hostToContainerPort := make(map[int]int) + filteredArgs := []string{} + skipNext = false + skipNextVolume := false + skipNextRestart := false + skipNextPort := false + for i, arg := range args { + if skipNext { + skipNext = false + continue + } + if skipNextRestart { + skipNextRestart = false + continue + } + if skipNextPort { + skipNextPort = false + cp := extractContainerPortFromMapping(arg) + hp := extractHostPortFromMapping(arg) + if firstContainerPort == 0 && cp > 0 { + firstContainerPort = cp + } + if hp > 0 && cp > 0 { + hostToContainerPort[hp] = cp + } + continue + } + if skipNextVolume { + skipNextVolume = false + parts := strings.Split(arg, ":") + if len(parts) >= 2 { + containerPath := parts[1] + if idx := strings.LastIndex(containerPath, ":"); idx > 0 { + suffix := containerPath[idx:] + containerPath = containerPath[:idx] + filteredArgs = append(filteredArgs, fmt.Sprintf("%s:%s%s", serverDir, containerPath, suffix)) + } else { + filteredArgs = append(filteredArgs, fmt.Sprintf("%s:%s", serverDir, containerPath)) + } + } else { + filteredArgs = append(filteredArgs, arg) + } + continue + } + if arg == "-d" || arg == "--detach" { + continue + } + if (arg == "-p" || arg == "--publish") && i+1 < len(args) { + skipNextPort = true + continue + } + if strings.HasPrefix(arg, "-p=") || strings.HasPrefix(arg, "--publish=") { + portVal := "" + if strings.HasPrefix(arg, "-p=") { + portVal = strings.TrimPrefix(arg, "-p=") + } else { + portVal = strings.TrimPrefix(arg, "--publish=") + } + cp := extractContainerPortFromMapping(portVal) + hp := extractHostPortFromMapping(portVal) + if firstContainerPort == 0 && cp > 0 { + firstContainerPort = cp + } + if hp > 0 && cp > 0 { + hostToContainerPort[hp] = cp + } + continue + } + if arg == "--restart" && i+1 < len(args) { + skipNextRestart = true + continue + } + if strings.HasPrefix(arg, "--restart=") { + continue + } + if arg == "--name" && i+1 < len(args) { + skipNext = true + continue + } + if strings.HasPrefix(arg, "--name=") { + continue + } + if (arg == "-m" || arg == "--memory" || arg == "--memory-swap" || arg == "--cpu-period" || arg == "--cpu-quota") && i+1 < len(args) { + skipNext = true + continue + } + if strings.HasPrefix(arg, "-m=") || strings.HasPrefix(arg, "--memory=") || strings.HasPrefix(arg, "--memory-swap=") || strings.HasPrefix(arg, "--cpu-period=") || strings.HasPrefix(arg, "--cpu-quota=") { + continue + } + if arg == "--cpus" && i+1 < len(args) { + skipNext = true + continue + } + if strings.HasPrefix(arg, "--cpus=") { + continue + } + if (arg == "-v" || arg == "--volume") && i+1 < len(args) { + filteredArgs = append(filteredArgs, arg) + skipNextVolume = true + continue + } + if strings.HasPrefix(arg, "-v=") || strings.HasPrefix(arg, "--volume=") { + prefix := "-v=" + if strings.HasPrefix(arg, "--volume=") { + prefix = "--volume=" + } + volSpec := strings.TrimPrefix(arg, prefix) + parts := strings.Split(volSpec, ":") + if len(parts) >= 2 { + containerPath := parts[1] + if idx := strings.LastIndex(containerPath, ":"); idx > 0 { + suffix := containerPath[idx:] + containerPath = containerPath[:idx] + filteredArgs = append(filteredArgs, fmt.Sprintf("%s%s:%s%s", prefix, serverDir, containerPath, suffix)) + } else { + filteredArgs = append(filteredArgs, fmt.Sprintf("%s%s:%s", prefix, serverDir, containerPath)) + } + } else { + filteredArgs = append(filteredArgs, arg) + } + continue + } + filteredArgs = append(filteredArgs, arg) + } + + pidsLimit := defaultPidsLimit + if resources != nil && resources.PidsLimit != nil && *resources.PidsLimit >= minPidsLimit && *resources.PidsLimit <= maxPidsLimit { + pidsLimit = *resources.PidsLimit + } + finalArgs := dockerRunInteractiveArgs() + finalArgs = append(finalArgs, "--restart", "unless-stopped", "--name", name) + finalArgs = append(finalArgs, "--cap-drop=ALL", fmt.Sprintf("--pids-limit=%d", pidsLimit)) + finalArgs = append(finalArgs, panelSafeCaps()...) + if resources != nil { + if resources.RamMb != nil && *resources.RamMb > 0 { + finalArgs = append(finalArgs, "--memory", fmt.Sprintf("%dm", *resources.RamMb)) + finalArgs = append(finalArgs, "--memory-reservation", fmt.Sprintf("%dm", *resources.RamMb*90/100)) + if resources.SwapMb == nil { + finalArgs = append(finalArgs, "--memory-swap", fmt.Sprintf("%dm", *resources.RamMb)) + } else { + swapVal := *resources.SwapMb + if swapVal == -1 { + finalArgs = append(finalArgs, "--memory-swap", fmt.Sprintf("%dm", *resources.RamMb)) + } else if swapVal == 0 { + finalArgs = append(finalArgs, "--memory-swap", "-1") + } else { + totalSwap := *resources.RamMb + swapVal + finalArgs = append(finalArgs, "--memory-swap", fmt.Sprintf("%dm", totalSwap)) + } + } + } + if resources.CpuCores != nil && *resources.CpuCores > 0 && *resources.CpuCores <= 128 { + effCores, _ := computeCpuLimit(*resources.CpuCores) + cpuQuota := int64(float64(cpuPeriod) * effCores) + finalArgs = append(finalArgs, "--cpu-period", fmt.Sprintf("%d", cpuPeriod)) + finalArgs = append(finalArgs, "--cpu-quota", fmt.Sprintf("%d", cpuQuota)) + } + if resources.CpuWeight != nil && *resources.CpuWeight >= minCpuWeight && *resources.CpuWeight <= maxCpuWeight { + finalArgs = append(finalArgs, "--cpu-shares", fmt.Sprintf("%d", dockerCpuSharesFromWeight(*resources.CpuWeight))) + } + if resources.IoWeight != nil && *resources.IoWeight >= minIoWeight && *resources.IoWeight <= maxIoWeight { + finalArgs = append(finalArgs, "--blkio-weight", fmt.Sprintf("%d", *resources.IoWeight)) + } + if resources.FileLimit != nil && *resources.FileLimit >= minFileLimit && *resources.FileLimit <= maxFileLimit { + finalArgs = append(finalArgs, "--ulimit", fmt.Sprintf("nofile=%d:%d", *resources.FileLimit, *resources.FileLimit)) + } + } + + effContainerPort := 0 + if hostPort > 0 { + effContainerPort = hostPort + if firstContainerPort > 0 { + effContainerPort = firstContainerPort + } + finalArgs = append(finalArgs, "-p", fmt.Sprintf("%d:%d", hostPort, effContainerPort)) + fmt.Printf("[port-enforce] %s: only exposing allocated port %d -> container %d (stripped all other -p flags)\n", name, hostPort, effContainerPort) + } else if firstContainerPort > 0 { + effContainerPort = firstContainerPort + } + if metaRes, ok := meta["resources"].(map[string]any); ok { + for _, ap := range runtimeIntSlice(metaRes["ports"]) { + if ap > 0 && ap != hostPort { + finalArgs = append(finalArgs, "-p", fmt.Sprintf("%d:%d", ap, ap)) + fmt.Printf("[port-manage] %s: exposing additional port %d:%d\n", name, ap, ap) + } + } + } + portForwards := a.loadPortForwards(serverDir) + for _, pf := range portForwards { + targetContainerPort := pf.Internal + if cp, ok := hostToContainerPort[pf.Internal]; ok { + targetContainerPort = cp + } else if effContainerPort > 0 { + if pf.Internal == hostPort { + targetContainerPort = effContainerPort + } + } + finalArgs = append(finalArgs, "-p", fmt.Sprintf("%d:%d", pf.Public, targetContainerPort)) + fmt.Printf("[port-forwards] %s: forwarding public %d -> container %d (internal host port was %d)\n", name, pf.Public, targetContainerPort, pf.Internal) + } + + finalArgs = append(finalArgs, filteredArgs...) + + hasVolumeMount := false + for _, arg := range filteredArgs { + if arg == "-v" || arg == "--volume" || strings.HasPrefix(arg, "-v=") || strings.HasPrefix(arg, "--volume=") { + hasVolumeMount = true + break + } + } + if !hasVolumeMount { + fmt.Printf("[docker] WARNING: no volume mounts in startup command for %s — auto-injecting from image inspection\n", name) + imgCfg := a.docker.inspectImageConfig(ctx, dockerImage) + injected := false + for _, volPath := range imgCfg.Volumes { + finalArgs = append(finalArgs, "-v", fmt.Sprintf("%s:%s", serverDir, volPath)) + fmt.Printf("[docker] auto-injected volume: %s -> %s (from image VOLUME)\n", serverDir, volPath) + injected = true + } + if !injected { + envPaths := getDataPathsFromEnv(imgCfg.Env) + for _, envPath := range envPaths { + finalArgs = append(finalArgs, "-v", fmt.Sprintf("%s:%s", serverDir, envPath)) + fmt.Printf("[docker] auto-injected volume: %s -> %s (from image ENV)\n", serverDir, envPath) + injected = true + break + } + } + if !injected && imgCfg.Workdir != "" && imgCfg.Workdir != "/" { + finalArgs = append(finalArgs, "-v", fmt.Sprintf("%s:%s", serverDir, imgCfg.Workdir)) + fmt.Printf("[docker] auto-injected volume: %s -> %s (from image WORKDIR)\n", serverDir, imgCfg.Workdir) + injected = true + } + if !injected { + defaultPath := "/data" + if !isGameServerDockerImage(dockerImage) { + defaultPath = "/app" + } + finalArgs = append(finalArgs, "-v", fmt.Sprintf("%s:%s", serverDir, defaultPath)) + fmt.Printf("[docker] auto-injected volume: %s -> %s (default fallback)\n", serverDir, defaultPath) + } + } + + if a.debug { + fmt.Printf("[docker] executing: docker %v\n", finalArgs) + } + + outStr, errStr, exitCode, err := a.docker.runCollect(ctx, finalArgs...) + if err != nil || exitCode != 0 { + fmt.Printf("[docker] startup command error (exit %d): stdout=%s stderr=%s\n", exitCode, strings.TrimSpace(outStr), strings.TrimSpace(errStr)) + return fmt.Errorf("container start failed: %s", strings.TrimSpace(errStr)) + } + + containerId := strings.TrimSpace(outStr) + if containerId != "" { + fmt.Printf("[docker] container started with ID: %s\n", containerId[:12]) + } + + go a.recoverMisplacedFiles(name, serverDir) + + time.Sleep(500 * time.Millisecond) + statusOut, _, _, _ := a.docker.runCollect(ctx, "inspect", "--format", "{{.State.Status}} {{.State.ExitCode}}", name) + statusParts := strings.Fields(strings.TrimSpace(statusOut)) + if len(statusParts) >= 1 { + status := statusParts[0] + exitStr := "0" + if len(statusParts) >= 2 { + exitStr = statusParts[1] + } + fmt.Printf("[docker] container status after start: %s (exit code: %s)\n", status, exitStr) + + if status == "exited" || status == "dead" { + logsOut, _, _, _ := a.docker.runCollect(ctx, "logs", "--tail", "50", name) + fmt.Printf("[docker] container crashed! Last logs:\n%s\n", logsOut) + return fmt.Errorf("container exited immediately with code %s", exitStr) + } + } + + return nil +} + +func extractContainerPortFromMapping(mapping string) int { + s := mapping + if slashIdx := strings.Index(s, "/"); slashIdx > 0 { + s = s[:slashIdx] + } + parts := strings.Split(s, ":") + if len(parts) == 0 { + return 0 + } + last := strings.TrimSpace(parts[len(parts)-1]) + p, _ := strconv.Atoi(last) + return p +} + +func extractHostPortFromMapping(mapping string) int { + s := mapping + if slashIdx := strings.Index(s, "/"); slashIdx > 0 { + s = s[:slashIdx] + } + parts := strings.Split(s, ":") + switch len(parts) { + case 1: + return 0 + case 2: + p, _ := strconv.Atoi(strings.TrimSpace(parts[0])) + return p + case 3: + p, _ := strconv.Atoi(strings.TrimSpace(parts[1])) + return p + } + return 0 +} + +func validateStartupCommandPorts(startupCmd string, allocatedPort int, additionalAllocatedPorts []int, reservedPorts ...int) string { + allowedPorts := make([]int, 0, 1+len(additionalAllocatedPorts)) + if allocatedPort > 0 { + allowedPorts = append(allowedPorts, allocatedPort) + } + for _, p := range additionalAllocatedPorts { + if p > 0 { + allowedPorts = append(allowedPorts, p) + } + } + return validateDockerRunCommandSafety(startupCmd, allowedPorts, reservedPorts, "") +} + +func extractDockerImageFromCommand(cmdStr string) string { + cmd := strings.TrimSpace(cmdStr) + cmdLower := strings.ToLower(cmd) + if !strings.HasPrefix(cmdLower, "docker run") { + return "" + } + argsStr := strings.TrimSpace(cmd[len("docker run"):]) + args := parseShellArgs(argsStr) + + flagsWithValue := map[string]bool{ + "-e": true, "--env": true, "-v": true, "--volume": true, + "-p": true, "--publish": true, "-w": true, "--workdir": true, + "--name": true, "-m": true, "--memory": true, "--cpus": true, + "--memory-swap": true, "--memory-reservation": true, "--cpu-period": true, "--cpu-quota": true, + "-u": true, "--user": true, "-h": true, "--hostname": true, + "--network": true, "--net": true, "--restart": true, + "-l": true, "--label": true, "--entrypoint": true, + "--mount": true, "--tmpfs": true, "--device": true, + "--pid": true, "--ipc": true, "--userns": true, "--uts": true, "--cgroupns": true, + "--shm-size": true, "--ulimit": true, "--dns": true, "--dns-search": true, + "--add-host": true, "--log-driver": true, "--log-opt": true, + "--stop-signal": true, "--stop-timeout": true, "--health-cmd": true, + "--health-interval": true, "--health-retries": true, "--health-timeout": true, + "--runtime": true, "--platform": true, "--pull": true, + "--ip": true, "--ip6": true, "--mac-address": true, + "--expose": true, "--link": true, "--cidfile": true, + } + + skipNext := false + for i := 0; i < len(args); i++ { + arg := args[i] + if skipNext { + skipNext = false + continue + } + argLower := strings.ToLower(strings.TrimSpace(arg)) + flagName := argLower + if strings.HasPrefix(argLower, "--") { + if k, _, ok := strings.Cut(argLower, "="); ok { + flagName = k + } + } + if strings.HasPrefix(argLower, "-") { + if strings.Contains(argLower, "=") { + continue + } + if flagsWithValue[flagName] { + skipNext = true + } + continue + } + return arg + } + return "" +} + +func normalizeDockerImage(raw string) string { + img := strings.TrimSpace(raw) + if img == "" { + return "" + } + if at := strings.Index(img, "@"); at > 0 { + img = img[:at] + } + if colon := strings.LastIndex(img, ":"); colon > 0 { + afterColon := img[colon+1:] + if !strings.Contains(afterColon, "/") { + img = img[:colon] + } + } + img = strings.ToLower(img) + img = strings.TrimPrefix(img, "docker.io/") + img = strings.TrimPrefix(img, "index.docker.io/") + if !strings.Contains(img, "/") { + img = "library/" + img + } + return img +} + +func parseShellArgs(s string) []string { + var args []string + var current strings.Builder + inQuote := rune(0) + escape := false + + for _, r := range s { + if escape { + if r == '\n' || r == '\r' { + escape = false + continue + } + current.WriteRune(r) + escape = false + continue + } + if r == '\\' { + escape = true + continue + } + if inQuote != 0 { + if r == inQuote { + inQuote = 0 + } else { + current.WriteRune(r) + } + continue + } + if r == '"' || r == '\'' { + inQuote = r + continue + } + if r == ' ' || r == '\t' || r == '\n' || r == '\r' { + if current.Len() > 0 { + args = append(args, current.String()) + current.Reset() + } + continue + } + current.WriteRune(r) + } + if current.Len() > 0 { + args = append(args, current.String()) + } + return args +} + +func (a *Agent) startCustomDockerContainer(ctx context.Context, name, serverDir string, meta map[string]any, hostPort int, resources *resourceLimits) error { + a.docker.rmForce(ctx, name) + + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + runtimeObj = make(map[string]any) + } + if a.debug { + fmt.Printf("[docker] startCustomDockerContainer for %s\n", name) + } + + image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) + if image == "" || image == "" { + return fmt.Errorf("no docker image specified") + } + if tag == "" || tag == "" { + tag = "latest" + } + imageRef := image + ":" + tag + imgCfg := a.inspectRuntimeImageConfig(ctx, imageRef) + + ensureVolumeWritable(serverDir) + tpl := strings.ToLower(fmt.Sprint(meta["type"])) + if tpl == "" || tpl == "" { + tpl = strings.ToLower(fmt.Sprint(runtimeObj["providerId"])) + } + if normalizeCfxRuntimeLayout(tpl, runtimeObj, serverDir) { + meta["runtime"] = runtimeObj + _ = a.saveMeta(serverDir, meta) + } + + hasCustomVolumes := len(runtimeStringSlice(runtimeObj["volumes"])) > 0 + explicitCommandTemplate := sanitizeRuntimeCommand(runtimeObj["command"]) + adpanelStartup := startupTemplateFromRuntime(runtimeObj) + installCfg := installConfigFromRuntime(runtimeObj) + runtimeInstallPath := "" + if installCfg != nil { + runtimeInstallPath = normalizeContainerWorkdir(installCfg.RuntimePath) + } + if runtimeInstallPath == "" && adpanelStartup != "" { + runtimeInstallPath = "/home/container" + } + + binds, dataDir := a.resolveStructuredBinds(tpl, runtimeObj, serverDir) + workdir := normalizeContainerWorkdir(runtimeObj["workdir"]) + if !hasCustomVolumes { + inferredDataPath := false + if runtimeInstallPath != "" { + dataDir = runtimeInstallPath + binds = []string{fmt.Sprintf("%s:%s", serverDir, dataDir)} + inferredDataPath = true + if workdir == "" { + workdir = runtimeInstallPath + } + } else if len(imgCfg.Volumes) > 0 { + dataDir = imgCfg.Volumes[0] + binds = []string{fmt.Sprintf("%s:%s", serverDir, dataDir)} + inferredDataPath = true + } else if envPaths := getDataPathsFromEnv(imgCfg.Env); len(envPaths) > 0 { + dataDir = envPaths[0] + binds = []string{fmt.Sprintf("%s:%s", serverDir, dataDir)} + inferredDataPath = true + } else if imgCfg.Workdir != "" && imgCfg.Workdir != "/" && (explicitCommandTemplate != "" || hasManagedRuntimeDefaults(tpl)) { + dataDir = imgCfg.Workdir + binds = []string{fmt.Sprintf("%s:%s", serverDir, dataDir)} + inferredDataPath = true + if workdir == "" { + workdir = imgCfg.Workdir + } + } + if !inferredDataPath && explicitCommandTemplate == "" && !hasManagedRuntimeDefaults(tpl) { + dataDir = "" + binds = nil + } + } else if explicitCommandTemplate == "" || shouldPreferImageDefaultRuntimeCommand(explicitCommandTemplate, imgCfg) { + binds, dataDir = sanitizeCustomImageDefaultBinds(imageRef, imgCfg, binds, dataDir) + } + + preparePaths := []string{dataDir, workdir, imgCfg.Workdir} + for _, bind := range binds { + preparePaths = append(preparePaths, parseVolumeSpecContainerPath(bind)) + } + if explicitCommandTemplate != "" { + preparePaths = append(preparePaths, commandReferencedContainerPaths(explicitCommandTemplate, workdir, dataDir)...) + } + preparedPath := a.prepareServerDirFromImage(ctx, imageRef, serverDir, imgCfg, preparePaths) + if preparedPath != "" && len(binds) == 0 && !hasManagedRuntimeDefaults(tpl) { + dataDir = preparedPath + binds = []string{fmt.Sprintf("%s:%s", serverDir, dataDir)} + if workdir == "" { + workdir = dataDir + } + fmt.Printf("[docker] mounted prepared image path for %s: %s -> %s\n", imageRef, serverDir, dataDir) + } + + env := runtimeEnvMap(runtimeObj["env"]) + if env == nil { + env = map[string]string{} + } + applyRuntimeHostPortEnv(tpl, env, hostPort) + renderRuntimeEnvTemplates(tpl, env, hostPort) + if adpanelStartup != "" { + for key, value := range adpanelStartupDefaultEnv(name, hostPort, resources, adpanelStartup) { + if _, exists := env[key]; !exists { + env[key] = value + } + } + env["STARTUP"] = renderADPanelStartupTemplate(adpanelStartup, env, hostPort) + } + + mainContainerPort := hostPort + if ports := runtimeIntSlice(runtimeObj["ports"]); len(ports) > 0 { + if p := ports[0]; p > 0 { + mainContainerPort = p + } + } + if runtimeUsesHostPortInsideContainer(tpl, runtimeObj, env) && hostPort > 0 { + mainContainerPort = hostPort + } + if mainContainerPort <= 0 { + mainContainerPort = hostPort + } + + startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) + if startFile == "" || startFile == "" { + startFile = defaultStartFileForType(tpl) + } + commandTemplate := explicitCommandTemplate + if adpanelStartup != "" { + commandTemplate = "" + } else if commandTemplate == "" { + commandTemplate = defaultRuntimeCommandForType(tpl, startFile, dataDir) + } + if commandTemplate == "" && !imageConfigHasRuntimeDefault(imgCfg) { + if adpanelStartup != "" && strings.TrimSpace(env["STARTUP"]) != "" { + commandTemplate = "" + } else { + commandTemplate = "sleep infinity" + } + } + if commandTemplate != "" && shouldPreferImageDefaultRuntimeCommand(commandTemplate, imgCfg) { + fmt.Printf("[docker] ignoring path-only template command for %s and using image default entrypoint/cmd: %s\n", imageRef, commandTemplate) + commandTemplate = "" + if imageWorkdir := normalizeContainerWorkdir(imgCfg.Workdir); imageWorkdir != "" { + workdir = imageWorkdir + } + } + var cmdArgs []string + if adpanelStartup != "" && !imageConfigHasRuntimeDefault(imgCfg) && strings.TrimSpace(env["STARTUP"]) != "" { + cmdArgs = []string{"sh", "-lc", env["STARTUP"]} + } else if commandTemplate != "" { + ensureRuntimeEntrypointScaffold(serverDir, tpl, commandTemplate, dataDir, workdir, startFile, hostPort) + var err error + cmdArgs, err = buildRenderedRuntimeProcessArgs(tpl, commandTemplate, dataDir, startFile, imageRef, hostPort, resources, meta) + if err != nil { + return err + } + } + + uid, gid := statUIDGID(serverDir) + req := dockerContainerCreateRequest{ + Image: imageRef, + Env: envMapToList(env), + Cmd: cmdArgs, + WorkingDir: workdir, + User: a.structuredContainerUser(ctx, imageRef, uid, gid, runtimeObj), + Tty: containerTTYForHost(), + OpenStdin: true, + AttachStdin: true, + AttachStdout: true, + AttachStderr: true, + } + portBindings, exposedPorts := a.buildStructuredPortBindings(serverDir, meta, hostPort, mainContainerPort) + req.ExposedPorts = exposedPorts + desiredRestart := strings.TrimSpace(fmt.Sprint(runtimeObj["restart"])) + if desiredRestart == "" { + desiredRestart = "" + } + resources = withRuntimeDefaultFileLimit(resources, tpl, imageRef) + req.HostConfig = buildStructuredHostConfig( + binds, + portBindings, + resources, + "no", + false, + ) + + if err := a.runStructuredContainerWithCompatUser(ctx, name, req); err != nil { + return err + } + if err := a.monitorCustomContainerBootstrap(ctx, name, imageRef); err != nil { + return err + } + if desiredRestart != "" && strings.ToLower(desiredRestart) != "no" { + a.docker.updateRestartPolicy(ctx, name, desiredRestart) + } + go a.recoverMisplacedFiles(name, serverDir) + return nil +} + +func isGameServerDockerImage(image string) bool { + imageLower := strings.ToLower(image) + gameServerPatterns := []string{ + "csgo", "cs2", "counterstrike", + "minecraft", "paper", "spigot", "bukkit", "forge", "fabric", + "hytale", "hytale-docker", "rxmarin/hytale", + "valheim", "rust", "ark", "terraria", + "assetto", "dayz", "zomboid", + "fivem", "redm", "ragemp", "gtav", "gta5", + "factorio", "satisfactory", + "teamspeak", "ts3", "mumble", + "starbound", "unturned", "7daystodie", "7dtd", + "conan", "empyrion", "hurtworld", + "mordhau", "squad", "insurgency", + "garrysmod", "gmod", "srcds", + "avorion", "astroneer", "barotrauma", + "palworld", "enshrouded", "soulmask", + "ptero-eggs", + "cm2network", "gameservermanagers", "linuxgsm", + "steamcmd", "itzg/minecraft", "ich777", + } + for _, pattern := range gameServerPatterns { + if strings.Contains(imageLower, pattern) { + return true + } + } + return false +} + +func getGameServerDataPath(image string) string { + imageLower := strings.ToLower(image) + + if strings.Contains(imageLower, "cm2network/csgo") || strings.Contains(imageLower, "csgo") { + return "/home/steam/csgo-dedicated" + } + if strings.Contains(imageLower, "cm2network/cs2") || strings.Contains(imageLower, "cs2") { + return "/home/steam/cs2-dedicated" + } + if strings.Contains(imageLower, "cm2network/tf2") { + return "/home/steam/tf2-dedicated" + } + + if strings.Contains(imageLower, "fivem") || strings.Contains(imageLower, "cfx") { + return "/config" + } + + if strings.Contains(imageLower, "ragemp") { + return "/ragemp" + } + + if strings.Contains(imageLower, "valheim") { + return "/config" + } + + if strings.Contains(imageLower, "rust") && !strings.Contains(imageLower, "rustlang") { + return "/steamcmd/rust" + } + + if strings.Contains(imageLower, "ark") { + return "/ark" + } + + if strings.Contains(imageLower, "itzg/minecraft") { + return "/data" + } + + if strings.Contains(imageLower, "terraria") { + return "/config" + } + + if strings.Contains(imageLower, "factorio") { + return "/factorio" + } + + if strings.Contains(imageLower, "satisfactory") { + return "/config" + } + + if strings.Contains(imageLower, "teamspeak") || strings.Contains(imageLower, "ts3") { + return "/var/ts3server" + } + + if strings.Contains(imageLower, "7daystodie") || strings.Contains(imageLower, "7dtd") { + return "/steamcmd/7dtd" + } + + if strings.Contains(imageLower, "garrysmod") || strings.Contains(imageLower, "gmod") { + return "/home/steam/gmod-dedicated" + } + + if strings.Contains(imageLower, "palworld") { + return "/palworld" + } + + if strings.Contains(imageLower, "enshrouded") { + return "/config" + } + + if strings.Contains(imageLower, "linuxgsm") || strings.Contains(imageLower, "gameservermanagers") { + return "/home/linuxgsm" + } + + if strings.Contains(imageLower, "ich777") { + return "/serverdata" + } + + return "/data" +} + +func getGameServerUID(image string) int { + imageLower := strings.ToLower(image) + + if strings.Contains(imageLower, "cm2network") { + return 1000 + } + + if strings.Contains(imageLower, "itzg/minecraft") { + return 1000 + } + + if strings.Contains(imageLower, "linuxgsm") || strings.Contains(imageLower, "gameservermanagers") { + return 1000 + } + + if strings.Contains(imageLower, "ich777") { + return 99 + } + + return 1000 +} + +func fixGameServerVolumePermissions(serverDir string, image string) error { + uid := getGameServerUID(image) + gid := uid + + fmt.Printf("[docker] Setting volume permissions for game server: chown -R %d:%d %s\n", uid, gid, serverDir) + + resolvedServerDir, resolveErr := filepath.EvalSymlinks(serverDir) + if resolveErr != nil { + return fmt.Errorf("cannot resolve server directory path: %v", resolveErr) + } + if resolvedServerDir != filepath.Clean(serverDir) { + fmt.Printf("[security] serverDir is a symlink: %s -> %s, using resolved path\n", serverDir, resolvedServerDir) + serverDir = resolvedServerDir + } + + cmd := exec.Command("chown", "-Rh", fmt.Sprintf("%d:%d", uid, gid), serverDir) + if output, err := cmd.CombinedOutput(); err != nil { + fmt.Printf("[docker] Warning: chown failed: %v, output: %s\n", err, string(output)) + if err2 := os.Chown(serverDir, uid, gid); err2 != nil { + return fmt.Errorf("failed to set volume permissions: %v", err2) + } + } + + if err := os.Chmod(serverDir, 0755); err != nil { + fmt.Printf("[docker] Warning: failed to chmod %s: %v\n", serverDir, err) + } + + fmt.Printf("[docker] Volume permissions set successfully for %s\n", serverDir) + return nil +} + +func guessStartupCommand(serverDir string, image string) string { + imageLower := strings.ToLower(image) + + if _, err := os.Stat(filepath.Join(serverDir, "package.json")); err == nil { + return "cd /app && npm install --production && npm start" + } + + if _, err := os.Stat(filepath.Join(serverDir, "requirements.txt")); err == nil { + if _, err := os.Stat(filepath.Join(serverDir, "main.py")); err == nil { + return "cd /app && pip install -r requirements.txt && python main.py" + } + if _, err := os.Stat(filepath.Join(serverDir, "app.py")); err == nil { + return "cd /app && pip install -r requirements.txt && python app.py" + } + if _, err := os.Stat(filepath.Join(serverDir, "run.py")); err == nil { + return "cd /app && pip install -r requirements.txt && python run.py" + } + return "cd /app && pip install -r requirements.txt && python main.py" + } + + if strings.Contains(imageLower, "python") { + if _, err := os.Stat(filepath.Join(serverDir, "main.py")); err == nil { + return "python /app/main.py" + } + if _, err := os.Stat(filepath.Join(serverDir, "app.py")); err == nil { + return "python /app/app.py" + } + return "python /app/main.py" + } + + if strings.Contains(imageLower, "node") { + if _, err := os.Stat(filepath.Join(serverDir, "index.js")); err == nil { + return "node /app/index.js" + } + if _, err := os.Stat(filepath.Join(serverDir, "app.js")); err == nil { + return "node /app/app.js" + } + return "node /app/index.js" + } + + if strings.Contains(imageLower, "go") || strings.Contains(imageLower, "golang") { + if _, err := os.Stat(filepath.Join(serverDir, "main.go")); err == nil { + return "cd /app && go run main.go" + } + return "cd /app && go run ." + } + + if strings.Contains(imageLower, "java") || strings.Contains(imageLower, "openjdk") { + files, _ := filepath.Glob(filepath.Join(serverDir, "*.jar")) + if len(files) > 0 { + jarName := filepath.Base(files[0]) + return fmt.Sprintf("java -jar /app/%s", jarName) + } + return "java -jar /app/app.jar" + } + + if strings.Contains(imageLower, "ruby") { + if _, err := os.Stat(filepath.Join(serverDir, "Gemfile")); err == nil { + return "cd /app && bundle install && bundle exec ruby main.rb" + } + return "ruby /app/main.rb" + } + + if strings.Contains(imageLower, "php") { + return "php -S 0.0.0.0:${PORT:-8080} -t /app" + } + + if strings.Contains(imageLower, "nginx") { + return "" + } + + if strings.Contains(imageLower, "redis") { + return "" + } + + if strings.Contains(imageLower, "postgres") || strings.Contains(imageLower, "mysql") || strings.Contains(imageLower, "mariadb") { + return "" + } + + return "" +} + +type logTail struct { + name string + closed bool + dockerSnapshotPrimed bool + + mu sync.Mutex + writeMu sync.Mutex + clients map[chan string]struct{} + recent []string + recentN int + suppressEchoes []commandEchoSuppressEntry + knownEchoDupes map[string]struct{} + + // Persistent on-disk console log (Pterodactyl/Wings-style). Every line that + // enters the ring buffer is also appended here so a refresh can be served + // from a durable source that does NOT get recycled like the in-memory ring. + // The file is truncated whenever the container (re)starts. + persistMu sync.Mutex + persistPath string + persistLines int + + // snapshotEpochMs is a STABLE time anchor (UnixMilli) used to assign + // synthetic, strictly-increasing timestamps to persisted snapshot lines that + // have no real per-line timestamp. It is set once (lazily, on first use) and + // reset on a genuine container (re)start. Because it does not change between + // refreshes, the same on-disk line is always served with the SAME synthetic + // ts, so the panel's client-side dedup (keyed on ts:source:line) stays + // stable and stops re-appending boot lines on every refresh. + snapshotEpochMs int64 + + // runStartMs is the wall-clock anchor (UnixMilli) for the CURRENT persisted + // run. It is captured the moment the persisted log is (re)scoped to a run + // (genuine container restart, or first seed when the node attaches to an + // already-running container). Synthetic snapshot timestamps are assigned + // FORWARD from this anchor (runStartMs + position*step), never backward from + // "now". + // + // Why this matters: the panel marks a console "reset" at server-start time + // (wall clock) and then drops any history line whose ts < resetAt. The old + // scheme anchored the synthetic window at (now - count*step) and stepped + // forward to end at "now", so the EARLIEST boot lines received timestamps + // far in the past — well before the start/reset boundary — and the panel + // filtered them out, leaving only the last few lines after a refresh. By + // anchoring forward from the actual run start (which is ~= the panel's + // resetAt) every snapshot line is guaranteed to be >= resetAt, so the full + // boot log survives a refresh. It is reset (to 0) on a genuine restart so a + // new run re-anchors. + runStartMs int64 + + stopCh chan struct{} + cmd *exec.Cmd + conn io.ReadWriteCloser +} + +type commandEchoSuppressEntry struct { + command string + expiresAt time.Time + remaining int +} + +type logSnapshotCall struct { + done chan struct{} + entries []logSnapshotEntry +} + +type logSnapshotEntry struct { + line string + ts int64 +} + +const ( + logTailRecentMaxLines = 1200 + consoleCommandEchoSuppressTTL = 8 * time.Second + // Maximum number of lines kept in the persistent on-disk console log per + // server. When exceeded, the oldest lines are trimmed (rotated) so the file + // stays bounded, exactly like Pterodactyl/Wings cap their console buffer. + consolePersistMaxLines = 5000 + // Marker prefix used to embed a user-issued console command as a single, + // in-order line inside the very same log stream as its output. This makes + // the node's log buffer the one and only source of truth for console + // ordering (Pterodactyl/Wings-style), so commands and their output never + // need to be re-interleaved from two clocks on the panel side. The prefix + // is plain ASCII (no leading ">=. " or control chars) so it survives + // cleanLogLine untouched. The panel/client recognise this prefix and render + // it as a "[HH:MM:SS CMD] " line. + consoleCommandMarkerPrefix = "ADPANELCMD>> " +) + +type logManager struct { + mu sync.Mutex + tails map[string]*logTail + d Docker + debug bool + + // logsDir is the directory where per-server persistent console logs are + // stored. Set by the agent after construction; if empty, persistence is + // disabled (in-memory only) and behaviour falls back to the ring buffer. + logsDir string + + snapshotMu sync.Mutex + snapshotInFlight map[string]*logSnapshotCall +} + +func newLogManager(d Docker, debug bool) *logManager { + return &logManager{ + tails: map[string]*logTail{}, + d: d, + debug: debug, + snapshotInFlight: map[string]*logSnapshotCall{}, + } +} + +func normalizeStreamedLogLine(raw string) string { + line := strings.TrimRight(raw, "\r\n") + if strings.HasPrefix(line, "stdout:") { + line = strings.TrimPrefix(line, "stdout:") + } else if strings.HasPrefix(line, "stderr:") { + line = strings.TrimPrefix(line, "stderr:") + } + return cleanLogLine(line) +} + +func (t *logTail) appendRecentLocked(line string) { + if line == "" { + return + } + limit := t.recentN + if limit <= 0 { + limit = logTailRecentMaxLines + } + for _, part := range strings.Split(line, "\n") { + part = strings.TrimRight(part, "\r") + if part == "" { + continue + } + t.recent = append(t.recent, part) + } + if overflow := len(t.recent) - limit; overflow > 0 { + copy(t.recent, t.recent[overflow:]) + t.recent = t.recent[:limit] + } +} + +func (t *logTail) appendRecentBatch(lines []string) { + if len(lines) == 0 { + return + } + t.mu.Lock() + for _, line := range lines { + t.appendRecentLocked(cleanLogLine(line)) + } + t.mu.Unlock() +} + +func (t *logTail) snapshotRecent(tail int) []string { + if tail <= 0 { + return nil + } + t.mu.Lock() + defer t.mu.Unlock() + if len(t.recent) == 0 { + return nil + } + if tail > len(t.recent) { + tail = len(t.recent) + } + out := make([]string, tail) + copy(out, t.recent[len(t.recent)-tail:]) + return out +} + +// --- Persistent on-disk console log (Pterodactyl/Wings-style) -------------- +// +// Rationale: the in-memory ring buffer (`recent`, capped at +// logTailRecentMaxLines) is recycled. A bulky burst of output (e.g. a Minecraft +// `/help` dump) or a few minutes of activity evicts older output while the tiny +// command-marker lines persist longer, so a refresh after ~5-10 min showed only +// "> cmd" markers plus the last command's output. Wings/Pterodactyl avoid this +// by streaming every line to a durable file and serving the console from it. +// +// We mirror that: every line written to the ring buffer is also appended to a +// per-server file. The file is truncated when the container (re)starts so it is +// always scoped to the current run, and it is line-capped so it stays bounded. + +func (lm *logManager) persistDirReady() string { + if lm == nil || strings.TrimSpace(lm.logsDir) == "" { + return "" + } + if err := ensureDir(lm.logsDir); err != nil { + return "" + } + return lm.logsDir +} + +func (lm *logManager) persistPathFor(name string) string { + dir := lm.persistDirReady() + if dir == "" { + return "" + } + safe := sanitizeName(name) + if safe == "" { + safe = "unknown" + } + return filepath.Join(dir, safe+".log") +} + +// bindPersistPath wires the on-disk log path for a tail and seeds its current +// line count so rotation works immediately after a restart. +func (lm *logManager) bindPersistPath(t *logTail) { + if lm == nil || t == nil { + return + } + path := lm.persistPathFor(t.name) + if path == "" { + return + } + t.persistMu.Lock() + if t.persistPath == "" { + t.persistPath = path + t.persistLines = countFileLines(path) + } + t.persistMu.Unlock() +} + +// truncatePersistedLog clears the on-disk console log. Called when the +// container (re)starts so the persisted console always reflects the current +// run only (matches "delete on each re-run of the container"). +func (t *logTail) truncatePersistedLog() { + t.persistMu.Lock() + defer t.persistMu.Unlock() + if t.persistPath == "" { + return + } + if f, err := os.OpenFile(t.persistPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600); err == nil { + _ = f.Close() + } + t.persistLines = 0 + // New run => the synthetic-timestamp anchors must be re-based so the next + // snapshot reflects the fresh run. runStartMs captures the wall-clock moment + // this run's persisted log begins; synthetic snapshot timestamps are + // assigned forward from it so they always land at/after the panel's + // start-time reset marker (and therefore survive the panel's resetAt filter). + t.mu.Lock() + t.snapshotEpochMs = 0 + t.runStartMs = time.Now().UnixMilli() + t.mu.Unlock() +} + +// markRunStartIfUnset records the run-start anchor when it has not been set yet +// (e.g. the node attaches to an already-running container and seeds the empty +// persisted log from docker logs without a preceding truncate). Using the +// earliest available anchor keeps synthetic snapshot timestamps monotonic and +// at/after the panel's reset boundary. +func (t *logTail) markRunStartIfUnset() { + t.mu.Lock() + if t.runStartMs == 0 { + t.runStartMs = time.Now().UnixMilli() + } + t.mu.Unlock() +} + +func (t *logTail) runStartAnchor() int64 { + t.mu.Lock() + defer t.mu.Unlock() + return t.runStartMs +} + +// snapshotEpoch returns a STABLE base UnixMilli timestamp used as the anchor for +// assigning synthetic timestamps to persisted snapshot lines that carry no real +// per-line timestamp. It is computed once and cached on the tail so every +// refresh serves the same on-disk line with the same synthetic ts (keeping the +// panel's client-side dedup stable). +// +// The anchor is the CURRENT run's start time (runStartMs), so synthetic +// timestamps are assigned FORWARD from the run start: ts(pos) = base + +// pos*stepMs. This guarantees every line is >= the run start, which is ~= the +// panel's start-time reset marker, so the panel never filters boot lines out as +// "before reset" (the bug where only the last few lines survived a refresh). +// +// `count` is unused for the anchor itself but retained for signature +// compatibility; the forward anchoring no longer needs to shift the window into +// the past. If runStartMs is somehow unset we fall back to a conservative +// recent anchor that still keeps lines close to "now". +func (t *logTail) snapshotEpoch(count int, stepMs int64) int64 { + t.mu.Lock() + defer t.mu.Unlock() + if t.snapshotEpochMs == 0 { + if t.runStartMs > 0 { + t.snapshotEpochMs = t.runStartMs + } else { + if count < 0 { + count = 0 + } + t.snapshotEpochMs = time.Now().UnixMilli() - int64(count)*stepMs + } + } + return t.snapshotEpochMs +} + +// persistedLineCount returns the total number of lines currently in the durable +// on-disk console log. Used to anchor synthetic snapshot timestamps to absolute +// file positions so they stay stable as the file grows. +func (t *logTail) persistedLineCount() int { + t.persistMu.Lock() + defer t.persistMu.Unlock() + return t.persistLines +} + +// appendPersistedLines appends already-cleaned lines to the on-disk console log +// and rotates (drops oldest lines) once the cap is exceeded. It never blocks the +// live stream meaningfully: failures are silently ignored so streaming keeps +// working even if disk is unavailable. +func (t *logTail) appendPersistedLines(lines []string) { + if t == nil || len(lines) == 0 { + return + } + t.persistMu.Lock() + defer t.persistMu.Unlock() + if t.persistPath == "" { + return + } + + var buf strings.Builder + added := 0 + for _, line := range lines { + for _, part := range strings.Split(line, "\n") { + part = strings.TrimRight(part, "\r") + if part == "" { + continue + } + buf.WriteString(part) + buf.WriteByte('\n') + added++ + } + } + if added == 0 { + return + } + + f, err := os.OpenFile(t.persistPath, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0o600) + if err != nil { + return + } + _, _ = f.WriteString(buf.String()) + _ = f.Close() + t.persistLines += added + + if t.persistLines > consolePersistMaxLines { + t.rotatePersistedLogLocked() + } +} + +// rotatePersistedLogLocked trims the on-disk log to the last +// consolePersistMaxLines lines. Caller must hold persistMu. +func (t *logTail) rotatePersistedLogLocked() { + if t.persistPath == "" { + return + } + data, err := os.ReadFile(t.persistPath) + if err != nil { + return + } + lines := strings.Split(string(data), "\n") + // strings.Split leaves a trailing empty element after the final newline. + if n := len(lines); n > 0 && lines[n-1] == "" { + lines = lines[:n-1] + } + if len(lines) <= consolePersistMaxLines { + t.persistLines = len(lines) + return + } + keep := lines[len(lines)-consolePersistMaxLines:] + tmp := t.persistPath + ".tmp" + if err := os.WriteFile(tmp, []byte(strings.Join(keep, "\n")+"\n"), 0o600); err != nil { + return + } + if err := os.Rename(tmp, t.persistPath); err != nil { + _ = os.Remove(tmp) + return + } + t.persistLines = len(keep) +} + +// readPersistedSnapshot returns up to `tail` of the most recent persisted lines. +func (t *logTail) readPersistedSnapshot(tail int) []string { + if t == nil || tail <= 0 { + return nil + } + t.persistMu.Lock() + path := t.persistPath + t.persistMu.Unlock() + if path == "" { + return nil + } + data, err := os.ReadFile(path) + if err != nil { + return nil + } + lines := strings.Split(string(data), "\n") + if n := len(lines); n > 0 && lines[n-1] == "" { + lines = lines[:n-1] + } + if len(lines) == 0 { + return nil + } + if tail < len(lines) { + lines = lines[len(lines)-tail:] + } + out := make([]string, len(lines)) + copy(out, lines) + return out +} + +func countFileLines(path string) int { + f, err := os.Open(path) + if err != nil { + return 0 + } + defer f.Close() + count := 0 + buf := make([]byte, 64*1024) + for { + n, err := f.Read(buf) + for i := 0; i < n; i++ { + if buf[i] == '\n' { + count++ + } + } + if err != nil { + break + } + } + return count +} + +func normalizeCommandEchoText(value string) string { + text := strings.ReplaceAll(value, "\r\n", "\n") + text = strings.ReplaceAll(text, "\r", "\n") + text = strings.ReplaceAll(text, "\n", " ") + text = strings.Join(strings.Fields(strings.TrimSpace(text)), " ") + if len(text) >= 2 { + if (strings.HasPrefix(text, `"`) && strings.HasSuffix(text, `"`)) || + (strings.HasPrefix(text, `'`) && strings.HasSuffix(text, `'`)) { + text = strings.TrimSpace(text[1 : len(text)-1]) + } + } + return text +} + +func duplicatedFirstRuneCommandEcho(command string) string { + if command == "" { + return "" + } + r, size := utf8.DecodeRuneInString(command) + if r == utf8.RuneError && size == 0 { + return "" + } + return string(r) + command +} + +func isPrefixedCommandEchoArtifact(text, command string) bool { + if text == "" || command == "" || text == command { + return false + } + if !strings.HasSuffix(text, command) { + return false + } + prefix := strings.TrimSpace(strings.TrimSuffix(text, command)) + return prefix != "" && strings.HasPrefix(command, prefix) +} + +func isLikelyCommandEchoArtifact(line, command string) bool { + text := normalizeCommandEchoText(line) + cmd := normalizeCommandEchoText(command) + if text == "" || cmd == "" { + return false + } + if text == cmd || text == "$ "+cmd { + return true + } + if text == duplicatedFirstRuneCommandEcho(cmd) { + return true + } + if isPrefixedCommandEchoArtifact(text, cmd) { + return true + } + return false +} + +func (t *logTail) addCommandEchoSuppress(command string) { + cmd := normalizeCommandEchoText(command) + if cmd == "" { + return + } + now := time.Now() + t.mu.Lock() + defer t.mu.Unlock() + kept := t.suppressEchoes[:0] + for _, entry := range t.suppressEchoes { + if entry.remaining > 0 && now.Before(entry.expiresAt) { + kept = append(kept, entry) + } + } + t.suppressEchoes = append(kept, commandEchoSuppressEntry{ + command: cmd, + expiresAt: now.Add(consoleCommandEchoSuppressTTL), + remaining: 3, + }) + dupe := duplicatedFirstRuneCommandEcho(cmd) + if dupe != "" { + if t.knownEchoDupes == nil { + t.knownEchoDupes = make(map[string]struct{}) + } + t.knownEchoDupes[dupe] = struct{}{} + } + if len(t.suppressEchoes) > 24 { + t.suppressEchoes = t.suppressEchoes[len(t.suppressEchoes)-24:] + } +} + +func (t *logTail) shouldSuppressCommandEcho(line string) bool { + if line == "" { + return false + } + now := time.Now() + t.mu.Lock() + defer t.mu.Unlock() + text := normalizeCommandEchoText(line) + if text != "" && t.knownEchoDupes != nil { + if _, ok := t.knownEchoDupes[text]; ok { + return true + } + } + if len(t.suppressEchoes) == 0 { + return false + } + suppressed := false + kept := t.suppressEchoes[:0] + for _, entry := range t.suppressEchoes { + if entry.remaining <= 0 || !now.Before(entry.expiresAt) { + continue + } + if !suppressed && isLikelyCommandEchoArtifact(line, entry.command) { + entry.remaining-- + suppressed = true + } + if entry.remaining > 0 { + kept = append(kept, entry) + } + } + t.suppressEchoes = kept + return suppressed +} + +func (t *logTail) markDockerSnapshotPrimed() bool { + t.mu.Lock() + defer t.mu.Unlock() + if t.dockerSnapshotPrimed { + return false + } + t.dockerSnapshotPrimed = true + return true +} + +func splitDockerLogTimestamp(raw string) (string, int64) { + line := strings.TrimRight(raw, "\r") + token, rest, ok := strings.Cut(line, " ") + if !ok || token == "" || rest == "" { + return line, 0 + } + if t, err := time.Parse(time.RFC3339Nano, token); err == nil { + return strings.TrimLeft(rest, " \t"), t.UnixMilli() + } + return line, 0 +} + +func parseDockerLogSnapshotEntries(raw string, tail int) []logSnapshotEntry { + if raw == "" { + return nil + } + raw = stripDockerStreamFraming(raw) + raw = strings.ReplaceAll(raw, "\r\n", "\n") + raw = strings.ReplaceAll(raw, "\r", "\n") + parts := strings.Split(raw, "\n") + entries := make([]logSnapshotEntry, 0, len(parts)) + for _, part := range parts { + part = strings.TrimRight(part, "\r") + if strings.TrimSpace(part) == "" { + continue + } + linePart, ts := splitDockerLogTimestamp(part) + cleaned := cleanLogLine(linePart) + if cleaned == "" { + continue + } + for _, line := range strings.Split(cleaned, "\n") { + line = strings.TrimRight(line, "\r") + if line == "" { + continue + } + entries = append(entries, logSnapshotEntry{line: line, ts: ts}) + } + } + if tail > 0 && len(entries) > tail { + entries = entries[len(entries)-tail:] + } + return entries +} + +func parseDockerLogSnapshot(raw string, tail int) []string { + entries := parseDockerLogSnapshotEntries(raw, tail) + lines := make([]string, 0, len(entries)) + for _, entry := range entries { + lines = append(lines, entry.line) + } + return lines +} + +func (lm *logManager) fetchTailSnapshotSingleflight(name string, tail int, fetch func() []logSnapshotEntry) []logSnapshotEntry { + if tail <= 0 || fetch == nil { + return nil + } + key := fmt.Sprintf("%s:%d", name, tail) + + lm.snapshotMu.Lock() + if call, ok := lm.snapshotInFlight[key]; ok { + lm.snapshotMu.Unlock() + <-call.done + return append([]logSnapshotEntry(nil), call.entries...) + } + call := &logSnapshotCall{done: make(chan struct{})} + lm.snapshotInFlight[key] = call + lm.snapshotMu.Unlock() + + entries := fetch() + + lm.snapshotMu.Lock() + call.entries = append([]logSnapshotEntry(nil), entries...) + close(call.done) + delete(lm.snapshotInFlight, key) + lm.snapshotMu.Unlock() + + return append([]logSnapshotEntry(nil), entries...) +} + +func (lm *logManager) getOrCreate(name string) *logTail { + lm.mu.Lock() + defer lm.mu.Unlock() + if t, ok := lm.tails[name]; ok { + return t + } + t := &logTail{ + name: name, + clients: map[chan string]struct{}{}, + recentN: logTailRecentMaxLines, + stopCh: make(chan struct{}), + } + lm.tails[name] = t + lm.bindPersistPath(t) + go lm.followLoop(t) + return t +} + +func (lm *logManager) removeIfEmpty(t *logTail) { + lm.mu.Lock() + defer lm.mu.Unlock() + + t.mu.Lock() + clientCount := len(t.clients) + alreadyClosed := t.closed + t.mu.Unlock() + + if clientCount == 0 && !alreadyClosed { + t.mu.Lock() + if t.closed { + t.mu.Unlock() + return + } + t.closed = true + cmd := t.cmd + conn := t.conn + t.mu.Unlock() + + close(t.stopCh) + if cmd != nil && cmd.Process != nil { + _ = cmd.Process.Kill() + } + if conn != nil { + _ = conn.Close() + } + delete(lm.tails, t.name) + } +} + +func (lm *logManager) primeDockerLogSnapshot(t *logTail, tail int) { + if t == nil || tail <= 0 || !t.markDockerSnapshotPrimed() { + return + } + + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + stdout, stderr, _, _ := lm.d.runCollect(ctx, "logs", "--timestamps", "--tail", fmt.Sprint(tail), t.name) + cancel() + + entries := parseDockerLogSnapshotEntries(stdout, tail) + for _, entry := range parseDockerLogSnapshotEntries(stderr, tail) { + lower := strings.ToLower(entry.line) + if strings.Contains(lower, "no such container") || strings.Contains(lower, "can not get logs from container which is dead") { + continue + } + entries = append(entries, entry) + } + sort.SliceStable(entries, func(i, j int) bool { + left := entries[i].ts + right := entries[j].ts + if left == 0 || right == 0 { + return false + } + return left < right + }) + if len(entries) > tail { + entries = entries[len(entries)-tail:] + } + lines := make([]string, 0, len(entries)) + for _, entry := range entries { + lines = append(lines, entry.line) + } + t.appendRecentBatch(lines) +} + +// seedPersistedLogFromDocker writes the current docker-logs tail into an empty +// persistent console file. Used only when the node process (re)starts against a +// container that was already running, so prior output survives a panel/node +// restart without being duplicated by the live stream (which only carries new +// lines from attach time onward). +func (lm *logManager) seedPersistedLogFromDocker(t *logTail, tail int) { + if t == nil || tail <= 0 { + return + } + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + stdout, stderr, _, _ := lm.d.runCollect(ctx, "logs", "--timestamps", "--tail", fmt.Sprint(tail), t.name) + cancel() + + entries := parseDockerLogSnapshotEntries(stdout, tail) + for _, entry := range parseDockerLogSnapshotEntries(stderr, tail) { + lower := strings.ToLower(entry.line) + if strings.Contains(lower, "no such container") || strings.Contains(lower, "can not get logs from container which is dead") { + continue + } + entries = append(entries, entry) + } + sort.SliceStable(entries, func(i, j int) bool { + left := entries[i].ts + right := entries[j].ts + if left == 0 || right == 0 { + return false + } + return left < right + }) + if len(entries) > tail { + entries = entries[len(entries)-tail:] + } + lines := make([]string, 0, len(entries)) + for _, entry := range entries { + if entry.line != "" { + lines = append(lines, entry.line) + } + } + t.appendPersistedLines(lines) +} + +func (lm *logManager) broadcastLiveLogLine(t *logTail, prefix, raw string) { + line := cleanLogLine(raw) + if line == "" { + return + } + if t.shouldSuppressCommandEcho(line) { + return + } + lower := strings.ToLower(line) + if strings.Contains(lower, "no such container") { + return + } + if strings.Contains(lower, "can not get logs from container which is dead") { + return + } + lm.sendToClients(t, prefix+line) +} + +func (lm *logManager) suppressCommandEcho(name, command string) { + if lm == nil { + return + } + dockerName := dockerContainerName(name) + if dockerName == "" { + return + } + lm.mu.Lock() + t := lm.tails[dockerName] + if t == nil && dockerName != name { + t = lm.tails[name] + } + lm.mu.Unlock() + if t == nil { + return + } + t.addCommandEchoSuppress(command) +} + +// recordCommandLine embeds a user-issued command into the live log stream as a +// single marker line, both broadcasting it to connected clients and appending +// it to the recent ring buffer. Because it is inserted at the exact moment the +// command is accepted, it lands in correct chronological position relative to +// surrounding output, and it survives a refresh via the normal log snapshot. +// This is the single source of truth for command ordering; the panel no longer +// merges a separate command list. +func (lm *logManager) recordCommandLine(name, command string) { + if lm == nil { + return + } + cmd := normalizeCommandEchoText(command) + if strings.TrimSpace(name) == "" || cmd == "" { + return + } + // Use getOrCreate so the marker is ALWAYS persisted into the recent ring + // buffer, even if no SSE client is currently attached (otherwise the command + // would be silently dropped and never appear after a refresh). The SSE + // handler registers its tail under the raw server name, so create/lookup the + // tail under that same key to guarantee a single shared buffer. + t := lm.getOrCreate(name) + if t == nil { + return + } + + // Ensure the boot/log snapshot is primed before we record the marker, so the + // command lands in correct chronological position. If the user sends a + // command right after start (before the live stream has filled the buffer), + // priming pulls the existing docker logs first; the marker is then appended + // after them rather than being pinned at the very top on refresh. + lm.primeDockerLogSnapshot(t, 200) + + marker := consoleCommandMarkerPrefix + cmd + // Persist the marker into the ring buffer AND broadcast it live, in a single + // locked operation so live clients and the persisted record are identical and + // in the same order. The ring buffer is the single authoritative source the + // panel replays on refresh, so the marker must always be recorded here at the + // exact moment the command is accepted; this places it in correct + // chronological position relative to surrounding output (Wings-style: the + // command line lives inline in the one log stream). + t.mu.Lock() + t.appendRecentLocked(marker) + for ch := range t.clients { + select { + case ch <- marker: + default: + } + } + t.mu.Unlock() + // Persist the command marker to the durable on-disk log too, so it survives + // a refresh in correct chronological position alongside output. + t.appendPersistedLines([]string{marker}) +} + +func (lm *logManager) followDockerLogsCLI(t *logTail) error { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + + cmd := exec.CommandContext(ctx, "docker", "logs", "-f", "--tail", "0", t.name) + stdout, err := cmd.StdoutPipe() + if err != nil { + return err + } + stderr, err := cmd.StderrPipe() + if err != nil { + return err + } + if err := cmd.Start(); err != nil { + return err + } + + t.mu.Lock() + t.cmd = cmd + t.conn = nil + t.mu.Unlock() + + done := make(chan struct{}) + go func() { + select { + case <-t.stopCh: + cancel() + case <-done: + } + }() + + var wg sync.WaitGroup + scan := func(r io.Reader, prefix string) { + defer wg.Done() + sc := bufio.NewScanner(r) + buf := make([]byte, 0, 64*1024) + sc.Buffer(buf, 2*1024*1024) + for sc.Scan() { + lm.broadcastLiveLogLine(t, prefix, sc.Text()) + } + } + wg.Add(2) + go scan(stdout, "stdout:") + go scan(stderr, "stderr:") + + err = cmd.Wait() + close(done) + wg.Wait() + + t.mu.Lock() + if t.cmd == cmd { + t.cmd = nil + } + t.mu.Unlock() + + if ctx.Err() != nil { + return ctx.Err() + } + return err +} + +func (lm *logManager) followLoop(t *logTail) { + backoff := 1 * time.Second + lastState := "" + fmt.Printf("[logs] starting follow loop for container: %s\n", t.name) + for { + select { + case <-t.stopCh: + fmt.Printf("[logs] stop signal received for: %s\n", t.name) + return + default: + } + + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + state := lm.d.containerState(ctx, t.name) + cancel() + if state == "" { + if lastState != "" && lastState != "missing" { + fmt.Printf("[logs] container %s no longer exists, waiting...\n", t.name) + } + lastState = "missing" + time.Sleep(backoff) + if backoff < 5*time.Second { + backoff += 500 * time.Millisecond + } + continue + } + + if state != "running" { + if state != lastState { + fmt.Printf("[logs] container %s is %s, waiting for running state before attaching logs\n", t.name, state) + } + lastState = state + time.Sleep(backoff) + if backoff < 5*time.Second { + backoff += 500 * time.Millisecond + } + continue + } + + if lastState != "running" { + fmt.Printf("[logs] container %s running, attaching to live logs\n", t.name) + // Truncate the persistent console log on a genuine (re)start so it is + // always scoped to the current container run (Pterodactyl/Wings reset + // the console on each boot). A real restart is when we previously saw + // the container in a concrete non-running state (exited/created/etc.). + // The empty `lastState` ("") case is the node process itself starting + // up against an already-running container: there we must NOT wipe the + // existing on-disk history, and instead seed it from docker logs if it + // is empty so a refresh still shows prior output. + if lastState != "" && lastState != "missing" { + // Genuine container (re)start: reset the durable log to scope it + // to this run, then immediately re-seed it from docker logs. The + // live attach below uses "--tail 0" / API attach which only + // carries lines emitted AFTER attach time, so without this seed + // the server's boot/startup output (everything printed between + // the truncate and the moment we attach) would be permanently + // missing from the persistent file and vanish on refresh. Seeding + // from docker logs captures that boot window; "--tail 0" on the + // live stream guarantees the seed and the live tail do not + // overlap, so there is no duplication. + t.truncatePersistedLog() + lm.seedPersistedLogFromDocker(t, 200) + } else if len(t.readPersistedSnapshot(1)) == 0 { + // Node attached to an already-running container with an empty + // persisted log: seed it and anchor the run-start so synthetic + // snapshot timestamps are assigned forward from a sane point + // (truncatePersistedLog was NOT called here, so set the anchor + // explicitly). + t.markRunStartIfUnset() + lm.seedPersistedLogFromDocker(t, 200) + } else { + // Persisted history already exists from a prior run/seed; make + // sure the synthetic-ts anchor is set so refreshes don't fall + // back to the legacy "now - count*step" past-anchored window. + t.markRunStartIfUnset() + } + lm.primeDockerLogSnapshot(t, 200) + } + lastState = "running" + backoff = 1 * time.Second + + if preferDockerCLIConsoleTransport() { + if err := lm.followDockerLogsCLI(t); err != nil { + if lm.debug { + fmt.Printf("[logs] Docker CLI log stream ended for %s: %v\n", t.name, err) + } + } + select { + case <-t.stopCh: + return + default: + time.Sleep(500 * time.Millisecond) + continue + } + } + + openStdin := false + if !preferDockerCLIPTYStdinTransport() { + openStdinCtx, openStdinCancel := context.WithTimeout(context.Background(), 3*time.Second) + openStdin = lm.d.containerOpenStdin(openStdinCtx, t.name) + openStdinCancel() + } + + attachCtx, attachCancel := context.WithTimeout(context.Background(), 10*time.Second) + stream, err := lm.d.attachContainerAPI(attachCtx, t.name, dockerAttachOptions{Stdin: openStdin, Stdout: true, Stderr: true}) + attachCancel() + if err != nil { + fmt.Printf("[logs] failed to attach live stream for %s: %v\n", t.name, err) + if cliErr := lm.followDockerLogsCLI(t); cliErr != nil && lm.debug { + fmt.Printf("[logs] Docker CLI log fallback ended for %s: %v\n", t.name, cliErr) + } + select { + case <-t.stopCh: + return + default: + time.Sleep(1 * time.Second) + continue + } + } + + select { + case <-t.stopCh: + _ = stream.Close() + return + default: + } + + t.mu.Lock() + t.conn = stream + t.mu.Unlock() + + broadcast := func(r io.Reader) { + sc := bufio.NewScanner(r) + buf := make([]byte, 0, 64*1024) + sc.Buffer(buf, 2*1024*1024) + for sc.Scan() { + lm.broadcastLiveLogLine(t, "stdout:", sc.Text()) + } + } + + broadcast(stream) + _ = stream.Close() + + t.mu.Lock() + t.conn = nil + t.mu.Unlock() + + select { + case <-t.stopCh: + return + default: + time.Sleep(500 * time.Millisecond) + } + } +} + +func (lm *logManager) sendToClients(t *logTail, s string) { + cleaned := normalizeStreamedLogLine(s) + t.mu.Lock() + t.appendRecentLocked(cleaned) + for ch := range t.clients { + select { + case ch <- s: + default: + } + } + t.mu.Unlock() + // Mirror every streamed line into the durable on-disk log so a refresh is + // served from a source that is not recycled like the in-memory ring. + if cleaned != "" { + t.appendPersistedLines([]string{cleaned}) + } +} + +func (lm *logManager) writeCommand(name, command string) error { + if lm == nil { + return fmt.Errorf("log manager unavailable") + } + dockerName := dockerContainerName(name) + cmd := strings.TrimSpace(command) + if dockerName == "" || cmd == "" { + return fmt.Errorf("missing-params") + } + + lm.mu.Lock() + t := lm.tails[dockerName] + if t == nil && dockerName != name { + t = lm.tails[name] + } + lm.mu.Unlock() + if t == nil { + return fmt.Errorf("live console stream unavailable") + } + + t.mu.Lock() + conn := t.conn + closed := t.closed + t.mu.Unlock() + if closed || conn == nil { + return fmt.Errorf("live console stream unavailable") + } + + line := strings.TrimRight(cmd, "\r\n") + "\n" + t.writeMu.Lock() + defer t.writeMu.Unlock() + if deadlineWriter, ok := conn.(interface{ SetWriteDeadline(time.Time) error }); ok { + _ = deadlineWriter.SetWriteDeadline(time.Now().Add(stdinWriteTimeout)) + defer deadlineWriter.SetWriteDeadline(time.Time{}) + } + if _, err := io.WriteString(conn, line); err != nil { + _ = conn.Close() + t.mu.Lock() + if t.conn == conn { + t.conn = nil + } + t.mu.Unlock() + return fmt.Errorf("live console stdin write failed: %w", err) + } + return nil +} + +func (lm *logManager) resetRecent(name string) { + lm.mu.Lock() + t, ok := lm.tails[name] + if !ok { + dockerName := dockerContainerName(name) + if dockerName != name { + t, ok = lm.tails[dockerName] + } + } + lm.mu.Unlock() + if !ok || t == nil { + return + } + + t.mu.Lock() + t.recent = nil + t.suppressEchoes = nil + t.knownEchoDupes = nil + t.dockerSnapshotPrimed = false + t.mu.Unlock() + // Also clear the durable on-disk console log so a manual console reset wipes + // persisted history, matching the in-memory reset. + t.truncatePersistedLog() +} + +func (a *Agent) resetConsoleLogs(name string) { + cleanName := strings.TrimSpace(name) + if cleanName == "" { + return + } + // Truncate the durable on-disk console log up front, by PATH, so it is wiped + // even when no in-memory tail currently exists (e.g. the previous tail was + // killed on stop/restart). This is what guarantees old logs disappear on a + // container re-run, matching Pterodactyl/Wings. + if a.logs != nil { + a.logs.truncatePersistedLogByName(cleanName) + a.logs.resetRecent(cleanName) + } + ctx, cancel := context.WithTimeout(context.Background(), 4*time.Second) + defer cancel() + if err := a.docker.clearContainerLogs(ctx, cleanName); err != nil && a.debug { + fmt.Printf("[logs] failed to clear docker logs for %s: %v\n", cleanName, err) + } + if a.logs != nil { + a.logs.truncatePersistedLogByName(cleanName) + a.logs.resetRecent(cleanName) + } +} + +// truncatePersistedLogByName clears the persistent console log file for a server +// regardless of whether an in-memory tail exists. It resolves the same path used +// by tails (both the raw name and the docker container name) so a reset always +// hits the right file. +func (lm *logManager) truncatePersistedLogByName(name string) { + if lm == nil { + return + } + candidates := map[string]struct{}{} + if p := lm.persistPathFor(name); p != "" { + candidates[p] = struct{}{} + } + if dockerName := dockerContainerName(name); dockerName != "" && dockerName != name { + if p := lm.persistPathFor(dockerName); p != "" { + candidates[p] = struct{}{} + } + } + for path := range candidates { + if f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0o600); err == nil { + _ = f.Close() + } + } + // Also reset the in-memory line counter on any live tail so rotation stays + // consistent after the wipe. + lm.mu.Lock() + for _, key := range []string{name, dockerContainerName(name)} { + if t, ok := lm.tails[key]; ok && t != nil { + t.persistMu.Lock() + t.persistLines = 0 + t.persistMu.Unlock() + } + } + lm.mu.Unlock() +} + +func (lm *logManager) killTail(name string) { + lm.mu.Lock() + defer lm.mu.Unlock() + + t, ok := lm.tails[name] + if !ok || t == nil { + return + } + + t.mu.Lock() + alreadyClosed := t.closed + if !alreadyClosed { + t.closed = true + } + cmd := t.cmd + conn := t.conn + t.mu.Unlock() + + if cmd != nil && cmd.Process != nil { + _ = cmd.Process.Kill() + } + if conn != nil { + _ = conn.Close() + } + + if !alreadyClosed { + close(t.stopCh) + } + delete(lm.tails, name) +} + +func (a *Agent) ensureLiveLogs(name string) { + if a == nil || a.logs == nil || strings.TrimSpace(name) == "" { + return + } + a.logs.getOrCreate(name) +} + +func getDirSizeBytes(dir string) (int64, error) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + cmd := exec.CommandContext(ctx, "du", "-sb", dir) + out, err := cmd.Output() + if err != nil { + return getDirSizeBytesGo(dir) + } + + parts := strings.Fields(string(out)) + if len(parts) < 1 { + return getDirSizeBytesGo(dir) + } + + size, err := strconv.ParseInt(parts[0], 10, 64) + if err != nil { + return getDirSizeBytesGo(dir) + } + return size, nil +} + +func getDirSizeBytesGo(dir string) (int64, error) { + var size int64 + err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return nil + } + if !info.IsDir() { + size += info.Size() + } + return nil + }) + return size, err +} + +type diskMonitor struct { + agent *Agent + interval time.Duration + stopCh chan struct{} + debug bool +} + +func newDiskMonitor(agent *Agent, interval time.Duration, debug bool) *diskMonitor { + if interval <= 0 { + interval = 60 * time.Second + } + // Allow operators to tighten the enforcement window without rebuilding. A + // shorter interval reduces how far a container can overshoot its quota before + // being stopped. Clamped to a sane range so it can never become a busy-loop + // that pins CPU with repeated `du` scans. + if v := os.Getenv("DISK_MONITOR_MS"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n >= 2000 && n <= 600000 { + interval = time.Duration(n) * time.Millisecond + } + } + return &diskMonitor{ + agent: agent, + interval: interval, + stopCh: make(chan struct{}), + debug: debug, + } +} + +func (dm *diskMonitor) start() { + go dm.monitorLoop() +} + +func (dm *diskMonitor) stop() { + close(dm.stopCh) +} + +func (dm *diskMonitor) monitorLoop() { + time.Sleep(10 * time.Second) + + ticker := time.NewTicker(dm.interval) + defer ticker.Stop() + + for { + select { + case <-dm.stopCh: + return + case <-ticker.C: + dm.checkAllServers() + } + } +} + +func (dm *diskMonitor) checkAllServers() { + // adpanel:multidisk - check servers on EVERY disk, not just the primary + // volumes dir. Secondary-disk servers were never inspected, so their + // over-limit usage (e.g. a container downloading a jar larger than its quota) + // was never enforced. + names := dm.agent.enumerateServerNames() + + for _, serverName := range names { + serverDir := dm.agent.serverDir(serverName) + + limitBytes := dm.agent.getServerDiskLimitBytes(serverDir) + if limitBytes <= 0 { + continue + } + + // Optimization: only a *running* container can grow its volume. Skipping + // stopped servers avoids a `du -sb` scan per idle server every cycle, which + // is what keeps CPU/RAM flat even with a short interval and many servers on + // both primary and secondary disks. A stopped over-limit server is already + // stopped, so re-stopping it would be a no-op anyway. + checkCtx, checkCancel := context.WithTimeout(context.Background(), 4*time.Second) + running := dm.agent.containerIsRunning(checkCtx, serverName) + checkCancel() + if !running { + continue + } + + usedBytes, err := getDirSizeBytes(serverDir) + if err != nil { + if dm.debug { + fmt.Fprintf(os.Stderr, "[disk-monitor] error getting size for %s: %v\n", serverName, err) + } + continue + } + + if dm.debug { + usedGb := float64(usedBytes) / (1024 * 1024 * 1024) + limitGb := float64(limitBytes) / (1024 * 1024 * 1024) + fmt.Printf("[disk-monitor] %s: %.2f GB / %.2f GB\n", serverName, usedGb, limitGb) + } + + if usedBytes > limitBytes { + dm.handleOverLimit(serverName, usedBytes, limitBytes) + } + } +} + +func (dm *diskMonitor) handleOverLimit(serverName string, usedBytes, limitBytes int64) { + usedGb := float64(usedBytes) / (1024 * 1024 * 1024) + limitGb := float64(limitBytes) / (1024 * 1024 * 1024) + + fmt.Printf("[disk-monitor] Server %s exceeded disk limit: %.2f GB / %.2f GB - stopping container\n", + serverName, usedGb, limitGb) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + + if !dm.agent.docker.containerExists(ctx, serverName) { + return + } + + out, _, _, err := dm.agent.docker.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", serverName) + if err != nil || strings.TrimSpace(out) != "true" { + return + } + + stopCtx, stopCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer stopCancel() + + _, _, _, err = dm.agent.docker.runCollect(stopCtx, "stop", "-t", "30", serverName) + if err != nil { + fmt.Fprintf(os.Stderr, "[disk-monitor] error stopping %s: %v\n", serverName, err) + } else { + fmt.Printf("[disk-monitor] Container %s stopped due to disk limit exceeded\n", serverName) + } +} + +type networkAbuseMonitor struct { + agent *Agent + interval time.Duration + workers int + stopCh chan struct{} + debug bool +} + +func newNetworkAbuseMonitor(agent *Agent, interval time.Duration, debug bool) *networkAbuseMonitor { + if interval <= 0 { + interval = 5 * time.Second + } + if v := os.Getenv("NETWORK_ABUSE_MONITOR_MS"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n >= 1000 && n <= 60000 { + interval = time.Duration(n) * time.Millisecond + } + } + + workers := runtime.NumCPU() * 2 + if workers < 4 { + workers = 4 + } + if workers > 16 { + workers = 16 + } + if v := os.Getenv("NETWORK_ABUSE_MONITOR_WORKERS"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n >= 1 && n <= 64 { + workers = n + } + } + + return &networkAbuseMonitor{ + agent: agent, + interval: interval, + workers: workers, + stopCh: make(chan struct{}), + debug: debug, + } +} + +func (nm *networkAbuseMonitor) start() { + go nm.monitorLoop() +} + +func (nm *networkAbuseMonitor) stop() { + close(nm.stopCh) +} + +func (nm *networkAbuseMonitor) monitorLoop() { + time.Sleep(12 * time.Second) + + ticker := time.NewTicker(nm.interval) + defer ticker.Stop() + + for { + select { + case <-nm.stopCh: + return + default: + nm.checkAllServers() + } + + select { + case <-nm.stopCh: + return + case <-ticker.C: + } + } +} + +func (nm *networkAbuseMonitor) checkAllServers() { + // adpanel:multidisk - enumerate across every disk so network anti-abuse rules + // (inbound/outbound caps + reset window) are enforced for secondary-disk + // servers too, not only those on the primary volumes dir. + names := nm.agent.enumerateServerNames() + if len(names) == 0 { + return + } + + workers := nm.workers + if workers > len(names) { + workers = len(names) + } + jobs := make(chan string) + var wg sync.WaitGroup + for i := 0; i < workers; i++ { + wg.Add(1) + go func() { + defer wg.Done() + for name := range jobs { + nm.checkServer(name) + } + }() + } + + for _, name := range names { + select { + case <-nm.stopCh: + close(jobs) + wg.Wait() + return + case jobs <- name: + } + } + close(jobs) + wg.Wait() +} + +func (nm *networkAbuseMonitor) checkServer(serverName string) { + if !isValidContainerName(serverName) || nm.agent == nil { + return + } + + serverDir := nm.agent.serverDir(serverName) + meta := nm.agent.loadMeta(serverDir) + rule := networkAntiAbuseRuleFromMeta(meta) + if !rule.enabled { + return + } + + inspectCtx, inspectCancel := context.WithTimeout(context.Background(), 3500*time.Millisecond) + inspected, exists, err := nm.agent.inspectContainerForStats(inspectCtx, serverName) + inspectCancel() + if err != nil || !exists || !inspected.State.Running { + if nm.debug && err != nil { + fmt.Fprintf(os.Stderr, "[network-abuse] inspect %s failed: %v\n", serverName, err) + } + return + } + + statsCtx, statsCancel := context.WithTimeout(context.Background(), 3500*time.Millisecond) + stats, err := nm.agent.readContainerStatsForServer(statsCtx, serverName) + statsCancel() + if err != nil { + if nm.debug { + fmt.Fprintf(os.Stderr, "[network-abuse] stats %s failed: %v\n", serverName, err) + } + return + } + if len(stats.Networks) == 0 { + return + } + + rawRx, rawTx := sumDockerNetworkBytes(stats.Networks) + if nm.agent.resourceStats == nil { + return + } + entry := nm.agent.resourceStats.get(serverName) + now := time.Now() + entry.mu.Lock() + entry.touchedAt = now + _, _, windowRx, windowTx, _ := entry.updateNetworkCounters(inspected.ID, rawRx, rawTx, now, rule.resetEvery) + entry.mu.Unlock() + + inboundExceeded := rule.inboundLimitBytes > 0 && windowRx >= rule.inboundLimitBytes + outboundExceeded := rule.outboundLimitBytes > 0 && windowTx >= rule.outboundLimitBytes + if !inboundExceeded && !outboundExceeded { + return + } + + reason := "network limit reached" + if inboundExceeded && outboundExceeded { + reason = "inbound and outbound network limits reached" + } else if inboundExceeded { + reason = "inbound network limit reached" + } else if outboundExceeded { + reason = "outbound network limit reached" + } + if nm.debug { + fmt.Printf("[network-abuse] %s exceeded limit: inbound=%d/%d outbound=%d/%d\n", + serverName, windowRx, rule.inboundLimitBytes, windowTx, rule.outboundLimitBytes) + } + if err := nm.agent.stopServerForPolicy(serverName, reason); err != nil && nm.debug { + fmt.Fprintf(os.Stderr, "[network-abuse] stop %s failed: %v\n", serverName, err) + } +} + +func (a *Agent) stopServerForPolicy(name, reason string) error { + if !isValidContainerName(name) { + return fmt.Errorf("invalid container name") + } + + opMu := a.getServerOpLock(name) + opMu.Lock() + defer opMu.Unlock() + + a.stopMu.Lock() + if lastStop, ok := a.stoppingNow[name]; ok && time.Since(lastStop) < 5*time.Second { + a.stopMu.Unlock() + return nil + } + a.stoppingNow[name] = time.Now() + a.stopMu.Unlock() + defer func() { + a.stopMu.Lock() + delete(a.stoppingNow, name) + a.stopMu.Unlock() + }() + + inspectCtx, inspectCancel := context.WithTimeout(context.Background(), 5*time.Second) + inspected, exists, err := a.inspectContainerForStats(inspectCtx, name) + inspectCancel() + if err != nil { + return err + } + if !exists || !inspected.State.Running { + return nil + } + + updateCtx, updateCancel := context.WithTimeout(context.Background(), 5*time.Second) + a.docker.updateRestartNo(updateCtx, name) + updateCancel() + + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + + serverDir := a.serverDir(name) + meta := a.loadMeta(serverDir) + serverType := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) + templateType := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) + isMinecraft := serverType == "" || serverType == "minecraft" || templateType == "minecraft" + + if isMinecraft { + commandCtx, commandCancel := context.WithTimeout(context.Background(), 5*time.Second) + _ = a.docker.sendCommand(commandCtx, a.stdinMgr, name, "stop", nil) + commandCancel() + } + + a.broadcastContainerEvent(name, "stopping") + time.Sleep(a.stopGrace) + + stopCtx, stopCancel := context.WithTimeout(context.Background(), 30*time.Second) + a.docker.stop(stopCtx, name) + stopCancel() + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + + a.broadcastContainerEvent(name, "stopped") + fmt.Printf("[network-abuse] Container %s stopped safely: %s\n", name, reason) + auditLog.Log("server_stop", "node-agent", "", name, "network-abuse-stop", "success", map[string]any{"reason": reason}) + return nil +} + +func (a *Agent) getServerDiskUsage(serverDir string) int64 { + size, err := getDirSizeBytes(serverDir) + if err != nil { + return 0 + } + return size +} + +// getServerBackupsUsage returns the total on-disk size of a server's backups +// directory. adpanel:backup-storage - backups are stored under serverBackupsDir, +// which lives OUTSIDE the server's volume dir, so getServerDiskUsage never sees +// them. We surface this so the panel can show "server files + backups" and so the +// disk-limit guard treats backups as occupied space. +func (a *Agent) getServerBackupsUsage(serverName string) int64 { + backupsDir := a.serverBackupsDir(serverName) + if st, err := os.Stat(backupsDir); err != nil || !st.IsDir() { + return 0 + } + size, err := getDirSizeBytes(backupsDir) + if err != nil { + return 0 + } + return size +} + +// getServerTotalUsage returns the combined occupied storage for a server: +// its files plus all of its backups. adpanel:backup-storage - this is the value +// that must be compared against the storage limit, because a backup is a full +// copy of the server and counts toward the quota. +func (a *Agent) getServerTotalUsage(serverDir string) int64 { + used := a.getServerDiskUsage(serverDir) + if name := filepath.Base(serverDir); name != "" && name != "." && name != ".adpanel_meta" { + used += a.getServerBackupsUsage(name) + } + return used +} + +// containerIsRunning is a cheap "is this server live?" check used to skip disk +// scans for stopped containers. It returns false on any error/absence so callers +// treat unknown state as "nothing to enforce right now". +func (a *Agent) containerIsRunning(ctx context.Context, name string) bool { + if !a.docker.containerExists(ctx, name) { + return false + } + out, _, _, err := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", name) + if err != nil { + return false + } + return strings.TrimSpace(out) == "true" +} + +func (a *Agent) getServerDiskLimitBytes(serverDir string) int64 { + meta := a.loadMeta(serverDir) + resources, ok := meta["resources"].(map[string]any) + if !ok { + return 0 + } + if val, ok := resources["storageMb"]; ok { + var limitMb int64 + switch v := val.(type) { + case float64: + limitMb = int64(v) + case int: + limitMb = int64(v) + case int64: + limitMb = v + } + if limitMb > 0 { + return limitMb * 1024 * 1024 + } + } + if val, ok := resources["storageGb"]; ok { + var limitGb int64 + switch v := val.(type) { + case float64: + limitGb = int64(v) + case int: + limitGb = int64(v) + case int64: + limitGb = v + } + if limitGb > 0 { + return limitGb * 1024 * 1024 * 1024 + } + } + return 0 +} + +func (a *Agent) checkDiskLimit(serverDir string, extraBytes int64) map[string]any { + limitBytes := a.getServerDiskLimitBytes(serverDir) + if limitBytes <= 0 { + return nil + } + // adpanel:backup-storage - count server files AND backups against the quota. + usedBytes := a.getServerTotalUsage(serverDir) + if usedBytes+extraBytes > limitBytes { + usedMb := float64(usedBytes) / (1024 * 1024) + limitMb := float64(limitBytes) / (1024 * 1024) + return map[string]any{ + "error": "disk_limit_exceeded", + "message": fmt.Sprintf("This server has exceeded its disk space limit. Used: %.1f MB / %.1f MB", usedMb, limitMb), + "usedBytes": usedBytes, + "limitBytes": limitBytes, + "usedMb": usedMb, + "limitMb": limitMb, + } + } + return nil +} + +func (a *Agent) serverNameFromPath(absPath string) string { + // adpanel:multidisk - reverse-map a path to its server name across every + // registered disk's volumes root. Falls back to primary-only behavior when no + // additional disks are present. + c := filepath.Clean(absPath) + for _, root := range a.allDiskVolumeRoots() { + rel, err := filepath.Rel(root, c) + if err != nil { + continue + } + parts := strings.SplitN(filepath.ToSlash(rel), "/", 2) + if len(parts) == 0 || parts[0] == "" || parts[0] == "." || parts[0] == ".." { + continue + } + return parts[0] + } + return "" +} + +func (a *Agent) checkDiskLimitForPath(absPath string, extraBytes int64) map[string]any { + serverName := a.serverNameFromPath(absPath) + if serverName == "" || serverName == ".adpanel_meta" { + return nil + } + serverDir := a.serverDir(serverName) + if diskErr := a.checkDiskLimit(serverDir, extraBytes); diskErr != nil { + return diskErr + } + // adpanel:multidisk - also enforce the per-disk capacity ceiling. No-op for the + // primary disk and for disks without a limit, so single-disk behavior is unchanged. + return a.checkDiskCapacityForPath(absPath, extraBytes) +} + +func (a *Agent) checkDiskLimitForPathAfterReplacing(absPath string, replacedBytes int64) map[string]any { + serverName := a.serverNameFromPath(absPath) + if serverName == "" || serverName == ".adpanel_meta" { + return nil + } + serverDir := a.serverDir(serverName) + limitBytes := a.getServerDiskLimitBytes(serverDir) + if limitBytes <= 0 { + return nil + } + // adpanel:backup-storage - backups occupy quota too, so they must be part of + // the post-replacement total when validating an in-place overwrite. + usedBytes := a.getServerTotalUsage(serverDir) + finalUsedBytes := usedBytes - replacedBytes + if finalUsedBytes < 0 { + finalUsedBytes = 0 + } + if finalUsedBytes > limitBytes { + usedMb := float64(finalUsedBytes) / (1024 * 1024) + limitMb := float64(limitBytes) / (1024 * 1024) + return map[string]any{ + "error": "disk_limit_exceeded", + "message": fmt.Sprintf("This server has exceeded its disk space limit. Used: %.1f MB / %.1f MB", usedMb, limitMb), + "usedBytes": finalUsedBytes, + "limitBytes": limitBytes, + "usedMb": usedMb, + "limitMb": limitMb, + } + } + return nil +} + +func diskLimitUploadPayload(usedBytes, limitBytes, incomingBytes int64) map[string]any { + if usedBytes < 0 { + usedBytes = 0 + } + if incomingBytes < 0 { + incomingBytes = 0 + } + remainingBytes := limitBytes - usedBytes + if remainingBytes < 0 { + remainingBytes = 0 + } + usedMb := float64(usedBytes) / (1024 * 1024) + limitMb := float64(limitBytes) / (1024 * 1024) + return map[string]any{ + "error": "disk_limit_exceeded", + "message": fmt.Sprintf("Upload would exceed this server's disk space limit. Used: %.1f MB / %.1f MB", usedMb, limitMb), + "usedBytes": usedBytes, + "limitBytes": limitBytes, + "remainingBytes": remainingBytes, + "incomingBytes": incomingBytes, + "usedMb": usedMb, + "limitMb": limitMb, + } +} + +func (a *Agent) uploadDiskAllowanceForPath(absPath string, replacedBytes int64) (allowedBytes, baseUsedBytes, limitBytes int64, limited bool, diskErr map[string]any) { + serverName := a.serverNameFromPath(absPath) + if serverName == "" || serverName == ".adpanel_meta" { + return 0, 0, 0, false, nil + } + serverDir := a.serverDir(serverName) + limitBytes = a.getServerDiskLimitBytes(serverDir) + if limitBytes <= 0 { + return 0, 0, 0, false, nil + } + // adpanel:backup-storage - the remaining upload allowance is the limit minus + // EVERYTHING already occupying it (server files + backups), so uploads are + // blocked once backups have saturated the quota even if the files are small. + usedBytes := a.getServerTotalUsage(serverDir) + baseUsedBytes = usedBytes - replacedBytes + if baseUsedBytes < 0 { + baseUsedBytes = 0 + } + if baseUsedBytes > limitBytes { + return 0, baseUsedBytes, limitBytes, true, diskLimitUploadPayload(baseUsedBytes, limitBytes, 0) + } + return limitBytes - baseUsedBytes, baseUsedBytes, limitBytes, true, nil +} + +func copyUploadWithLimits(dst io.Writer, src io.Reader, maxBytes int64, diskAllowedBytes int64) (int64, string, error) { + const maxInt64 = int64(^uint64(0) >> 1) + if maxBytes <= 0 { + maxBytes = maxInt64 + } + buf := make([]byte, 64*1024) + var written int64 + for { + n, readErr := src.Read(buf) + if n > 0 { + next := written + int64(n) + if next > maxBytes { + return written, "upload", nil + } + if diskAllowedBytes >= 0 && next > diskAllowedBytes { + return written, "disk", nil + } + if _, writeErr := dst.Write(buf[:n]); writeErr != nil { + return written, "", writeErr + } + written = next + } + if readErr == io.EOF { + return written, "", nil + } + if readErr != nil { + return written, "", readErr + } + } +} + +func protectNodeProcess() { + pid := os.Getpid() + path := fmt.Sprintf("/proc/%d/oom_score_adj", pid) + err := os.WriteFile(path, []byte("-1000"), 0o644) + if err != nil { + fmt.Fprintf(os.Stderr, "[oom-protect] WARNING: could not set oom_score_adj to -1000: %v\n", err) + fmt.Fprintln(os.Stderr, "[oom-protect] The node process may be killed by Linux OOM killer under memory pressure.") + fmt.Fprintln(os.Stderr, "[oom-protect] Ensure this process runs as root or has CAP_SYS_RESOURCE.") + } else { + fmt.Printf("[oom-protect] Node process (PID %d) protected with oom_score_adj=-1000\n", pid) + } +} + +type containerMemState struct { + state string + since time.Time + lastPct float64 +} + +type memoryMonitor struct { + agent *Agent + interval time.Duration + stopCh chan struct{} + debug bool + + recentKills map[string]time.Time + recentKillsMu sync.Mutex + + containerStates map[string]*containerMemState + statesMu sync.Mutex +} + +func newMemoryMonitor(agent *Agent, interval time.Duration, debug bool) *memoryMonitor { + return &memoryMonitor{ + agent: agent, + interval: interval, + stopCh: make(chan struct{}), + debug: debug, + recentKills: make(map[string]time.Time), + containerStates: make(map[string]*containerMemState), + } +} + +func (mm *memoryMonitor) start() { + go mm.monitorLoop() +} + +func (mm *memoryMonitor) stop() { + close(mm.stopCh) +} + +func (mm *memoryMonitor) monitorLoop() { + time.Sleep(15 * time.Second) + + ticker := time.NewTicker(mm.interval) + defer ticker.Stop() + + for { + select { + case <-mm.stopCh: + return + case <-ticker.C: + mm.tick() + } + } +} + +func (mm *memoryMonitor) tick() { + totalKB, availKB, err := readSystemMemory() + if err != nil { + if mm.debug { + fmt.Fprintf(os.Stderr, "[mem-monitor] error reading /proc/meminfo: %v\n", err) + } + return + } + + if totalKB == 0 { + return + } + + usedPercent := float64(totalKB-availKB) / float64(totalKB) * 100.0 + + if mm.debug { + fmt.Printf("[mem-monitor] System memory: %.1f%% used (%d MB / %d MB)\n", + usedPercent, + (totalKB-availKB)/1024, + totalKB/1024) + } + + hostTotalBytes := int64(totalKB) * 1024 + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + out, _, _, err := mm.agent.docker.runCollect(ctx, "ps", "--no-trunc", "--format", "{{.ID}}|{{.Names}}") + if err != nil { + if mm.debug { + fmt.Fprintf(os.Stderr, "[mem-monitor] docker ps error: %v\n", err) + } + return + } + + lines := strings.Split(strings.TrimSpace(out), "\n") + if len(lines) == 0 || (len(lines) == 1 && lines[0] == "") { + return + } + + mm.pruneRecentKills() + + activeIDs := make(map[string]struct{}, len(lines)) + + for _, line := range lines { + parts := strings.SplitN(strings.TrimSpace(line), "|", 2) + if len(parts) != 2 || parts[0] == "" { + continue + } + containerID := parts[0] + containerName := parts[1] + activeIDs[containerID] = struct{}{} + + mm.recentKillsMu.Lock() + if _, killed := mm.recentKills[containerID]; killed { + mm.recentKillsMu.Unlock() + continue + } + mm.recentKillsMu.Unlock() + + usageBytes, limitBytes := mm.readContainerCgroupMemory(containerID) + if usageBytes < 0 { + continue + } + + effectiveLimit := limitBytes + isUnlimited := false + if limitBytes <= 0 || limitBytes >= hostTotalBytes { + effectiveLimit = hostTotalBytes + isUnlimited = true + } + + containerUsedPct := float64(usageBytes) / float64(effectiveLimit) * 100.0 + + if mm.debug && containerUsedPct > 75.0 { + limitLabel := fmt.Sprintf("%d MB", effectiveLimit/(1024*1024)) + if isUnlimited { + limitLabel = fmt.Sprintf("%d MB (host RAM)", effectiveLimit/(1024*1024)) + } + fmt.Printf("[mem-monitor] Container %s: %.1f%% memory (%d MB / %s)\n", + containerName, containerUsedPct, + usageBytes/(1024*1024), limitLabel) + } + + if containerUsedPct >= 99.0 { + idShort := containerID + if len(idShort) > 12 { + idShort = idShort[:12] + } + limitDesc := fmt.Sprintf("%d MB", effectiveLimit/(1024*1024)) + if isUnlimited { + limitDesc = fmt.Sprintf("%d MB (host RAM, unlimited server)", effectiveLimit/(1024*1024)) + } + fmt.Printf("[mem-monitor] Container %s (%s) at %.1f%% of memory limit (%d MB / %s) — FORCE KILLING\n", + containerName, idShort, containerUsedPct, + usageBytes/(1024*1024), limitDesc) + + mm.killContainer(containerID, containerName) + mm.setContainerState(containerID, "normal") + continue + } + + if containerUsedPct >= 96.0 { + state := mm.getContainerState(containerID) + + if state == nil || state.state != "stopping" { + idShort := containerID + if len(idShort) > 12 { + idShort = idShort[:12] + } + limitDesc := fmt.Sprintf("%d MB", effectiveLimit/(1024*1024)) + if isUnlimited { + limitDesc = fmt.Sprintf("%d MB (host RAM, unlimited server)", effectiveLimit/(1024*1024)) + } + fmt.Printf("[mem-monitor] Container %s (%s) at %.1f%% of memory limit (%d MB / %s) — graceful stop\n", + containerName, idShort, containerUsedPct, + usageBytes/(1024*1024), limitDesc) + + mm.gracefulStopContainer(containerID, containerName) + mm.setContainerState(containerID, "stopping") + } else if mm.debug { + fmt.Printf("[mem-monitor] Container %s still at %.1f%% — graceful stop already issued, waiting for 99%% to force kill\n", + containerName, containerUsedPct) + } + + mm.updateContainerPct(containerID, containerUsedPct) + continue + } + + if containerUsedPct < 90.0 { + state := mm.getContainerState(containerID) + if state != nil && state.state != "normal" { + if mm.debug { + fmt.Printf("[mem-monitor] Container %s recovered to %.1f%% — clearing warning state\n", + containerName, containerUsedPct) + } + mm.setContainerState(containerID, "normal") + } + } + } + + mm.pruneContainerStates(activeIDs) +} + +func readSystemMemory() (totalKB, availKB int64, err error) { + data, err := os.ReadFile("/proc/meminfo") + if err != nil { + return 0, 0, err + } + var memTotal, memAvailable, memFree, buffers, cached int64 + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + val, _ := strconv.ParseInt(fields[1], 10, 64) + switch fields[0] { + case "MemTotal:": + memTotal = val + case "MemAvailable:": + memAvailable = val + case "MemFree:": + memFree = val + case "Buffers:": + buffers = val + case "Cached:": + cached = val + } + } + if memAvailable > 0 { + return memTotal, memAvailable, nil + } + return memTotal, memFree + buffers + cached, nil +} + +func (mm *memoryMonitor) readContainerCgroupMemory(containerID string) (usageBytes, limitBytes int64) { + cgroupV2Base := fmt.Sprintf("/sys/fs/cgroup/system.slice/docker-%s.scope", containerID) + + usage := readInt64File(cgroupV2Base + "/memory.current") + limit := readInt64File(cgroupV2Base + "/memory.max") + if usage >= 0 && limit > 0 { + return usage, limit + } + + cgroupV2Alt := fmt.Sprintf("/sys/fs/cgroup/docker/%s", containerID) + usage = readInt64File(cgroupV2Alt + "/memory.current") + limit = readInt64File(cgroupV2Alt + "/memory.max") + if usage >= 0 && limit > 0 { + return usage, limit + } + + cgroupV1Base := fmt.Sprintf("/sys/fs/cgroup/memory/docker/%s", containerID) + usage = readInt64File(cgroupV1Base + "/memory.usage_in_bytes") + limit = readInt64File(cgroupV1Base + "/memory.limit_in_bytes") + if usage >= 0 && limit > 0 { + return usage, limit + } + + cgroupV1Sys := fmt.Sprintf("/sys/fs/cgroup/memory/system.slice/docker-%s.scope", containerID) + usage = readInt64File(cgroupV1Sys + "/memory.usage_in_bytes") + limit = readInt64File(cgroupV1Sys + "/memory.limit_in_bytes") + if usage >= 0 && limit > 0 { + return usage, limit + } + + return -1, -1 +} + +func readInt64File(path string) int64 { + data, err := os.ReadFile(path) + if err != nil { + return -1 + } + s := strings.TrimSpace(string(data)) + if s == "max" || s == "" { + return -1 + } + val, err := strconv.ParseInt(s, 10, 64) + if err != nil { + return -1 + } + return val +} + +func (mm *memoryMonitor) gracefulStopContainer(containerID, containerName string) { + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + idShort := containerID + if len(idShort) > 12 { + idShort = idShort[:12] + } + + _, errStr, _, err := mm.agent.docker.runCollect(ctx, "stop", "-t", "15", containerID) + if err != nil { + fmt.Fprintf(os.Stderr, "[mem-monitor] failed to gracefully stop container %s (%s): %v — %s\n", + containerName, idShort, err, strings.TrimSpace(errStr)) + return + } + + fmt.Printf("[mem-monitor] Gracefully stopped container %s (%s) due to high memory usage\n", + containerName, idShort) + + mm.recentKillsMu.Lock() + mm.recentKills[containerID] = time.Now() + mm.recentKillsMu.Unlock() +} + +func (mm *memoryMonitor) killContainer(containerID, containerName string) { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + idShort := containerID + if len(idShort) > 12 { + idShort = idShort[:12] + } + + _, errStr, _, err := mm.agent.docker.runCollect(ctx, "kill", containerID) + if err != nil { + fmt.Fprintf(os.Stderr, "[mem-monitor] failed to kill container %s (%s): %v — %s\n", + containerName, idShort, err, strings.TrimSpace(errStr)) + return + } + + fmt.Printf("[mem-monitor] Force killed container %s (%s) due to critical memory overuse\n", + containerName, idShort) + + mm.recentKillsMu.Lock() + mm.recentKills[containerID] = time.Now() + mm.recentKillsMu.Unlock() +} + +func (mm *memoryMonitor) getContainerState(containerID string) *containerMemState { + mm.statesMu.Lock() + defer mm.statesMu.Unlock() + return mm.containerStates[containerID] +} + +func (mm *memoryMonitor) setContainerState(containerID, state string) { + mm.statesMu.Lock() + defer mm.statesMu.Unlock() + mm.containerStates[containerID] = &containerMemState{ + state: state, + since: time.Now(), + } +} + +func (mm *memoryMonitor) updateContainerPct(containerID string, pct float64) { + mm.statesMu.Lock() + defer mm.statesMu.Unlock() + if s, ok := mm.containerStates[containerID]; ok { + s.lastPct = pct + } +} + +func (mm *memoryMonitor) pruneContainerStates(activeIDs map[string]struct{}) { + mm.statesMu.Lock() + defer mm.statesMu.Unlock() + for id := range mm.containerStates { + if _, active := activeIDs[id]; !active { + delete(mm.containerStates, id) + } + } +} + +func (mm *memoryMonitor) pruneRecentKills() { + mm.recentKillsMu.Lock() + defer mm.recentKillsMu.Unlock() + + cutoff := time.Now().Add(-60 * time.Second) + for id, t := range mm.recentKills { + if t.Before(cutoff) { + delete(mm.recentKills, id) + } + } +} + +type rateLimiter struct { + mu sync.Mutex + attempts map[string]*rateLimitEntry + limit int + window time.Duration + maxSize int +} + +type rateLimitEntry struct { + count int + resetAt time.Time +} + +var trustProxyHeaders = false + +var authRateLimiter = &rateLimiter{ + attempts: make(map[string]*rateLimitEntry), + limit: 100, + window: 5 * time.Minute, + maxSize: 50000, +} + +func (rl *rateLimiter) allow(ip string) bool { + rl.mu.Lock() + defer rl.mu.Unlock() + + now := time.Now() + + if len(rl.attempts) >= rl.maxSize { + for k, v := range rl.attempts { + if now.After(v.resetAt) { + delete(rl.attempts, k) + } + } + + if len(rl.attempts) >= rl.maxSize { + var oldestKey string + var oldestTime time.Time + first := true + for k, v := range rl.attempts { + if first || v.resetAt.Before(oldestTime) { + oldestKey = k + oldestTime = v.resetAt + first = false + } + } + if oldestKey != "" { + delete(rl.attempts, oldestKey) + } + } + } + + entry, exists := rl.attempts[ip] + + if !exists || now.After(entry.resetAt) { + rl.attempts[ip] = &rateLimitEntry{count: 1, resetAt: now.Add(rl.window)} + return true + } + + entry.count++ + if entry.count > rl.limit { + return false + } + return true +} + +var rateLimitCleanupOnce sync.Once + +func startRateLimitCleanup() { + rateLimitCleanupOnce.Do(func() { + go func() { + for { + time.Sleep(time.Minute) + authRateLimiter.mu.Lock() + now := time.Now() + for ip, entry := range authRateLimiter.attempts { + if now.After(entry.resetAt) { + delete(authRateLimiter.attempts, ip) + } + } + authRateLimiter.mu.Unlock() + } + }() + }) +} + +func getClientIP(r *http.Request) string { + if trustProxyHeaders { + if xff := r.Header.Get("X-Forwarded-For"); xff != "" { + parts := strings.Split(xff, ",") + if len(parts) > 0 { + return strings.TrimSpace(parts[0]) + } + } + } + host, _, err := net.SplitHostPort(r.RemoteAddr) + if err != nil { + return r.RemoteAddr + } + return host +} + +func (a *Agent) ServeHTTP(w http.ResponseWriter, r *http.Request) { + w.Header().Set("X-Content-Type-Options", "nosniff") + w.Header().Set("X-Frame-Options", "DENY") + w.Header().Set("X-XSS-Protection", "1; mode=block") + w.Header().Set("Referrer-Policy", "strict-origin-when-cross-origin") + w.Header().Set("Permissions-Policy", "geolocation=(), microphone=(), camera=()") + w.Header().Set("Cache-Control", "no-store, no-cache, must-revalidate") + w.Header().Set("Content-Security-Policy", "default-src 'none'; frame-ancestors 'none'") + if r.TLS != nil { + w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains") + } + + path := r.URL.Path + method := r.Method + + if method == "HEAD" && path == "/ping" { + w.WriteHeader(204) + return + } + if method == "GET" && path == "/health" { + jsonWrite(w, 200, map[string]any{ + "ok": true, + "version": NodeVersion, + "time": time.Now().UnixMilli(), + }) + return + } + + if strings.HasPrefix(path, "/v1/servers/") { + rest := strings.TrimPrefix(path, "/v1/servers/") + parts := strings.Split(rest, "/") + if len(parts) >= 2 { + name := sanitizeName(parts[0]) + action := parts[1] + if name == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid name"}) + return + } + if method == "POST" && action == "apply-version" { + a.handleApplyVersion(w, r, name) + return + } + } + } + + clientIP := getClientIP(r) + + if !a.authOK(r) { + if !authRateLimiter.allow(clientIP) { + auditLog.Log("rate_limit", clientIP, "", path, method, "blocked", nil) + jsonWrite(w, 429, map[string]any{"error": "too many requests"}) + return + } + auditLog.Log("auth_failure", clientIP, "", path, method, "denied", nil) + jsonWrite(w, 401, map[string]any{"error": "unauthorized"}) + return + } + + switch { + case method == "GET" && path == "/api/system/stats": + a.handleSystemStats(w, r) + return + + case method == "GET" && path == "/v1/info": + jsonWrite(w, 200, map[string]any{ + "ok": true, + "node": map[string]any{ + "uuid": a.uuid, + "version": NodeVersion, + "autoUpdate": a.readNodeInformation().NodeAutoUpdate, + "dataRoot": a.dataRoot, + "volumesDir": a.volumesDir, + }, + }) + return + + case method == "GET" && path == "/v1/ports/check": + a.handlePortCheck(w, r) + return + + case method == "GET" && path == "/v1/update/info": + a.handleNodeUpdateInfo(w, r) + return + + case method == "POST" && path == "/v1/update/auto": + a.handleNodeUpdateAuto(w, r) + return + + case method == "POST" && path == "/v1/update/install": + a.handleNodeUpdateInstall(w, r) + return + + case method == "GET" && path == "/v1/disks": + a.handleDiskList(w, r) + return + + case method == "POST" && path == "/v1/disks": + a.handleDiskAdd(w, r) + return + + case method == "DELETE" && path == "/v1/disks": + a.handleDiskDelete(w, r) + return + + case method == "GET" && path == "/v1/ws": + a.handleWebSocket(w, r) + return + + case method == "GET" && path == "/v1/servers": + a.handleListServers(w, r) + return + + case method == "POST" && (path == "/v1/servers" || path == "/v1/servers/create"): + a.handleCreateServer(w, r) + return + + case method == "POST" && path == "/v1/runtime/startup-command": + a.handleTemplateStartupCommand(w, r) + return + + case method == "POST" && path == "/v1/fs/list": + a.handleFSList(w, r) + return + case method == "POST" && path == "/v1/fs/read": + a.handleFSRead(w, r) + return + case method == "POST" && path == "/v1/fs/download": + a.handleFSDownload(w, r) + return + case method == "POST" && path == "/v1/fs/write": + a.handleFSWrite(w, r) + return + case method == "POST" && path == "/v1/fs/delete": + a.handleFSDelete(w, r) + return + case method == "POST" && path == "/v1/fs/delete-batch": + a.handleFSDeleteBatch(w, r) + return + case method == "POST" && path == "/v1/fs/rename": + a.handleFSRename(w, r) + return + case method == "POST" && path == "/v1/fs/extract": + a.handleFSExtract(w, r) + return + case method == "POST" && path == "/v1/fs/uploadRaw": + a.handleFSUploadRaw(w, r) + return + case method == "POST" && path == "/v1/fs/upload": + a.handleFSUploadStream(w, r) + return + case method == "POST" && path == "/v1/fs/uploadUrl": + a.handleFSUploadURL(w, r) + return + + case method == "POST" && path == "/v1/server/command": + a.handleServerCommandBody(w, r) + return + } + + if strings.HasPrefix(path, "/v1/servers/") { + rest := strings.TrimPrefix(path, "/v1/servers/") + parts := strings.Split(rest, "/") + // adpanel:multidisk - GET /v1/servers/ must return BOTH the resolved + // per-server baseDir (so the panel can route to the correct disk root) and the + // live resource stats. handleServerInfo now merges the disk-routing fields into + // the stats payload, so a single-name GET falls through to it below instead of + // being answered by a stats-less early return (which made the panel show "—"). + if len(parts) >= 2 { + name := sanitizeName(parts[0]) + action := parts[1] + if name == "" { + jsonWrite(w, 400, map[string]any{"error": "invalid name"}) + return + } + switch action { + case "": + case "runtime": + if method == "POST" { + a.handleRuntime(w, r, name) + return + } + case "start": + if method == "POST" { + a.handleStart(w, r, name) + return + } + case "stop": + if method == "POST" { + a.handleStop(w, r, name) + return + } + case "restart": + if method == "POST" { + a.handleRestart(w, r, name) + return + } + case "command": + if method == "POST" { + a.handleCommand(w, r, name) + return + } + case "logs": + if method == "GET" && len(parts) == 2 { + a.handleLogsSSE(w, r, name) + return + } + if method == "POST" && len(parts) == 3 && parts[2] == "reset" { + a.handleResetLogs(w, r, name) + return + } + case "kill": + if method == "POST" { + a.handleKill(w, r, name) + return + } + case "delete-status": + if method == "GET" { + a.handleDeleteStatus(w, r, name) + return + } + case "files": + if len(parts) >= 3 { + sub := parts[2] + switch sub { + case "list": + if method == "GET" { + a.handleFilesList(w, r, name) + return + } + case "read": + if method == "GET" { + a.handleFilesRead(w, r, name) + return + } + case "write": + if method == "PUT" { + a.handleFilesWrite(w, r, name) + return + } + case "delete": + if method == "DELETE" { + a.handleFilesDelete(w, r, name) + return + } + case "upload": + if method == "POST" { + a.handleFilesUpload(w, r, name) + return + } + case "archive": + if method == "POST" { + a.handleFilesArchive(w, r, name) + return + } + } + } + case "backups": + if len(parts) == 2 { + if method == "GET" { + a.handleBackupsList(w, r, name) + return + } + if method == "POST" { + a.handleBackupsCreate(w, r, name) + return + } + } else if len(parts) >= 3 { + backupId := parts[2] + if len(parts) == 3 { + if method == "DELETE" { + a.handleBackupsDelete(w, r, name, backupId) + return + } + } else if len(parts) == 4 && parts[3] == "restore" { + if method == "POST" { + a.handleBackupsRestore(w, r, name, backupId) + return + } + } + } + case "subdomains": + if method == "POST" { + a.handleSubdomains(w, r, name) + return + } + case "resources": + if method == "GET" { + a.handleGetResources(w, r, name) + return + } + if method == "PATCH" { + a.handleUpdateResources(w, r, name) + return + } + case "port-forwards": + if method == "GET" { + a.handleGetPortForwards(w, r, name) + return + } + if method == "PATCH" { + a.handleUpdatePortForwards(w, r, name) + return + } + case "extract-image": + if method == "POST" { + a.handleExtractImage(w, r, name) + return + } + case "import-archive": + if method == "POST" && len(parts) == 2 { + a.handleImportArchive(w, r, name) + return + } + if method == "GET" && len(parts) == 3 && parts[2] == "progress" { + a.handleImportArchiveProgress(w, r, name) + return + } + case "export": + if method == "GET" { + a.handleExportServer(w, r, name) + return + } + case "import-tar": + if method == "POST" { + a.handleImportTar(w, r, name) + return + } + case "reinstall": + if method == "POST" && len(parts) == 2 { + a.handleReinstallServer(w, r, name) + return + } + default: + if method == "GET" && len(parts) == 2 { + a.handleServerInfo(w, r, name) + return + } + } + } else if method == "GET" && len(parts) == 1 { + name := sanitizeName(parts[0]) + a.handleServerInfo(w, r, name) + return + } + if method == "DELETE" && len(parts) == 1 { + name := sanitizeName(parts[0]) + a.handleDeleteServer(w, r, name) + return + } + } + + jsonWrite(w, 404, map[string]any{"error": "not found"}) +} + +func (a *Agent) handlePortCheck(w http.ResponseWriter, r *http.Request) { + port, ok := parseStrictPortValue(r.URL.Query().Get("port")) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid port"}) + return + } + exclude := sanitizeName(r.URL.Query().Get("exclude")) + rawProtocols := strings.TrimSpace(r.URL.Query().Get("protocols")) + if rawProtocols == "" { + rawProtocols = strings.TrimSpace(r.URL.Query().Get("protocol")) + } + protocols := []string{"tcp"} + if rawProtocols != "" { + protocols = nil + for _, part := range strings.Split(rawProtocols, ",") { + if protocol := normalizePortProtocolName(part); protocol != "" { + protocols = append(protocols, protocol) + } + } + if len(protocols) == 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid protocol"}) + return + } + } + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + available, owner, reason := a.hostPortAvailabilityForProtocols(ctx, port, protocols, exclude) + cancel() + + payload := map[string]any{ + "ok": true, + "port": port, + "protocols": protocols, + "available": available, + } + if owner != "" { + payload["owner"] = owner + } + if reason != "" { + payload["reason"] = reason + } + jsonWrite(w, 200, payload) +} + +func (a *Agent) handleSystemStats(w http.ResponseWriter, r *http.Request) { + var memStats runtime.MemStats + runtime.ReadMemStats(&memStats) + + var ramTotalMb, ramUsedMb, ramFreeMb float64 + if memInfo, err := os.ReadFile("/proc/meminfo"); err == nil { + lines := strings.Split(string(memInfo), "\n") + var memTotal, memAvailable, memFree, buffers, cached int64 + for _, line := range lines { + fields := strings.Fields(line) + if len(fields) < 2 { + continue + } + val, _ := strconv.ParseInt(fields[1], 10, 64) + switch fields[0] { + case "MemTotal:": + memTotal = val + case "MemAvailable:": + memAvailable = val + case "MemFree:": + memFree = val + case "Buffers:": + buffers = val + case "Cached:": + cached = val + } + } + ramTotalMb = float64(memTotal) / 1024 + if memAvailable > 0 { + ramFreeMb = float64(memAvailable) / 1024 + } else { + ramFreeMb = float64(memFree+buffers+cached) / 1024 + } + ramUsedMb = ramTotalMb - ramFreeMb + } + + var cpuPercent float64 + if stat, err := os.ReadFile("/proc/stat"); err == nil { + lines := strings.Split(string(stat), "\n") + for _, line := range lines { + if strings.HasPrefix(line, "cpu ") { + fields := strings.Fields(line) + if len(fields) >= 5 { + user, _ := strconv.ParseFloat(fields[1], 64) + nice, _ := strconv.ParseFloat(fields[2], 64) + system, _ := strconv.ParseFloat(fields[3], 64) + idle, _ := strconv.ParseFloat(fields[4], 64) + iowait := 0.0 + if len(fields) >= 6 { + iowait, _ = strconv.ParseFloat(fields[5], 64) + } + total := user + nice + system + idle + iowait + if total > 0 { + cpuPercent = ((total - idle - iowait) / total) * 100 + } + } + break + } + } + } + + var diskTotalGb, diskUsedGb, diskFreeGb float64 + if stat, err := os.Stat(a.dataRoot); err == nil && stat.IsDir() { + var statfs syscall.Statfs_t + if syscall.Statfs(a.dataRoot, &statfs) == nil { + diskTotalGb = float64(statfs.Blocks*uint64(statfs.Bsize)) / (1024 * 1024 * 1024) + diskFreeGb = float64(statfs.Bavail*uint64(statfs.Bsize)) / (1024 * 1024 * 1024) + diskUsedGb = diskTotalGb - diskFreeGb + } + } + + var uptimeSeconds float64 + if uptime, err := os.ReadFile("/proc/uptime"); err == nil { + fields := strings.Fields(string(uptime)) + if len(fields) >= 1 { + uptimeSeconds, _ = strconv.ParseFloat(fields[0], 64) + } + } + + hostname, _ := os.Hostname() + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "cpu_percent": cpuPercent, + "cpu_cores": runtime.NumCPU(), + "ram_used_mb": ramUsedMb, + "ram_total_mb": ramTotalMb, + "ram_free_mb": ramFreeMb, + "disk_used_gb": diskUsedGb, + "disk_total_gb": diskTotalGb, + "disk_free_gb": diskFreeGb, + "uptime": int64(uptimeSeconds), + "hostname": hostname, + "os": runtime.GOOS, + "arch": runtime.GOARCH, + "go_version": runtime.Version(), + "node_version": NodeVersion, + }) +} + +func (a *Agent) serverDir(name string) string { + // adpanel:multidisk - route to the server's assigned disk. Defaults to the + // primary volumes root when the server has no disk assignment (back-compat). + disk := a.diskForServer(name) + if disk.Primary || disk.ID == primaryDiskID { + return filepath.Join(a.volumesDir, name) + } + return filepath.Join(a.diskLayoutVolumes(disk.MountPath), name) +} + +func (a *Agent) metaDir() string { + return filepath.Join(a.volumesDir, ".adpanel_meta") +} + +func (a *Agent) metaPath(name string) string { + safe := sanitizeName(name) + if safe == "" { + safe = "unknown" + } + return filepath.Join(a.metaDir(), safe+".json") +} + +func (a *Agent) loadMeta(serverDir string) map[string]any { + serverName := filepath.Base(serverDir) + extPath := a.metaPath(serverName) + b, err := os.ReadFile(extPath) + if err != nil { + legacyPath := filepath.Join(serverDir, "adpanel.json") + b, err = os.ReadFile(legacyPath) + if err != nil { + return map[string]any{} + } + _ = ensureDir(a.metaDir()) + _ = writeFileNoFollow(extPath, b, 0o600) + _ = os.Remove(legacyPath) + } + var m map[string]any + if json.Unmarshal(b, &m) != nil { + return map[string]any{} + } + return m +} + +func (a *Agent) saveMeta(serverDir string, meta map[string]any) error { + serverName := filepath.Base(serverDir) + _ = ensureDir(a.metaDir()) + b, err := json.MarshalIndent(meta, "", " ") + if err != nil { + return err + } + return writeFileNoFollow(a.metaPath(serverName), b, 0o600) +} + +func (a *Agent) getMetaLock(serverDir string) *sync.Mutex { + key := filepath.Clean(serverDir) + val, _ := a.metaLocks.LoadOrStore(key, &sync.Mutex{}) + return val.(*sync.Mutex) +} + +func (a *Agent) modifyMeta(serverDir string, fn func(meta map[string]any)) error { + mu := a.getMetaLock(serverDir) + mu.Lock() + defer mu.Unlock() + meta := a.loadMeta(serverDir) + fn(meta) + return a.saveMeta(serverDir, meta) +} + +func (a *Agent) getServerOpLock(name string) *sync.Mutex { + val, _ := a.serverOpLocks.LoadOrStore(name, &sync.Mutex{}) + return val.(*sync.Mutex) +} + +type ServerStatus struct { + Name string `json:"name"` + Status string `json:"status"` + CPU *float64 `json:"cpu,omitempty"` + CpuLimit *float64 `json:"cpuLimit,omitempty"` + Memory *float64 `json:"memory,omitempty"` + Disk *float64 `json:"disk,omitempty"` + Uptime *int64 `json:"uptime,omitempty"` +} + +func (a *Agent) handleListServers(w http.ResponseWriter, r *http.Request) { + // adpanel:multidisk - enumerate servers across every disk root, not just the + // primary volumes dir, so secondary-disk servers are listed with live data. + names := a.enumerateServerNames() + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + var servers []ServerStatus + for _, name := range names { + serverDir := a.serverDir(name) + + ss := ServerStatus{ + Name: name, + Status: "stopped", + } + + meta := a.loadMeta(serverDir) + cpuCoresConfig := metaCpuCores(meta) + _, cpuLimit := computeCpuLimit(cpuCoresConfig) + ss.CpuLimit = &cpuLimit + + if a.docker.containerExists(ctx, name) { + out, _, _, err := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", name) + if err == nil && strings.TrimSpace(out) == "true" { + ss.Status = "running" + + startedAt, _, _, startErr := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.StartedAt}}", name) + if startErr == nil && strings.TrimSpace(startedAt) != "" { + startTime, parseErr := time.Parse(time.RFC3339Nano, strings.TrimSpace(startedAt)) + if parseErr == nil { + uptime := int64(time.Since(startTime).Seconds()) + ss.Uptime = &uptime + } + } + + statsOut, _, _, statsErr := a.docker.runCollect(ctx, "stats", "--no-stream", "--format", + "{{.CPUPerc}}|{{.MemUsage}}", name) + if statsErr == nil && strings.TrimSpace(statsOut) != "" { + parts := strings.Split(strings.TrimSpace(statsOut), "|") + if len(parts) >= 2 { + cpuStr := strings.TrimSuffix(strings.TrimSpace(parts[0]), "%") + if cpu, err := strconv.ParseFloat(cpuStr, 64); err == nil { + if cpu > cpuLimit { + cpu = cpuLimit + } + ss.CPU = &cpu + } + memParts := strings.Split(parts[1], "/") + if len(memParts) >= 1 { + memMb := parseMemoryString(strings.TrimSpace(memParts[0])) + if memMb > 0 { + ss.Memory = &memMb + } + } + } + } + } + } + + diskBytes := a.getServerTotalUsage(serverDir) + if diskBytes > 0 { + diskMb := float64(diskBytes) / (1024 * 1024) + ss.Disk = &diskMb + } + + servers = append(servers, ss) + } + + resources := map[string]any{ + "totalMemory": runtime.MemStats{}.Sys, + "cpuCount": runtime.NumCPU(), + } + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "servers": servers, + "resources": resources, + }) +} + +type resourceLimits struct { + RamMb *int `json:"ramMb"` + CpuCores *float64 `json:"cpuCores"` + StorageMb *int `json:"storageMb"` + StorageGb *int `json:"storageGb"` + SwapMb *int `json:"swapMb"` + BackupsMax *int `json:"backupsMax"` + MaxSchedules *int `json:"maxSchedules"` + IoWeight *int `json:"ioWeight"` + CpuWeight *int `json:"cpuWeight"` + PidsLimit *int `json:"pidsLimit"` + FileLimit *int `json:"fileLimit"` + NetworkInboundLimitMb *int64 `json:"networkInboundLimitMb"` + NetworkOutboundLimitMb *int64 `json:"networkOutboundLimitMb"` + NetworkResetMinutes *int `json:"networkResetMinutes"` +} + +type dockerTemplateConfig struct { + Image string `json:"image"` + Tag string `json:"tag"` + Command string `json:"command"` + ADPanelStartup string `json:"adpanelStartup"` + ADPanelStartupSnake string `json:"adpanel_startup"` + LegacyStartup string `json:"pterodactylStartup"` + LegacyStartupSnake string `json:"pterodactyl_startup"` + StartupDisplay string `json:"startupDisplay"` + StartupDisplaySnake string `json:"startup_display"` + StartupPreview string `json:"startupPreview"` + StartupPreviewSnake string `json:"startup_preview"` + ImageDefaultStartup string `json:"imageDefaultStartup"` + ImageDefaultStartupSnake string `json:"image_default_startup"` + JavaVersion string `json:"javaVersion"` + Java string `json:"java"` + Ports []int `json:"ports"` + PortProtocols map[string][]string `json:"portProtocols"` + Volumes []string `json:"volumes"` + Workdir string `json:"workdir"` + WorkingDir string `json:"workingDir"` + Env map[string]string `json:"env"` + Restart string `json:"restart"` + RestartPolicy string `json:"restartPolicy"` + RunAsRoot bool `json:"runAsRoot"` + RunAsRootSnake bool `json:"run_as_root"` + StartupCommand string `json:"startupCommand"` + Install *templateInstallConfig `json:"install"` + Installation *templateInstallConfig `json:"installation"` + Console any `json:"console"` +} + +type templateInstallConfig struct { + Image string `json:"image"` + Container string `json:"container"` + Script string `json:"script"` + Entrypoint string `json:"entrypoint"` + MountPath string `json:"mountPath"` + ContainerPath string `json:"containerPath"` + RuntimePath string `json:"runtimePath"` + TimeoutSeconds int `json:"timeoutSeconds"` + Timeout int `json:"timeout"` + MinimumStorageMb int `json:"minimumStorageMb"` + AllowEmpty bool `json:"allowEmpty"` + AllowEmptyResult bool `json:"allowEmptyResult"` + Env map[string]string `json:"env"` +} + +type templateStartupCommandReq struct { + TemplateId string `json:"templateId"` + Image string `json:"image"` + Tag string `json:"tag"` + StartFile string `json:"startFile"` + DataDir string `json:"dataDir"` + FallbackCommand string `json:"fallbackCommand"` +} + +func (a *Agent) handleTemplateStartupCommand(w http.ResponseWriter, r *http.Request) { + var req templateStartupCommandReq + if err := readJSON(w, r, 1<<20, &req); err != nil { + jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) + return + } + + templateType := strings.ToLower(strings.TrimSpace(req.TemplateId)) + image := strings.TrimSpace(req.Image) + tag := strings.TrimSpace(req.Tag) + if image == "" { + jsonWrite(w, 400, map[string]any{"error": "missing image"}) + return + } + if strings.ContainsAny(image, " \t\r\n") { + jsonWrite(w, 400, map[string]any{"error": "invalid image"}) + return + } + if tag == "" { + tag = "latest" + } + if strings.ContainsAny(tag, " \t\r\n") { + jsonWrite(w, 400, map[string]any{"error": "invalid tag"}) + return + } + + startFile := strings.TrimSpace(req.StartFile) + if startFile == "" { + startFile = defaultStartFileForType(templateType) + } + dataDir := strings.TrimSpace(req.DataDir) + if dataDir == "" { + dataDir = defaultDataDirForType(templateType) + } + + imageRef := image + ":" + tag + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + + command, source, inspected, err := a.inferRuntimeProcessCommandFromImage(ctx, templateType, imageRef, startFile, dataDir, req.FallbackCommand) + if err != nil { + jsonWrite(w, 502, map[string]any{"ok": false, "error": "failed to infer startup command", "detail": err.Error()}) + return + } + workingDir := strings.TrimSpace(inspected.Workdir) + if workingDir == "" { + workingDir = "/" + } + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "command": command, + "source": source, + "imageRef": imageRef, + "entrypoint": inspected.Entrypoint, + "cmd": inspected.Cmd, + "workingDir": workingDir, + "env": inspected.Env, + }) +} + +type createReq struct { + Name string `json:"name"` + Template string `json:"templateId"` + MCFork string `json:"mcFork"` + MCVersion string `json:"mcVersion"` + HostPort int `json:"hostPort"` + AutoStart bool `json:"autoStart"` + AsyncSetup bool `json:"asyncSetup"` + Resources *resourceLimits `json:"resources"` + Docker *dockerTemplateConfig `json:"docker"` + StartupCommand string `json:"startupCommand"` + JavaVersion string `json:"javaVersion"` + ImportUrl string `json:"importUrl"` + DiskID string `json:"diskId"` +} + +func (a *Agent) handleCreateServer(w http.ResponseWriter, r *http.Request) { + var req createReq + if err := readJSON(w, r, a.uploadLimit, &req); err != nil { + jsonWrite(w, 400, map[string]any{"error": "bad json", "detail": err.Error()}) + return + } + + if a.debug { + fmt.Printf("[createServer] Received request - Name: %s, Template: %s\n", req.Name, req.Template) + } + + name := sanitizeName(req.Name) + if name == "" { + jsonWrite(w, 400, map[string]any{"error": "invalid name"}) + return + } + if strings.TrimSpace(req.Template) == "" { + jsonWrite(w, 400, map[string]any{"error": "missing templateId"}) + return + } + if req.HostPort != 0 { + if _, ok := parseStrictPortValue(req.HostPort); !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid hostPort"}) + return + } + } + if req.Docker != nil { + for _, p := range req.Docker.Ports { + if _, ok := parseStrictPortValue(p); !ok { + jsonWrite(w, 400, map[string]any{"error": fmt.Sprintf("invalid docker port: %d", p)}) + return + } + } + if cleanPortProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(req.Docker.PortProtocols) > 0 && len(cleanPortProtocols) == 0 { + jsonWrite(w, 400, map[string]any{"error": "invalid docker port protocols"}) + return + } + } + if strings.TrimSpace(req.StartupCommand) != "" || (req.Docker != nil && strings.TrimSpace(req.Docker.StartupCommand) != "") { + jsonWrite(w, 400, map[string]any{"error": "raw docker startup commands are no longer supported"}) + return + } + if reason := validateResourcePerformanceLimits(req.Resources); reason != "" { + jsonWrite(w, 400, map[string]any{"error": reason}) + return + } + + templateForPort := strings.ToLower(strings.TrimSpace(req.Template)) + hostPortForCheck := req.HostPort + if hostPortForCheck == 0 { + if templateForPort == "minecraft" { + hostPortForCheck = 25565 + } else if req.Docker != nil && len(req.Docker.Ports) > 0 && req.Docker.Ports[0] > 0 { + hostPortForCheck = req.Docker.Ports[0] + } else { + hostPortForCheck = 8080 + } + } + protocolsForMainPort := []string{"tcp"} + if req.Docker != nil { + portProtocols := runtimePortProtocolMap(sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports)) + if len(req.Docker.Ports) > 0 { + protocolsForMainPort = portProtocolsFor(portProtocols, req.Docker.Ports[0]) + } + } + + if hostPortForCheck > 0 { + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + available, owner, reason := a.hostPortAvailabilityForProtocols(ctx, hostPortForCheck, protocolsForMainPort, "") + cancel() + if !available { + msg := fmt.Sprintf("port %d is already in use", hostPortForCheck) + if owner != "" { + msg = fmt.Sprintf("port %d is already used by container %s", hostPortForCheck, owner) + } else if reason != "" { + msg = fmt.Sprintf("port %d is unavailable (%s)", hostPortForCheck, reason) + } + jsonWrite(w, 409, map[string]any{"error": msg, "code": "port_in_use", "port": hostPortForCheck, "owner": owner}) + return + } + } + + opMu := a.getServerOpLock(name) + opMu.Lock() + defer opMu.Unlock() + + // adpanel:multidisk - resolve and validate the target disk before any path is + // computed. Unknown/empty diskId => primary (back-compat). The routing cache is + // primed now so serverDir(name) and serverBackupsDir(name) route correctly for + // the rest of this handler; __diskId is persisted into meta further below. + targetDisk, diskOK := a.diskByID(req.DiskID) + if !diskOK { + jsonWrite(w, 400, map[string]any{"error": "invalid diskId"}) + return + } + a.setServerDiskMapping(name, targetDisk.ID) + if capErr := a.checkDiskCapacity(targetDisk, 0); capErr != nil { + a.invalidateServerDiskCache(name) + jsonWrite(w, 507, capErr) + return + } + + serverDir := a.serverDir(name) + + if _, err := os.Stat(serverDir); err == nil { + extMetaExists := false + if _, metaErr := os.Stat(a.metaPath(name)); metaErr == nil { + extMetaExists = true + } + legacyPath := filepath.Join(serverDir, "adpanel.json") + legacyExists := false + if _, metaErr := os.Stat(legacyPath); metaErr == nil { + legacyExists = true + } + if extMetaExists || legacyExists { + jsonWrite(w, 400, map[string]any{"error": "server already exists"}) + return + } + fmt.Printf("[createServer] Found stale server directory without meta, cleaning up: %s\n", serverDir) + if err := os.RemoveAll(serverDir); err != nil { + fmt.Printf("[createServer] Warning: failed to clean stale directory: %v\n", err) + } + } + _ = ensureDir(serverDir) + + template := strings.ToLower(strings.TrimSpace(req.Template)) + meta := map[string]any{} + // adpanel:multidisk - persist the assigned disk so serverDir/serverBackupsDir + // route correctly across restarts. Omitted for primary to keep meta unchanged + // for the common single-disk case. + if !(targetDisk.Primary || targetDisk.ID == primaryDiskID) { + meta["__diskId"] = targetDisk.ID + } + if template != "minecraft" { + if req.Docker == nil || strings.TrimSpace(req.Docker.Image) == "" { + _ = os.RemoveAll(serverDir) + jsonWrite(w, 400, map[string]any{"error": "no docker image specified", "detail": "Template payload must include docker.image"}) + return + } + } + + resourcesMeta := map[string]any{} + if req.Resources != nil { + if req.Resources.RamMb != nil && *req.Resources.RamMb > 0 { + resourcesMeta["ramMb"] = *req.Resources.RamMb + } + if req.Resources.CpuCores != nil && *req.Resources.CpuCores > 0 { + resourcesMeta["cpuCores"] = *req.Resources.CpuCores + } + if req.Resources.StorageMb != nil && *req.Resources.StorageMb > 0 { + resourcesMeta["storageMb"] = *req.Resources.StorageMb + } else if req.Resources.StorageGb != nil && *req.Resources.StorageGb > 0 { + resourcesMeta["storageGb"] = *req.Resources.StorageGb + } + if req.Resources.SwapMb != nil { + resourcesMeta["swapMb"] = *req.Resources.SwapMb + } + if req.Resources.BackupsMax != nil { + resourcesMeta["backupsMax"] = *req.Resources.BackupsMax + } + if req.Resources.MaxSchedules != nil { + resourcesMeta["maxSchedules"] = *req.Resources.MaxSchedules + } + if req.Resources.IoWeight != nil { + resourcesMeta["ioWeight"] = *req.Resources.IoWeight + } + if req.Resources.CpuWeight != nil { + resourcesMeta["cpuWeight"] = *req.Resources.CpuWeight + } + if req.Resources.PidsLimit != nil { + resourcesMeta["pidsLimit"] = *req.Resources.PidsLimit + } + if req.Resources.FileLimit != nil { + resourcesMeta["fileLimit"] = *req.Resources.FileLimit + } + if req.Resources.NetworkInboundLimitMb != nil && *req.Resources.NetworkInboundLimitMb > 0 { + resourcesMeta["networkInboundLimitMb"] = *req.Resources.NetworkInboundLimitMb + } + if req.Resources.NetworkOutboundLimitMb != nil && *req.Resources.NetworkOutboundLimitMb > 0 { + resourcesMeta["networkOutboundLimitMb"] = *req.Resources.NetworkOutboundLimitMb + } + if req.Resources.NetworkResetMinutes != nil && *req.Resources.NetworkResetMinutes > 0 { + resourcesMeta["networkResetMinutes"] = *req.Resources.NetworkResetMinutes + } + } + + if template == "minecraft" { + fork := req.MCFork + if fork == "" { + fork = "paper" + } + ver := req.MCVersion + if ver == "" { + ver = "1.21.8" + } + hostPort := req.HostPort + if hostPort == 0 { + hostPort = 25565 + } + + writeMinecraftScaffold(serverDir, name, fork, ver) + + mcImage := defaultMinecraftProcessImage + mcTag := defaultMinecraftProcessTag + mcCommand := defaultMinecraftProcessCommand + mcWorkdir := "/data" + rawJavaVersion := strings.TrimSpace(req.JavaVersion) + if rawJavaVersion == "" && req.Docker != nil { + rawJavaVersion = javaVersionFromDockerConfig(req.Docker) + } + mcJavaVersion := normalizeMinecraftJavaVersion(rawJavaVersion) + if strings.TrimSpace(rawJavaVersion) != "" && mcJavaVersion == "" { + jsonWrite(w, 400, map[string]any{"error": "unsupported minecraft java version"}) + return + } + if req.Docker != nil && req.Docker.Image != "" { + mcImage = req.Docker.Image + if req.Docker.Tag != "" { + mcTag = req.Docker.Tag + } + reqWorkdir := strings.TrimSpace(req.Docker.Workdir) + if reqWorkdir == "" { + reqWorkdir = strings.TrimSpace(req.Docker.WorkingDir) + } + if reqWorkdir != "" { + cleanWorkdir := normalizeContainerWorkdir(reqWorkdir) + if cleanWorkdir == "" { + jsonWrite(w, 400, map[string]any{"error": "invalid workdir (must be an absolute path like /data)"}) + return + } + mcWorkdir = cleanWorkdir + } + if cmd := sanitizeRuntimeCommand(req.Docker.Command); cmd != "" { + mcCommand = normalizeLegacyRuntimeProcessCommand("minecraft", cmd, "server.jar", "/data") + if reason := validateRuntimeProcessCommand(mcCommand); reason != "" { + jsonWrite(w, 400, map[string]any{"error": reason}) + return + } + } + } + if mcJavaVersion == "" { + mcJavaVersion = minecraftJavaVersionFromTag(mcTag) + } + if mcJavaVersion != "" { + mcImage = defaultMinecraftProcessImage + mcTag = minecraftJavaTag(mcJavaVersion) + } + + meta = map[string]any{ + "type": "minecraft", + "fork": fork, + "version": ver, + "start": "server.jar", + "hostPort": hostPort, + "runtime": map[string]any{ + "image": mcImage, + "tag": mcTag, + "command": mcCommand, + "workdir": mcWorkdir, + "javaVersion": func() any { + if mcJavaVersion != "" { + return mcJavaVersion + } + return nil + }(), + }, + } + if len(resourcesMeta) > 0 { + meta["resources"] = resourcesMeta + } + if startupDisplay := startupDisplayFromDockerConfig(req.Docker); startupDisplay != "" { + if runtimeObj, ok := meta["runtime"].(map[string]any); ok { + runtimeObj["startupDisplay"] = startupDisplay + } + } + if req.Docker != nil { + if runtimeObj, ok := meta["runtime"].(map[string]any); ok { + if restart := strings.TrimSpace(req.Docker.Restart); restart != "" { + runtimeObj["restart"] = restart + } else if restartPolicy := strings.TrimSpace(req.Docker.RestartPolicy); restartPolicy != "" { + runtimeObj["restart"] = restartPolicy + } + if req.Docker.Console != nil { + runtimeObj["console"] = req.Docker.Console + } + } + } + if req.AsyncSetup { + meta["setupStatus"] = "queued" + meta["setupMessage"] = "Server setup queued" + meta["setupUpdatedAt"] = time.Now().UnixMilli() + } + _ = a.saveMeta(serverDir, meta) + + if req.AsyncSetup { + auditLog.Log("server_create", getClientIP(r), "", name, "create", "accepted", map[string]any{"template": req.Template, "asyncSetup": true}) + continueSetup := a.prepareMinecraftCreateSetup(req, name, serverDir, meta) + if latestMeta := a.loadMeta(serverDir); latestMeta != nil { + meta = latestMeta + } + if continueSetup { + go a.finishMinecraftCreateSetup(req, name, serverDir, meta, hostPort) + } + jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "meta": meta, "asyncSetup": true}) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + jarURL := getMinecraftJarURL(ctx, a.dl, fork, ver, a.debug) + cancel() + + ctxD, cancelD := context.WithTimeout(context.Background(), 30*time.Minute) + if err := a.dl.downloadToFile(ctxD, jarURL, filepath.Join(serverDir, "server.jar")); err != nil { + cancelD() + jsonWrite(w, 500, map[string]any{"error": "download failed", "detail": err.Error()}) + return + } + cancelD() + + enforceServerProps(serverDir) + + if req.ImportUrl != "" { + fmt.Printf("[createServer] Importing archive from URL for Minecraft server: %s\n", req.ImportUrl) + if err := a.downloadAndExtractArchiveSync(name, serverDir, req.ImportUrl); err != nil { + fmt.Printf("[createServer] Warning: archive import failed: %v\n", err) + } + } + + if req.AutoStart { + ctx, cancel := context.WithTimeout(context.Background(), 120*time.Second) + err := a.startMinecraftContainer(ctx, name, serverDir, hostPort, req.Resources, nil) + cancel() + if err != nil { + fmt.Printf("[createServer] Container startup failed, cleaning up: %s - %v\n", name, err) + _ = os.RemoveAll(serverDir) + _ = os.Remove(a.metaPath(name)) + jsonWrite(w, 500, map[string]any{"error": "failed to start server", "detail": err.Error()}) + return + } + a.ensureLiveLogs(name) + } + } else { + hostPort := req.HostPort + if hostPort == 0 { + if req.Docker != nil && len(req.Docker.Ports) > 0 && req.Docker.Ports[0] > 0 { + hostPort = req.Docker.Ports[0] + } else { + hostPort = 8080 + } + } + + runtimeConfig := map[string]any{} + if req.Docker != nil { + if req.Docker.Image != "" { + runtimeConfig["image"] = req.Docker.Image + } + if req.Docker.Tag != "" { + runtimeConfig["tag"] = req.Docker.Tag + } + if cmd := sanitizeRuntimeCommand(req.Docker.Command); cmd != "" { + cleanCmd := normalizeLegacyRuntimeProcessCommand(template, cmd, defaultStartFileForType(template), defaultDataDirForType(template)) + if reason := validateRuntimeProcessCommand(cleanCmd); reason != "" { + jsonWrite(w, 400, map[string]any{"error": reason}) + return + } + runtimeConfig["command"] = cleanCmd + } + if len(req.Docker.Ports) > 0 { + runtimeConfig["ports"] = req.Docker.Ports + } + if portProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(portProtocols) > 0 { + runtimeConfig["portProtocols"] = portProtocols + } + if len(req.Docker.Volumes) > 0 { + runtimeConfig["volumes"] = req.Docker.Volumes + } + if len(req.Docker.Env) > 0 { + runtimeConfig["env"] = req.Docker.Env + } + if startup := startupTemplateFromDockerConfig(req.Docker); startup != "" { + runtimeConfig["adpanelStartup"] = startup + delete(runtimeConfig, "command") + } + if startupDisplay := startupDisplayFromDockerConfig(req.Docker); startupDisplay != "" { + runtimeConfig["startupDisplay"] = startupDisplay + } + if install := dockerTemplateInstall(req.Docker); install != nil { + runtimeConfig["install"] = install + } + reqWorkdir := strings.TrimSpace(req.Docker.Workdir) + if reqWorkdir == "" { + reqWorkdir = strings.TrimSpace(req.Docker.WorkingDir) + } + if reqWorkdir != "" { + cleanWorkdir := normalizeContainerWorkdir(reqWorkdir) + if cleanWorkdir == "" { + jsonWrite(w, 400, map[string]any{"error": "invalid workdir (must be an absolute path like /app)"}) + return + } + runtimeConfig["workdir"] = cleanWorkdir + } + if restart := strings.TrimSpace(req.Docker.Restart); restart != "" { + runtimeConfig["restart"] = restart + } else if restartPolicy := strings.TrimSpace(req.Docker.RestartPolicy); restartPolicy != "" { + runtimeConfig["restart"] = restartPolicy + } + if req.Docker.RunAsRoot || req.Docker.RunAsRootSnake { + runtimeConfig["runAsRoot"] = true + } + if req.Docker.Console != nil { + runtimeConfig["console"] = req.Docker.Console + } + runtimeConfig["providerId"] = "custom" + } + if _, ok := runtimeConfig["command"]; !ok { + if defaultCmd := defaultRuntimeCommandForType(template, defaultStartFileForType(template), defaultDataDirForType(template)); defaultCmd != "" { + runtimeConfig["command"] = defaultCmd + } + } + if _, ok := runtimeConfig["workdir"]; !ok && hasManagedRuntimeDefaults(template) { + runtimeConfig["workdir"] = defaultDataDirForType(template) + } + + meta = map[string]any{ + "type": template, + "template": template, + "hostPort": hostPort, + "createdAt": time.Now().UnixMilli(), + } + if len(runtimeConfig) > 0 { + meta["runtime"] = runtimeConfig + } + if len(resourcesMeta) > 0 { + meta["resources"] = resourcesMeta + } + if req.AsyncSetup { + meta["setupStatus"] = "queued" + meta["setupMessage"] = "Server setup queued" + meta["setupUpdatedAt"] = time.Now().UnixMilli() + } + + fmt.Printf("[createServer] Final meta to save: %+v\n", meta) + _ = a.saveMeta(serverDir, meta) + + if req.AsyncSetup { + auditLog.Log("server_create", getClientIP(r), "", name, "create", "accepted", map[string]any{"template": req.Template, "asyncSetup": true}) + continueSetup := a.prepareCustomCreateSetup(req, name, serverDir, meta) + if latestMeta := a.loadMeta(serverDir); latestMeta != nil { + meta = latestMeta + } + if continueSetup { + go a.finishCustomCreateSetup(req, name, serverDir, meta, hostPort) + } + jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "meta": meta, "asyncSetup": true}) + return + } + + if install := installConfigFromRuntime(runtimeConfig); install != nil { + if err := a.runTemplateInstall(name, serverDir, install, runtimeConfig, hostPort, req.Resources); err != nil { + fmt.Printf("[createServer] Template install failed, cleaning up: %s - %v\n", name, err) + _ = os.RemoveAll(serverDir) + _ = os.Remove(a.metaPath(name)) + jsonWrite(w, 500, map[string]any{"error": "failed to install server", "detail": err.Error()}) + return + } + } + + if req.ImportUrl != "" { + fmt.Printf("[createServer] Importing archive from URL: %s\n", req.ImportUrl) + if err := a.downloadAndExtractArchiveSync(name, serverDir, req.ImportUrl); err != nil { + fmt.Printf("[createServer] Warning: archive import failed: %v\n", err) + } + } + switch template { + case "python": + scaffoldPython(serverDir, defaultStartFileForType(template)) + case "nodejs", "discord-bot": + scaffoldNode(serverDir, defaultStartFileForType(template), hostPort) + } + + hasImage := req.Docker != nil && req.Docker.Image != "" + if req.AutoStart && hasImage { + ctx, cancel := context.WithTimeout(context.Background(), 240*time.Second) + var err error + if isManagedProcessRuntime(template) { + err = a.startRuntimeContainer(ctx, name, serverDir, meta, hostPort, req.Resources, nil) + } else { + err = a.startCustomDockerContainer(ctx, name, serverDir, meta, hostPort, req.Resources) + } + cancel() + if err != nil { + fmt.Printf("[createServer] Container startup failed, cleaning up: %s - %v\n", name, err) + _ = os.RemoveAll(serverDir) + _ = os.Remove(a.metaPath(name)) + jsonWrite(w, 500, map[string]any{"error": "failed to start server", "detail": err.Error()}) + return + } + a.ensureLiveLogs(name) + } + } + + auditLog.Log("server_create", getClientIP(r), "", name, "create", "success", map[string]any{"template": req.Template}) + jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "meta": meta}) +} + +func resourceRamLimitMbFromMeta(meta map[string]any) float64 { + resources, _ := meta["resources"].(map[string]any) + if resources == nil { + return 0 + } + return anyToFloat64(resources["ramMb"]) +} + +func resourceStorageLimitMbFromMeta(meta map[string]any) float64 { + resources, _ := meta["resources"].(map[string]any) + if resources == nil { + return 0 + } + if v := anyToFloat64(resources["storageMb"]); v > 0 { + return v + } + if v := anyToFloat64(resources["storageGb"]); v > 0 { + return v * 1024 + } + return 0 +} + +func buildNetworkStatsPayload(inboundBytes, outboundBytes uint64) map[string]any { + return map[string]any{ + "inboundBytes": inboundBytes, + "outboundBytes": outboundBytes, + "rxBytes": inboundBytes, + "txBytes": outboundBytes, + } +} + +type networkAntiAbuseRule struct { + inboundLimitBytes uint64 + outboundLimitBytes uint64 + resetEvery time.Duration + enabled bool +} + +func networkLimitMbToBytes(mb int64) uint64 { + if mb <= 0 { + return 0 + } + maxMb := int64(^uint64(0) / (1024 * 1024)) + if mb > maxMb { + return ^uint64(0) + } + return uint64(mb) * 1024 * 1024 +} + +func networkAntiAbuseRuleFromMeta(meta map[string]any) networkAntiAbuseRule { + resources, _ := meta["resources"].(map[string]any) + if resources == nil { + return networkAntiAbuseRule{} + } + inboundMb := anyToInt64(resources["networkInboundLimitMb"]) + outboundMb := anyToInt64(resources["networkOutboundLimitMb"]) + if inboundMb <= 0 && outboundMb <= 0 { + return networkAntiAbuseRule{} + } + resetMinutes := anyToInt(resources["networkResetMinutes"]) + if resetMinutes <= 0 { + resetMinutes = defaultNetworkResetMins + } + if resetMinutes < minNetworkResetMins || resetMinutes > maxNetworkResetMins { + resetMinutes = defaultNetworkResetMins + } + return networkAntiAbuseRule{ + inboundLimitBytes: networkLimitMbToBytes(inboundMb), + outboundLimitBytes: networkLimitMbToBytes(outboundMb), + resetEvery: time.Duration(resetMinutes) * time.Minute, + enabled: inboundMb > 0 || outboundMb > 0, + } +} + +func uint64Remaining(limit, used uint64) uint64 { + if limit == 0 || used >= limit { + return 0 + } + return limit - used +} + +func attachNetworkAntiAbusePayload(payload map[string]any, rule networkAntiAbuseRule, windowRx, windowTx uint64, windowStartedAt time.Time) { + if payload == nil || !rule.enabled { + return + } + payload["windowInboundBytes"] = windowRx + payload["windowOutboundBytes"] = windowTx + payload["inboundLimitBytes"] = rule.inboundLimitBytes + payload["outboundLimitBytes"] = rule.outboundLimitBytes + payload["inboundRemainingBytes"] = uint64Remaining(rule.inboundLimitBytes, windowRx) + payload["outboundRemainingBytes"] = uint64Remaining(rule.outboundLimitBytes, windowTx) + payload["resetEveryMinutes"] = int(rule.resetEvery / time.Minute) + if !windowStartedAt.IsZero() && rule.resetEvery > 0 { + payload["windowStartedAt"] = windowStartedAt.UTC().Format(time.RFC3339) + payload["windowResetsAt"] = windowStartedAt.Add(rule.resetEvery).UTC().Format(time.RFC3339) + } +} + +func normalizeDockerContainerStatus(status string) string { + switch strings.ToLower(strings.TrimSpace(status)) { + case "running": + return "running" + case "created", "exited", "dead", "removing", "paused": + return "stopped" + case "": + return "stopped" + default: + return strings.ToLower(strings.TrimSpace(status)) + } +} + +func (a *Agent) getServerResourcePayload(ctx context.Context, name string) (map[string]any, error) { + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + return nil, os.ErrNotExist + } + + if a.resourceStats == nil { + return a.collectServerResourcePayload(ctx, name, serverDir, nil), nil + } + + entry := a.resourceStats.get(name) + entry.mu.Lock() + defer entry.mu.Unlock() + + now := time.Now() + entry.touchedAt = now + if entry.payload != nil && now.Before(entry.expiresAt) { + // Return a deep copy: the cached map is shared across concurrent + // requests for the same server. Callers mutate (e.g. add baseDir) and + // JSON-encode the result outside of this lock, so handing out the + // cached map directly causes "concurrent map writes". + return deepCopyPayload(entry.payload), nil + } + + payload := a.collectServerResourcePayload(ctx, name, serverDir, entry) + entry.payload = payload + entry.expiresAt = now.Add(a.resourceStats.ttl) + // Hand the caller its own copy and keep the cache copy private. + return deepCopyPayload(payload), nil +} + +func (a *Agent) collectServerResourcePayload(ctx context.Context, name, serverDir string, entry *serverResourceStatsCacheEntry) map[string]any { + meta := a.loadMeta(serverDir) + status := "stopped" + now := time.Now() + + memoryUsedMb := float64(0) + memoryLimitMb := resourceRamLimitMbFromMeta(meta) + memoryPercent := float64(0) + uptimeSeconds := int64(0) + + cpuEffCores, cpuMaxPercent := computeCpuLimit(metaCpuCores(meta)) + cpuPercent := float64(0) + + networkRule := networkAntiAbuseRuleFromMeta(meta) + var networkPayload map[string]any + if entry != nil && entry.seenNetwork { + networkPayload = buildNetworkStatsPayload(entry.totalRx, entry.totalTx) + attachNetworkAntiAbusePayload(networkPayload, networkRule, entry.networkWindowRx, entry.networkWindowTx, entry.networkWindowStartedAt) + } + + inspected, exists, inspectErr := a.inspectContainerForStats(ctx, name) + if inspectErr != nil { + status = "unknown" + } else if exists { + status = normalizeDockerContainerStatus(inspected.State.Status) + if inspected.State.Running { + status = "running" + + if appliedMemoryMb := hostConfigMemoryLimitMb(inspected.HostConfig); appliedMemoryMb > 0 { + memoryLimitMb = appliedMemoryMb + } + if appliedCPULimit := hostConfigCpuLimitPercent(inspected.HostConfig); appliedCPULimit > 0 { + cpuMaxPercent = appliedCPULimit + cpuEffCores = appliedCPULimit / 100.0 + } + + if strings.TrimSpace(inspected.State.StartedAt) != "" { + if startTime, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(inspected.State.StartedAt)); err == nil { + uptimeSeconds = int64(time.Since(startTime).Seconds()) + } + } + + if stats, err := a.readContainerStatsForServer(ctx, name); err == nil { + cpuPercent = dockerCPUPercent(stats) + if cpuMaxPercent > 0 && cpuPercent > cpuMaxPercent { + cpuPercent = cpuMaxPercent + } + + memoryUsedMb = float64(dockerMemoryUsedBytes(stats.MemoryStats)) / (1024 * 1024) + if memoryLimitMb > 0 { + memoryPercent = (memoryUsedMb / memoryLimitMb) * 100 + } + + if len(stats.Networks) > 0 && entry != nil { + rawRx, rawTx := sumDockerNetworkBytes(stats.Networks) + totalRx, totalTx, windowRx, windowTx, windowStartedAt := entry.updateNetworkCounters(inspected.ID, rawRx, rawTx, now, networkRule.resetEvery) + networkPayload = buildNetworkStatsPayload(totalRx, totalTx) + attachNetworkAntiAbusePayload(networkPayload, networkRule, windowRx, windowTx, windowStartedAt) + } + } + } + } + + var serverBytes int64 + if entry != nil { + serverBytes = entry.cachedDiskUsage(a, serverDir, now, a.resourceStats.diskTTL) + } else { + serverBytes = a.getServerDiskUsage(serverDir) + } + + // adpanel:backup-storage - backups live outside serverDir, so add them on top + // of the server-file usage. The combined value is what the panel shows and + // what the disk-limit guard enforces, so "server occupied storage + backups" + // is a single, consistent number everywhere. + var backupsBytes int64 + if entry != nil { + backupsBytes = entry.cachedBackupsUsage(a, name, now, a.resourceStats.diskTTL) + } else { + backupsBytes = a.getServerBackupsUsage(name) + } + + diskUsageBytes := serverBytes + backupsBytes + diskUsageMb := float64(diskUsageBytes) / (1024 * 1024) + diskUsageGb := float64(diskUsageBytes) / (1024 * 1024 * 1024) + serverUsageMb := float64(serverBytes) / (1024 * 1024) + backupsUsageMb := float64(backupsBytes) / (1024 * 1024) + + storageLimitMb := resourceStorageLimitMbFromMeta(meta) + diskInfo := map[string]any{ + "usedBytes": diskUsageBytes, + "usedMb": diskUsageMb, + "usedGb": diskUsageGb, + // Breakdown so the UI can render "server files + backups". + "serverBytes": serverBytes, + "serverMb": serverUsageMb, + "backupsBytes": backupsBytes, + "backupsMb": backupsUsageMb, + } + diskPercent := float64(0) + if storageLimitMb > 0 { + limitBytes := int64(storageLimitMb) * 1024 * 1024 + diskInfo["limitBytes"] = limitBytes + diskInfo["limitGb"] = storageLimitMb / 1024 + diskInfo["limitMb"] = storageLimitMb + if limitBytes > 0 { + diskPercent = (float64(diskUsageBytes) / float64(limitBytes)) * 100 + } + diskInfo["percentUsed"] = diskPercent + } + + stats := map[string]any{ + "cpu": map[string]any{ + "percent": cpuPercent, + "cores": cpuEffCores, + "limit": cpuMaxPercent, + }, + "memory": map[string]any{ + "usedMb": memoryUsedMb, + "limitMb": memoryLimitMb, + "percent": memoryPercent, + }, + "disk": map[string]any{ + "usedMb": diskUsageMb, + "limitMb": storageLimitMb, + "percent": diskPercent, + "serverMb": serverUsageMb, + "backupsMb": backupsUsageMb, + }, + } + if networkPayload != nil { + stats["network"] = networkPayload + } + + payload := map[string]any{ + "ok": true, + "name": name, + "status": status, + "meta": meta, + "disk": diskInfo, + "stats": stats, + "uptime": uptimeSeconds, + } + if networkPayload != nil { + payload["network"] = networkPayload + } + return payload +} + +func (a *Agent) handleServerInfo(w http.ResponseWriter, r *http.Request, name string) { + ctx, cancel := context.WithTimeout(r.Context(), 3500*time.Millisecond) + defer cancel() + + payload, err := a.getServerResourcePayload(ctx, name) + if errors.Is(err, os.ErrNotExist) { + jsonWrite(w, 404, map[string]any{"error": "not found"}) + return + } + if err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to collect resource stats"}) + return + } + // adpanel:multidisk - expose the resolved per-server baseDir / disk routing on the + // SAME GET /v1/servers/ response that carries live stats. Previously a + // dedicated early-return handler answered this route with only the baseDir fields + // and no stats/uptime/network, which made the panel render "—" for every metric of + // servers it resolved through this endpoint (notably secondary-disk servers). Merge + // both concerns into one payload so the panel gets disk routing *and* live stats. + if payload != nil { + disk := a.diskForServer(name) + payload["baseDir"] = a.serverDir(name) + payload["diskId"] = disk.ID + payload["diskRoot"] = a.diskLayoutVolumes(disk.MountPath) + payload["primary"] = disk.Primary || disk.ID == primaryDiskID + } + jsonWrite(w, 200, payload) +} + +func (a *Agent) handleGetResources(w http.ResponseWriter, r *http.Request, name string) { + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "not found"}) + return + } + + meta := a.loadMeta(serverDir) + resources, _ := meta["resources"].(map[string]any) + if resources == nil { + resources = make(map[string]any) + } + + if _, hasMb := resources["storageMb"]; !hasMb { + if gb, hasGb := resources["storageGb"]; hasGb { + var gbVal float64 + switch v := gb.(type) { + case float64: + gbVal = v + case int: + gbVal = float64(v) + case int64: + gbVal = float64(v) + } + if gbVal > 0 { + resources["storageMb"] = int(gbVal * 1024) + } + } + } + configuredCommand := "" + command := "" + commandSource := "" + imageDefaultCommand := "" + imageRef := "" + templateType := "" + javaVersion := "" + if t, ok := meta["template"].(string); ok { + templateType = t + } else if t, ok := meta["type"].(string); ok { + templateType = t + } + startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj != nil { + configuredCommand = normalizeLegacyRuntimeProcessCommand(templateType, fmt.Sprint(runtimeObj["command"]), startFile, defaultDataDirForType(templateType)) + adpanelStartup := startupTemplateFromRuntime(runtimeObj) + if adpanelStartup != "" { + configuredCommand = "" + command = adpanelStartup + commandSource = "adpanel-startup" + } + image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) + if image != "" && image != "" { + if tag == "" || tag == "" { + tag = "latest" + } + imageRef = image + ":" + tag + javaVersion = normalizeMinecraftJavaVersion(runtimeObj["javaVersion"]) + if javaVersion == "" { + javaVersion = minecraftJavaVersionFromTag(tag) + } + } + } + if command == "" && configuredCommand != "" { + command = configuredCommand + commandSource = "configured" + } + if command == "" { + command = defaultRuntimeCommandForType( + templateType, + startFile, + defaultDataDirForType(templateType), + ) + if command != "" { + commandSource = "template-default" + } + } + if command == "" && imageRef != "" { + inspectCtx, inspectCancel := context.WithTimeout(context.Background(), 8*time.Second) + imgCfg := a.inspectRuntimeImageConfig(inspectCtx, imageRef) + inspectCancel() + imageDefaultCommand = normalizeLegacyRuntimeProcessCommand( + templateType, + runtimeCommandFromImageConfig(imgCfg), + startFile, + defaultDataDirForType(templateType), + ) + if imageDefaultCommand != "" && validateRuntimeProcessCommand(imageDefaultCommand) == "" { + command = imageDefaultCommand + commandSource = "image-default" + } + } + if command == "" && imageRef != "" { + command = "sleep infinity" + commandSource = "fallback" + } + + template := templateType + + var memoryUsedMb, memoryLimitMb float64 + if res, ok := resources["ramMb"]; ok { + switch v := res.(type) { + case float64: + memoryLimitMb = v + case int: + memoryLimitMb = float64(v) + case int64: + memoryLimitMb = float64(v) + } + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if a.docker.containerExists(ctx, name) { + out, _, _, err := a.docker.runCollect(ctx, "inspect", "-f", "{{.State.Running}}", name) + if err == nil && strings.TrimSpace(out) == "true" { + if inspectedMemoryLimitMb, _, inspectErr := a.inspectContainerAppliedLimits(ctx, name); inspectErr == nil && inspectedMemoryLimitMb > 0 { + memoryLimitMb = inspectedMemoryLimitMb + } + statsOut, _, _, statsErr := a.docker.runCollect(ctx, "stats", "--no-stream", "--format", + "{{.MemUsage}}", name) + if statsErr == nil && strings.TrimSpace(statsOut) != "" { + memParts := strings.Split(strings.TrimSpace(statsOut), "/") + if len(memParts) >= 2 { + memoryUsedMb = parseMemoryString(strings.TrimSpace(memParts[0])) + } + } + } + } + + stats := map[string]any{ + "memory": map[string]any{ + "usedMb": memoryUsedMb, + "limitMb": memoryLimitMb, + }, + } + + var hostPort int + if port, ok := parseStrictPortValue(meta["hostPort"]); ok { + hostPort = port + } + + payload := map[string]any{ + "ok": true, + "resources": resources, + "command": command, + "configuredCommand": configuredCommand, + "effectiveCommand": command, + "commandSource": commandSource, + "imageDefaultCommand": imageDefaultCommand, + "imageRef": imageRef, + "template": template, + "stats": stats, + "hostPort": hostPort, + } + if strings.EqualFold(strings.TrimSpace(templateType), "minecraft") { + payload["javaVersion"] = javaVersion + payload["minecraftJava"] = minecraftJavaOptionsPayload(javaVersion) + } + jsonWrite(w, 200, payload) +} + +func (a *Agent) buildEffectiveDockerCommand(name, serverDir string, meta map[string]any) string { + typ := strings.ToLower(fmt.Sprint(meta["type"])) + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + runtimeObj = make(map[string]any) + } + + hostPort := 0 + if port, ok := parseStrictPortValue(meta["hostPort"]); ok { + hostPort = port + } + + resources := resourceLimitsFromMeta(meta) + appendPerformancePreviewArgs := func(parts []string) []string { + if resources == nil { + return parts + } + if resources.PidsLimit != nil && *resources.PidsLimit >= minPidsLimit && *resources.PidsLimit <= maxPidsLimit { + parts = append(parts, "--pids-limit", fmt.Sprintf("%d", *resources.PidsLimit)) + } + if resources.CpuWeight != nil && *resources.CpuWeight >= minCpuWeight && *resources.CpuWeight <= maxCpuWeight { + parts = append(parts, "--cpu-shares", fmt.Sprintf("%d", dockerCpuSharesFromWeight(*resources.CpuWeight))) + } + if resources.IoWeight != nil && *resources.IoWeight >= minIoWeight && *resources.IoWeight <= maxIoWeight { + parts = append(parts, "--blkio-weight", fmt.Sprintf("%d", *resources.IoWeight)) + } + if resources.FileLimit != nil && *resources.FileLimit >= minFileLimit && *resources.FileLimit <= maxFileLimit { + parts = append(parts, "--ulimit", fmt.Sprintf("nofile=%d:%d", *resources.FileLimit, *resources.FileLimit)) + } + return parts + } + + rm, _ := meta["resources"].(map[string]any) + var ramMb, cpuCoresVal, swapMb float64 + var hasRam, hasCpu, hasSwap bool + if rm != nil { + if v, ok := rm["ramMb"].(float64); ok && v > 0 { + ramMb = v + hasRam = true + } + if v, ok := rm["cpuCores"].(float64); ok && v > 0 { + cpuCoresVal = v + hasCpu = true + } + if v, ok := rm["swapMb"].(float64); ok { + swapMb = v + hasSwap = true + } + } + + switch typ { + case "minecraft": + if hostPort == 0 { + hostPort = 25565 + } + uid, gid := statUIDGID(serverDir) + parts := []string{dockerRunInteractivePrefix(), + "--name", name, + "--restart", "unless-stopped", + "-p", fmt.Sprintf("%d:25565", hostPort), + } + portForwardsMC := a.loadPortForwards(serverDir) + for _, pf := range portForwardsMC { + parts = append(parts, "-p", fmt.Sprintf("%d:%d", pf.Public, 25565)) + } + parts = append(parts, + "-v", fmt.Sprintf("%s:/data", serverDir), + "-e", "EULA=TRUE", + "-e", "TYPE=CUSTOM", + "-e", "CUSTOM_SERVER=/data/server.jar", + "-e", "ENABLE_RCON=false", + "-e", "CREATE_CONSOLE_IN_PIPE=true", + "-e", fmt.Sprintf("UID=%d", uid), + "-e", fmt.Sprintf("GID=%d", gid), + ) + if hasRam { + parts = append(parts, "--memory", fmt.Sprintf("%dm", int(ramMb))) + parts = append(parts, "--memory-reservation", fmt.Sprintf("%dm", int(ramMb*90/100))) + if !hasSwap || int(swapMb) == -1 { + parts = append(parts, "--memory-swap", fmt.Sprintf("%dm", int(ramMb))) + } else if int(swapMb) == 0 { + parts = append(parts, "--memory-swap", "-1") + } else { + parts = append(parts, "--memory-swap", fmt.Sprintf("%dm", int(ramMb)+int(swapMb))) + } + } + if hasCpu && cpuCoresVal <= 128 { + cpuQuota := int64(float64(cpuPeriod) * cpuCoresVal) + parts = append(parts, "--cpu-period", fmt.Sprintf("%d", cpuPeriod)) + parts = append(parts, "--cpu-quota", fmt.Sprintf("%d", cpuQuota)) + } + parts = appendPerformancePreviewArgs(parts) + mcImage := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + mcTag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) + if mcImage == "" || mcImage == "" { + mcImage = "itzg/minecraft-server" + } + if mcTag == "" || mcTag == "" { + mcTag = "latest" + } + parts = append(parts, mcImage+":"+mcTag) + return strings.Join(parts, " ") + + case "python", "nodejs", "discord-bot", "runtime": + isPython := typ == "python" + isNode := typ == "nodejs" || typ == "discord-bot" + image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) + if image == "" || image == "" { + if isPython { + image = "python" + } else { + image = "node" + } + } + if tag == "" || tag == "" { + if isPython { + tag = "3.12-slim" + } else { + tag = "20-alpine" + } + } + imageRef := image + ":" + tag + + parts := []string{dockerRunInteractivePrefix(), "--name", name, "--restart", "unless-stopped"} + if hasRam { + parts = append(parts, "--memory", fmt.Sprintf("%dm", int(ramMb))) + parts = append(parts, "--memory-reservation", fmt.Sprintf("%dm", int(ramMb*90/100))) + if !hasSwap || int(swapMb) == -1 { + parts = append(parts, "--memory-swap", fmt.Sprintf("%dm", int(ramMb))) + } else if int(swapMb) == 0 { + parts = append(parts, "--memory-swap", "-1") + } else { + parts = append(parts, "--memory-swap", fmt.Sprintf("%dm", int(ramMb)+int(swapMb))) + } + } + if hasCpu && cpuCoresVal <= 128 { + cpuQuota := int64(float64(cpuPeriod) * cpuCoresVal) + parts = append(parts, "--cpu-period", fmt.Sprintf("%d", cpuPeriod)) + parts = append(parts, "--cpu-quota", fmt.Sprintf("%d", cpuQuota)) + } + parts = appendPerformancePreviewArgs(parts) + if hostPort > 0 { + parts = append(parts, "-p", fmt.Sprintf("%d:%d", hostPort, hostPort)) + } + portForwardsRT := a.loadPortForwards(serverDir) + for _, pf := range portForwardsRT { + parts = append(parts, "-p", fmt.Sprintf("%d:%d", pf.Public, pf.Internal)) + } + vols := []string{fmt.Sprintf("%s:/app", serverDir)} + if runtimeVolumes := runtimeStringSlice(runtimeObj["volumes"]); len(runtimeVolumes) > 0 { + vols = vols[:0] + for _, s := range runtimeVolumes { + if s != "" { + vols = append(vols, s) + } + } + if len(vols) == 0 { + vols = []string{fmt.Sprintf("%s:/app", serverDir)} + } + } + for _, v := range vols { + parts = append(parts, "-v", v) + } + if env := runtimeEnvMap(runtimeObj["env"]); len(env) > 0 { + for k, v := range env { + parts = append(parts, "-e", fmt.Sprintf("%s=%s", k, v)) + } + } + if hostPort > 0 { + parts = append(parts, "-e", fmt.Sprintf("PORT=%d", hostPort)) + } + uid, gid := statUIDGID(serverDir) + parts = append(parts, "-e", fmt.Sprintf("UID=%d", uid)) + parts = append(parts, "-e", fmt.Sprintf("GID=%d", gid)) + parts = append(parts, imageRef) + + startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) + if startFile == "" || startFile == "" { + if isPython { + startFile = "main.py" + } else { + startFile = "index.js" + } + } + cmd := strings.TrimSpace(fmt.Sprint(runtimeObj["command"])) + if cmd == "" || cmd == "" { + if isPython { + cmd = fmt.Sprintf("python /app/%s", startFile) + } else if isNode { + cmd = fmt.Sprintf("node /app/%s", startFile) + } + } + if cmd != "" { + cmd = normalizeLegacyRuntimeProcessCommand(typ, cmd, startFile, "/app") + if args, err := buildProcessCommandArgs(cmd); err == nil { + parts = append(parts, args...) + } + } + return strings.Join(parts, " ") + + default: + image := strings.TrimSpace(fmt.Sprint(runtimeObj["image"])) + tag := strings.TrimSpace(fmt.Sprint(runtimeObj["tag"])) + if image == "" || image == "" { + return "" + } + if tag == "" || tag == "" { + tag = "latest" + } + imageRef := image + ":" + tag + if hostPort == 0 { + hostPort = 8080 + } + parts := []string{dockerRunInteractivePrefix(), "--name", name, "--restart", "unless-stopped"} + if hasRam { + parts = append(parts, "--memory", fmt.Sprintf("%dm", int(ramMb))) + parts = append(parts, "--memory-reservation", fmt.Sprintf("%dm", int(ramMb*90/100))) + } + if hasCpu && cpuCoresVal <= 128 { + cpuQuota := int64(float64(cpuPeriod) * cpuCoresVal) + parts = append(parts, "--cpu-period", fmt.Sprintf("%d", cpuPeriod)) + parts = append(parts, "--cpu-quota", fmt.Sprintf("%d", cpuQuota)) + } + parts = appendPerformancePreviewArgs(parts) + defaultContainerPort := hostPort + if ports := runtimeIntSlice(runtimeObj["ports"]); len(ports) > 0 && ports[0] > 0 { + defaultContainerPort = ports[0] + } + parts = append(parts, "-p", fmt.Sprintf("%d:%d", hostPort, defaultContainerPort)) + portForwards := a.loadPortForwards(serverDir) + for _, pf := range portForwards { + containerPort := defaultContainerPort + if containerPort <= 0 { + containerPort = pf.Internal + } + parts = append(parts, "-p", fmt.Sprintf("%d:%d", pf.Public, containerPort)) + } + vols := []string{} + hasTemplateVols := false + if runtimeVolumes := runtimeStringSlice(runtimeObj["volumes"]); len(runtimeVolumes) > 0 { + for _, s := range runtimeVolumes { + if s != "" { + s = strings.ReplaceAll(s, "{BOT_DIR}", serverDir) + s = strings.ReplaceAll(s, "{SERVER_DIR}", serverDir) + vols = append(vols, s) + hasTemplateVols = true + } + } + } + if !hasTemplateVols { + inspCtx, inspCancel := context.WithTimeout(context.Background(), 10*time.Second) + imgCfg := a.docker.inspectImageConfig(inspCtx, imageRef) + inspCancel() + if len(imgCfg.Volumes) > 0 { + for _, p := range imgCfg.Volumes { + vols = append(vols, fmt.Sprintf("%s:%s", serverDir, p)) + } + } else if envPaths := getDataPathsFromEnv(imgCfg.Env); len(envPaths) > 0 { + vols = append(vols, fmt.Sprintf("%s:%s", serverDir, envPaths[0])) + } else if imgCfg.Workdir != "" && imgCfg.Workdir != "/" { + vols = append(vols, fmt.Sprintf("%s:%s", serverDir, imgCfg.Workdir)) + } else { + vols = append(vols, fmt.Sprintf("%s:/data", serverDir)) + } + } + for _, v := range vols { + parts = append(parts, "-v", v) + } + if env := runtimeEnvMap(runtimeObj["env"]); len(env) > 0 { + for k, v := range env { + parts = append(parts, "-e", fmt.Sprintf("%s=%s", k, v)) + } + } + if hostPort > 0 { + parts = append(parts, "-e", fmt.Sprintf("PORT=%d", hostPort)) + } + parts = append(parts, imageRef) + cmd := strings.TrimSpace(fmt.Sprint(runtimeObj["command"])) + if cmd != "" && cmd != "" { + parts = append(parts, "sh", "-lc", fmt.Sprintf("%q", cmd)) + } + return strings.Join(parts, " ") + } +} + +func (a *Agent) handleUpdateResources(w http.ResponseWriter, r *http.Request, name string) { + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "not found"}) + return + } + + var req struct { + Resources struct { + RamMb *int `json:"ramMb"` + CpuCores *float64 `json:"cpuCores"` + StorageMb *int `json:"storageMb"` + StorageGb *int `json:"storageGb"` + SwapMb *int `json:"swapMb"` + BackupsMax *int `json:"backupsMax"` + MaxSchedules *int `json:"maxSchedules"` + IoWeight *int `json:"ioWeight"` + CpuWeight *int `json:"cpuWeight"` + PidsLimit *int `json:"pidsLimit"` + FileLimit *int `json:"fileLimit"` + NetworkInboundLimitMb *int64 `json:"networkInboundLimitMb"` + NetworkOutboundLimitMb *int64 `json:"networkOutboundLimitMb"` + NetworkResetMinutes *int `json:"networkResetMinutes"` + Ports []int `json:"ports"` + Command *string `json:"command"` + StartupCommand *string `json:"startupCommand"` + JavaVersion *string `json:"javaVersion"` + } `json:"resources"` + Command *string `json:"command"` + MainPort *int `json:"mainPort"` + StartupCommand *string `json:"startupCommand"` + JavaVersion *string `json:"javaVersion"` + } + + if err := readJSON(w, r, 1<<20, &req); err != nil { + jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) + return + } + if (req.StartupCommand != nil && strings.TrimSpace(*req.StartupCommand) != "") || + (req.Resources.StartupCommand != nil && strings.TrimSpace(*req.Resources.StartupCommand) != "") { + jsonWrite(w, 400, map[string]any{"error": "raw docker startup commands are no longer supported"}) + return + } + if req.MainPort != nil { + if _, ok := parseStrictPortValue(*req.MainPort); !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid mainPort"}) + return + } + } + if reason := validateResourcePerformanceLimits(&resourceLimits{ + IoWeight: req.Resources.IoWeight, + CpuWeight: req.Resources.CpuWeight, + PidsLimit: req.Resources.PidsLimit, + FileLimit: req.Resources.FileLimit, + NetworkInboundLimitMb: req.Resources.NetworkInboundLimitMb, + NetworkOutboundLimitMb: req.Resources.NetworkOutboundLimitMb, + NetworkResetMinutes: req.Resources.NetworkResetMinutes, + }); reason != "" { + jsonWrite(w, 400, map[string]any{"error": reason}) + return + } + + metaMu := a.getMetaLock(serverDir) + metaMu.Lock() + defer metaMu.Unlock() + + meta := a.loadMeta(serverDir) + if meta == nil { + meta = make(map[string]any) + } + stripLegacyStartupCommandFields(meta) + + resources, ok := meta["resources"].(map[string]any) + if !ok { + resources = make(map[string]any) + } + + if req.Resources.RamMb != nil { + resources["ramMb"] = *req.Resources.RamMb + } + if req.Resources.CpuCores != nil { + resources["cpuCores"] = *req.Resources.CpuCores + } + if req.Resources.StorageMb != nil { + resources["storageMb"] = *req.Resources.StorageMb + delete(resources, "storageGb") + } else if req.Resources.StorageGb != nil { + resources["storageGb"] = *req.Resources.StorageGb + delete(resources, "storageMb") + } + if req.Resources.SwapMb != nil { + resources["swapMb"] = *req.Resources.SwapMb + } + if req.Resources.BackupsMax != nil { + resources["backupsMax"] = *req.Resources.BackupsMax + } + if req.Resources.MaxSchedules != nil { + resources["maxSchedules"] = *req.Resources.MaxSchedules + } + if req.Resources.IoWeight != nil { + resources["ioWeight"] = *req.Resources.IoWeight + } + if req.Resources.CpuWeight != nil { + resources["cpuWeight"] = *req.Resources.CpuWeight + } + if req.Resources.PidsLimit != nil { + resources["pidsLimit"] = *req.Resources.PidsLimit + } + if req.Resources.FileLimit != nil { + resources["fileLimit"] = *req.Resources.FileLimit + } + if req.Resources.NetworkInboundLimitMb != nil { + if *req.Resources.NetworkInboundLimitMb > 0 { + resources["networkInboundLimitMb"] = *req.Resources.NetworkInboundLimitMb + } else { + delete(resources, "networkInboundLimitMb") + } + } + if req.Resources.NetworkOutboundLimitMb != nil { + if *req.Resources.NetworkOutboundLimitMb > 0 { + resources["networkOutboundLimitMb"] = *req.Resources.NetworkOutboundLimitMb + } else { + delete(resources, "networkOutboundLimitMb") + } + } + if req.Resources.NetworkResetMinutes != nil { + if *req.Resources.NetworkResetMinutes > 0 { + resources["networkResetMinutes"] = *req.Resources.NetworkResetMinutes + } else { + delete(resources, "networkResetMinutes") + } + } + if req.Resources.Ports != nil { + validPorts := make([]int, 0, len(req.Resources.Ports)) + seenPorts := make(map[int]bool, len(req.Resources.Ports)) + for _, p := range req.Resources.Ports { + if _, ok := parseStrictPortValue(p); !ok { + jsonWrite(w, 400, map[string]any{"error": fmt.Sprintf("invalid port: %d", p)}) + return + } + if seenPorts[p] { + continue + } + seenPorts[p] = true + validPorts = append(validPorts, p) + } + resources["ports"] = validPorts + } + + meta["resources"] = resources + if req.MainPort != nil { + meta["hostPort"] = *req.MainPort + } + + javaVersionProvided := req.JavaVersion != nil || req.Resources.JavaVersion != nil + if javaVersionProvided { + rawJavaVersion := "" + if req.JavaVersion != nil { + rawJavaVersion = *req.JavaVersion + } else if req.Resources.JavaVersion != nil { + rawJavaVersion = *req.Resources.JavaVersion + } + cleanJavaVersion := normalizeMinecraftJavaVersion(rawJavaVersion) + if cleanJavaVersion == "" { + jsonWrite(w, 400, map[string]any{"error": "unsupported minecraft java version"}) + return + } + templateType := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) + if templateType == "" { + templateType = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) + } + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + runtimeObj = make(map[string]any) + } + commandLooksMinecraft := strings.Contains(strings.ToLower(sanitizeRuntimeCommand(runtimeObj["command"])), "server.jar") + if templateType != "minecraft" && !strings.Contains(templateType, "minecraft") && !commandLooksMinecraft { + jsonWrite(w, 400, map[string]any{"error": "java version selection is only available for minecraft"}) + return + } + runtimeObj["image"] = defaultMinecraftProcessImage + runtimeObj["tag"] = minecraftJavaTag(cleanJavaVersion) + runtimeObj["javaVersion"] = cleanJavaVersion + if sanitizeRuntimeCommand(runtimeObj["command"]) == "" { + runtimeObj["command"] = defaultMinecraftProcessCommand + } + if normalizeContainerWorkdir(runtimeObj["workdir"]) == "" { + runtimeObj["workdir"] = defaultDataDirForType("minecraft") + } + meta["runtime"] = runtimeObj + } + + commandProvided := req.Command != nil || req.Resources.Command != nil + if commandProvided { + rawCommand := "" + if req.Command != nil { + rawCommand = *req.Command + } else if req.Resources.Command != nil { + rawCommand = *req.Resources.Command + } + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + runtimeObj = make(map[string]any) + } + templateType := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) + if templateType == "" { + templateType = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) + } + startFile := strings.TrimSpace(fmt.Sprint(meta["start"])) + cleanCommand := normalizeLegacyRuntimeProcessCommand(templateType, rawCommand, startFile, defaultDataDirForType(templateType)) + if cleanCommand != "" { + if reason := validateRuntimeProcessCommand(cleanCommand); reason != "" { + jsonWrite(w, 400, map[string]any{"error": reason}) + return + } + } + if cleanCommand == "" { + delete(runtimeObj, "command") + } else { + runtimeObj["command"] = cleanCommand + } + meta["runtime"] = runtimeObj + } + + if err := a.saveMeta(serverDir, meta); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to save meta"}) + return + } + + if a.debug { + a.logf("[resources] Updated resources for %s: %+v", name, resources) + } + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "resources": resources, + "command": func() string { + if runtimeObj, ok := meta["runtime"].(map[string]any); ok { + return sanitizeRuntimeCommand(runtimeObj["command"]) + } + return "" + }(), + "javaVersion": func() string { + if runtimeObj, ok := meta["runtime"].(map[string]any); ok { + return normalizeMinecraftJavaVersion(runtimeObj["javaVersion"]) + } + return "" + }(), + "hostPort": meta["hostPort"], + }) +} + +func (a *Agent) handleGetPortForwards(w http.ResponseWriter, r *http.Request, name string) { + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "not found"}) + return + } + meta := a.loadMeta(serverDir) + portForwards := []map[string]any{} + if pf, ok := meta["portForwards"].([]any); ok { + for _, item := range pf { + if m, ok := item.(map[string]any); ok { + pub, pubOk := parseStrictPortValue(m["publicPort"]) + internal, internalOk := parseStrictPortValue(m["internalPort"]) + if pubOk && internalOk { + portForwards = append(portForwards, map[string]any{ + "publicPort": pub, + "internalPort": internal, + }) + } + } + } + } + + hostPort := 0 + if port, ok := parseStrictPortValue(meta["hostPort"]); ok { + hostPort = port + } + allocatedPorts := []int{} + if hostPort > 0 { + allocatedPorts = append(allocatedPorts, hostPort) + } + if resources, ok := meta["resources"].(map[string]any); ok { + for _, port := range runtimeIntSlice(resources["ports"]) { + if port > 0 { + allocatedPorts = append(allocatedPorts, port) + } + } + } + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "portForwards": portForwards, + "hostPort": meta["hostPort"], + "allocatedPorts": allocatedPorts, + }) +} + +func (a *Agent) handleUpdatePortForwards(w http.ResponseWriter, r *http.Request, name string) { + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "not found"}) + return + } + + var req struct { + PortForwards []struct { + PublicPort int `json:"publicPort"` + InternalPort int `json:"internalPort"` + } `json:"portForwards"` + } + if err := readJSON(w, r, 1<<20, &req); err != nil { + jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) + return + } + + metaMu := a.getMetaLock(serverDir) + metaMu.Lock() + defer metaMu.Unlock() + + meta := a.loadMeta(serverDir) + if meta == nil { + meta = make(map[string]any) + } + + allocatedSet := make(map[int]bool) + hostPort := 0 + if port, ok := parseStrictPortValue(meta["hostPort"]); ok { + hostPort = port + } + if hostPort > 0 { + allocatedSet[hostPort] = true + } + if resources, ok := meta["resources"].(map[string]any); ok { + for _, port := range runtimeIntSlice(resources["ports"]) { + if port > 0 { + allocatedSet[port] = true + } + } + } + + forwards := make([]map[string]any, 0, len(req.PortForwards)) + seen := make(map[int]bool) + for _, pf := range req.PortForwards { + if pf.PublicPort < 1 || pf.PublicPort > 65535 { + jsonWrite(w, 400, map[string]any{"error": fmt.Sprintf("invalid public port: %d", pf.PublicPort)}) + return + } + if pf.InternalPort < 1 || pf.InternalPort > 65535 { + jsonWrite(w, 400, map[string]any{"error": fmt.Sprintf("invalid internal port: %d", pf.InternalPort)}) + return + } + if !allocatedSet[pf.InternalPort] { + jsonWrite(w, 400, map[string]any{"error": fmt.Sprintf("internal port %d is not allocated to this server", pf.InternalPort)}) + return + } + if seen[pf.PublicPort] { + jsonWrite(w, 400, map[string]any{"error": fmt.Sprintf("duplicate public port: %d", pf.PublicPort)}) + return + } + seen[pf.PublicPort] = true + forwards = append(forwards, map[string]any{ + "publicPort": pf.PublicPort, + "internalPort": pf.InternalPort, + }) + } + + meta["portForwards"] = forwards + if err := a.saveMeta(serverDir, meta); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to save meta"}) + return + } + + fmt.Printf("[port-forwards] Updated port forwards for %s: %d rules\n", name, len(forwards)) + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) loadPortForwards(serverDir string) []struct{ Public, Internal int } { + meta := a.loadMeta(serverDir) + var result []struct{ Public, Internal int } + pf, ok := meta["portForwards"].([]any) + if !ok { + return result + } + for _, item := range pf { + m, ok := item.(map[string]any) + if !ok { + continue + } + pub, pubOk := parseStrictPortValue(m["publicPort"]) + internal, internalOk := parseStrictPortValue(m["internalPort"]) + if pubOk && internalOk { + result = append(result, struct{ Public, Internal int }{pub, internal}) + } + } + return result +} + +func (a *Agent) handleExtractImage(w http.ResponseWriter, r *http.Request, name string) { + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "not found"}) + return + } + if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil { + jsonWrite(w, 507, diskErr) + return + } + + var req struct { + Image string `json:"image"` + Tag string `json:"tag"` + ExtractPath string `json:"extractPath"` + Paths []string `json:"paths"` + } + + if err := readJSON(w, r, 1<<20, &req); err != nil { + jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) + return + } + + image := strings.TrimSpace(req.Image) + tag := strings.TrimSpace(req.Tag) + + if image == "" { + meta := a.loadMeta(serverDir) + if meta != nil { + if rt, ok := meta["runtime"].(map[string]any); ok { + image = strings.TrimSpace(fmt.Sprint(rt["image"])) + if tag == "" { + tag = strings.TrimSpace(fmt.Sprint(rt["tag"])) + } + } + } + } + + if image == "" { + jsonWrite(w, 400, map[string]any{"error": "no image specified"}) + return + } + + if tag == "" { + tag = "latest" + } + imageRef := image + ":" + tag + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Minute) + defer cancel() + + fmt.Printf("[extract-image] Pulling image %s for server %s\n", imageRef, name) + a.docker.pull(ctx, imageRef) + + extractPaths := req.Paths + if len(extractPaths) == 0 && req.ExtractPath != "" { + extractPaths = []string{req.ExtractPath} + } + if len(extractPaths) == 0 { + extractPaths = []string{ + "/ragemp", "/fivem", "/config", "/server", "/gameserver", + "/rust", "/ark", "/minecraft", "/csgo", "/valheim", + "/app", "/data", "/opt", "/home", + "/usr/src/app", "/usr/app", "/var/www", "/srv", + } + } + + var extractedPath string + for _, extractPath := range extractPaths { + err := a.docker.extractImageFiles(ctx, imageRef, serverDir, extractPath) + if err == nil { + extractedPath = extractPath + fmt.Printf("[extract-image] Extracted files from %s:%s to %s\n", imageRef, extractPath, serverDir) + break + } + } + + if extractedPath == "" { + jsonWrite(w, 200, map[string]any{ + "ok": true, + "extracted": false, + "message": "Could not extract files - image may not have files in common locations", + }) + return + } + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "extracted": true, + "path": extractedPath, + "image": imageRef, + }) +} + +func (a *Agent) handleImportArchive(w http.ResponseWriter, r *http.Request, name string) { + srvDir := a.serverDir(name) + + if st, err := os.Stat(srvDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "server not found", "detail": "Server directory does not exist"}) + return + } + if diskErr := a.checkDiskLimit(srvDir, 0); diskErr != nil { + jsonWrite(w, 507, diskErr) + return + } + + var req struct { + ArchiveUrl string `json:"archiveUrl"` + } + + if err := readJSON(w, r, 1<<20, &req); err != nil { + jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) + return + } + + archiveUrl := strings.TrimSpace(req.ArchiveUrl) + if archiveUrl == "" { + jsonWrite(w, 400, map[string]any{"error": "archiveUrl is required"}) + return + } + + parsedUrl, err := url.Parse(archiveUrl) + if err != nil || (parsedUrl.Scheme != "http" && parsedUrl.Scheme != "https") { + jsonWrite(w, 400, map[string]any{"error": "invalid URL - must be http or https"}) + return + } + + pathname := strings.ToLower(parsedUrl.Path) + validExt := false + allowedExts := []string{".zip", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".7z", ".rar"} + for _, ext := range allowedExts { + if strings.HasSuffix(pathname, ext) { + validExt = true + break + } + } + if !validExt { + jsonWrite(w, 400, map[string]any{"error": "invalid archive format. Supported: .zip, .tar.gz, .tgz, .tar.bz2, .tbz2, .7z, .rar"}) + return + } + + a.importProgressMu.Lock() + a.importProgress[name] = &ImportProgress{ + Status: "downloading", + Percent: 0, + Downloaded: 0, + Total: 0, + } + a.importProgressMu.Unlock() + + go a.downloadAndExtractArchive(name, srvDir, archiveUrl) + + jsonWrite(w, 200, map[string]any{"ok": true, "message": "Import started"}) +} + +func (a *Agent) handleExportServer(w http.ResponseWriter, r *http.Request, name string) { + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "server not found"}) + return + } + + rc := http.NewResponseController(w) + _ = rc.SetWriteDeadline(time.Time{}) + + backupsDir := a.serverBackupsDir(name) + + sizeBytes, _ := getDirSizeBytes(serverDir) + if st, err := os.Stat(backupsDir); err == nil && st.IsDir() { + if bsz, err := getDirSizeBytes(backupsDir); err == nil { + sizeBytes += bsz + } + } + if sizeBytes > 0 { + w.Header().Set("X-ADPanel-Server-Bytes", fmt.Sprint(sizeBytes)) + } + w.Header().Set("Content-Type", "application/x-tar") + w.Header().Set("Content-Disposition", fmt.Sprintf("attachment; filename=%s.tar", name)) + + tw := tar.NewWriter(w) + defer tw.Close() + + err := filepath.Walk(serverDir, func(p string, info os.FileInfo, err error) error { + if err != nil || info == nil { + return nil + } + rel, relErr := filepath.Rel(serverDir, p) + if relErr != nil { + return nil + } + if rel == "." { + return nil + } + if info.Mode()&os.ModeSymlink != 0 { + return nil + } + + hdr, hdrErr := tar.FileInfoHeader(info, "") + if hdrErr != nil { + return nil + } + hdr.Name = filepath.ToSlash(rel) + if info.IsDir() && !strings.HasSuffix(hdr.Name, "/") { + hdr.Name += "/" + } + if err := tw.WriteHeader(hdr); err != nil { + return err + } + if !info.Mode().IsRegular() { + return nil + } + f, openErr := os.Open(p) + if openErr != nil { + return nil + } + _, _ = io.Copy(tw, f) + f.Close() + return nil + }) + if err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to walk directory"}) + return + } + + if st, err := os.Stat(backupsDir); err == nil && st.IsDir() { + err := filepath.Walk(backupsDir, func(p string, info os.FileInfo, err error) error { + if err != nil || info == nil { + return nil + } + rel, relErr := filepath.Rel(backupsDir, p) + if relErr != nil { + return nil + } + if rel == "." { + return nil + } + if info.Mode()&os.ModeSymlink != 0 { + return nil + } + + hdr, hdrErr := tar.FileInfoHeader(info, "") + if hdrErr != nil { + return nil + } + hdr.Name = ".adpanel_backups/" + filepath.ToSlash(rel) + if info.IsDir() && !strings.HasSuffix(hdr.Name, "/") { + hdr.Name += "/" + } + if err := tw.WriteHeader(hdr); err != nil { + return err + } + if !info.Mode().IsRegular() { + return nil + } + f, openErr := os.Open(p) + if openErr != nil { + return nil + } + _, _ = io.Copy(tw, f) + f.Close() + return nil + }) + if err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to walk directory"}) + return + } + } + + metaPath := a.metaPath(name) + if metaInfo, metaErr := os.Stat(metaPath); metaErr == nil && metaInfo.Mode().IsRegular() { + hdr, hdrErr := tar.FileInfoHeader(metaInfo, "") + if hdrErr == nil { + hdr.Name = ".adpanel_meta/" + sanitizeName(name) + ".json" + if err := tw.WriteHeader(hdr); err == nil { + if f, openErr := os.Open(metaPath); openErr == nil { + _, _ = io.Copy(tw, f) + f.Close() + } + } + } + } +} + +// purgeServerCopiesOnAllDisks removes any existing copy of a server's volumes and +// backups directories from EVERY disk this node owns (primary + registered). +// adpanel:multidisk - used before an import/transfer extraction so the server is +// placed cleanly on exactly one target disk. Without this, a re-transfer that +// changes the destination disk (e.g. secondary -> primary) would leave the old +// copy behind; the back-compat scan in diskForServer would then re-adopt the +// stale secondary directory and orphan the freshly imported files. Removing all +// copies up front makes placement deterministic regardless of prior history. +func (a *Agent) purgeServerCopiesOnAllDisks(name string) { + safe := sanitizeName(name) + if safe == "" { + return + } + // Primary disk roots. + _ = os.RemoveAll(filepath.Join(a.volumesDir, safe)) + _ = os.RemoveAll(filepath.Join(a.backupsDir(), safe)) + // Every registered (secondary) disk. + for _, d := range a.registeredDisks() { + _ = os.RemoveAll(filepath.Join(a.diskLayoutVolumes(d.MountPath), safe)) + _ = os.RemoveAll(filepath.Join(a.diskLayoutBackups(d.MountPath), safe)) + } +} + +func (a *Agent) handleImportTar(w http.ResponseWriter, r *http.Request, name string) { + if name == "" { + jsonWrite(w, 400, map[string]any{"error": "invalid name"}) + return + } + + // adpanel:multidisk - a transfer lands the server on a disk OWNED BY THIS + // (the destination) node. The incoming tar carries the SOURCE node's meta, + // whose __diskId references a disk that only exists on the source. Adopting + // that ID verbatim would mis-route the server (or, if this node happens to + // own a disk with the same ID, point it at the wrong/empty location) and + // orphan the extracted files. We therefore: + // 1. resolve the destination disk from an optional ?diskId= (default + // primary), priming the routing cache BEFORE computing any path so files + // extract onto the correct disk, and + // 2. extract the source meta into a temp dir (never verbatim into metaDir), + // strip its stale __diskId, re-stamp the destination disk's __diskId + // (omitted for primary, exactly like createServer), and persist it. + // This guarantees the panel/node always resolve a secondary-disk server to + // "/adpanel/volumes/" with backups at + // "/adpanel/backups/", and a primary-disk server to the + // default roots, across restarts and cold caches. + opMu := a.getServerOpLock(name) + opMu.Lock() + defer opMu.Unlock() + + targetDisk, diskOK := a.diskByID(strings.TrimSpace(r.URL.Query().Get("diskId"))) + if !diskOK { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid diskId"}) + return + } + a.setServerDiskMapping(name, targetDisk.ID) + + serverDir := a.serverDir(name) + if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil { + a.invalidateServerDiskCache(name) + jsonWrite(w, 507, diskErr) + return + } + if capErr := a.checkDiskCapacity(targetDisk, 0); capErr != nil { + a.invalidateServerDiskCache(name) + jsonWrite(w, 507, capErr) + return + } + // Remove any prior copy of this server on EVERY disk before extracting, so the + // import lands cleanly on the target disk and no stale copy (from an earlier + // transfer to a different disk) can be re-adopted later and orphan these files. + a.purgeServerCopiesOnAllDisks(name) + _ = os.RemoveAll(serverDir) + _ = ensureDir(serverDir) + + backupsDir := a.serverBackupsDir(name) + _ = os.RemoveAll(backupsDir) + _ = ensureDir(backupsDir) + + // Extract the incoming meta into a quarantine dir so the source's __diskId is + // never written into our metaDir as-is. We normalize and persist it below. + tmpMetaDir, mkErr := os.MkdirTemp("", "adpanel-import-meta-") + if mkErr != nil { + a.invalidateServerDiskCache(name) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed", "detail": "temp meta dir"}) + return + } + defer os.RemoveAll(tmpMetaDir) + + _ = ensureDir(a.metaDir()) + tr := tar.NewReader(r.Body) + if err := extractTarSafeRouted(tr, serverDir, backupsDir, tmpMetaDir); err != nil { + a.invalidateServerDiskCache(name) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed", "detail": err.Error()}) + return + } + + // Normalize and persist the destination-correct meta. + meta := map[string]any{} + importedMetaPath := filepath.Join(tmpMetaDir, sanitizeName(name)+".json") + if b, err := os.ReadFile(importedMetaPath); err == nil { + var m map[string]any + if json.Unmarshal(b, &m) == nil && m != nil { + meta = m + } + } + // The source's disk identity is meaningless here; drop it unconditionally. + delete(meta, "__diskId") + // Re-stamp this node's disk assignment. Omit for primary to keep meta minimal + // for the common single-disk case (mirrors createServer). + if !(targetDisk.Primary || targetDisk.ID == primaryDiskID) { + meta["__diskId"] = targetDisk.ID + } + if err := a.saveMeta(serverDir, meta); err != nil { + a.invalidateServerDiskCache(name) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed", "detail": "persist meta: " + err.Error()}) + return + } + + // Reload routing from the authoritative, just-written meta. + a.invalidateServerDiskCache(name) + a.setServerDiskMapping(name, targetDisk.ID) + + jsonWrite(w, 200, map[string]any{"ok": true, "diskId": targetDisk.ID}) +} + +func (a *Agent) downloadAndExtractArchive(name, serverDir, archiveUrl string) { + a.importSem <- struct{}{} + defer func() { <-a.importSem }() + + defer func() { + if r := recover(); r != nil { + fmt.Fprintf(os.Stderr, "[import-archive] panic recovered for %s: %v\n", name, r) + a.importProgressMu.Lock() + a.importProgress[name] = &ImportProgress{ + Status: "error", Error: "internal error", + } + a.importProgressMu.Unlock() + } + time.AfterFunc(5*time.Minute, func() { + a.importProgressMu.Lock() + delete(a.importProgress, name) + a.importProgressMu.Unlock() + }) + }() + + updateProgress := func(status string, percent int, downloaded, total int64, errMsg string) { + a.importProgressMu.Lock() + a.importProgress[name] = &ImportProgress{ + Status: status, + Percent: percent, + Downloaded: downloaded, + Total: total, + Error: errMsg, + } + a.importProgressMu.Unlock() + } + + if _, err := a.dl.safeURL(archiveUrl); err != nil { + updateProgress("error", 0, 0, 0, fmt.Sprintf("invalid URL: blocked by security policy")) + if a.debug { + fmt.Printf("[import-archive] SSRF blocked for %s: %v\n", name, err) + } + return + } + + if a.debug { + fmt.Printf("[import-archive] Starting download for server %s from %s\n", name, archiveUrl) + } + + dlCtx, dlCancel := context.WithTimeout(context.Background(), 30*time.Minute) + defer dlCancel() + req, err := http.NewRequestWithContext(dlCtx, "GET", archiveUrl, nil) + if err != nil { + if a.debug { + fmt.Printf("[import-archive] Request creation error for %s: %v\n", name, err) + } + updateProgress("error", 0, 0, 0, "download failed") + return + } + resp, err := a.dl.client().Do(req) + if err != nil { + if a.debug { + fmt.Printf("[import-archive] Download error for %s: %v\n", name, err) + } + updateProgress("error", 0, 0, 0, "download failed") + return + } + defer resp.Body.Close() + + if resp.StatusCode != 200 { + if a.debug { + fmt.Printf("[import-archive] HTTP error for %s: %d\n", name, resp.StatusCode) + } + updateProgress("error", 0, 0, 0, fmt.Sprintf("HTTP error: %d", resp.StatusCode)) + return + } + + totalSize := resp.ContentLength + if totalSize <= 0 { + totalSize = 0 + } + + tmpFile, err := os.CreateTemp("", "import-archive-*") + if err != nil { + updateProgress("error", 0, 0, 0, "failed to create temp file") + return + } + tmpPath := tmpFile.Name() + defer os.Remove(tmpPath) + + // adpanel:multidisk - enforce the per-server storage quota during import so a + // download (and subsequent extraction) can never push the server over its + // limit, regardless of which disk the server lives on. headroom is computed + // from the server's OWNING disk via serverDir (already disk-routed). + limitBytes := a.getServerDiskLimitBytes(serverDir) + var headroom int64 = -1 // -1 => unlimited + if limitBytes > 0 { + // adpanel:backup-storage - existing backups occupy quota, so subtract the + // combined (files + backups) usage when computing import headroom. + used := a.getServerTotalUsage(serverDir) + headroom = limitBytes - used + if headroom < 0 { + headroom = 0 + } + } + + var downloaded int64 = 0 + buf := make([]byte, 32*1024) + + for { + n, readErr := resp.Body.Read(buf) + if n > 0 { + downloaded += int64(n) + // Reject as soon as the import would exceed the server's quota. The + // archive's on-disk size is a lower bound on what extraction will add, + // so this is a safe, exploit-proof ceiling. + if headroom >= 0 && downloaded > headroom { + tmpFile.Close() + limitMb := float64(limitBytes) / (1024 * 1024) + updateProgress("error", 0, downloaded, totalSize, + fmt.Sprintf("disk limit exceeded: import would exceed the server's %.0f MB storage limit", limitMb)) + return + } + _, writeErr := tmpFile.Write(buf[:n]) + if writeErr != nil { + tmpFile.Close() + updateProgress("error", 0, downloaded, totalSize, "failed to write temp file") + return + } + + var percent int + if totalSize > 0 { + percent = int((downloaded * 100) / totalSize) + } else { + percent = 0 + } + updateProgress("downloading", percent, downloaded, totalSize, "") + } + if readErr == io.EOF { + break + } + if readErr != nil { + tmpFile.Close() + updateProgress("error", 0, downloaded, totalSize, fmt.Sprintf("download error: %v", readErr)) + return + } + } + tmpFile.Close() + + fmt.Printf("[import-archive] Download complete for %s: %d bytes\n", name, downloaded) + + updateProgress("extracting", 100, downloaded, totalSize, "") + + pathname := strings.ToLower(archiveUrl) + var extractErr error + + if strings.HasSuffix(pathname, ".zip") { + extractErr = extractZipSafe(tmpPath, serverDir) + } else if strings.HasSuffix(pathname, ".tar.gz") || strings.HasSuffix(pathname, ".tgz") { + extractErr = a.extractTarGzSafe(tmpPath, serverDir) + } else if strings.HasSuffix(pathname, ".tar.bz2") || strings.HasSuffix(pathname, ".tbz2") { + extractErr = a.extractTarBz2Safe(tmpPath, serverDir) + } else if strings.HasSuffix(pathname, ".tar.xz") || strings.HasSuffix(pathname, ".txz") { + extractErr = a.extractTarXzSafe(tmpPath, serverDir) + } else if strings.HasSuffix(pathname, ".7z") { + extractErr = a.extract7z(tmpPath, serverDir) + } else if strings.HasSuffix(pathname, ".rar") { + extractErr = a.extractRar(tmpPath, serverDir) + } else { + extractErr = fmt.Errorf("unsupported archive format") + } + + if extractErr != nil { + if a.debug { + fmt.Printf("[import-archive] Extract error for %s: %v\n", name, extractErr) + } + updateProgress("error", 100, downloaded, totalSize, fmt.Sprintf("extraction failed: %v", extractErr)) + return + } + + _ = sanitizeExtractedTree(serverDir) + + if a.debug { + fmt.Printf("[import-archive] Extraction complete for %s\n", name) + } + updateProgress("complete", 100, downloaded, totalSize, "") +} + +func (a *Agent) extractZip(zipPath, destDir string) error { + r, err := zip.OpenReader(zipPath) + if err != nil { + return err + } + defer r.Close() + + for _, f := range r.File { + fpath := filepath.Join(destDir, f.Name) + if !strings.HasPrefix(filepath.Clean(fpath), filepath.Clean(destDir)+string(os.PathSeparator)) { + continue + } + + if f.FileInfo().IsDir() { + os.MkdirAll(fpath, 0o755) + continue + } + + if err := os.MkdirAll(filepath.Dir(fpath), 0o755); err != nil { + return err + } + + outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|syscall.O_NOFOLLOW, sanitizeFileMode(f.Mode(), false)) + if err != nil { + return err + } + + rc, err := f.Open() + if err != nil { + outFile.Close() + return err + } + + _, err = io.Copy(outFile, rc) + rc.Close() + outFile.Close() + if err != nil { + return err + } + } + return nil +} + +func (a *Agent) extractTarGz(archivePath, destDir string) error { + f, err := os.Open(archivePath) + if err != nil { + return err + } + defer f.Close() + + gzr, err := gzip.NewReader(f) + if err != nil { + return err + } + defer gzr.Close() + + return a.extractTar(gzr, destDir) +} + +func (a *Agent) extractTarBz2(archivePath, destDir string) error { + f, err := os.Open(archivePath) + if err != nil { + return err + } + defer f.Close() + + bzr := bzip2.NewReader(f) + return a.extractTar(bzr, destDir) +} + +func (a *Agent) extractTarGzSafe(archivePath, destDir string) error { + f, err := os.Open(archivePath) + if err != nil { + return err + } + defer f.Close() + + gzr, err := gzip.NewReader(f) + if err != nil { + return err + } + defer gzr.Close() + + tr := tar.NewReader(gzr) + return extractTarSafe(tr, destDir) +} + +func (a *Agent) extractTarBz2Safe(archivePath, destDir string) error { + f, err := os.Open(archivePath) + if err != nil { + return err + } + defer f.Close() + + bzr := bzip2.NewReader(f) + tr := tar.NewReader(bzr) + return extractTarSafe(tr, destDir) +} + +func (a *Agent) extractTarXzSafe(archivePath, destDir string) error { + f, err := os.Open(archivePath) + if err != nil { + return err + } + defer f.Close() + + xzr, err := xz.NewReader(f) + if err != nil { + return err + } + tr := tar.NewReader(xzr) + return extractTarSafe(tr, destDir) +} + +func (a *Agent) extractTar(r io.Reader, destDir string) error { + tr := tar.NewReader(r) + + for { + header, err := tr.Next() + if err == io.EOF { + break + } + if err != nil { + return err + } + + fpath := filepath.Join(destDir, header.Name) + if !strings.HasPrefix(filepath.Clean(fpath), filepath.Clean(destDir)+string(os.PathSeparator)) { + continue + } + + switch header.Typeflag { + case tar.TypeDir: + if err := os.MkdirAll(fpath, 0o755); err != nil { + return err + } + case tar.TypeReg: + if err := os.MkdirAll(filepath.Dir(fpath), 0o755); err != nil { + return err + } + outFile, err := os.OpenFile(fpath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|syscall.O_NOFOLLOW, sanitizeFileMode(os.FileMode(header.Mode), false)) + if err != nil { + return err + } + if _, err := io.Copy(outFile, tr); err != nil { + outFile.Close() + return err + } + outFile.Close() + } + } + return nil +} + +func (a *Agent) extract7z(archivePath, destDir string) error { + tmpDir, err := os.MkdirTemp("", "adpanel-7z-*") + if err != nil { + return fmt.Errorf("failed to create temp dir: %v", err) + } + defer os.RemoveAll(tmpDir) + + cmd := exec.Command("7z", "x", "-y", "-o"+tmpDir, archivePath) + output, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("7z extraction failed: %v - %s", err, string(output)) + } + + return validateAndMoveExtracted(tmpDir, destDir) +} + +func (a *Agent) extractRar(archivePath, destDir string) error { + tmpDir, err := os.MkdirTemp("", "adpanel-rar-*") + if err != nil { + return fmt.Errorf("failed to create temp dir: %v", err) + } + defer os.RemoveAll(tmpDir) + + cmd := exec.Command("unrar", "x", "-y", archivePath, tmpDir+"/") + output, err := cmd.CombinedOutput() + if err != nil { + return fmt.Errorf("rar extraction failed: %v - %s", err, string(output)) + } + + return validateAndMoveExtracted(tmpDir, destDir) +} + +func validateAndMoveExtracted(tmpDir, destDir string) error { + return filepath.Walk(tmpDir, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + rel, err := filepath.Rel(tmpDir, path) + if err != nil { + return fmt.Errorf("cannot compute relative path: %v", err) + } + if rel == "." { + return nil + } + if info.Mode()&os.ModeSymlink != 0 { + return nil + } + dest := filepath.Join(destDir, rel) + if !isUnder(destDir, dest) { + return fmt.Errorf("zip-slip blocked: %s escapes destination", rel) + } + if info.IsDir() { + return os.MkdirAll(dest, sanitizeFileMode(info.Mode(), true)) + } + if err := os.MkdirAll(filepath.Dir(dest), 0o755); err != nil { + return err + } + if moveErr := os.Rename(path, dest); moveErr != nil { + return moveErr + } + return os.Chmod(dest, sanitizeFileMode(info.Mode(), false)) + }) +} + +func (a *Agent) downloadAndExtractArchiveSync(name, serverDir, archiveUrl string) error { + if _, err := a.dl.safeURL(archiveUrl); err != nil { + if a.debug { + fmt.Printf("[import-archive] SSRF blocked for %s: %v\n", name, err) + } + return fmt.Errorf("invalid URL: blocked by security policy") + } + + parsedUrl, _ := url.Parse(archiveUrl) + pathname := strings.ToLower(parsedUrl.Path) + validExt := false + allowedExts := []string{".zip", ".tar.gz", ".tgz", ".tar.bz2", ".tbz2", ".tar.xz", ".txz", ".7z", ".rar"} + for _, ext := range allowedExts { + if strings.HasSuffix(pathname, ext) { + validExt = true + break + } + } + if !validExt { + return fmt.Errorf("unsupported archive format (supported: .zip, .tar.gz, .tgz, .tar.bz2, .tbz2, .tar.xz, .txz, .7z, .rar)") + } + + if a.debug { + fmt.Printf("[import-archive] Starting download for server %s from %s\n", name, archiveUrl) + } + + resp, err := a.dl.client().Get(archiveUrl) + if err != nil { + return fmt.Errorf("download failed") + } + defer resp.Body.Close() + + if resp.StatusCode != 200 { + return fmt.Errorf("HTTP error: %d", resp.StatusCode) + } + + const maxImportSize int64 = 10 << 30 + if resp.ContentLength > maxImportSize { + return fmt.Errorf("archive too large (max 10GB)") + } + + tmpFile, err := os.CreateTemp("", "import-archive-*") + if err != nil { + return fmt.Errorf("failed to create temp file") + } + tmpPath := tmpFile.Name() + defer os.Remove(tmpPath) + + limitedReader := io.LimitReader(resp.Body, maxImportSize) + downloaded, err := io.Copy(tmpFile, limitedReader) + tmpFile.Close() + if err != nil { + return fmt.Errorf("download error") + } + + if a.debug { + fmt.Printf("[import-archive] Download complete for %s: %d bytes\n", name, downloaded) + } + + archivePathLower := strings.ToLower(archiveUrl) + var extractErr error + + if strings.HasSuffix(archivePathLower, ".zip") { + extractErr = extractZipSafe(tmpPath, serverDir) + } else if strings.HasSuffix(archivePathLower, ".tar.gz") || strings.HasSuffix(archivePathLower, ".tgz") { + extractErr = a.extractTarGzSafe(tmpPath, serverDir) + } else if strings.HasSuffix(archivePathLower, ".tar.bz2") || strings.HasSuffix(archivePathLower, ".tbz2") { + extractErr = a.extractTarBz2Safe(tmpPath, serverDir) + } else if strings.HasSuffix(archivePathLower, ".tar.xz") || strings.HasSuffix(archivePathLower, ".txz") { + extractErr = a.extractTarXzSafe(tmpPath, serverDir) + } else if strings.HasSuffix(archivePathLower, ".7z") { + extractErr = a.extract7z(tmpPath, serverDir) + } else if strings.HasSuffix(archivePathLower, ".rar") { + extractErr = a.extractRar(tmpPath, serverDir) + } else { + extractErr = fmt.Errorf("unsupported archive format") + } + + if extractErr != nil { + return fmt.Errorf("extraction failed: %v", extractErr) + } + + _ = sanitizeExtractedTree(serverDir) + + if a.debug { + fmt.Printf("[import-archive] Extraction complete for %s\n", name) + } + return nil +} + +func (a *Agent) handleImportArchiveProgress(w http.ResponseWriter, r *http.Request, name string) { + a.importProgressMu.RLock() + progress, exists := a.importProgress[name] + a.importProgressMu.RUnlock() + + if !exists { + jsonWrite(w, 200, map[string]any{ + "status": "not_found", + "percent": 0, + "downloaded": 0, + "total": 0, + }) + return + } + + jsonWrite(w, 200, map[string]any{ + "status": progress.Status, + "percent": progress.Percent, + "downloaded": progress.Downloaded, + "total": progress.Total, + "error": progress.Error, + }) +} + +func parseMemoryString(s string) float64 { + s = strings.TrimSpace(s) + s = strings.ToUpper(s) + + var multiplier float64 = 1 + var numStr string + + if strings.HasSuffix(s, "GIB") { + multiplier = 1024 + numStr = strings.TrimSuffix(s, "GIB") + } else if strings.HasSuffix(s, "GB") { + multiplier = 1024 + numStr = strings.TrimSuffix(s, "GB") + } else if strings.HasSuffix(s, "MIB") { + multiplier = 1 + numStr = strings.TrimSuffix(s, "MIB") + } else if strings.HasSuffix(s, "MB") { + multiplier = 1 + numStr = strings.TrimSuffix(s, "MB") + } else if strings.HasSuffix(s, "KIB") { + multiplier = 1.0 / 1024 + numStr = strings.TrimSuffix(s, "KIB") + } else if strings.HasSuffix(s, "KB") { + multiplier = 1.0 / 1024 + numStr = strings.TrimSuffix(s, "KB") + } else { + numStr = s + } + + val, err := strconv.ParseFloat(strings.TrimSpace(numStr), 64) + if err != nil { + return 0 + } + return val * multiplier +} + +type applyReq struct { + URL string `json:"url"` + NodeID string `json:"nodeId"` + DestPath string `json:"destPath"` + ProviderID string `json:"providerId"` + VersionID string `json:"versionId"` +} + +func (a *Agent) handleApplyVersion(w http.ResponseWriter, r *http.Request, name string) { + var req applyReq + if err := readJSON(w, r, 1<<20, &req); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad-json", "detail": err.Error()}) + return + } + if name == "" || strings.TrimSpace(req.URL) == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing-fields"}) + return + } + serverDir := a.serverDir(name) + if diskErr := a.checkDiskLimit(serverDir, 0); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + if !strings.HasPrefix(strings.ToLower(req.URL), "http://") && !strings.HasPrefix(strings.ToLower(req.URL), "https://") { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-url"}) + return + } + if req.NodeID != "" && a.uuid != "" && req.NodeID != a.uuid { + jsonWrite(w, 401, map[string]any{"ok": false, "error": "unauthorized"}) + return + } + ok, why := a.verifyPanelSignature(r, name, req.ProviderID, req.VersionID, req.URL, nil) + if !ok { + jsonWrite(w, 403, map[string]any{"ok": false, "error": why}) + return + } + + destRel := strings.TrimSpace(req.DestPath) + if destRel == "" { + destRel = "server.jar" + } + + baseDir := a.serverDir(name) + st, err := os.Stat(baseDir) + if err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"ok": false, "error": "server-dir-not-found"}) + return + } + + target, pathOk := safeJoin(baseDir, destRel) + if !pathOk { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-destPath"}) + return + } + _ = ensureDir(filepath.Dir(target)) + + if destRel == "server.jar" { + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + a.docker.stop(ctx, name) + cancel() + + ctxD, cancelD := context.WithTimeout(context.Background(), 30*time.Minute) + if err := a.dl.downloadToFile(ctxD, req.URL, target); err != nil { + cancelD() + jsonWrite(w, 500, map[string]any{"ok": false, "error": "download failed", "detail": err.Error()}) + return + } + cancelD() + + hostPort := 25565 + meta := a.loadMeta(baseDir) + if v, ok := meta["hostPort"]; ok { + switch vv := v.(type) { + case float64: + hostPort = int(vv) + case int: + hostPort = vv + } + } + enforceServerProps(baseDir) + + ctx2, cancel2 := context.WithTimeout(context.Background(), 15*time.Second) + a.docker.rmForce(ctx2, name) + cancel2() + + resources := resourceLimitsFromMeta(meta) + + ctx3, cancel3 := context.WithTimeout(context.Background(), 60*time.Second) + if err := a.startMinecraftContainer(ctx3, name, baseDir, hostPort, resources, nil); err != nil { + cancel3() + jsonWrite(w, 500, map[string]any{"ok": false, "error": "restart failed", "detail": err.Error()}) + return + } + cancel3() + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "msg": "applied", + "server": name, + "hostPort": hostPort, + "path": target, + }) + return + } + + ctxD, cancelD := context.WithTimeout(context.Background(), 30*time.Minute) + if err := a.dl.downloadToFile(ctxD, req.URL, target); err != nil { + cancelD() + jsonWrite(w, 500, map[string]any{"ok": false, "error": "download failed", "detail": err.Error()}) + return + } + cancelD() + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "msg": "downloaded", + "server": name, + "path": target, + "destPath": destRel, + }) +} + +type runtimeReq struct { + Runtime map[string]any `json:"runtime"` + Template string `json:"template"` + Start string `json:"start"` + Port any `json:"port"` + NodeID string `json:"nodeId"` +} + +func (a *Agent) handleRuntime(w http.ResponseWriter, r *http.Request, name string) { + var req runtimeReq + if err := readJSON(w, r, a.uploadLimit, &req); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad-json", "detail": err.Error()}) + return + } + if name == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing-name"}) + return + } + if req.Runtime == nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing-runtime"}) + return + } + if rawStartup, exists := req.Runtime["startupCommand"]; exists && strings.TrimSpace(fmt.Sprint(rawStartup)) != "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "raw docker startup commands are no longer supported"}) + return + } + if req.NodeID != "" && a.uuid != "" && req.NodeID != a.uuid { + jsonWrite(w, 401, map[string]any{"ok": false, "error": "unauthorized"}) + return + } + + serverDir := a.serverDir(name) + + existingMeta := a.loadMeta(serverDir) + stripLegacyStartupCommandFields(existingMeta) + + hasStructuredRuntime := false + if existingMeta != nil { + if rt, ok := existingMeta["runtime"].(map[string]any); ok && len(rt) > 0 { + hasStructuredRuntime = true + } + } + + if !hasStructuredRuntime { + _ = os.RemoveAll(serverDir) + } + _ = ensureDir(serverDir) + + kind := strings.ToLower(strings.TrimSpace(req.Template)) + if kind == "" { + kind = strings.ToLower(fmt.Sprint(req.Runtime["providerId"])) + } + + finalStart := strings.TrimSpace(req.Start) + if finalStart == "" { + if kind == "python" { + finalStart = "main.py" + } else if kind == "nodejs" || kind == "discord-bot" { + finalStart = "index.js" + } + } + if finalStart != "" { + finalStart = filepath.Base(finalStart) + if finalStart == "." || finalStart == ".." { + finalStart = "" + } + } + + hostPort := 0 + if req.Port != nil { + parsedPort, ok := parseStrictPortValue(req.Port) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-port"}) + return + } + hostPort = parsedPort + } + + cleanRuntime := make(map[string]any) + for _, key := range []string{"providerId", "versionId", "image", "tag", "restart"} { + if raw, ok := req.Runtime[key]; ok { + clean := strings.TrimSpace(fmt.Sprint(raw)) + if clean != "" && clean != "" { + cleanRuntime[key] = clean + } + } + } + if rawCommand, ok := req.Runtime["command"]; ok { + if clean := normalizeLegacyRuntimeProcessCommand(kind, fmt.Sprint(rawCommand), finalStart, defaultDataDirForType(kind)); clean != "" { + if reason := validateRuntimeProcessCommand(clean); reason != "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": reason}) + return + } + cleanRuntime["command"] = clean + } + } + if rawEnv, ok := req.Runtime["env"].(map[string]any); ok && len(rawEnv) > 0 { + cleanEnv := make(map[string]any) + for key, value := range rawEnv { + envKey := strings.TrimSpace(key) + if envKey == "" { + continue + } + envValue := strings.TrimSpace(fmt.Sprint(value)) + if envValue == "" { + envValue = "" + } + cleanEnv[envKey] = envValue + } + if len(cleanEnv) > 0 { + cleanRuntime["env"] = cleanEnv + } + } + if rawVolumes, ok := req.Runtime["volumes"].([]any); ok && len(rawVolumes) > 0 { + cleanVolumes := make([]any, 0, len(rawVolumes)) + for _, entry := range rawVolumes { + spec := strings.TrimSpace(fmt.Sprint(entry)) + if spec == "" || spec == "" { + continue + } + if strings.ContainsAny(spec, "\x00\r\n") { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-volume-spec"}) + return + } + cleanVolumes = append(cleanVolumes, spec) + } + if len(cleanVolumes) > 0 { + cleanRuntime["volumes"] = cleanVolumes + } + } + if rawPorts, ok := req.Runtime["ports"].([]any); ok && len(rawPorts) > 0 { + cleanPorts := make([]any, 0, len(rawPorts)) + seenPorts := make(map[int]struct{}, len(rawPorts)) + for _, entry := range rawPorts { + port, ok := parseStrictPortValue(entry) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid-runtime-port"}) + return + } + if _, seen := seenPorts[port]; seen { + continue + } + seenPorts[port] = struct{}{} + cleanPorts = append(cleanPorts, port) + } + if len(cleanPorts) > 0 { + cleanRuntime["ports"] = cleanPorts + } + } + + switch kind { + case "python": + scaffoldPython(serverDir, finalStart) + case "nodejs", "discord-bot": + p := hostPort + if p == 0 { + p = 3001 + } + scaffoldNode(serverDir, finalStart, p) + default: + if finalStart != "" { + _ = os.WriteFile(filepath.Join(serverDir, finalStart), []byte(""), 0o644) + } + } + + meta := map[string]any{ + "type": func() string { + if kind != "" { + return kind + } + return "runtime" + }(), + "runtime": cleanRuntime, + "start": func() any { + if finalStart != "" { + return finalStart + } + return nil + }(), + "hostPort": func() any { + if hostPort > 0 { + return hostPort + } + return nil + }(), + "updatedAt": time.Now().UnixMilli(), + } + + if existingMeta != nil { + if ca, ok := existingMeta["createdAt"]; ok { + meta["createdAt"] = ca + } + if tpl, ok := existingMeta["template"]; ok { + meta["template"] = tpl + } + if pf, ok := existingMeta["portForwards"]; ok { + meta["portForwards"] = pf + } + if res, ok := existingMeta["resources"]; ok { + meta["resources"] = res + } + if dig, ok := existingMeta["lastImageDigest"]; ok { + meta["lastImageDigest"] = dig + } + if existingRt, ok := existingMeta["runtime"].(map[string]any); ok { + newRt, _ := meta["runtime"].(map[string]any) + if newRt == nil { + newRt = make(map[string]any) + } + if img, ok := existingRt["image"]; ok && newRt["image"] == nil { + newRt["image"] = img + } + if tag, ok := existingRt["tag"]; ok && newRt["tag"] == nil { + newRt["tag"] = tag + } + meta["runtime"] = newRt + } + } + + _ = a.saveMeta(serverDir, meta) + + img := strings.TrimSpace(fmt.Sprint(req.Runtime["image"])) + tag := strings.TrimSpace(fmt.Sprint(req.Runtime["tag"])) + if img == "" { + if kind == "python" { + img = "python" + if tag == "" { + tag = "3.12-slim" + } + } else { + img = "node" + if tag == "" { + tag = "20-alpine" + } + } + } + ref := img + if tag != "" { + ref = img + ":" + tag + } + ctx, cancel := context.WithTimeout(context.Background(), 2*time.Minute) + _ = a.docker.pullImageAPI(ctx, ref) + cancel() + + jsonWrite(w, 200, map[string]any{"ok": true, "type": meta["type"], "start": meta["start"], "hostPort": meta["hostPort"]}) +} + +func (a *Agent) handleStart(w http.ResponseWriter, r *http.Request, name string) { + if !isValidContainerName(name) { + jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) + return + } + + opMu := a.getServerOpLock(name) + opMu.Lock() + defer opMu.Unlock() + + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "not found"}) + return + } + meta := a.loadMeta(serverDir) + if stripLegacyStartupCommandFields(meta) { + _ = a.saveMeta(serverDir, meta) + } + if normalizeRustRuntimeForPterodactyl(meta) { + _ = a.saveMeta(serverDir, meta) + } + typ := strings.ToLower(fmt.Sprint(meta["type"])) + if a.debug { + fmt.Printf("[handleStart] Server: %s, type: %s\n", name, typ) + } + + var body struct { + HostPort int `json:"hostPort"` + Env map[string]string `json:"env"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil && !errors.Is(err, io.EOF) { + jsonWrite(w, 400, map[string]any{"error": "invalid request body"}) + return + } + if body.HostPort != 0 { + if _, ok := parseStrictPortValue(body.HostPort); !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid hostPort"}) + return + } + } + + resolveStartPort := func(defaultPort int) int { + if body.HostPort > 0 { + return body.HostPort + } + if storedPort, ok := parseStrictPortValue(meta["hostPort"]); ok { + return storedPort + } + return defaultPort + } + + resources := resourceLimitsFromMeta(meta) + a.resetConsoleLogs(name) + + ctx, cancel := context.WithTimeout(context.Background(), 240*time.Second) + defer cancel() + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + + if typ == "minecraft" { + hp := resolveStartPort(25565) + enforceServerProps(serverDir) + if err := a.startMinecraftContainer(ctx, name, serverDir, hp, resources, body.Env); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to start container", "detail": err.Error()}) + return + } + a.ensureLiveLogs(name) + auditLog.Log("server_start", getClientIP(r), "", name, "start", "success", map[string]any{"type": "minecraft"}) + a.broadcastContainerEvent(name, "running") + jsonWrite(w, 200, map[string]any{"ok": true}) + return + } + + if meta["runtime"] != nil && (typ == "python" || typ == "nodejs" || typ == "discord-bot" || typ == "runtime") { + hp := resolveStartPort(0) + if err := a.startRuntimeContainer(ctx, name, serverDir, meta, hp, resources, body.Env); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to start container", "detail": err.Error()}) + return + } + a.ensureLiveLogs(name) + auditLog.Log("server_start", getClientIP(r), "", name, "start", "success", map[string]any{"type": typ}) + a.broadcastContainerEvent(name, "running") + jsonWrite(w, 200, map[string]any{"ok": true}) + return + } + + if typ != "minecraft" && typ != "python" && typ != "nodejs" && typ != "discord-bot" && typ != "runtime" { + hp := resolveStartPort(8080) + + if meta["runtime"] == nil { + meta["runtime"] = make(map[string]any) + } + + if err := a.startCustomDockerContainer(ctx, name, serverDir, meta, hp, resources); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to start container", "detail": err.Error()}) + return + } + a.ensureLiveLogs(name) + auditLog.Log("server_start", getClientIP(r), "", name, "start", "success", map[string]any{"type": typ}) + a.broadcastContainerEvent(name, "running") + jsonWrite(w, 200, map[string]any{"ok": true}) + return + } + + jsonWrite(w, 400, map[string]any{"error": "unsupported template for start"}) +} + +func (a *Agent) handleStop(w http.ResponseWriter, r *http.Request, name string) { + if !isValidContainerName(name) { + jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) + return + } + + waitMode := r.URL.Query().Get("wait") == "true" + + opMu := a.getServerOpLock(name) + opMu.Lock() + + a.stopMu.Lock() + if !waitMode { + if lastStop, ok := a.stoppingNow[name]; ok && time.Since(lastStop) < 5*time.Second { + a.stopMu.Unlock() + opMu.Unlock() + jsonWrite(w, 200, map[string]any{"ok": true, "note": "already stopping"}) + return + } + } + a.stoppingNow[name] = time.Now() + a.stopMu.Unlock() + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if !a.docker.containerExists(ctx, name) { + a.resetConsoleLogs(name) + opMu.Unlock() + jsonWrite(w, 200, map[string]any{"ok": true, "note": "not running"}) + return + } + + a.docker.updateRestartNo(ctx, name) + + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + + serverDir := a.serverDir(name) + meta := a.loadMeta(serverDir) + serverType := strings.ToLower(fmt.Sprint(meta["type"])) + isMinecraft := serverType == "" || serverType == "minecraft" + + if isMinecraft { + _ = a.docker.sendCommand(ctx, a.stdinMgr, name, "stop", nil) + } + + if waitMode { + time.Sleep(a.stopGrace) + ctx2, cancel2 := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel2() + a.docker.stop(ctx2, name) + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + a.stopMu.Lock() + delete(a.stoppingNow, name) + a.stopMu.Unlock() + a.resetConsoleLogs(name) + opMu.Unlock() + a.broadcastContainerEvent(name, "stopped") + jsonWrite(w, 200, map[string]any{"ok": true, "stopped": true}) + auditLog.Log("server_stop", getClientIP(r), "", name, "stop", "success", nil) + return + } + + stopRequestedAt := time.Now() + opMu.Unlock() + + go func() { + time.Sleep(a.stopGrace) + + opMu := a.getServerOpLock(name) + opMu.Lock() + defer opMu.Unlock() + + ctx2, cancel2 := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel2() + startedAt, _, _, _ := a.docker.runCollect(ctx2, "inspect", "-f", "{{.State.StartedAt}}", name) + if t, err := time.Parse(time.RFC3339Nano, strings.TrimSpace(startedAt)); err == nil { + if t.After(stopRequestedAt) { + a.stopMu.Lock() + delete(a.stoppingNow, name) + a.stopMu.Unlock() + return + } + } + + a.docker.stop(ctx2, name) + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + a.resetConsoleLogs(name) + a.stopMu.Lock() + delete(a.stoppingNow, name) + a.stopMu.Unlock() + }() + + a.broadcastContainerEvent(name, "stopping") + jsonWrite(w, 200, map[string]any{"ok": true, "stopping": true}) + auditLog.Log("server_stop", getClientIP(r), "", name, "stop", "success", nil) +} + +func shouldRecreateContainerOnRestart(meta map[string]any) bool { + if meta == nil { + return false + } + template := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) + if template == "" || template == "" { + template = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) + } + if template == "rust" { + return true + } + runtimeObj, _ := meta["runtime"].(map[string]any) + if runtimeObj == nil { + return false + } + image := strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["image"]))) + tag := strings.ToLower(strings.TrimSpace(fmt.Sprint(runtimeObj["tag"]))) + imageRef := image + ":" + tag + return strings.Contains(imageRef, "pterodactyl/games:rust") || + strings.Contains(imageRef, "parkervcp/games:rust") || + strings.Contains(imageRef, "didstopia/rust-server") +} + +func (a *Agent) handleRestart(w http.ResponseWriter, r *http.Request, name string) { + if !isValidContainerName(name) { + jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) + return + } + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + if !a.docker.containerExists(ctx, name) { + jsonWrite(w, 400, map[string]any{"error": "not running"}) + return + } + + serverDir := a.serverDir(name) + meta := a.loadMeta(serverDir) + if normalizeRustRuntimeForPterodactyl(meta) { + _ = a.saveMeta(serverDir, meta) + } + consoleMode := inferredConsoleModeForServer(meta) + recreateForConsoleStdin := consoleMode == "stdin" && (!a.docker.containerOpenStdin(ctx, name) || !a.docker.containerTTY(ctx, name)) + if shouldRecreateContainerOnRestart(meta) || recreateForConsoleStdin { + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + if a.logs != nil { + a.logs.resetRecent(name) + } + startCtx, startCancel := context.WithTimeout(context.Background(), 240*time.Second) + defer startCancel() + resources := resourceLimitsFromMeta(meta) + resolveStoredPort := func(defaultPort int) int { + if storedPort, ok := parseStrictPortValue(meta["hostPort"]); ok { + return storedPort + } + if runtimeObj, ok := meta["runtime"].(map[string]any); ok { + if ports := runtimeIntSlice(runtimeObj["ports"]); len(ports) > 0 && ports[0] > 0 { + return ports[0] + } + } + return defaultPort + } + typ := strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["type"]))) + if typ == "" || typ == "" { + typ = strings.ToLower(strings.TrimSpace(fmt.Sprint(meta["template"]))) + } + var startErr error + switch { + case typ == "minecraft": + hostPort := resolveStoredPort(25565) + enforceServerProps(serverDir) + startErr = a.startMinecraftContainer(startCtx, name, serverDir, hostPort, resources, nil) + case meta["runtime"] != nil && (typ == "python" || typ == "nodejs" || typ == "discord-bot" || typ == "runtime"): + hostPort := resolveStoredPort(0) + startErr = a.startRuntimeContainer(startCtx, name, serverDir, meta, hostPort, resources, nil) + default: + hostPort := resolveStoredPort(8080) + startErr = a.startCustomDockerContainer(startCtx, name, serverDir, meta, hostPort, resources) + } + if startErr != nil { + jsonWrite(w, 500, map[string]any{"error": "container recreate failed", "detail": startErr.Error()}) + return + } + a.ensureLiveLogs(name) + a.broadcastContainerEvent(name, "running") + jsonWrite(w, 200, map[string]any{"ok": true, "recreated": true, "reason": func() string { + if recreateForConsoleStdin { + return "stdin" + } + return "runtime" + }()}) + return + } + + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + if a.logs != nil { + a.logs.resetRecent(name) + } + _, errStr, _, err := a.docker.runCollect(ctx, "restart", name) + if err != nil { + if a.debug { + fmt.Printf("[docker] restart error for %s: %s\n", name, strings.TrimSpace(errStr)) + } + jsonWrite(w, 500, map[string]any{"error": "container restart failed"}) + return + } + a.ensureLiveLogs(name) + a.broadcastContainerEvent(name, "running") + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) broadcastConsoleChunk(name, prefix, chunk string) bool { + cleaned := cleanLogLine(chunk) + if cleaned == "" { + return false + } + cleaned = strings.ReplaceAll(cleaned, "\r\n", "\n") + cleaned = strings.ReplaceAll(cleaned, "\r", "\n") + t := a.logs.getOrCreate(name) + sent := false + for _, line := range strings.Split(cleaned, "\n") { + line = strings.TrimRight(line, " \t") + plain := strings.TrimSpace(ansiSGRRE.ReplaceAllString(line, "")) + if plain == "" { + continue + } + a.logs.sendToClients(t, prefix+line) + sent = true + } + return sent +} + +func isMissingExecShell(stderr string, execPath string, exitCode int) bool { + if exitCode != 126 && exitCode != 127 { + return false + } + lower := strings.ToLower(stderr) + base := strings.ToLower(filepath.Base(strings.TrimSpace(execPath))) + if base == "" { + return false + } + return (strings.Contains(lower, "executable file not found") || + strings.Contains(lower, "no such file or directory") || + strings.Contains(lower, "not found")) && strings.Contains(lower, base) +} + +func (a *Agent) executeShellConsoleCommand(ctx context.Context, name, command string) (int, error) { + shells := []string{"sh", "/bin/sh", "bash", "/bin/bash"} + for idx, shellPath := range shells { + stdout, stderr, exitCode, err := a.docker.runCollect(ctx, "exec", name, shellPath, "-lc", command) + sawOutput := false + if stdout != "" { + sawOutput = a.broadcastConsoleChunk(name, "stdout:", stdout) || sawOutput + } + if stderr != "" { + sawOutput = a.broadcastConsoleChunk(name, "stderr:", stderr) || sawOutput + } + if err != nil && isMissingExecShell(stderr, shellPath, exitCode) && idx < len(shells)-1 { + continue + } + if ctx.Err() != nil { + a.broadcastConsoleChunk(name, "stderr:", fmt.Sprintf("[command timed out] %s\n", command)) + return exitCode, ctx.Err() + } + if err != nil { + if !sawOutput { + a.broadcastConsoleChunk(name, "stderr:", fmt.Sprintf("[command exited with code %d]\n", exitCode)) + } + return exitCode, nil + } + if !sawOutput { + a.broadcastConsoleChunk(name, "stdout:", "[command exited with code 0]\n") + } + return 0, nil + } + a.broadcastConsoleChunk(name, "stderr:", "[command failed] no supported shell found in container\n") + return -1, fmt.Errorf("no supported shell found in container") +} + +func sanitizeCommandRequestID(raw string) string { + id := strings.TrimSpace(raw) + if id == "" { + return "" + } + if len(id) > consoleCommandRequestIDMaxLen { + id = id[:consoleCommandRequestIDMaxLen] + } + for _, r := range id { + if (r >= 'a' && r <= 'z') || + (r >= 'A' && r <= 'Z') || + (r >= '0' && r <= '9') || + r == '-' || r == '_' || r == ':' || r == '.' { + continue + } + return "" + } + return id +} + +func (a *Agent) claimConsoleCommand(name, command, requestID string) (bool, string) { + now := time.Now() + + a.commandMu.Lock() + defer a.commandMu.Unlock() + + if a.recentCommands == nil { + a.recentCommands = make(map[string]recentConsoleCommand) + } + + for key, entry := range a.recentCommands { + if now.Sub(entry.at) > consoleCommandRequestIDWindow { + delete(a.recentCommands, key) + } + } + if len(a.recentCommands) >= consoleCommandRecentMaxServers { + var oldestKey string + var oldestAt time.Time + for key, entry := range a.recentCommands { + if oldestKey == "" || entry.at.Before(oldestAt) { + oldestKey = key + oldestAt = entry.at + } + } + if oldestKey != "" { + delete(a.recentCommands, oldestKey) + } + } + + if entry, ok := a.recentCommands[name]; ok { + if requestID != "" && entry.requestID == requestID && now.Sub(entry.at) <= consoleCommandRequestIDWindow { + return false, "request_id" + } + // Rapid-duplicate guard: collapse the same command fired twice in a very + // short window ONLY when we cannot distinguish the two submissions by + // request id (i.e. no request id, or the same one). When the client sends + // a fresh, distinct request id, the repeat is a deliberate separate + // command and MUST be recorded as its own marker — otherwise sending + // "pl" twice dropped the second marker while its output still appeared, + // making outputs pile up with no "> pl" line between them. + sameOrNoRequestID := requestID == "" || entry.requestID == "" || entry.requestID == requestID + if sameOrNoRequestID && entry.command == command && now.Sub(entry.at) <= consoleCommandDuplicateWindow { + return false, "rapid_duplicate" + } + } + + a.recentCommands[name] = recentConsoleCommand{ + command: command, + requestID: requestID, + at: now, + } + return true, "" +} + +func (a *Agent) handleCommand(w http.ResponseWriter, r *http.Request, name string) { + if !isValidContainerName(name) { + jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) + return + } + + var body struct { + Command string `json:"command"` + RequestID string `json:"requestId"` + } + if err := readJSON(w, r, 16*1024, &body); err != nil { + jsonWrite(w, 400, map[string]any{"error": "bad json"}) + return + } + cmd := strings.TrimSpace(body.Command) + if cmd == "" { + jsonWrite(w, 400, map[string]any{"error": "missing command"}) + return + } + + if len(cmd) > stdinCommandMaxLen { + jsonWrite(w, 400, map[string]any{"error": "command too long", "max": stdinCommandMaxLen}) + return + } + requestID := sanitizeCommandRequestID(body.RequestID) + + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "not found"}) + return + } + + if ok, reason := a.claimConsoleCommand(name, cmd, requestID); !ok { + jsonWrite(w, 200, map[string]any{"ok": true, "deduplicated": true, "reason": reason}) + return + } + + meta := a.loadMeta(serverDir) + serverType := strings.ToLower(fmt.Sprint(meta["type"])) + consoleMode := inferredConsoleModeForServer(meta) + useExecShell := consoleMode == "exec" || consoleMode == "exec-shell" || consoleMode == "shell" + if a.logs != nil { + a.logs.suppressCommandEcho(name, cmd) + // Record the command as an in-order marker line in the same log stream + // as its output. This is the single source of truth for ordering so the + // panel never has to re-interleave commands and output from two clocks. + a.logs.recordCommandLine(name, cmd) + } + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + if useExecShell { + exitCode, err := a.executeShellConsoleCommand(ctx, name, cmd) + if err != nil { + jsonWrite(w, 200, map[string]any{ + "ok": false, + "error": "failed-to-send", + "detail": err.Error(), + "type": serverType, + "mode": "exec", + "exitCode": exitCode, + }) + return + } + jsonWrite(w, 200, map[string]any{"ok": true, "type": serverType, "mode": "exec", "exitCode": exitCode}) + return + } + + targetProcesses := consoleProcessTargetsForServer(meta) + if err := a.docker.sendCommand(ctx, a.stdinMgr, name, cmd, targetProcesses); err != nil { + detail := err.Error() + jsonWrite(w, 200, map[string]any{ + "ok": false, + "error": "failed-to-send", + "detail": detail, + "type": serverType, + "mode": "stdin", + }) + return + } + + jsonWrite(w, 200, map[string]any{"ok": true, "type": serverType, "mode": "stdin", "transport": "attached-stdin", "targeted": len(targetProcesses) > 0}) +} + +func (a *Agent) handleServerCommandBody(w http.ResponseWriter, r *http.Request) { + var body struct { + Name string `json:"name"` + Command string `json:"command"` + RequestID string `json:"requestId"` + } + if err := readJSON(w, r, 16*1024, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + name := sanitizeName(body.Name) + if name == "" || strings.TrimSpace(body.Command) == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing params"}) + return + } + r2 := *r + r2.URL = &url.URL{Path: "/v1/servers/" + name + "/command"} + commandBody, _ := json.Marshal(map[string]string{ + "command": body.Command, + "requestId": body.RequestID, + }) + r2.Body = io.NopCloser(bytes.NewReader(commandBody)) + r2.ContentLength = int64(len(commandBody)) + a.handleCommand(w, &r2, name) +} + +func (a *Agent) handleLogsSSE(w http.ResponseWriter, r *http.Request, name string) { + if !isValidContainerName(name) { + jsonWrite(w, 400, map[string]any{"error": "invalid container name"}) + return + } + + rc := http.NewResponseController(w) + _ = rc.SetWriteDeadline(time.Time{}) + + flusher, ok := w.(http.Flusher) + if !ok { + jsonWrite(w, 500, map[string]any{"error": "streaming not supported"}) + return + } + + tailN := 200 + const maxLogTail = 10000 + if q := r.URL.Query().Get("tail"); q != "" { + if n, err := strconv.Atoi(q); err == nil && n >= 0 { + tailN = n + if tailN > maxLogTail { + tailN = maxLogTail + } + } + } + + w.Header().Set("Content-Type", "text/event-stream") + w.Header().Set("Cache-Control", "no-cache, no-transform") + w.Header().Set("Connection", "keep-alive") + + sendEvent := func(ev string, data any) { + b, _ := json.Marshal(data) + fmt.Fprintf(w, "event: %s\ndata: %s\n\n", ev, string(b)) + flusher.Flush() + } + sendLine := func(line string, ts int64) { + cleaned := cleanLogLine(line) + if cleaned == "" { + return + } + payload := map[string]any{"line": cleaned} + if ts > 0 { + payload["ts"] = ts + } + b, _ := json.Marshal(payload) + fmt.Fprintf(w, "data: %s\n\n", string(b)) + flusher.Flush() + } + + sendEvent("hello", map[string]any{"server": name, "ts": time.Now().UnixMilli(), "tail": tailN}) + t := a.logs.getOrCreate(name) + + // Safety net for the synthetic-timestamp anchor: if a refresh races ahead of + // the follow loop's run-start detection, make sure the run-start anchor is + // set so synthetic snapshot timestamps are assigned forward from a sane, + // recent point (>= the panel's start-time reset marker) rather than from the + // legacy past-anchored window that caused early boot lines to be filtered + // out on refresh. + t.markRunStartIfUnset() + + if tailN > 0 { + snapshot := []logSnapshotEntry{} + snapshotFromDockerLogs := false + + // Primary source: the durable on-disk console log. It is run-scoped + // (truncated on container restart), line-capped, contains command + // markers inline, and is NOT recycled like the in-memory ring buffer, + // so a refresh after a long-running session shows the full console + // exactly like Pterodactyl/Wings. We prefer it over the ring buffer + // because the ring evicts older output under load. + persisted := t.readPersistedSnapshot(tailN) + if len(persisted) > 0 { + snapshot = make([]logSnapshotEntry, 0, len(persisted)) + for _, line := range persisted { + snapshot = append(snapshot, logSnapshotEntry{line: line}) + } + } + + // Secondary source: the in-memory ring buffer (covers the window before + // the persistent file exists, e.g. very first lines after node boot). + if len(snapshot) == 0 && !preferDockerCLIConsoleTransport() { + recentSnapshot := t.snapshotRecent(tailN) + snapshot = make([]logSnapshotEntry, 0, len(recentSnapshot)) + for _, line := range recentSnapshot { + snapshot = append(snapshot, logSnapshotEntry{line: line}) + } + } + if len(snapshot) == 0 { + snapshotFromDockerLogs = true + shouldReadDockerLogs := true + stateCtx, stateCancel := context.WithTimeout(context.Background(), 2*time.Second) + state := a.docker.containerState(stateCtx, name) + stateCancel() + if state != "" && state != "running" { + shouldReadDockerLogs = false + } + if shouldReadDockerLogs { + snapshot = a.logs.fetchTailSnapshotSingleflight(name, tailN, func() []logSnapshotEntry { + ctx, cancel := context.WithTimeout(context.Background(), 6*time.Second) + out, errOut, _, _ := a.docker.runCollect(ctx, "logs", "--timestamps", "--tail", fmt.Sprint(tailN), name) + cancel() + entries := append(parseDockerLogSnapshotEntries(out, tailN), parseDockerLogSnapshotEntries(errOut, tailN)...) + sort.SliceStable(entries, func(i, j int) bool { + left := entries[i].ts + right := entries[j].ts + if left == 0 || right == 0 { + return false + } + return left < right + }) + if len(entries) > tailN { + entries = entries[len(entries)-tailN:] + } + return entries + }) + } + } + if snapshotFromDockerLogs && len(snapshot) > 0 { + lines := make([]string, 0, len(snapshot)) + for _, entry := range snapshot { + lines = append(lines, entry.line) + } + t.appendRecentBatch(lines) + t.markDockerSnapshotPrimed() + // Seed the durable log if it is still empty so later refreshes are + // served from disk rather than re-hitting docker logs each time. + if len(t.readPersistedSnapshot(1)) == 0 { + t.appendPersistedLines(lines) + } + } + // Assign synthetic, strictly-increasing timestamps to snapshot lines + // that carry no real per-line timestamp (the on-disk durable log and + // the in-memory ring buffer store text only, so entry.ts == 0 there). + // + // Two independent panel behaviours constrain these timestamps: + // + // 1. RESET FILTER (the "only the last few lines survive a refresh" bug): + // the panel marks a console reset at server-start time (wall clock) + // and drops every history line whose ts < resetAt. Synthetic + // timestamps must therefore be >= the run start. We anchor the window + // FORWARD from runStart (snapshotEpoch == runStartMs) and step forward + // by ABSOLUTE file position, so the EARLIEST boot line sits at + // ~runStart and is never filtered out. + // + // The previous scheme anchored the window to END at "now" by stepping + // BACKWARD from it (base = now - count*step), which pushed the early + // boot lines far before resetAt — exactly what deleted them on a + // refresh taken shortly after start, while a refresh ~10 min later + // "worked" only because by then more lines had shifted the window. + // + // 2. COMMAND DEDUP BUCKET: the panel dedups rendered command markers on a + // coarse time bucket (CONSOLE_COMMAND_RENDER_BUCKET_MS = 2500ms). Two + // genuine repeats of the same command must land in different buckets, + // so the step is kept larger than that bucket. + // + // The step is FIXED (not adaptive) and anchored to each line's ABSOLUTE + // position in the persisted file, so a given on-disk line always receives + // the SAME synthetic ts across refreshes even as the file grows — keeping + // the panel's client-side dedup (keyed on ts:source:line) stable. Exact + // ts ordering between the snapshot tail and subsequent live lines is not + // required: the panel renders the snapshot first (ordered by the + // server-assigned monotonic seq) and appends live lines after it. + const snapshotSyntheticStepMs int64 = 3000 + if n := len(snapshot); n > 0 { + base := t.snapshotEpoch(n, snapshotSyntheticStepMs) + // Anchor synthetic timestamps to each line's ABSOLUTE position in the + // persisted file, not its index within this particular tail slice. + // If the file later grows, an older line keeps the same absolute + // position (and therefore the same synthetic ts) across refreshes, so + // the panel's client-side dedup never re-appends it. The first line + // of the returned tail sits at absolute offset (total - n). + absStart := t.persistedLineCount() - n + if absStart < 0 { + absStart = 0 + } + for i := range snapshot { + if snapshot[i].ts <= 0 { + snapshot[i].ts = base + int64(absStart+i)*snapshotSyntheticStepMs + } + } + } + for _, entry := range snapshot { + sendLine(entry.line, entry.ts) + } + } + ch := make(chan string, 256) + + t.mu.Lock() + t.clients[ch] = struct{}{} + t.mu.Unlock() + + hb := time.NewTicker(15 * time.Second) + defer hb.Stop() + + notify := r.Context().Done() + for { + select { + case <-notify: + t.mu.Lock() + delete(t.clients, ch) + t.mu.Unlock() + a.logs.removeIfEmpty(t) + return + case line := <-ch: + line = normalizeStreamedLogLine(line) + sendLine(line, time.Now().UnixMilli()) + case <-hb.C: + sendEvent("keepalive", map[string]any{"ts": time.Now().UnixMilli()}) + } + } +} + +func (a *Agent) handleResetLogs(w http.ResponseWriter, r *http.Request, name string) { + if !isValidContainerName(name) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid container name"}) + return + } + serverDir := a.serverDir(name) + if st, err := os.Stat(serverDir); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"ok": false, "error": "not found"}) + return + } + a.resetConsoleLogs(name) + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) handleKill(w http.ResponseWriter, r *http.Request, name string) { + a.logs.killTail(name) + a.resetConsoleLogs(name) + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + defer cancel() + if err := a.docker.brutalRemoveContainer(ctx, name); err != nil { + fmt.Printf("[kill] force removal warning for %s: %v\n", name, err) + a.removeContainerEventually(name) + } + a.resetConsoleLogs(name) + a.broadcastContainerEvent(name, "stopped") + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) handleDeleteServer(w http.ResponseWriter, r *http.Request, name string) { + if name == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid name"}) + return + } + filesOnly := r.URL.Query().Get("files_only") == "true" + if r.URL.Query().Get("async") == "true" { + serverDir := a.serverDir(name) + // adpanel:multidisk - validate against the server's OWNING volumes root, + // not the primary one, so secondary-disk servers pass the guard. + volRoot := a.serverVolumesRoot(name) + if filepath.Clean(serverDir) == volRoot { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "refusing to delete volumes root"}) + return + } + if !isUnder(volRoot, serverDir) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) + return + } + clientIP := getClientIP(r) + go func() { + if _, err := a.performDeleteServer(name, filesOnly, clientIP); err != nil { + fmt.Printf("[delete] async delete failed for %s: %v\n", name, err) + auditLog.Log("server_delete", clientIP, "", name, "delete", "failure", map[string]any{"error": err.Error()}) + } + }() + jsonWrite(w, http.StatusAccepted, map[string]any{"ok": true, "name": name, "deleting": true}) + return + } + + result, err := a.performDeleteServer(name, filesOnly, getClientIP(r)) + if err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to queue server delete", "detail": err.Error()}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "deleting": result.ServerQueued || result.BackupQueued}) +} + +type deleteServerResult struct { + ServerQueued bool + BackupQueued bool +} + +func (a *Agent) performDeleteServer(name string, filesOnly bool, clientIP string) (deleteServerResult, error) { + var result deleteServerResult + opMu := a.getServerOpLock(name) + opMu.Lock() + defer opMu.Unlock() + + a.logs.killTail(name) + a.logs.resetRecent(name) + if a.stdinMgr != nil { + a.stdinMgr.remove(name) + } + + if !filesOnly { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + if err := a.docker.brutalRemoveContainer(ctx, name); err != nil { + fmt.Printf("[delete] container removal warning for %s: %v\n", name, err) + } + cancel() + verifyCtx, verifyCancel := context.WithTimeout(context.Background(), 2*time.Second) + containerStillExists, containerCheckOk := a.containerExistsKnown(verifyCtx, name) + verifyCancel() + if !containerCheckOk || containerStillExists { + fmt.Printf("[delete] container still exists or could not be checked for %s; queued retry cleanup\n", name) + a.removeContainerEventually(name) + } + a.logs.resetRecent(name) + } + + serverDir := a.serverDir(name) + backupsDir := a.serverBackupsDir(name) + // adpanel:multidisk - resolve the OWNING roots for this server so all guards + // and detach operations target the correct disk. Using the hardcoded primary + // roots here previously rejected secondary-disk deletes ("invalid path") and + // left their volume + backups behind. + volRoot := a.serverVolumesRoot(name) + bkRoot := a.serverBackupsRoot(name) + fmt.Printf("[delete] attempting to detach server directory: %s\n", serverDir) + + if filepath.Clean(serverDir) == volRoot { + return result, fmt.Errorf("refusing to delete volumes root") + } + if !isUnder(volRoot, serverDir) { + return result, fmt.Errorf("invalid path") + } + + if _, err := os.Stat(serverDir); os.IsNotExist(err) { + fmt.Printf("[delete] directory already gone: %s\n", serverDir) + _ = os.Remove(a.metaPath(name)) + if isUnder(bkRoot, backupsDir) { + if detachedBackup, backupExists, detachErr := a.detachPathForAsyncDelete(bkRoot, backupsDir, "backups", name); detachErr != nil { + fmt.Printf("[delete] backup detach warning for %s: %v\n", name, detachErr) + } else if backupExists { + result.BackupQueued = true + removeDetachedPathAsync("backups", detachedBackup) + } + } + auditLog.Log("server_delete", clientIP, "", name, "delete", "success", nil) + return result, nil + } + + detachedServer, serverExists, err := a.detachPathForAsyncDelete(volRoot, serverDir, "server", name) + if err != nil { + fmt.Printf("[delete] error detaching %s: %v\n", serverDir, err) + return result, err + } + _ = os.Remove(a.metaPath(name)) + if serverExists { + result.ServerQueued = true + removeDetachedPathAsync("server", detachedServer) + } + + if isUnder(bkRoot, backupsDir) { + if detachedBackup, backupExists, detachErr := a.detachPathForAsyncDelete(bkRoot, backupsDir, "backups", name); detachErr != nil { + fmt.Printf("[delete] backup detach warning for %s: %v\n", name, detachErr) + } else if backupExists { + result.BackupQueued = true + removeDetachedPathAsync("backups", detachedBackup) + } + } + + // adpanel:multidisk - drop the cached server->disk mapping now that the server + // is gone, so a future server reusing this name resolves its disk freshly. + a.invalidateServerDiskCache(name) + + fmt.Printf("[delete] queued async cleanup for %s (serverQueued=%v backupsQueued=%v)\n", name, result.ServerQueued, result.BackupQueued) + auditLog.Log("server_delete", clientIP, "", name, "delete", "success", nil) + return result, nil +} + +func (a *Agent) removeContainerEventually(name string) { + go func() { + for attempt := 1; attempt <= 30; attempt++ { + ctx, cancel := context.WithTimeout(context.Background(), 8*time.Second) + err := a.docker.brutalRemoveContainer(ctx, name) + cancel() + + checkCtx, checkCancel := context.WithTimeout(context.Background(), 2*time.Second) + exists, checkOk := a.containerExistsKnown(checkCtx, name) + checkCancel() + if checkOk && !exists { + if err != nil { + fmt.Printf("[delete] container retry cleanup completed for %s after transient error: %v\n", name, err) + } else { + fmt.Printf("[delete] container retry cleanup completed for %s\n", name) + } + return + } + + if err != nil { + fmt.Printf("[delete] container retry %d failed for %s: %v\n", attempt, name, err) + } else { + fmt.Printf("[delete] container retry %d did not remove %s yet\n", attempt, name) + } + delay := time.Duration(attempt) * time.Second + if attempt <= 5 { + delay = time.Duration(attempt) * 250 * time.Millisecond + } + if delay > time.Minute { + delay = time.Minute + } + time.Sleep(delay) + } + fmt.Printf("[delete] container retry cleanup gave up for %s after repeated failures\n", name) + }() +} + +func (a *Agent) handleReinstallServer(w http.ResponseWriter, r *http.Request, name string) { + if name == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid name"}) + return + } + + serverDir := a.serverDir(name) + // adpanel:multidisk - guard against the server's OWNING volumes root so + // secondary-disk servers are not wrongly rejected as "invalid path". + volRoot := a.serverVolumesRoot(name) + if filepath.Clean(serverDir) == volRoot { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "refusing to operate on volumes root"}) + return + } + if !isUnder(volRoot, serverDir) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) + return + } + + var req struct { + TemplateId string `json:"templateId"` + Docker *dockerTemplateConfig `json:"docker"` + StartupCommand string `json:"startupCommand"` + HostPort int `json:"hostPort"` + JavaVersion string `json:"javaVersion"` + } + if err := readJSON(w, r, a.uploadLimit, &req); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json", "detail": err.Error()}) + return + } + if strings.TrimSpace(req.StartupCommand) != "" || (req.Docker != nil && strings.TrimSpace(req.Docker.StartupCommand) != "") { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "raw docker startup commands are no longer supported"}) + return + } + + template := strings.ToLower(strings.TrimSpace(req.TemplateId)) + if template == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing templateId"}) + return + } + if req.HostPort != 0 { + if _, ok := parseStrictPortValue(req.HostPort); !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid hostPort"}) + return + } + } + if req.Docker != nil { + for _, p := range req.Docker.Ports { + if _, ok := parseStrictPortValue(p); !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": fmt.Sprintf("invalid docker port: %d", p)}) + return + } + } + if cleanPortProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(req.Docker.PortProtocols) > 0 && len(cleanPortProtocols) == 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid docker port protocols"}) + return + } + } + + if ok, why := a.verifyReinstallAdminRequest(r, name, template); !ok { + auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "denied", map[string]any{"reason": why}) + jsonWrite(w, 403, map[string]any{"ok": false, "error": why}) + return + } + + fmt.Printf("[reinstall] Starting reinstall for server %s with template %s\n", name, template) + + a.logs.killTail(name) + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + a.docker.updateRestartNo(ctx, name) + a.docker.rmForce(ctx, name) + cancel() + fmt.Printf("[reinstall] Container removed for %s\n", name) + + oldMeta := a.loadMeta(serverDir) + stripLegacyStartupCommandFields(oldMeta) + existingResources, _ := oldMeta["resources"].(map[string]any) + oldRuntime, _ := oldMeta["runtime"].(map[string]any) + + if _, err := os.Stat(serverDir); err == nil { + if err := os.RemoveAll(serverDir); err != nil { + fmt.Printf("[reinstall] Error removing server dir %s: %v\n", serverDir, err) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to delete server files"}) + return + } + fmt.Printf("[reinstall] Server directory removed: %s\n", serverDir) + } + + _ = os.Remove(a.metaPath(name)) + + if err := ensureDir(serverDir); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to create server directory"}) + return + } + + hostPort := req.HostPort + if hostPort == 0 { + if existingPort, ok := parseStrictPortValue(oldMeta["hostPort"]); ok { + hostPort = existingPort + } else if req.Docker != nil && len(req.Docker.Ports) > 0 { + hostPort = req.Docker.Ports[0] + } else if template == "minecraft" { + hostPort = 25565 + } else { + hostPort = 8080 + } + } + + runtimeConfig := map[string]any{} + rawJavaVersion := strings.TrimSpace(req.JavaVersion) + if rawJavaVersion == "" && req.Docker != nil { + rawJavaVersion = javaVersionFromDockerConfig(req.Docker) + } + if cleanJavaVersion := normalizeMinecraftJavaVersion(rawJavaVersion); strings.TrimSpace(rawJavaVersion) != "" { + if cleanJavaVersion == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "unsupported minecraft java version"}) + return + } + if template != "minecraft" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "java version selection is only available for minecraft"}) + return + } + runtimeConfig["javaVersion"] = cleanJavaVersion + } + if req.Docker != nil { + if req.Docker.Image != "" { + runtimeConfig["image"] = req.Docker.Image + } + if req.Docker.Tag != "" { + runtimeConfig["tag"] = req.Docker.Tag + } + if cmd := sanitizeRuntimeCommand(req.Docker.Command); cmd != "" { + startFile := defaultStartFileForType(template) + dataDir := defaultDataDirForType(template) + cleanCmd := normalizeLegacyRuntimeProcessCommand(template, cmd, startFile, dataDir) + if reason := validateRuntimeProcessCommand(cleanCmd); reason != "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": reason}) + return + } + runtimeConfig["command"] = cleanCmd + } + if req.Docker.Ports != nil { + runtimeConfig["ports"] = req.Docker.Ports + } + if portProtocols := sanitizeDockerPortProtocols(req.Docker.PortProtocols, req.Docker.Ports); len(portProtocols) > 0 { + runtimeConfig["portProtocols"] = portProtocols + } + if req.Docker.Volumes != nil { + runtimeConfig["volumes"] = req.Docker.Volumes + } + if req.Docker.Env != nil { + runtimeConfig["env"] = req.Docker.Env + } + if startup := startupTemplateFromDockerConfig(req.Docker); startup != "" { + runtimeConfig["adpanelStartup"] = startup + delete(runtimeConfig, "command") + } + if startupDisplay := startupDisplayFromDockerConfig(req.Docker); startupDisplay != "" { + runtimeConfig["startupDisplay"] = startupDisplay + } + if install := dockerTemplateInstall(req.Docker); install != nil { + runtimeConfig["install"] = install + } + reqWorkdir := strings.TrimSpace(req.Docker.Workdir) + if reqWorkdir == "" { + reqWorkdir = strings.TrimSpace(req.Docker.WorkingDir) + } + if reqWorkdir != "" { + cleanWorkdir := normalizeContainerWorkdir(reqWorkdir) + if cleanWorkdir == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid workdir (must be an absolute path like /app)"}) + return + } + runtimeConfig["workdir"] = cleanWorkdir + } + if restart := strings.TrimSpace(req.Docker.Restart); restart != "" { + runtimeConfig["restart"] = restart + } else if restartPolicy := strings.TrimSpace(req.Docker.RestartPolicy); restartPolicy != "" { + runtimeConfig["restart"] = restartPolicy + } + if req.Docker.RunAsRoot || req.Docker.RunAsRootSnake { + runtimeConfig["runAsRoot"] = true + } + if req.Docker.Console != nil { + runtimeConfig["console"] = req.Docker.Console + } + runtimeConfig["providerId"] = "custom" + } + if oldRuntime != nil { + for _, key := range []string{"providerId", "versionId", "image", "tag", "javaVersion", "restart", "adpanelStartup", "install", "portProtocols", "runAsRoot"} { + if _, exists := runtimeConfig[key]; exists { + continue + } + if key == "portProtocols" { + if protocols := runtimePortProtocolMap(oldRuntime[key]); len(protocols) > 0 { + clean := map[string][]string{} + for port, values := range protocols { + clean[strconv.Itoa(port)] = values + } + runtimeConfig[key] = clean + } + continue + } + if key == "install" { + if install := installConfigFromRuntime(oldRuntime); install != nil { + runtimeConfig[key] = install + } + continue + } + if key == "runAsRoot" { + if runtimeBool(oldRuntime[key]) { + runtimeConfig[key] = true + } + continue + } + value := strings.TrimSpace(fmt.Sprint(oldRuntime[key])) + if key == "adpanelStartup" && (value == "" || value == "") { + value = startupTemplateFromRuntime(oldRuntime) + } + if value != "" && value != "" { + runtimeConfig[key] = value + } + } + if _, exists := runtimeConfig["command"]; !exists { + if cmd := sanitizeRuntimeCommand(oldRuntime["command"]); cmd != "" { + startFile := defaultStartFileForType(template) + dataDir := defaultDataDirForType(template) + cleanCmd := normalizeLegacyRuntimeProcessCommand(template, cmd, startFile, dataDir) + if validateRuntimeProcessCommand(cleanCmd) == "" { + runtimeConfig["command"] = cleanCmd + } + } + } + if _, exists := runtimeConfig["ports"]; !exists { + if rawPorts, ok := oldRuntime["ports"].([]any); ok && len(rawPorts) > 0 { + cleanPorts := make([]any, 0, len(rawPorts)) + seenPorts := make(map[int]struct{}, len(rawPorts)) + for _, entry := range rawPorts { + port, ok := parseStrictPortValue(entry) + if !ok { + continue + } + if _, seen := seenPorts[port]; seen { + continue + } + seenPorts[port] = struct{}{} + cleanPorts = append(cleanPorts, port) + } + if len(cleanPorts) > 0 { + runtimeConfig["ports"] = cleanPorts + } + } + } + if _, exists := runtimeConfig["volumes"]; !exists { + if rawVolumes, ok := oldRuntime["volumes"].([]any); ok && len(rawVolumes) > 0 { + cleanVolumes := make([]any, 0, len(rawVolumes)) + for _, entry := range rawVolumes { + spec := strings.TrimSpace(fmt.Sprint(entry)) + if spec == "" || spec == "" || strings.ContainsAny(spec, "\x00\r\n") { + continue + } + cleanVolumes = append(cleanVolumes, spec) + } + if len(cleanVolumes) > 0 { + runtimeConfig["volumes"] = cleanVolumes + } + } + } + if _, exists := runtimeConfig["env"]; !exists { + if rawEnv, ok := oldRuntime["env"].(map[string]any); ok && len(rawEnv) > 0 { + cleanEnv := make(map[string]any) + for key, value := range rawEnv { + envKey := strings.TrimSpace(key) + if envKey == "" { + continue + } + envValue := strings.TrimSpace(fmt.Sprint(value)) + if envValue == "" { + envValue = "" + } + cleanEnv[envKey] = envValue + } + if len(cleanEnv) > 0 { + runtimeConfig["env"] = cleanEnv + } + } + } + if _, exists := runtimeConfig["workdir"]; !exists { + oldWorkdir := strings.TrimSpace(fmt.Sprint(oldRuntime["workdir"])) + if oldWorkdir == "" || oldWorkdir == "" { + oldWorkdir = strings.TrimSpace(fmt.Sprint(oldRuntime["workingDir"])) + } + if cleanWorkdir := normalizeContainerWorkdir(oldWorkdir); cleanWorkdir != "" { + runtimeConfig["workdir"] = cleanWorkdir + } + } + if _, exists := runtimeConfig["console"]; !exists { + if rawConsole, ok := oldRuntime["console"]; ok && rawConsole != nil { + runtimeConfig["console"] = rawConsole + } + } + } + + startFile := strings.TrimSpace(fmt.Sprint(oldMeta["start"])) + if startFile == "" { + startFile = defaultStartFileForType(template) + } + + meta := map[string]any{ + "type": template, + "template": template, + "hostPort": hostPort, + "createdAt": time.Now().UnixMilli(), + } + // adpanel:multidisk - preserve the server's disk assignment across reinstall. + // serverDir/serverVolumesRoot were resolved at the top of this handler (so the + // files were correctly rebuilt on the owning disk), but the freshly rebuilt + // meta must keep __diskId or the server would silently fall back to the primary + // disk on the next cold cache / restart and orphan its secondary-disk files. + if diskID, ok := oldMeta["__diskId"].(string); ok && strings.TrimSpace(diskID) != "" { + meta["__diskId"] = strings.TrimSpace(diskID) + } + if oldCreatedAt, ok := oldMeta["createdAt"]; ok { + meta["createdAt"] = oldCreatedAt + } + if startFile != "" { + meta["start"] = startFile + } + if existingResources != nil && len(existingResources) > 0 { + meta["resources"] = existingResources + } + if existingPF, ok := oldMeta["portForwards"]; ok { + meta["portForwards"] = existingPF + } + + if template == "minecraft" { + fork := "paper" + ver := "1.21.8" + writeMinecraftScaffold(serverDir, name, fork, ver) + + dlCtx, dlCancel := context.WithTimeout(context.Background(), 30*time.Second) + jarURL := getMinecraftJarURL(dlCtx, a.dl, fork, ver, a.debug) + dlCancel() + + dlCtx2, dlCancel2 := context.WithTimeout(context.Background(), 30*time.Minute) + if err := a.dl.downloadToFile(dlCtx2, jarURL, filepath.Join(serverDir, "server.jar")); err != nil { + dlCancel2() + fmt.Printf("[reinstall] Failed to download minecraft jar: %v\n", err) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "download failed", "detail": err.Error()}) + return + } + dlCancel2() + + mcImage := defaultMinecraftProcessImage + mcTag := defaultMinecraftProcessTag + mcCommand := defaultMinecraftProcessCommand + mcWorkdir := defaultDataDirForType("minecraft") + mcJavaVersion := normalizeMinecraftJavaVersion(runtimeConfig["javaVersion"]) + if image, ok := runtimeConfig["image"].(string); ok && strings.TrimSpace(image) != "" { + mcImage = strings.TrimSpace(image) + } + if tag, ok := runtimeConfig["tag"].(string); ok && strings.TrimSpace(tag) != "" { + mcTag = strings.TrimSpace(tag) + } + if cmd, ok := runtimeConfig["command"].(string); ok && strings.TrimSpace(cmd) != "" { + mcCommand = strings.TrimSpace(cmd) + } + if workdir, ok := runtimeConfig["workdir"].(string); ok && strings.TrimSpace(workdir) != "" { + mcWorkdir = strings.TrimSpace(workdir) + } + if mcJavaVersion == "" { + mcJavaVersion = minecraftJavaVersionFromTag(mcTag) + } + if mcJavaVersion != "" { + mcImage = defaultMinecraftProcessImage + mcTag = minecraftJavaTag(mcJavaVersion) + } + + mcRuntime := map[string]any{ + "image": mcImage, + "tag": mcTag, + "command": mcCommand, + "workdir": mcWorkdir, + "javaVersion": mcJavaVersion, + } + for _, key := range []string{"providerId", "versionId", "ports", "volumes", "env", "restart", "console"} { + if value, ok := runtimeConfig[key]; ok && value != nil { + mcRuntime[key] = value + } + } + + meta = map[string]any{ + "type": "minecraft", + "fork": fork, + "version": ver, + "start": "server.jar", + "hostPort": hostPort, + "runtime": mcRuntime, + } + // adpanel:multidisk - the minecraft branch rebuilds meta from scratch, so + // re-apply the disk assignment that was carried over above. + if diskID, ok := oldMeta["__diskId"].(string); ok && strings.TrimSpace(diskID) != "" { + meta["__diskId"] = strings.TrimSpace(diskID) + } + if oldCreatedAt, ok := oldMeta["createdAt"]; ok { + meta["createdAt"] = oldCreatedAt + } + if existingResources != nil && len(existingResources) > 0 { + meta["resources"] = existingResources + } + if existingPF, ok := oldMeta["portForwards"]; ok { + meta["portForwards"] = existingPF + } + _ = a.saveMeta(serverDir, meta) + enforceServerProps(serverDir) + } else { + if cmd, ok := runtimeConfig["command"].(string); !ok || strings.TrimSpace(cmd) == "" { + if defaultCmd := defaultRuntimeCommandForType(template, startFile, defaultDataDirForType(template)); defaultCmd != "" { + runtimeConfig["command"] = defaultCmd + } + } + if _, ok := runtimeConfig["workdir"]; !ok && hasManagedRuntimeDefaults(template) { + runtimeConfig["workdir"] = defaultDataDirForType(template) + } + if len(runtimeConfig) > 0 { + meta["runtime"] = runtimeConfig + } + + if install := installConfigFromRuntime(runtimeConfig); install != nil { + if err := a.runTemplateInstall(name, serverDir, install, runtimeConfig, hostPort, nil); err != nil { + fmt.Printf("[reinstall] Template install failed: %v\n", err) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "install failed", "detail": err.Error()}) + return + } + } + + switch template { + case "python": + scaffoldPython(serverDir, startFile) + case "nodejs", "discord-bot": + p := hostPort + if p == 0 { + p = 3001 + } + scaffoldNode(serverDir, startFile, p) + default: + if startFile != "" { + _ = os.WriteFile(filepath.Join(serverDir, filepath.Base(startFile)), []byte(""), 0o644) + } + } + + _ = a.saveMeta(serverDir, meta) + + if img, ok := runtimeConfig["image"].(string); ok && strings.TrimSpace(img) != "" { + tag := "latest" + if t, ok := runtimeConfig["tag"].(string); ok && strings.TrimSpace(t) != "" { + tag = strings.TrimSpace(t) + } + imageRef := strings.TrimSpace(img) + ":" + tag + pullCtx, pullCancel := context.WithTimeout(context.Background(), 10*time.Minute) + if err := a.docker.ensureImageAvailableAPI(pullCtx, imageRef); err != nil { + pullCancel() + jsonWrite(w, 500, map[string]any{"ok": false, "error": "docker image pull failed", "detail": err.Error()}) + return + } + pullCancel() + ensureVolumeWritable(serverDir) + } + } + + fmt.Printf("[reinstall] Server %s reinstalled successfully with template %s\n", name, template) + + // Recreate the Docker container exactly like a fresh create. The old container + // was force-removed at the start of the reinstall; without this step the server + // would be left with rebuilt files but no running container, which is the broken + // behaviour reported from the UI. We reload meta from disk so the container is + // started from the persisted, authoritative state (including __diskId routing). + startCtx, startCancel := context.WithTimeout(context.Background(), 240*time.Second) + freshMeta := a.loadMeta(serverDir) + if len(freshMeta) == 0 { + freshMeta = meta + } + startResources := resourceLimitsFromMeta(freshMeta) + var startErr error + if template == "minecraft" { + startErr = a.startMinecraftContainer(startCtx, name, serverDir, hostPort, startResources, nil) + } else if isManagedProcessRuntime(template) { + startErr = a.startRuntimeContainer(startCtx, name, serverDir, freshMeta, hostPort, startResources, nil) + } else if img, ok := runtimeConfig["image"].(string); ok && strings.TrimSpace(img) != "" { + startErr = a.startCustomDockerContainer(startCtx, name, serverDir, freshMeta, hostPort, startResources) + } else { + fmt.Printf("[reinstall] No container image resolved for %s (template %s); skipping container start\n", name, template) + } + startCancel() + if startErr != nil { + fmt.Printf("[reinstall] Container start failed for %s: %v\n", name, startErr) + auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "start-failed", map[string]any{"template": template, "error": startErr.Error()}) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "server files reinstalled but container failed to start", "detail": startErr.Error()}) + return + } + a.ensureLiveLogs(name) + + auditLog.Log("server_reinstall", getClientIP(r), "", name, "reinstall", "success", map[string]any{"template": template}) + jsonWrite(w, 200, map[string]any{"ok": true, "name": name, "template": template, "meta": meta}) +} + +func (a *Agent) handleFilesList(w http.ResponseWriter, r *http.Request, name string) { + root := a.serverDir(name) + if st, err := os.Stat(root); err != nil || !st.IsDir() { + jsonWrite(w, 404, map[string]any{"error": "server not found"}) + return + } + rel := r.URL.Query().Get("path") + dir, ok := safeJoin(root, rel) + if !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid path"}) + return + } + st, err := os.Lstat(dir) + if err != nil || !st.IsDir() { + jsonWrite(w, 400, map[string]any{"error": "not a directory"}) + return + } + if err := ensureResolvedUnder(root, dir); err != nil { + jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) + return + } + ents, err := os.ReadDir(dir) + if err != nil { + if a.debug { + fmt.Printf("[files] list error for %s: %v\n", dir, err) + } + jsonWrite(w, 500, map[string]any{"error": "failed to read directory"}) + return + } + out := make([]map[string]any, 0, len(ents)) + for _, e := range ents { + typ := "file" + if e.IsDir() { + typ = "dir" + } + out = append(out, map[string]any{"name": e.Name(), "type": typ}) + } + jsonWrite(w, 200, map[string]any{"ok": true, "entries": out, "path": rel}) +} + +func (a *Agent) handleFilesRead(w http.ResponseWriter, r *http.Request, name string) { + root := a.serverDir(name) + rel := r.URL.Query().Get("path") + file, ok := safeJoin(root, rel) + if !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid path"}) + return + } + info, err := os.Lstat(file) + if err != nil { + jsonWrite(w, 404, map[string]any{"error": "file not found"}) + return + } + if info.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"error": "cannot read symlink"}) + return + } + if err := ensureResolvedUnder(root, file); err != nil { + jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) + return + } + if info.IsDir() { + jsonWrite(w, 400, map[string]any{"error": "path is a directory"}) + return + } + const maxEditorRead = 10 << 20 + if info.Size() > maxEditorRead { + jsonWrite(w, 400, map[string]any{"error": "file too large (max 10MB)"}) + return + } + b, err := os.ReadFile(file) + if err != nil { + if a.debug { + fmt.Printf("[files] read error for %s: %v\n", file, err) + } + jsonWrite(w, 500, map[string]any{"error": "failed to read file"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true, "path": rel, "content": string(b)}) +} + +func (a *Agent) handleFilesWrite(w http.ResponseWriter, r *http.Request, name string) { + root := a.serverDir(name) + var body struct { + Path string `json:"path"` + Content string `json:"content"` + } + if err := readJSON(w, r, 10<<20, &body); err != nil { + jsonWrite(w, 400, map[string]any{"error": "bad json or content too large (max 10MB)"}) + return + } + if diskErr := a.checkDiskLimit(root, int64(len(body.Content))); diskErr != nil { + jsonWrite(w, 507, diskErr) + return + } + file, ok := safeJoin(root, body.Path) + if !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid path"}) + return + } + + parentDir := filepath.Dir(file) + if parentDir != root { + resolvedParent, err := filepath.EvalSymlinks(parentDir) + if err == nil && !isUnder(root, resolvedParent) { + jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) + return + } + } + + _ = ensureDir(filepath.Dir(file)) + if rp, err := filepath.EvalSymlinks(filepath.Dir(file)); err == nil && !isUnder(root, rp) { + jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) + return + } + if info, err := os.Lstat(file); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"error": "cannot write to symlink"}) + return + } + } + if err := writeFileNoFollow(file, []byte(body.Content), 0o644); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) handleFilesDelete(w http.ResponseWriter, r *http.Request, name string) { + root := a.serverDir(name) + var body struct { + Path string `json:"path"` + IsDir bool `json:"isDir"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil { + jsonWrite(w, 400, map[string]any{"error": "bad json"}) + return + } + p, ok := safeJoin(root, body.Path) + if !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid path"}) + return + } + if filepath.Clean(p) == filepath.Clean(root) { + jsonWrite(w, 400, map[string]any{"error": "refusing to delete server root"}) + return + } + if _, err := os.Lstat(p); err != nil { + jsonWrite(w, 200, map[string]any{"ok": true, "note": "already missing"}) + return + } + if err := ensureResolvedUnder(root, p); err != nil { + jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) + return + } + parentDir := filepath.Dir(p) + if parentDir != root { + resolvedParent, rpErr := filepath.EvalSymlinks(parentDir) + if rpErr == nil && !isUnder(root, resolvedParent) { + jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) + return + } + } + var err error + if body.IsDir { + err = os.RemoveAll(p) + } else { + err = os.Remove(p) + } + if err != nil { + jsonWrite(w, 500, map[string]any{"error": "delete operation failed"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) handleFilesUpload(w http.ResponseWriter, r *http.Request, name string) { + root := a.serverDir(name) + var body struct { + DestDir string `json:"destDir"` + Filename string `json:"filename"` + Content string `json:"content"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil { + jsonWrite(w, 400, map[string]any{"error": "bad json"}) + return + } + if diskErr := a.checkDiskLimit(root, int64(len(body.Content))); diskErr != nil { + jsonWrite(w, 507, diskErr) + return + } + if strings.TrimSpace(body.Filename) == "" { + jsonWrite(w, 400, map[string]any{"error": "missing filename"}) + return + } + destDir, ok := safeJoin(root, body.DestDir) + if !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid path"}) + return + } + _ = ensureDir(destDir) + if err := ensureResolvedUnder(root, destDir); err != nil { + jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) + return + } + + fn := filepath.Base(body.Filename) + fn = strings.NewReplacer("\r", "_", "\n", "_", "\x00", "_").Replace(fn) + if fn == "" || fn == "." || fn == ".." { + jsonWrite(w, 400, map[string]any{"error": "invalid filename"}) + return + } + destFile := filepath.Join(destDir, fn) + if !isUnder(destDir, destFile) { + jsonWrite(w, 400, map[string]any{"error": "invalid filename"}) + return + } + + b64 := body.Content + if strings.HasPrefix(b64, "data:") { + if i := strings.Index(b64, ","); i >= 0 { + b64 = b64[i+1:] + } + } + const maxBase64Upload = 25 << 20 + if base64.StdEncoding.DecodedLen(len(b64)) > maxBase64Upload { + jsonWrite(w, 400, map[string]any{"error": "file too large for base64 upload; use stream upload"}) + return + } + data, err := base64.StdEncoding.DecodeString(b64) + if err != nil { + jsonWrite(w, 400, map[string]any{"error": "invalid base64"}) + return + } + if err := writeFileNoFollow(destFile, data, 0o644); err != nil { + if a.debug { + fmt.Printf("[files] upload error for %s: %v\n", destFile, err) + } + jsonWrite(w, 500, map[string]any{"error": "failed to write file"}) + return + } + rel, _ := filepath.Rel(root, destFile) + jsonWrite(w, 200, map[string]any{"ok": true, "path": rel}) +} + +func (a *Agent) handleFilesArchive(w http.ResponseWriter, r *http.Request, name string) { + root := a.serverDir(name) + var body struct { + Paths []string `json:"paths"` + DestDir string `json:"destDir"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil { + jsonWrite(w, 400, map[string]any{"error": "bad json"}) + return + } + if len(body.Paths) == 0 { + jsonWrite(w, 400, map[string]any{"error": "no paths specified"}) + return + } + if diskErr := a.checkDiskLimit(root, 0); diskErr != nil { + jsonWrite(w, 507, diskErr) + return + } + + destDir, ok := safeJoin(root, body.DestDir) + if !ok { + jsonWrite(w, 400, map[string]any{"error": "invalid destination path"}) + return + } + _ = ensureDir(destDir) + resolvedDest, rdErr := filepath.EvalSymlinks(destDir) + if rdErr == nil && !isUnder(root, resolvedDest) { + jsonWrite(w, 400, map[string]any{"error": "symlink escape blocked"}) + return + } + + archiveName := fmt.Sprintf("archive-%s.tar.gz", time.Now().Format("20060102-150405")) + archivePath := filepath.Join(destDir, archiveName) + + outFile, err := os.OpenFile(archivePath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644) + if err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to create archive"}) + return + } + defer outFile.Close() + + gw := gzip.NewWriter(outFile) + defer gw.Close() + + tw := tar.NewWriter(gw) + defer tw.Close() + + for _, p := range body.Paths { + srcPath, ok := safeJoin(root, p) + if !ok { + continue + } + if err := ensureResolvedUnder(root, srcPath); err != nil { + continue + } + info, err := os.Lstat(srcPath) + if err != nil { + continue + } + if info.Mode()&os.ModeSymlink != 0 { + continue + } + baseName := filepath.Base(srcPath) + + if info.IsDir() { + _ = filepath.WalkDir(srcPath, func(path string, d os.DirEntry, walkErr error) error { + if walkErr != nil || d == nil { + return nil + } + if d.Type()&os.ModeSymlink != 0 { + return nil + } + fi, fiErr := d.Info() + if fiErr != nil { + return nil + } + rel, relErr := filepath.Rel(srcPath, path) + if relErr != nil { + return nil + } + if rel == "." { + return nil + } + if fi.Mode()&os.ModeSymlink != 0 { + return nil + } + if resolved, rErr := filepath.EvalSymlinks(path); rErr == nil && !isUnder(root, resolved) { + return nil + } + hdr, hdrErr := tar.FileInfoHeader(fi, "") + if hdrErr != nil { + return nil + } + hdr.Mode = int64(sanitizeFileMode(os.FileMode(hdr.Mode), fi.IsDir())) + hdr.Uid = 0 + hdr.Gid = 0 + hdr.Uname = "" + hdr.Gname = "" + hdr.Name = filepath.ToSlash(filepath.Join(baseName, rel)) + if fi.IsDir() && !strings.HasSuffix(hdr.Name, "/") { + hdr.Name += "/" + } + if err := tw.WriteHeader(hdr); err != nil { + return nil + } + if !fi.Mode().IsRegular() { + return nil + } + f, openErr := os.Open(path) + if openErr != nil { + return nil + } + _, _ = io.Copy(tw, f) + f.Close() + return nil + }) + } else { + if info.Mode()&os.ModeSymlink != 0 { + continue + } + hdr, hdrErr := tar.FileInfoHeader(info, "") + if hdrErr != nil { + continue + } + hdr.Mode = int64(sanitizeFileMode(os.FileMode(hdr.Mode), false)) + hdr.Uid = 0 + hdr.Gid = 0 + hdr.Uname = "" + hdr.Gname = "" + hdr.Name = baseName + if err := tw.WriteHeader(hdr); err != nil { + continue + } + if info.Mode().IsRegular() { + f, openErr := os.Open(srcPath) + if openErr != nil { + continue + } + _, _ = io.Copy(tw, f) + f.Close() + } + } + } + + if err := tw.Close(); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to finalize archive"}) + return + } + if err := gw.Close(); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to finalize archive"}) + return + } + + relPath, _ := filepath.Rel(root, archivePath) + jsonWrite(w, 200, map[string]any{"ok": true, "path": relPath, "name": archiveName}) +} + +func (a *Agent) backupsDir() string { + return filepath.Join(a.dataRoot, "backups") +} + +func (a *Agent) serverBackupsDir(serverName string) string { + // adpanel:multidisk - backups live on the same disk as the server. Defaults + // to the primary backups root for unassigned servers (back-compat). + disk := a.diskForServer(serverName) + if disk.Primary || disk.ID == primaryDiskID { + return filepath.Join(a.backupsDir(), sanitizeName(serverName)) + } + return filepath.Join(a.diskLayoutBackups(disk.MountPath), sanitizeName(serverName)) +} + +// serverVolumesRoot returns the volumes root that owns the given server's files. +// adpanel:multidisk - this is the parent under which the server directory lives, +// which is the primary volumes dir for unassigned servers and the disk-specific +// volumes root otherwise. Delete/detach guards must validate against THIS root, +// not a.volumesDir, or secondary-disk servers are wrongly rejected as "invalid +// path" and their files/backups are never removed. +func (a *Agent) serverVolumesRoot(serverName string) string { + disk := a.diskForServer(serverName) + if disk.Primary || disk.ID == primaryDiskID { + return filepath.Clean(a.volumesDir) + } + return filepath.Clean(a.diskLayoutVolumes(disk.MountPath)) +} + +// serverBackupsRoot returns the backups root that owns the given server's backups +// (the parent of serverBackupsDir). Used as the detach parentRoot for backups. +func (a *Agent) serverBackupsRoot(serverName string) string { + disk := a.diskForServer(serverName) + if disk.Primary || disk.ID == primaryDiskID { + return filepath.Clean(a.backupsDir()) + } + return filepath.Clean(a.diskLayoutBackups(disk.MountPath)) +} + +func deletionTrashDir(parent string) string { + return filepath.Join(parent, ".adpanel_deleting") +} + +func deletionTombstoneName(label, name string) string { + safe := sanitizeName(name) + if safe == "" { + safe = "unknown" + } + label = sanitizeName(label) + if label == "" { + label = "path" + } + return fmt.Sprintf("%s-%s-%d", label, safe, time.Now().UnixNano()) +} + +func deleteTrashPrefix(label, name string) string { + safe := sanitizeName(name) + if safe == "" { + safe = "unknown" + } + label = sanitizeName(label) + if label == "" { + label = "path" + } + return fmt.Sprintf("%s-%s-", label, safe) +} + +func pathExists(path string) bool { + _, err := os.Lstat(path) + return err == nil +} + +func deleteTrashEntryExists(parentRoot, label, name string) bool { + entries, err := os.ReadDir(deletionTrashDir(parentRoot)) + if err != nil { + return false + } + prefix := deleteTrashPrefix(label, name) + for _, entry := range entries { + if strings.HasPrefix(entry.Name(), prefix) { + return true + } + } + return false +} + +func (a *Agent) containerExistsKnown(ctx context.Context, name string) (bool, bool) { + if exists, err := a.docker.containerExistsAPI(ctx, name); err == nil { + return exists, true + } + if ctx.Err() != nil { + return false, false + } + _, errText, _, err := a.docker.runCollect(ctx, "inspect", name) + if err == nil { + return true, true + } + if ctx.Err() != nil { + return false, false + } + msg := strings.ToLower(errText) + if strings.Contains(msg, "no such object") || strings.Contains(msg, "no such container") || strings.Contains(msg, "not found") { + return false, true + } + return false, false +} + +func (a *Agent) deleteStatus(ctx context.Context, name string) map[string]any { + containerExists, containerCheckOk := a.containerExistsKnown(ctx, name) + serverDirExists := pathExists(a.serverDir(name)) + metaExists := pathExists(a.metaPath(name)) + backupsDir := a.serverBackupsDir(name) + // adpanel:multidisk - validate the backups path against the server's OWNING + // backups root, not the primary one. Otherwise secondary-disk backups are + // never inspected and the panel can wrongly conclude the delete is complete. + bkRoot := a.serverBackupsRoot(name) + backupsDirExists := false + if isUnder(bkRoot, backupsDir) { + backupsDirExists = pathExists(backupsDir) + } + volRoot := a.serverVolumesRoot(name) + serverTrashExists := deleteTrashEntryExists(volRoot, "server", name) + backupTrashExists := deleteTrashEntryExists(bkRoot, "backups", name) + deleted := containerCheckOk && !containerExists && !serverDirExists && !metaExists && !backupsDirExists + return map[string]any{ + "ok": true, + "deleteStatus": true, + "name": name, + "deleted": deleted, + "containerExists": containerExists, + "containerCheckOk": containerCheckOk, + "serverDirExists": serverDirExists, + "metaExists": metaExists, + "backupsDirExists": backupsDirExists, + "serverTrashExists": serverTrashExists, + "backupTrashExists": backupTrashExists, + } +} + +func (a *Agent) handleDeleteStatus(w http.ResponseWriter, r *http.Request, name string) { + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + jsonWrite(w, 200, a.deleteStatus(ctx, name)) +} + +func (a *Agent) detachPathForAsyncDelete(parentRoot, target, label, name string) (string, bool, error) { + parentRoot = filepath.Clean(parentRoot) + target = filepath.Clean(target) + if parentRoot == "" || target == "" || target == "." || target == string(os.PathSeparator) { + return "", false, fmt.Errorf("invalid delete path") + } + if filepath.Clean(parentRoot) == target { + return "", false, fmt.Errorf("refusing to delete root") + } + if !isUnder(parentRoot, target) { + return "", false, fmt.Errorf("delete path escapes root") + } + if _, err := os.Lstat(target); err != nil { + if os.IsNotExist(err) { + return "", false, nil + } + return "", false, err + } + + trashRoot := deletionTrashDir(parentRoot) + if err := ensureDir(trashRoot); err != nil { + return "", true, err + } + + var lastErr error + for i := 0; i < 10; i++ { + dst := filepath.Join(trashRoot, deletionTombstoneName(label, name)) + if i > 0 { + dst = fmt.Sprintf("%s-%d", dst, i) + } + if err := os.Rename(target, dst); err == nil { + return dst, true, nil + } else { + if os.IsNotExist(err) { + return "", false, nil + } + lastErr = err + time.Sleep(25 * time.Millisecond) + } + } + return "", true, lastErr +} + +func chmodTreeWritable(root string) { + _ = filepath.Walk(root, func(p string, info os.FileInfo, err error) error { + if err != nil || info == nil { + return nil + } + if info.Mode()&os.ModeSymlink != 0 { + return nil + } + if info.IsDir() { + _ = os.Chmod(p, 0o777) + return nil + } + _ = os.Chmod(p, info.Mode().Perm()|0o600) + return nil + }) +} + +func removeAllWritable(root string) error { + root = filepath.Clean(root) + if root == "" || root == "." || root == string(os.PathSeparator) { + return fmt.Errorf("refusing to remove unsafe path") + } + if err := os.RemoveAll(root); err == nil { + return nil + } else { + firstErr := err + chmodTreeWritable(root) + if retryErr := os.RemoveAll(root); retryErr != nil { + return fmt.Errorf("%v; retry after chmod failed: %w", firstErr, retryErr) + } + } + return nil +} + +func removeDetachedPathAsync(label, root string) { + root = filepath.Clean(root) + if root == "" || root == "." || root == string(os.PathSeparator) { + return + } + go func() { + started := time.Now() + if err := removeAllWritable(root); err != nil { + fmt.Printf("[delete] async cleanup failed for %s %s after %s: %v\n", label, root, time.Since(started).Round(time.Millisecond), err) + return + } + fmt.Printf("[delete] async cleanup completed for %s %s in %s\n", label, root, time.Since(started).Round(time.Millisecond)) + }() +} + +func (a *Agent) cleanupPendingDeletes() { + // adpanel:multidisk - sweep the deletion trash on EVERY disk (primary + + // secondaries), not just the primary roots. Detached tombstones for + // secondary-disk servers/backups live under each disk's own volumes/backups + // trash dir and would otherwise leak on restart. + roots := []string{deletionTrashDir(a.volumesDir), deletionTrashDir(a.backupsDir())} + for _, d := range a.registeredDisks() { + roots = append(roots, + deletionTrashDir(a.diskLayoutVolumes(d.MountPath)), + deletionTrashDir(a.diskLayoutBackups(d.MountPath)), + ) + } + seen := map[string]struct{}{} + for _, root := range roots { + root = filepath.Clean(root) + if _, dup := seen[root]; dup { + continue + } + seen[root] = struct{}{} + entries, err := os.ReadDir(root) + if err != nil { + continue + } + for _, entry := range entries { + removeDetachedPathAsync("startup-trash", filepath.Join(root, entry.Name())) + } + } +} + +type BackupMeta struct { + ID string `json:"id"` + Name string `json:"name"` + Description string `json:"description"` + ServerName string `json:"serverName"` + CreatedAt int64 `json:"createdAt"` + Size int64 `json:"size"` + Status string `json:"status"` +} + +func (a *Agent) loadBackupMeta(backupDir string) *BackupMeta { + metaPath := filepath.Join(backupDir, "backup.json") + data, err := os.ReadFile(metaPath) + if err != nil { + return nil + } + var meta BackupMeta + if err := json.Unmarshal(data, &meta); err != nil { + return nil + } + return &meta +} + +func (a *Agent) saveBackupMeta(backupDir string, meta *BackupMeta) error { + data, err := json.MarshalIndent(meta, "", " ") + if err != nil { + return err + } + return writeFileNoFollow(filepath.Join(backupDir, "backup.json"), data, 0644) +} + +func getDirSize(path string) int64 { + var size int64 + filepath.Walk(path, func(_ string, info os.FileInfo, err error) error { + if err == nil && !info.IsDir() { + size += info.Size() + } + return nil + }) + return size +} + +func (a *Agent) handleBackupsList(w http.ResponseWriter, r *http.Request, serverName string) { + backupsDir := a.serverBackupsDir(serverName) + + entries, err := os.ReadDir(backupsDir) + if err != nil { + if os.IsNotExist(err) { + jsonWrite(w, 200, map[string]any{"ok": true, "backups": []any{}}) + return + } + jsonWrite(w, 500, map[string]any{"error": err.Error()}) + return + } + + var backups []BackupMeta + for _, entry := range entries { + if !entry.IsDir() { + continue + } + backupDir := filepath.Join(backupsDir, entry.Name()) + meta := a.loadBackupMeta(backupDir) + if meta != nil { + backups = append(backups, *meta) + } + } + + for i := 0; i < len(backups)-1; i++ { + for j := i + 1; j < len(backups); j++ { + if backups[j].CreatedAt > backups[i].CreatedAt { + backups[i], backups[j] = backups[j], backups[i] + } + } + } + + jsonWrite(w, 200, map[string]any{"ok": true, "backups": backups}) +} + +func (a *Agent) handleBackupsCreate(w http.ResponseWriter, r *http.Request, serverName string) { + serverDir := a.serverDir(serverName) + if _, err := os.Stat(serverDir); err != nil { + jsonWrite(w, 404, map[string]any{"error": "server not found"}) + return + } + // adpanel:backup-storage - a backup is a full copy of the server's files, so + // it consumes roughly the current server-file size on top of the already + // occupied storage (files + existing backups). Reject up front when that + // projected total would exceed the storage limit, so we never start an + // expensive copy that would blow past the quota. + projectedBackupBytes := a.getServerDiskUsage(serverDir) + if diskErr := a.checkDiskLimit(serverDir, projectedBackupBytes); diskErr != nil { + jsonWrite(w, 507, diskErr) + return + } + + meta := a.loadMeta(serverDir) + if resources, ok := meta["resources"].(map[string]any); ok { + if backupsMaxRaw, ok := resources["backupsMax"]; ok { + var backupsMax int + switch v := backupsMaxRaw.(type) { + case float64: + backupsMax = int(v) + case int: + backupsMax = v + case int64: + backupsMax = int(v) + } + + if backupsMax > 0 { + backupsDir := a.serverBackupsDir(serverName) + entries, err := os.ReadDir(backupsDir) + currentCount := 0 + if err == nil { + for _, e := range entries { + if e.IsDir() { + currentCount++ + } + } + } + if currentCount >= backupsMax { + jsonWrite(w, 403, map[string]any{ + "error": "backup_limit_reached", + "message": fmt.Sprintf("Maximum backup limit reached (%d/%d). Delete old backups to create new ones.", currentCount, backupsMax), + "current": currentCount, + "max": backupsMax, + }) + return + } + } + } + } + + var body struct { + Name string `json:"name"` + Description string `json:"description"` + } + _ = readJSON(w, r, 1024*1024, &body) + + backupId := fmt.Sprintf("%d_%s", time.Now().UnixMilli(), randomHex(6)) + + backupDir := filepath.Join(a.serverBackupsDir(serverName), backupId) + if err := ensureDir(backupDir); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to create backup directory"}) + return + } + + dataDir := filepath.Join(backupDir, "data") + if err := ensureDir(dataDir); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to create data directory"}) + return + } + + if err := copyDir(serverDir, dataDir); err != nil { + os.RemoveAll(backupDir) + jsonWrite(w, 500, map[string]any{"error": "failed to copy server files: " + err.Error()}) + return + } + + size := getDirSize(dataDir) + + backupName := strings.TrimSpace(body.Name) + if backupName == "" { + backupName = fmt.Sprintf("Backup %s", time.Now().Format("2006-01-02 15:04")) + } + + backupMeta := &BackupMeta{ + ID: backupId, + Name: backupName, + Description: strings.TrimSpace(body.Description), + ServerName: serverName, + CreatedAt: time.Now().UnixMilli(), + Size: size, + Status: "complete", + } + + if err := a.saveBackupMeta(backupDir, backupMeta); err != nil { + os.RemoveAll(backupDir) + jsonWrite(w, 500, map[string]any{"error": "failed to save backup metadata"}) + return + } + + a.logf("Created backup %s for server %s (size: %d bytes)", backupId, serverName, size) + jsonWrite(w, 200, map[string]any{"ok": true, "backup": backupMeta}) +} + +func (a *Agent) handleSubdomains(w http.ResponseWriter, r *http.Request, serverName string) { + var body struct { + Domain string `json:"domain"` + Action string `json:"action"` + Port int `json:"port"` + } + if err := readJSON(w, r, 1024, &body); err != nil { + jsonWrite(w, 400, map[string]any{"error": "bad json"}) + return + } + + action := strings.ToLower(strings.TrimSpace(body.Action)) + if action != "create" && action != "delete" { + jsonWrite(w, 400, map[string]any{"error": "action must be 'create' or 'delete'"}) + return + } + + domain := strings.TrimSpace(body.Domain) + if !isValidDomainName(domain) { + jsonWrite(w, 400, map[string]any{"error": "invalid domain name"}) + return + } + + safeDomain := sanitizeName(domain) + if safeDomain == "" { + jsonWrite(w, 400, map[string]any{"error": "invalid domain name"}) + return + } + confPath := filepath.Join("/etc/nginx/conf.d", fmt.Sprintf("%s-%s.conf", serverName, safeDomain)) + + if action == "delete" { + os.Remove(confPath) + if err := exec.Command("nginx", "-t").Run(); err != nil { + jsonWrite(w, 500, map[string]any{"error": "nginx config test failed after delete"}) + return + } + exec.Command("systemctl", "reload", "nginx").Run() + jsonWrite(w, 200, map[string]any{"ok": true}) + return + } + + serverDir := a.serverDir(serverName) + meta := a.loadMeta(serverDir) + + allowedPort := anyToInt(meta["hostPort"]) + + var targetPort int + + allocatedPorts := make(map[int]bool) + if allowedPort > 0 { + allocatedPorts[allowedPort] = true + } + forwards := a.loadPortForwards(serverDir) + for _, pf := range forwards { + if pf.Public > 0 { + allocatedPorts[pf.Public] = true + } + } + + if len(allocatedPorts) == 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "server has no allocated ports for subdomain proxy"}) + return + } + + if body.Port > 0 { + if !allocatedPorts[body.Port] { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "port is not allocated to this server"}) + return + } + targetPort = body.Port + } else if allowedPort > 0 { + targetPort = allowedPort + } else if len(forwards) > 0 { + targetPort = forwards[0].Public + } + + if targetPort < 1 || targetPort > 65535 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "no valid port available"}) + return + } + + config := fmt.Sprintf(`server { + listen 80; + server_name %s; + + location / { + proxy_pass http://127.0.0.1:%d; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + } +}`, domain, targetPort) + + if err := writeFileNoFollow(confPath, []byte(config), 0644); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to write nginx config"}) + return + } + + if err := exec.Command("nginx", "-t").Run(); err != nil { + os.Remove(confPath) + jsonWrite(w, 500, map[string]any{"error": "nginx config validation failed - config removed"}) + return + } + + if err := exec.Command("systemctl", "reload", "nginx").Run(); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to reload nginx"}) + return + } + + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func isValidDomainName(d string) bool { + if len(d) == 0 || len(d) > 253 { + return false + } + if strings.ContainsAny(d, "\"';{}$\\`()!@#%^&=+[]|<>?/ \t\n\r") { + return false + } + labels := strings.Split(d, ".") + if len(labels) == 0 { + return false + } + for _, label := range labels { + if len(label) == 0 || len(label) > 63 { + return false + } + if label[0] == '-' || label[len(label)-1] == '-' { + return false + } + for i, c := range label { + if c == '*' { + if i != 0 || label != "*" { + return false + } + continue + } + if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || + (c >= '0' && c <= '9') || c == '-') { + return false + } + } + } + return true +} + +func (a *Agent) handleBackupsRestore(w http.ResponseWriter, r *http.Request, serverName, backupId string) { + if !validateBackupId(backupId) { + jsonWrite(w, 400, map[string]any{"error": "invalid backup id format"}) + return + } + + backupDir := filepath.Join(a.serverBackupsDir(serverName), backupId) + dataDir := filepath.Join(backupDir, "data") + + if _, err := os.Stat(dataDir); err != nil { + jsonWrite(w, 404, map[string]any{"error": "backup not found"}) + return + } + + var body struct { + DeleteOldFiles bool `json:"deleteOldFiles"` + } + _ = readJSON(w, r, 1024, &body) + + serverDir := a.serverDir(serverName) + if !body.DeleteOldFiles { + backupSize, _ := getDirSizeBytes(dataDir) + if diskErr := a.checkDiskLimit(serverDir, backupSize); diskErr != nil { + jsonWrite(w, 507, diskErr) + return + } + // adpanel:multidisk - backups live on the server's disk; enforce per-disk + // capacity (no-op on primary / unlimited disks). + if capErr := a.checkDiskCapacity(a.diskForServer(serverName), backupSize); capErr != nil { + jsonWrite(w, 507, capErr) + return + } + } + + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + a.docker.updateRestartNo(ctx, serverName) + a.docker.stop(ctx, serverName) + cancel() + + if body.DeleteOldFiles { + entries, _ := os.ReadDir(serverDir) + for _, entry := range entries { + p := filepath.Join(serverDir, entry.Name()) + os.RemoveAll(p) + } + } + + if err := copyDir(dataDir, serverDir); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to restore backup: " + err.Error()}) + return + } + + a.logf("Restored backup %s for server %s (deleteOldFiles=%v)", backupId, serverName, body.DeleteOldFiles) + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) handleBackupsDelete(w http.ResponseWriter, r *http.Request, serverName, backupId string) { + if !validateBackupId(backupId) { + jsonWrite(w, 400, map[string]any{"error": "invalid backup id format"}) + return + } + + backupDir := filepath.Join(a.serverBackupsDir(serverName), backupId) + + if _, err := os.Stat(backupDir); err != nil { + jsonWrite(w, 404, map[string]any{"error": "backup not found"}) + return + } + + if err := os.RemoveAll(backupDir); err != nil { + jsonWrite(w, 500, map[string]any{"error": "failed to delete backup"}) + return + } + + a.logf("Deleted backup %s for server %s", backupId, serverName) + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func randomHex(n int) string { + b := make([]byte, n) + _, _ = rand.Read(b) + return hex.EncodeToString(b) +} + +func validateBackupId(id string) bool { + if id == "" || len(id) > 64 { + return false + } + for _, c := range id { + if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_') { + return false + } + } + return true +} + +func copyDir(src, dst string) error { + srcResolved, err := filepath.EvalSymlinks(src) + if err != nil { + return fmt.Errorf("failed to resolve source path: %w", err) + } + + return filepath.Walk(srcResolved, func(path string, info os.FileInfo, err error) error { + if err != nil { + return err + } + + if info.Mode()&os.ModeSymlink != 0 { + return nil + } + + linfo, err := os.Lstat(path) + if err != nil { + return err + } + if linfo.Mode()&os.ModeSymlink != 0 { + return nil + } + + relPath, err := filepath.Rel(srcResolved, path) + if err != nil { + return err + } + destPath := filepath.Join(dst, relPath) + + if !isUnder(dst, destPath) { + return fmt.Errorf("path traversal detected: %s", relPath) + } + + if linfo.IsDir() { + return os.MkdirAll(destPath, linfo.Mode()) + } + + srcFile, err := os.OpenFile(path, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + if errors.Is(err, syscall.ELOOP) { + return nil + } + return err + } + defer srcFile.Close() + + srcStat, err := srcFile.Stat() + if err != nil { + return err + } + if !srcStat.Mode().IsRegular() { + return nil + } + + parent := filepath.Dir(destPath) + resolvedParent, rpErr := filepath.EvalSymlinks(parent) + if rpErr == nil && !isUnder(dst, resolvedParent) { + return fmt.Errorf("symlink escape blocked: %s", relPath) + } + if di, lpErr := os.Lstat(destPath); lpErr == nil && (di.Mode()&os.ModeSymlink != 0) { + return nil + } + dstFile, err := os.OpenFile(destPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC|syscall.O_NOFOLLOW, linfo.Mode()) + if err != nil { + return err + } + defer dstFile.Close() + + if _, err := io.Copy(dstFile, srcFile); err != nil { + return err + } + + return os.Chmod(destPath, linfo.Mode()) + }) +} + +// --- adpanel:multidisk:registry (anchor) --- +// +// Disk registry, layout helpers, per-server routing, capacity checks and the +// admin API. All of this is dormant until an additional disk is registered: with +// only the primary disk, every helper resolves to the existing a.volumesDir / +// a.backupsDir() paths, so behavior is identical to single-disk and no migration +// is required. + +const primaryDiskID = "primary" + +// diskLayoutVolumes returns the volumes root for a given mount path. +// For the primary mount (a.dataRoot) this equals a.volumesDir exactly. +func (a *Agent) diskLayoutVolumes(mountPath string) string { + if filepath.Clean(mountPath) == filepath.Clean(a.dataRoot) { + return a.volumesDir + } + return filepath.Join(filepath.Clean(mountPath), "adpanel", "volumes") +} + +// diskLayoutBackups returns the backups root for a given mount path. +// For the primary mount this equals a.backupsDir() exactly. +func (a *Agent) diskLayoutBackups(mountPath string) string { + if filepath.Clean(mountPath) == filepath.Clean(a.dataRoot) { + return a.backupsDir() + } + return filepath.Join(filepath.Clean(mountPath), "adpanel", "backups") +} + +// primaryDisk returns the synthetic primary disk descriptor. +func (a *Agent) primaryDisk() NodeDisk { + return NodeDisk{ID: primaryDiskID, MountPath: filepath.Clean(a.dataRoot), Primary: true} +} + +// registeredDisks returns the persisted additional disks (never the primary). +func (a *Agent) registeredDisks() []NodeDisk { + info := a.readNodeInformation() + out := make([]NodeDisk, 0, len(info.Disks)) + for _, d := range info.Disks { + if strings.TrimSpace(d.ID) == "" || d.Primary || d.ID == primaryDiskID { + continue + } + if strings.TrimSpace(d.MountPath) == "" { + continue + } + out = append(out, d) + } + return out +} + +// allDisks returns the primary disk first, then all registered additional disks. +func (a *Agent) allDisks() []NodeDisk { + disks := []NodeDisk{a.primaryDisk()} + disks = append(disks, a.registeredDisks()...) + return disks +} + +// diskByID resolves a disk descriptor by its ID. Empty or "primary" => primary. +func (a *Agent) diskByID(id string) (NodeDisk, bool) { + id = strings.TrimSpace(id) + if id == "" || id == primaryDiskID { + return a.primaryDisk(), true + } + for _, d := range a.registeredDisks() { + if d.ID == id { + return d, true + } + } + return NodeDisk{}, false +} + +// diskForServer returns the disk that owns a server, based on its persisted meta. +// Absent/unknown diskId defaults to the primary disk (back-compat). Results are +// cached to avoid a meta read on every FS request. +func (a *Agent) diskForServer(name string) NodeDisk { + name = sanitizeName(name) + if name == "" { + return a.primaryDisk() + } + a.disksMu.RLock() + if a.serverDiskCache != nil { + if id, ok := a.serverDiskCache[name]; ok { + a.disksMu.RUnlock() + if d, ok := a.diskByID(id); ok { + return d + } + return a.primaryDisk() + } + } + a.disksMu.RUnlock() + + // Meta always lives on the primary disk's .adpanel_meta, independent of where + // the server files reside, so this read is disk-location agnostic. + id := primaryDiskID + hasExplicitDiskID := false + metaPath := a.metaPath(name) + if b, err := os.ReadFile(metaPath); err == nil { + var m map[string]any + if json.Unmarshal(b, &m) == nil { + if v, ok := m["__diskId"].(string); ok && strings.TrimSpace(v) != "" { + id = strings.TrimSpace(v) + hasExplicitDiskID = true + } + } + } + + // adpanel:multidisk - legacy/back-compat recovery. Servers created before + // __diskId was persisted (or whose meta lost it) have no disk assignment in + // meta, so they would default to the primary disk even when their files + // physically live on a secondary disk. That mis-routing made delete/reinstall + // target the (empty) primary path, report success, and ORPHAN the real files + // + backups on the secondary disk. When meta carries no explicit __diskId, + // locate the server by scanning each registered disk's volumes root for its + // directory and adopt the owning disk. This is only hit on a cold cache for + // unassigned servers, so the cost is bounded. + if !hasExplicitDiskID { + if disk, found := a.locateServerDiskByScan(name); found { + id = disk.ID + } + } + + a.disksMu.Lock() + if a.serverDiskCache == nil { + a.serverDiskCache = map[string]string{} + } + a.serverDiskCache[name] = id + a.disksMu.Unlock() + + if d, ok := a.diskByID(id); ok { + return d + } + return a.primaryDisk() +} + +// locateServerDiskByScan finds which registered disk physically holds a server's +// directory. It is used as a back-compat fallback for servers whose meta has no +// persisted __diskId (created before multidisk routing). Secondary disks are +// checked first so a real secondary-disk server is correctly adopted; if the +// directory only exists on the primary disk (or nowhere), it reports not-found +// and the caller keeps the primary default. The first match wins. +func (a *Agent) locateServerDiskByScan(name string) (NodeDisk, bool) { + safe := sanitizeName(name) + if safe == "" { + return NodeDisk{}, false + } + for _, d := range a.registeredDisks() { + candidate := filepath.Join(a.diskLayoutVolumes(d.MountPath), safe) + if st, err := os.Stat(candidate); err == nil && st.IsDir() { + return d, true + } + } + return NodeDisk{}, false +} + +// invalidateServerDiskCache drops a cached server->disk mapping (after create/delete). +func (a *Agent) invalidateServerDiskCache(name string) { + name = sanitizeName(name) + a.disksMu.Lock() + if a.serverDiskCache != nil { + delete(a.serverDiskCache, name) + } + a.disksMu.Unlock() +} + +// setServerDiskMapping records a server's disk assignment in the routing cache. +func (a *Agent) setServerDiskMapping(name, diskID string) { + name = sanitizeName(name) + if name == "" { + return + } + if strings.TrimSpace(diskID) == "" { + diskID = primaryDiskID + } + a.disksMu.Lock() + if a.serverDiskCache == nil { + a.serverDiskCache = map[string]string{} + } + a.serverDiskCache[name] = diskID + a.disksMu.Unlock() +} + +// checkDiskCapacity enforces a per-disk capacity ceiling (LimitGb). It is a no-op +// for the primary disk and for disks with LimitGb<=0. used = volumes + backups. +func (a *Agent) checkDiskCapacity(disk NodeDisk, extraBytes int64) map[string]any { + if disk.Primary || disk.ID == primaryDiskID || disk.LimitGb <= 0 { + return nil + } + limitBytes := disk.LimitGb * 1024 * 1024 * 1024 + volBytes, _ := getDirSizeBytes(a.diskLayoutVolumes(disk.MountPath)) + bkBytes, _ := getDirSizeBytes(a.diskLayoutBackups(disk.MountPath)) + used := volBytes + bkBytes + if used+extraBytes > limitBytes { + return map[string]any{ + "error": "disk_capacity_exceeded", + "message": fmt.Sprintf("Target disk is full. Used: %.1f GB / %d GB", float64(used)/(1024*1024*1024), disk.LimitGb), + "usedBytes": used, + "limitBytes": limitBytes, + } + } + return nil +} + +// checkDiskCapacityForPath finds the owning disk of abs and enforces its capacity. +func (a *Agent) checkDiskCapacityForPath(abs string, extraBytes int64) map[string]any { + root := a.volumeRootFor(abs) + for _, d := range a.allDisks() { + if filepath.Clean(a.diskLayoutVolumes(d.MountPath)) == root { + return a.checkDiskCapacity(d, extraBytes) + } + } + return nil +} + +// pathAllowedForDisk rejects dangerous mount paths for new disks. +func pathAllowedForDisk(p string) (string, error) { + s := strings.TrimSpace(p) + if s == "" { + return "", fmt.Errorf("mount path required") + } + if !filepath.IsAbs(s) { + return "", fmt.Errorf("mount path must be absolute") + } + c := filepath.Clean(s) + if c != s { + return "", fmt.Errorf("mount path must be clean (no '.', '..', or trailing slash)") + } + denied := []string{"/var/lib/node", "/etc", "/proc", "/sys", "/dev", "/boot", "/root", "/bin", "/sbin", "/usr", "/lib", "/lib64"} + if c == "/" { + return "", fmt.Errorf("mount path %q is not allowed", c) + } + for _, d := range denied { + if c == d || isUnder(d, c) { + return "", fmt.Errorf("mount path %q is not allowed", c) + } + } + return c, nil +} + +func (a *Agent) handleDiskList(w http.ResponseWriter, r *http.Request) { + out := make([]map[string]any, 0) + for _, d := range a.allDisks() { + volBytes, _ := getDirSizeBytes(a.diskLayoutVolumes(d.MountPath)) + bkBytes, _ := getDirSizeBytes(a.diskLayoutBackups(d.MountPath)) + usedGb := float64(volBytes+bkBytes) / (1024 * 1024 * 1024) + entry := map[string]any{ + "id": d.ID, + "mountPath": d.MountPath, + "limitGb": d.LimitGb, + "usedGb": usedGb, + "primary": d.Primary || d.ID == primaryDiskID, + "freeMb": freeDiskMb(d.MountPath), + } + out = append(out, entry) + } + jsonWrite(w, 200, map[string]any{"ok": true, "disks": out}) +} + +func (a *Agent) handleDiskAdd(w http.ResponseWriter, r *http.Request) { + var body struct { + MountPath string `json:"mountPath"` + LimitGb int64 `json:"limitGb"` + } + if err := readJSON(w, r, 64*1024, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + mount, err := pathAllowedForDisk(body.MountPath) + if err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": err.Error()}) + return + } + if ok, reason := a.verifyNodeAdminRequest(r, "disk-add", mount); !ok { + jsonWrite(w, statusForAdminReason(reason), map[string]any{"ok": false, "error": reason}) + return + } + if body.LimitGb <= 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "limitGb must be > 0"}) + return + } + // EvalSymlinks re-check: the real path must also pass the allowlist. + if resolved, rErr := filepath.EvalSymlinks(mount); rErr == nil { + if _, vErr := pathAllowedForDisk(resolved); vErr != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "resolved mount path not allowed"}) + return + } + } + // Capacity sanity: limit cannot exceed currently free space on the mount. + freeGb := freeDiskMb(mount) / 1024 + if freeGb > 0 && body.LimitGb > freeGb { + jsonWrite(w, 400, map[string]any{"ok": false, "error": fmt.Sprintf("limitGb %d exceeds free space %d GB", body.LimitGb, freeGb)}) + return + } + volRoot := a.diskLayoutVolumes(mount) + bkRoot := a.diskLayoutBackups(mount) + if err := os.MkdirAll(volRoot, 0o750); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to create volumes dir"}) + return + } + if err := os.MkdirAll(bkRoot, 0o750); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to create backups dir"}) + return + } + // Real write-probe under /adpanel. + probe := filepath.Join(filepath.Clean(mount), "adpanel", ".adpanel_write_probe") + if err := os.WriteFile(probe, []byte("ok"), 0o600); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "mount path is not writable"}) + return + } + _ = os.Remove(probe) + + a.disksMu.Lock() + defer a.disksMu.Unlock() + info := a.readNodeInformation() + for _, d := range info.Disks { + if filepath.Clean(d.MountPath) == mount { + jsonWrite(w, 409, map[string]any{"ok": false, "error": "disk already registered"}) + return + } + } + disk := NodeDisk{ + ID: "disk-" + randomHex(8), + MountPath: mount, + LimitGb: body.LimitGb, + CreatedAt: time.Now().UTC().Format(time.RFC3339), + } + info.Disks = append(info.Disks, disk) + if err := a.writeNodeInformation(info); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to persist disk"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true, "disk": map[string]any{ + "id": disk.ID, "mountPath": disk.MountPath, "limitGb": disk.LimitGb, "primary": false, + }}) +} + +func (a *Agent) handleDiskDelete(w http.ResponseWriter, r *http.Request) { + var body struct { + ID string `json:"id"` + } + if err := readJSON(w, r, 64*1024, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + id := strings.TrimSpace(body.ID) + if id == "" || id == primaryDiskID { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot remove primary disk"}) + return + } + if ok, reason := a.verifyNodeAdminRequest(r, "disk-remove", id); !ok { + jsonWrite(w, statusForAdminReason(reason), map[string]any{"ok": false, "error": reason}) + return + } + disk, found := a.diskByID(id) + if !found || disk.Primary { + jsonWrite(w, 404, map[string]any{"ok": false, "error": "disk not found"}) + return + } + // Refuse if any server references the disk (has files under its volumes root). + volRoot := a.diskLayoutVolumes(disk.MountPath) + if ents, err := os.ReadDir(volRoot); err == nil { + for _, e := range ents { + if e.Name() == ".adpanel_meta" || e.Name() == ".adpanel_deleting" { + continue + } + jsonWrite(w, 409, map[string]any{"ok": false, "error": "disk is in use by one or more servers"}) + return + } + } + a.disksMu.Lock() + defer a.disksMu.Unlock() + info := a.readNodeInformation() + kept := make([]NodeDisk, 0, len(info.Disks)) + removed := false + for _, d := range info.Disks { + if d.ID == id { + removed = true + continue + } + kept = append(kept, d) + } + if !removed { + jsonWrite(w, 404, map[string]any{"ok": false, "error": "disk not found"}) + return + } + info.Disks = kept + if err := a.writeNodeInformation(info); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to persist"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func statusForAdminReason(reason string) int { + switch reason { + case "admin-required": + return 403 + default: + return 401 + } +} + +// allDiskVolumeRoots returns every registered disk's volumes root, primary first. +// When no additional disks are registered it returns exactly []string{a.volumesDir}, +// so all path-validation logic below behaves byte-for-byte identically to the +// single-disk implementation. This is the single source of truth for "which roots +// are valid"; every FS guard derives its root from these helpers. +func (a *Agent) allDiskVolumeRoots() []string { + roots := []string{filepath.Clean(a.volumesDir)} + for _, d := range a.additionalDiskVolumeRoots() { + c := filepath.Clean(strings.TrimSpace(d)) + if c == "" || c == "." { + continue + } + dup := false + for _, existing := range roots { + if existing == c { + dup = true + break + } + } + if !dup { + roots = append(roots, c) + } + } + return roots +} + +// additionalDiskVolumeRoots returns the volumes roots of non-primary disks. +// Until the disk registry is populated this returns nil, guaranteeing the +// primary-only fast path. Kept separate so registry wiring is a one-line change +// with no risk to the validation logic. +func (a *Agent) additionalDiskVolumeRoots() []string { + disks := a.registeredDisks() + if len(disks) == 0 { + return nil + } + out := make([]string, 0, len(disks)) + for _, d := range disks { + out = append(out, a.diskLayoutVolumes(d.MountPath)) + } + return out +} + +// volumeRootFor returns the registered disk root that owns abs. abs is expected +// to already be an absolute, cleaned path that passed safeUnderVolumes. If no +// registered root owns it (should not happen for validated paths), it falls back +// to a.volumesDir, which preserves the original single-disk behavior exactly. +func (a *Agent) volumeRootFor(abs string) string { + c := filepath.Clean(abs) + for _, root := range a.allDiskVolumeRoots() { + if c == root || isUnder(root, c) { + return root + } + } + return filepath.Clean(a.volumesDir) +} + +func (a *Agent) safeUnderVolumes(p string) (string, bool) { + s := strings.TrimSpace(p) + if s == "" { + return "", false + } + if !filepath.IsAbs(s) { + // Relative paths remain anchored to the primary volumes root, exactly as + // before. Absolute paths may target any registered disk root. + s = filepath.Join(a.volumesDir, s) + } + s = filepath.Clean(s) + for _, root := range a.allDiskVolumeRoots() { + if isUnder(root, s) || root == s { + return s, true + } + } + return "", false +} + +// adpanel:fs-scope - safeUnderServerOrVolumes is the hardened replacement used by +// every /v1/fs/* handler. When the panel supplies a serverName, the resolved path +// must live under that single server's directory (…//) and never +// the server root itself for write/delete style operations is decided by callers. +// This is defense-in-depth on top of safeUnderVolumes: even if a future caller +// forgets to prefix the panel baseDir, the node refuses to touch another server's +// files on the same disk. When serverName is empty the behaviour is identical to +// safeUnderVolumes (back-compat for any legacy caller). +func (a *Agent) safeUnderServerOrVolumes(server, p string) (string, bool) { + abs, ok := a.safeUnderVolumes(p) + if !ok { + return "", false + } + name := sanitizeName(server) + if name == "" { + // No server scope requested: fall back to disk-root containment only. + return abs, true + } + root := filepath.Clean(a.serverDir(name)) + if abs == root || isUnder(root, abs) { + return abs, true + } + return "", false +} + +func (a *Agent) handleFSList(w http.ResponseWriter, r *http.Request) { + var body struct { + Path string `json:"path"` + Server string `json:"server"` + Depth int `json:"depth"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) + return + } + st, err := os.Lstat(abs) + if err != nil || !st.IsDir() { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a directory"}) + return + } + if err := ensureResolvedUnder(a.volumeRootFor(abs), abs); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + ents, err := os.ReadDir(abs) + if err != nil { + if a.debug { + fmt.Printf("[fs] list error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to read directory"}) + return + } + out := make([]map[string]any, 0, len(ents)) + for _, e := range ents { + entryPath := filepath.Join(abs, e.Name()) + linfo, lErr := os.Lstat(entryPath) + if lErr != nil { + continue + } + if linfo.Mode()&os.ModeSymlink != 0 { + out = append(out, map[string]any{"name": e.Name(), "type": "symlink"}) + continue + } + typ := "file" + if linfo.IsDir() { + typ = "dir" + } + entry := map[string]any{"name": e.Name(), "type": typ} + if !linfo.IsDir() { + entry["size"] = linfo.Size() + } + out = append(out, entry) + } + jsonWrite(w, 200, map[string]any{"ok": true, "entries": out, "depth": body.Depth}) +} + +func (a *Agent) handleFSRead(w http.ResponseWriter, r *http.Request) { + var body struct { + Path string `json:"path"` + Server string `json:"server"` + Encoding string `json:"encoding"` + } + if err := readJSON(w, r, 1<<20, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) + return + } + info, err := os.Lstat(abs) + if err != nil { + jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found"}) + return + } + if info.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot read symlink"}) + return + } + if err := ensureResolvedUnder(a.volumeRootFor(abs), abs); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + if info.IsDir() { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "path is a directory"}) + return + } + const maxEditorRead = 10 << 20 + if info.Size() > maxEditorRead { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "file too large (max 10MB)"}) + return + } + rf, rfErr := os.OpenFile(abs, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if rfErr != nil { + if errors.Is(rfErr, syscall.ELOOP) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot read symlink"}) + return + } + if a.debug { + fmt.Printf("[fs] read error for %s: %v\n", abs, rfErr) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to read file"}) + return + } + defer rf.Close() + if rfStat, sErr := rf.Stat(); sErr != nil || !rfStat.Mode().IsRegular() { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "not a regular file"}) + return + } + b, err := io.ReadAll(io.LimitReader(rf, maxEditorRead)) + if err != nil { + if a.debug { + fmt.Printf("[fs] read error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to read file"}) + return + } + enc := strings.ToLower(strings.TrimSpace(body.Encoding)) + if enc == "" { + enc = "utf8" + } + content := "" + if enc == "utf8" { + content = string(b) + } else { + content = base64.StdEncoding.EncodeToString(b) + } + jsonWrite(w, 200, map[string]any{"ok": true, "content": content, "encoding": enc}) +} + +func (a *Agent) handleFSDownload(w http.ResponseWriter, r *http.Request) { + var body struct { + Path string `json:"path"` + Server string `json:"server"` + } + if err := readJSON(w, r, 1<<20, &body); err != nil { + http.Error(w, "bad json", 400) + return + } + abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) + if !ok { + http.Error(w, "invalid path", 400) + return + } + info, err := os.Lstat(abs) + if err != nil { + http.Error(w, "file not found", 404) + return + } + if info.Mode()&os.ModeSymlink != 0 { + http.Error(w, "cannot download symlink", 400) + return + } + if err := ensureResolvedUnder(a.volumeRootFor(abs), abs); err != nil { + http.Error(w, "symlink escape blocked", 400) + return + } + if info.IsDir() { + http.Error(w, "path is a directory", 400) + return + } + f, err := os.OpenFile(abs, os.O_RDONLY|syscall.O_NOFOLLOW, 0) + if err != nil { + if errors.Is(err, syscall.ELOOP) { + http.Error(w, "cannot download symlink", 400) + return + } + http.Error(w, "failed to open file", 500) + return + } + defer f.Close() + fStat, sErr := f.Stat() + if sErr != nil || !fStat.Mode().IsRegular() { + http.Error(w, "not a regular file", 400) + return + } + w.Header().Set("Content-Type", "application/octet-stream") + cdName := strings.Map(func(r rune) rune { + if r == '"' || r == '\\' || r < 0x20 || r == 0x7f { + return '_' + } + return r + }, filepath.Base(abs)) + w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename="%s"`, cdName)) + w.Header().Set("Content-Length", fmt.Sprintf("%d", fStat.Size())) + io.Copy(w, f) +} + +func (a *Agent) handleFSWrite(w http.ResponseWriter, r *http.Request) { + var body struct { + Path string `json:"path"` + Server string `json:"server"` + Content string `json:"content"` + Encoding string `json:"encoding"` + // Mode constrains the operation so the panel can enforce distinct + // files_create vs files_write permissions without a TOCTOU window: + // "create" -> target must NOT already exist (new file) + // "update" -> target MUST already exist (overwrite) + // "" -> either (legacy / back-compat) + Mode string `json:"mode"` + } + if err := readJSON(w, r, 10<<20, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json or content too large (max 10MB)"}) + return + } + abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) + return + } + mode := strings.ToLower(strings.TrimSpace(body.Mode)) + existedBefore := false + if _, statErr := os.Lstat(abs); statErr == nil { + existedBefore = true + } + if mode == "create" && existedBefore { + jsonWrite(w, 409, map[string]any{"ok": false, "error": "file already exists", "existed": true}) + return + } + if mode == "update" && !existedBefore { + jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found", "existed": false}) + return + } + if diskErr := a.checkDiskLimitForPath(abs, int64(len(body.Content))); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + + parentDir := filepath.Dir(abs) + resolvedParent, err := filepath.EvalSymlinks(parentDir) + if err == nil && !isUnder(a.volumeRootFor(abs), resolvedParent) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + + _ = ensureDir(filepath.Dir(abs)) + if rp, err := filepath.EvalSymlinks(filepath.Dir(abs)); err == nil && !isUnder(a.volumeRootFor(abs), rp) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + enc := strings.ToLower(strings.TrimSpace(body.Encoding)) + if enc == "" { + enc = "utf8" + } + var data []byte + if enc == "utf8" { + data = []byte(body.Content) + } else { + b, err := base64.StdEncoding.DecodeString(body.Content) + if err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid base64"}) + return + } + data = b + } + if info, err := os.Lstat(abs); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot write to symlink"}) + return + } + } + if err := writeFileNoFollow(abs, data, 0o644); err != nil { + if a.debug { + fmt.Printf("[fs] write error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true, "existed": existedBefore}) +} + +func (a *Agent) handleFSDelete(w http.ResponseWriter, r *http.Request) { + var body struct { + Path string `json:"path"` + Server string `json:"server"` + IsDir bool `json:"isDir"` + } + if err := readJSON(w, r, 64*1024, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) + return + } + if filepath.Clean(abs) == a.volumeRootFor(abs) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "refusing to delete volumes root"}) + return + } + + info, err := os.Lstat(abs) + if err != nil { + if os.IsNotExist(err) { + jsonWrite(w, 200, map[string]any{"ok": true, "note": "already missing"}) + return + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to access path"}) + return + } + + if info.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot delete symlinks"}) + return + } + if err := ensureResolvedUnder(a.volumeRootFor(abs), abs); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + + var delErr error + if body.IsDir { + delErr = os.RemoveAll(abs) + } else { + delErr = os.Remove(abs) + } + if delErr != nil { + if a.debug { + fmt.Printf("[fs] delete error for %s: %v\n", abs, delErr) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "delete operation failed"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) handleFSDeleteBatch(w http.ResponseWriter, r *http.Request) { + var body struct { + Server string `json:"server"` + Items []struct { + Path string `json:"path"` + IsDir bool `json:"isDir"` + } `json:"items"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + if len(body.Items) == 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "no items to delete"}) + return + } + if len(body.Items) > 500 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "too many items (max 500)"}) + return + } + + results := make([]map[string]any, 0, len(body.Items)) + successCount := 0 + failCount := 0 + + for _, item := range body.Items { + abs, ok := a.safeUnderServerOrVolumes(body.Server, item.Path) + if !ok { + results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "invalid path"}) + failCount++ + continue + } + if filepath.Clean(abs) == a.volumeRootFor(abs) { + results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "refusing to delete volumes root"}) + failCount++ + continue + } + linfo, err := os.Lstat(abs) + if err != nil { + results = append(results, map[string]any{"path": item.Path, "ok": true, "note": "already missing"}) + successCount++ + continue + } + if linfo.Mode()&os.ModeSymlink != 0 { + results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "cannot delete symlinks"}) + failCount++ + continue + } + if err := ensureResolvedUnder(a.volumeRootFor(abs), abs); err != nil { + results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "symlink escape blocked"}) + failCount++ + continue + } + if recheck, rcErr := os.Lstat(abs); rcErr != nil { + results = append(results, map[string]any{"path": item.Path, "ok": true, "note": "already missing"}) + successCount++ + continue + } else if recheck.Mode()&os.ModeSymlink != 0 { + results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "cannot delete symlinks"}) + failCount++ + continue + } + var delErr error + if item.IsDir { + delErr = os.RemoveAll(abs) + } else { + delErr = os.Remove(abs) + } + if delErr != nil { + if a.debug { + fmt.Printf("[fs] batch delete error for %s: %v\n", item.Path, delErr) + } + results = append(results, map[string]any{"path": item.Path, "ok": false, "error": "delete failed"}) + failCount++ + } else { + results = append(results, map[string]any{"path": item.Path, "ok": true}) + successCount++ + } + } + + jsonWrite(w, 200, map[string]any{ + "ok": failCount == 0, + "results": results, + "success": successCount, + "failed": failCount, + }) +} + +func (a *Agent) handleFSRename(w http.ResponseWriter, r *http.Request) { + var body struct { + Path string `json:"path"` + Server string `json:"server"` + NewName string `json:"newName"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + newName := sanitizeName(body.NewName) + if newName == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid newName"}) + return + } + abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) + return + } + renameRoot := a.volumeRootFor(abs) + if err := ensureResolvedUnder(renameRoot, abs); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + parent := filepath.Dir(abs) + target := filepath.Join(parent, newName) + if !isUnder(renameRoot, target) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid target"}) + return + } + resolvedParent, rpErr := filepath.EvalSymlinks(parent) + if rpErr == nil && !isUnder(renameRoot, resolvedParent) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + if li, lErr := os.Lstat(abs); lErr == nil && li.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot rename symlinks"}) + return + } + if err := os.Rename(abs, target); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "rename operation failed"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true}) +} + +func (a *Agent) handleFSExtract(w http.ResponseWriter, r *http.Request) { + var body struct { + Path string `json:"path"` + Server string `json:"server"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + abs, ok := a.safeUnderServerOrVolumes(body.Server, body.Path) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid path"}) + return + } + if diskErr := a.checkDiskLimitForPath(abs, 0); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + if err := ensureResolvedUnder(a.volumeRootFor(abs), abs); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + resolvedDir, rdErr := filepath.EvalSymlinks(filepath.Dir(abs)) + if rdErr == nil && !isUnder(a.volumeRootFor(abs), resolvedDir) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + st, err := os.Stat(abs) + if err != nil || st.IsDir() { + jsonWrite(w, 404, map[string]any{"ok": false, "error": "file not found"}) + return + } + dir := filepath.Dir(abs) + typ := detectArchiveType(abs) + if typ == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "unsupported archive type"}) + return + } + + switch typ { + case "zip": + if err := extractZipSafe(abs, dir); err != nil { + if a.debug { + fmt.Printf("[fs] extract zip error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) + return + } + case "tar": + f, err := os.Open(abs) + if err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open archive"}) + return + } + defer f.Close() + tr := tar.NewReader(f) + if err := extractTarSafe(tr, dir); err != nil { + if a.debug { + fmt.Printf("[fs] extract tar error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) + return + } + case "targz": + f, err := os.Open(abs) + if err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open archive"}) + return + } + defer f.Close() + gz, err := gzip.NewReader(f) + if err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "invalid gzip archive"}) + return + } + defer gz.Close() + tr := tar.NewReader(gz) + if err := extractTarSafe(tr, dir); err != nil { + if a.debug { + fmt.Printf("[fs] extract targz error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) + return + } + case "tarbz2": + f, err := os.Open(abs) + if err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to open archive"}) + return + } + defer f.Close() + br := bzip2.NewReader(f) + tr := tar.NewReader(br) + if err := extractTarSafe(tr, dir); err != nil { + if a.debug { + fmt.Printf("[fs] extract tarbz2 error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) + return + } + case "tarxz": + if err := a.extractTarXzSafe(abs, dir); err != nil { + if a.debug { + fmt.Printf("[fs] extract tarxz error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) + return + } + case "7z": + if err := a.extract7z(abs, dir); err != nil { + if a.debug { + fmt.Printf("[fs] extract 7z error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) + return + } + case "rar": + if err := a.extractRar(abs, dir); err != nil { + if a.debug { + fmt.Printf("[fs] extract rar error for %s: %v\n", abs, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "extract failed"}) + return + } + } + + _ = sanitizeExtractedTree(dir) + + jsonWrite(w, 200, map[string]any{"ok": true, "msg": "extracted"}) +} + +func (a *Agent) handleFSUploadRaw(w http.ResponseWriter, r *http.Request) { + var body struct { + Dir string `json:"dir"` + Server string `json:"server"` + Filename string `json:"filename"` + DataB64 string `json:"data_b64"` + } + if err := readJSON(w, r, a.uploadLimit, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + if strings.TrimSpace(body.Filename) == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing filename"}) + return + } + absDir, ok := a.safeUnderServerOrVolumes(body.Server, body.Dir) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) + return + } + if diskErr := a.checkDiskLimitForPath(absDir, int64(len(body.DataB64)*3/4)); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + _ = ensureDir(absDir) + if err := ensureResolvedUnder(a.volumeRootFor(absDir), absDir); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + + fn := filepath.Base(body.Filename) + fn = strings.NewReplacer("\r", "_", "\n", "_", "\x00", "_").Replace(fn) + if fn == "" || fn == "." || fn == ".." { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid filename"}) + return + } + dest := filepath.Join(absDir, fn) + if !isUnder(absDir, dest) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid filename"}) + return + } + + const maxBase64Upload = 25 << 20 + if base64.StdEncoding.DecodedLen(len(body.DataB64)) > maxBase64Upload { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "file too large for base64 upload; use stream upload"}) + return + } + data, err := base64.StdEncoding.DecodeString(body.DataB64) + if err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid base64"}) + return + } + if info, err := os.Lstat(dest); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot write to symlink"}) + return + } + } + if err := writeFileNoFollow(dest, data, 0o644); err != nil { + if a.debug { + fmt.Printf("[fs] upload raw error for %s: %v\n", dest, err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "failed to write file"}) + return + } + jsonWrite(w, 200, map[string]any{"ok": true, "path": dest}) +} + +func (a *Agent) handleFSUploadStream(w http.ResponseWriter, r *http.Request) { + r.Body = http.MaxBytesReader(w, r.Body, a.uploadLimit) + + mr, err := r.MultipartReader() + if err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad multipart"}) + return + } + + var absDir string + var destPath string + var uploaded bool + var written int64 + var serverScope string + + for { + part, err := mr.NextPart() + if errors.Is(err, io.EOF) { + break + } + if err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad multipart"}) + return + } + + formName := part.FormName() + fileName := part.FileName() + + if formName == "server" { + b, readErr := io.ReadAll(io.LimitReader(part, 4<<10)) + _ = part.Close() + if readErr != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid server"}) + return + } + serverScope = strings.TrimSpace(string(b)) + continue + } + + if formName == "dir" { + b, readErr := io.ReadAll(io.LimitReader(part, 64<<10)) + if readErr != nil { + _ = part.Close() + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) + return + } + _ = part.Close() + if len(b) >= 64<<10 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) + return + } + parsedDir, ok := a.safeUnderServerOrVolumes(serverScope, string(b)) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) + return + } + if err := ensureResolvedUnder(a.volumeRootFor(parsedDir), parsedDir); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + absDir = parsedDir + continue + } + + if formName != "file" || fileName == "" { + _, _ = io.Copy(io.Discard, part) + _ = part.Close() + continue + } + + if uploaded { + _, _ = io.Copy(io.Discard, part) + _ = part.Close() + jsonWrite(w, 400, map[string]any{"ok": false, "error": "too many files"}) + return + } + if absDir == "" { + _, _ = io.Copy(io.Discard, part) + _ = part.Close() + jsonWrite(w, 400, map[string]any{"ok": false, "error": "dir field must be sent before file"}) + return + } + + rawName := filepath.Base(fileName) + safeName := sanitizeName(rawName) + if safeName == "" { + safeName = "upload.bin" + } + + _ = ensureDir(absDir) + destPath = filepath.Join(absDir, safeName) + + var replacedBytes int64 + if info, err := os.Lstat(destPath); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + _ = part.Close() + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot overwrite symlink"}) + return + } + if info.IsDir() { + _ = part.Close() + jsonWrite(w, 400, map[string]any{"ok": false, "error": "destination is a directory"}) + return + } + replacedBytes = info.Size() + } + + allowedBytes, baseUsedBytes, limitBytes, diskLimited, diskErr := a.uploadDiskAllowanceForPath(absDir, replacedBytes) + if diskErr != nil { + _ = part.Close() + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + + out, err := os.OpenFile(destPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644) + if err != nil { + _ = part.Close() + if a.debug { + fmt.Printf("[fs] upload stream create error: %v\n", err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "file create failed"}) + return + } + + diskAllowedBytes := int64(-1) + if diskLimited { + diskAllowedBytes = allowedBytes + } + written, limitKind, err := copyUploadWithLimits(out, part, a.uploadLimit, diskAllowedBytes) + closeErr := out.Close() + _ = part.Close() + if err != nil { + _ = os.Remove(destPath) + if a.debug { + fmt.Printf("[fs] upload stream write error: %v\n", err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "write failed"}) + return + } + if closeErr != nil { + _ = os.Remove(destPath) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "close failed"}) + return + } + if limitKind == "upload" { + _ = os.Remove(destPath) + jsonWrite(w, 413, map[string]any{ + "ok": false, + "error": "file too large", + "limit_mb": a.uploadLimit / (1024 * 1024), + }) + return + } + if limitKind == "disk" { + _ = os.Remove(destPath) + out := diskLimitUploadPayload(baseUsedBytes, limitBytes, written+1) + out["ok"] = false + jsonWrite(w, 507, out) + return + } + + uploaded = true + } + + if !uploaded { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing file field"}) + return + } + + jsonWrite(w, 200, map[string]any{"ok": true, "path": destPath, "bytes": written}) +} + +func uploadURLAllowsAnyPort() bool { + return os.Getenv("ADPANEL_NODE_FETCH_ALLOW_ANY_PORT") == "1" || os.Getenv("REMOTE_FETCH_ALLOW_ANY_PORT") == "1" +} + +func uploadURLPortAllowed(u *url.URL) bool { + if uploadURLAllowsAnyPort() { + return true + } + port := u.Port() + return port == "" || port == "80" || port == "443" +} + +func sanitizeUploadFilenameForURL(name string) string { + s := strings.TrimSpace(name) + if s == "" { + return "" + } + if decoded, err := url.PathUnescape(s); err == nil { + s = decoded + } + s = strings.NewReplacer("\x00", "_", "\r", "_", "\n", "_", "\\", "/").Replace(s) + s = path.Base(s) + if s == "." || s == ".." || s == "/" || s == "" { + return "" + } + var b strings.Builder + for _, r := range s { + switch { + case r >= 'a' && r <= 'z', + r >= 'A' && r <= 'Z', + r >= '0' && r <= '9', + r == '.', r == '-', r == '_', r == ' ': + b.WriteRune(r) + default: + b.WriteByte('_') + } + } + out := strings.TrimSpace(strings.TrimLeft(b.String(), ".")) + if out == "" || out == "." || out == ".." { + return "" + } + if len(out) > 200 { + out = out[len(out)-200:] + out = strings.TrimLeft(out, ". ") + } + if out == "" || out == "." || out == ".." { + return "" + } + return out +} + +func filenameFromContentDisposition(cd string) string { + if strings.TrimSpace(cd) == "" { + return "" + } + _, params, err := mime.ParseMediaType(cd) + if err != nil { + return "" + } + return params["filename"] +} + +func openURLUploadTempFile(dir, filename string) (*os.File, string, error) { + prefix := "." + sanitizeUploadFilenameForURL(filename) + if prefix == "." { + prefix = ".download" + } + for i := 0; i < 16; i++ { + tmpPath := filepath.Join(dir, fmt.Sprintf("%s.%s.urlupload.tmp", prefix, randomHex(8))) + if !isUnder(dir, tmpPath) { + return nil, "", fmt.Errorf("invalid temp path") + } + f, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644) + if err == nil { + return f, tmpPath, nil + } + if os.IsExist(err) { + continue + } + return nil, "", err + } + return nil, "", fmt.Errorf("could not allocate temp file") +} + +func (a *Agent) handleFSUploadURL(w http.ResponseWriter, r *http.Request) { + var body struct { + Dir string `json:"dir"` + Server string `json:"server"` + URL string `json:"url"` + } + if err := readJSON(w, r, 16<<10, &body); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "bad json"}) + return + } + + rawURL := strings.TrimSpace(body.URL) + if rawURL == "" { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "missing url"}) + return + } + if len(rawURL) > 2048 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "url too long"}) + return + } + + parsedURL, err := a.dl.safeURL(rawURL) + if err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid url", "detail": err.Error()}) + return + } + if !uploadURLPortAllowed(parsedURL) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid url", "detail": "only ports 80/443 are allowed"}) + return + } + + absDir, ok := a.safeUnderServerOrVolumes(body.Server, body.Dir) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) + return + } + dirInfo, err := os.Lstat(absDir) + if err != nil || !dirInfo.IsDir() { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "target dir not found"}) + return + } + if dirInfo.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot upload into symlink"}) + return + } + if err := ensureResolvedUnder(a.volumeRootFor(absDir), absDir); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + if diskErr := a.checkDiskLimitForPath(absDir, 0); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + + maxBytes := a.uploadLimit + if maxBytes <= 0 { + maxBytes = 1024 * 1024 * 1024 + } + + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, parsedURL.String(), nil) + if err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid url"}) + return + } + req.Header.Set("User-Agent", "ADPanel-Node/"+NodeVersion) + req.Header.Set("Accept", "*/*") + + client := a.dl.clientNoProxy() + client.CheckRedirect = func(req *http.Request, via []*http.Request) error { + if len(via) >= 10 { + return fmt.Errorf("too many redirects") + } + nextURL, err := a.dl.safeURL(req.URL.String()) + if err != nil { + return err + } + if !uploadURLPortAllowed(nextURL) { + return fmt.Errorf("only ports 80/443 are allowed") + } + return nil + } + + resp, err := client.Do(req) + if err != nil { + if a.debug { + fmt.Printf("[fs] uploadUrl request error: %v\n", err) + } + jsonWrite(w, 502, map[string]any{"ok": false, "error": "fetch failed", "detail": "remote request failed"}) + return + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + io.Copy(io.Discard, io.LimitReader(resp.Body, 4<<10)) + jsonWrite(w, 502, map[string]any{"ok": false, "error": "fetch failed", "detail": fmt.Sprintf("remote http %d", resp.StatusCode)}) + return + } + + if resp.ContentLength > maxBytes { + jsonWrite(w, 413, map[string]any{ + "ok": false, + "error": "file too large", + "limit_mb": maxBytes / (1024 * 1024), + }) + return + } + + filename := sanitizeUploadFilenameForURL(filenameFromContentDisposition(resp.Header.Get("Content-Disposition"))) + if filename == "" && parsedURL.Path != "" { + filename = sanitizeUploadFilenameForURL(path.Base(parsedURL.Path)) + } + if filename == "" { + filename = "download.bin" + } + + destPath := filepath.Join(absDir, filename) + if !isUnder(absDir, destPath) { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid filename"}) + return + } + + var replacedBytes int64 + if info, err := os.Lstat(destPath); err == nil { + if info.Mode()&os.ModeSymlink != 0 { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "cannot overwrite symlink"}) + return + } + if info.IsDir() { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "destination is a directory"}) + return + } + replacedBytes = info.Size() + } + + if resp.ContentLength > 0 { + extraBytes := resp.ContentLength - replacedBytes + if extraBytes < 0 { + extraBytes = 0 + } + if diskErr := a.checkDiskLimitForPath(absDir, extraBytes); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + } + + allowedBytes, baseUsedBytes, limitBytes, diskLimited, diskErr := a.uploadDiskAllowanceForPath(absDir, replacedBytes) + if diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + if resp.ContentLength > 0 && diskLimited && resp.ContentLength > allowedBytes { + out := diskLimitUploadPayload(baseUsedBytes, limitBytes, resp.ContentLength) + out["ok"] = false + jsonWrite(w, 507, out) + return + } + + out, tmpPath, err := openURLUploadTempFile(absDir, filename) + if err != nil { + if a.debug { + fmt.Printf("[fs] uploadUrl create error: %v\n", err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "file create failed"}) + return + } + committed := false + defer func() { + if !committed && tmpPath != "" { + _ = os.Remove(tmpPath) + } + }() + + diskAllowedBytes := int64(-1) + if diskLimited { + diskAllowedBytes = allowedBytes + } + written, limitKind, copyErr := copyUploadWithLimits(out, resp.Body, maxBytes, diskAllowedBytes) + closeErr := out.Close() + if copyErr != nil { + if a.debug { + fmt.Printf("[fs] uploadUrl write error: %v\n", copyErr) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "write failed"}) + return + } + if closeErr != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "close failed"}) + return + } + if limitKind == "upload" { + jsonWrite(w, 413, map[string]any{ + "ok": false, + "error": "file too large", + "limit_mb": maxBytes / (1024 * 1024), + }) + return + } + if limitKind == "disk" { + out := diskLimitUploadPayload(baseUsedBytes, limitBytes, written+1) + out["ok"] = false + jsonWrite(w, 507, out) + return + } + + if diskErr := a.checkDiskLimitForPathAfterReplacing(absDir, replacedBytes); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + + if err := os.Rename(tmpPath, destPath); err != nil { + if a.debug { + fmt.Printf("[fs] uploadUrl rename error: %v\n", err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "rename failed"}) + return + } + committed = true + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "path": destPath, + "filename": filename, + "bytes": written, + "msg": fmt.Sprintf("Downloaded %s (%d bytes)", filename, written), + }) +} + +func main() { + cfgPath := os.Getenv("ADPANEL_NODE_CONFIG") + if strings.TrimSpace(cfgPath) == "" { + cfgPath = DefaultConfigPath + } + if _, err := os.Stat(cfgPath); err != nil { + fmt.Fprintf(os.Stderr, "[config] Missing config.yml at: %s\n", cfgPath) + fmt.Fprintln(os.Stderr, "[config] This agent does NOT generate a config file.") + os.Exit(1) + } + raw := string(mustReadFile(cfgPath)) + m, err := parseYAMLSubset(raw) + if err != nil { + fmt.Fprintf(os.Stderr, "[config] Failed to parse YAML: %v\n", err) + os.Exit(1) + } + cfg := Config{Raw: m} + + debug := cfg.Bool("debug") + token := cfg.String("token") + tokenID := cfg.String("token_id") + uuid := cfg.String("uuid") + + apiHost := cfg.String("api", "host") + if apiHost == "" { + apiHost = DefaultAPIHost + } + apiPort := cfg.Int("api", "port") + if apiPort == 0 { + apiPort = DefaultAPIPort + } + uploadMB := cfg.Int("api", "upload_limit") + if uploadMB == 0 { + uploadMB = 1024 + } + uploadLimit := int64(uploadMB) * 1024 * 1024 + + dataRoot := cfg.String("system", "data") + if dataRoot == "" { + dataRoot = DefaultDataRoot + } + + oldVolumesDir := filepath.Join(dataRoot, "volumes") + volumesDir := filepath.Join(dataRoot, "servers") + + if _, err := os.Stat(oldVolumesDir); err == nil { + if _, err := os.Stat(volumesDir); os.IsNotExist(err) { + fmt.Printf("[migration] Moving server data from %s to %s\n", oldVolumesDir, volumesDir) + if err := os.Rename(oldVolumesDir, volumesDir); err != nil { + fmt.Printf("[migration] Warning: could not migrate volumes: %v\n", err) + volumesDir = oldVolumesDir + } else { + fmt.Printf("[migration] Successfully migrated server data\n") + } + } + } + + _ = ensureDir(volumesDir) + + stopGraceMS := 1500 + if v := os.Getenv("STOP_GRACE_MS"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n >= 500 && n <= 30000 { + stopGraceMS = n + } + } + + headerTimeoutMS := 30000 + if v := os.Getenv("HTTP_TIMEOUT_MS"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n >= 1000 { + headerTimeoutMS = n + } + } + + downloadMax := int64(10) << 30 + if v := os.Getenv("DOWNLOAD_MAX_BYTES"); v != "" { + if n, err := strconv.ParseInt(v, 10, 64); err == nil && n > 0 { + downloadMax = n + } + } + + resourceStatsTTL := serverResourceStatsDefaultTTL + if v := os.Getenv("RESOURCE_STATS_CACHE_MS"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n >= 500 && n <= 30000 { + resourceStatsTTL = time.Duration(n) * time.Millisecond + } + } + resourceStatsDiskTTL := serverResourceStatsDiskTTL + if v := os.Getenv("RESOURCE_STATS_DISK_CACHE_MS"); v != "" { + if n, err := strconv.Atoi(v); err == nil && n >= 1000 && n <= 300000 { + resourceStatsDiskTTL = time.Duration(n) * time.Millisecond + } + } + + panelHMAC := strings.TrimSpace(os.Getenv("PANEL_HMAC_SECRET")) + if panelHMAC == "" { + panelHMAC = strings.TrimSpace(cfg.String("panel", "hmac_secret")) + } + + agent := &Agent{ + cfg: cfg, + debug: debug, + token: token, + tokenID: tokenID, + uuid: uuid, + apiHost: apiHost, + apiPort: apiPort, + uploadLimit: uploadLimit, + dataRoot: dataRoot, + volumesDir: volumesDir, + panelHMAC: panelHMAC, + stopGrace: time.Duration(stopGraceMS) * time.Millisecond, + docker: Docker{debug: debug}, + dl: Downloader{ + headerTimeout: time.Duration(headerTimeoutMS) * time.Millisecond, + maxBytes: downloadMax, + }, + resourceStats: newServerResourceStatsCache(resourceStatsTTL, resourceStatsDiskTTL), + stoppingNow: make(map[string]time.Time), + recentCommands: make(map[string]recentConsoleCommand), + importProgress: make(map[string]*ImportProgress), + importSem: make(chan struct{}, 3), + } + agent.ensureNodeInformationFile() + agent.cleanupPendingDeletes() + agent.logs = newLogManager(agent.docker, debug) + agent.logs.logsDir = filepath.Join(agent.metaDir(), "console-logs") + agent.stdinMgr = newStdinManager(&agent.docker, debug) + + protectNodeProcess() + + startRateLimitCleanup() + + diskMon := newDiskMonitor(agent, 60*time.Second, debug) + diskMon.start() + + memMon := newMemoryMonitor(agent, 10*time.Second, debug) + memMon.start() + + networkAbuseMon := newNetworkAbuseMonitor(agent, 5*time.Second, debug) + networkAbuseMon.start() + + statsCacheStop := make(chan struct{}) + go func() { + ticker := time.NewTicker(60 * time.Second) + defer ticker.Stop() + for { + select { + case <-ticker.C: + agent.resourceStats.cleanup(serverResourceStatsMaxIdle) + case <-statsCacheStop: + return + } + } + }() + + httpSrv := &http.Server{ + Addr: fmt.Sprintf("%s:%d", agent.apiHost, agent.apiPort), + Handler: agent, + ReadTimeout: 60 * time.Second, + ReadHeaderTimeout: 10 * time.Second, + WriteTimeout: 120 * time.Second, + IdleTimeout: 60 * time.Second, + MaxHeaderBytes: 1 << 20, + } + + fmt.Printf("[node] API listening on %s://%s:%d\n", func() string { + if cfg.Bool("api", "ssl", "enabled") { + return "https" + } + return "http" + }(), agent.apiHost, agent.apiPort) + + sig := make(chan os.Signal, 2) + signal.Notify(sig, syscall.SIGINT, syscall.SIGTERM) + + go func() { + <-sig + fmt.Println("[node] shutting down...") + + memMon.stop() + + diskMon.stop() + + networkAbuseMon.stop() + + close(statsCacheStop) + + if agent.stdinMgr != nil { + agent.stdinMgr.stop() + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + _ = httpSrv.Shutdown(ctx) + }() + + sslEnabled := cfg.Bool("api", "ssl", "enabled") + cert := cfg.String("api", "ssl", "cert") + key := cfg.String("api", "ssl", "key") + + if envCert := os.Getenv("API_TLS_CERT"); envCert != "" { + cert = envCert + } + if envKey := os.Getenv("API_TLS_KEY"); envKey != "" { + key = envKey + } + + if sslEnabled && cert != "" && key != "" { + if _, err := os.Stat(cert); err != nil { + fmt.Fprintf(os.Stderr, "[ssl] Certificate file not found: %s — falling back to HTTP\n", cert) + sslEnabled = false + } + if sslEnabled { + if _, err := os.Stat(key); err != nil { + fmt.Fprintf(os.Stderr, "[ssl] Key file not found: %s — falling back to HTTP\n", key) + sslEnabled = false + } + } + } else if sslEnabled && (cert == "" || key == "") { + fmt.Fprintln(os.Stderr, "[ssl] SSL enabled but cert/key paths not provided — falling back to HTTP") + sslEnabled = false + } + + if sslEnabled { + fmt.Printf("[node] Starting HTTPS with cert=%s key=%s\n", cert, key) + if err := httpSrv.ListenAndServeTLS(cert, key); err != nil && !errors.Is(err, http.ErrServerClosed) { + fmt.Fprintf(os.Stderr, "[https] error: %v\n", err) + os.Exit(1) + } + } else { + if err := httpSrv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) { + fmt.Fprintf(os.Stderr, "[http] error: %v\n", err) + os.Exit(1) + } + } +} diff --git a/multidisk_paths_test.go b/multidisk_paths_test.go new file mode 100644 index 0000000..d126351 --- /dev/null +++ b/multidisk_paths_test.go @@ -0,0 +1,360 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func newTestAgent(t *testing.T) (*Agent, string) { + t.Helper() + root := t.TempDir() + vol := filepath.Join(root, "servers") + if err := os.MkdirAll(vol, 0o750); err != nil { + t.Fatalf("mkdir volumes: %v", err) + } + if err := os.MkdirAll(filepath.Join(root, "backups"), 0o750); err != nil { + t.Fatalf("mkdir backups: %v", err) + } + return &Agent{dataRoot: root, volumesDir: vol}, vol +} + +func registerTestDisk(t *testing.T, a *Agent, mount string, limitGb int64) NodeDisk { + t.Helper() + if err := os.MkdirAll(a.diskLayoutVolumes(mount), 0o750); err != nil { + t.Fatalf("mkdir disk volumes: %v", err) + } + if err := os.MkdirAll(a.diskLayoutBackups(mount), 0o750); err != nil { + t.Fatalf("mkdir disk backups: %v", err) + } + info := a.readNodeInformation() + d := NodeDisk{ID: "disk-test-" + filepath.Base(mount), MountPath: filepath.Clean(mount), LimitGb: limitGb} + info.Disks = append(info.Disks, d) + if err := a.writeNodeInformation(info); err != nil { + t.Fatalf("persist disk: %v", err) + } + a.invalidateServerDiskCache("") + return d +} + +func TestSafeUnderVolumes_PrimaryOnly(t *testing.T) { + a, vol := newTestAgent(t) + in := filepath.Join(vol, "srv1", "file.txt") + got, ok := a.safeUnderVolumes(in) + if !ok || got != filepath.Clean(in) { + t.Fatalf("expected accept %q, got (%q,%v)", in, got, ok) + } + got, ok = a.safeUnderVolumes("srv1/x") + if !ok || got != filepath.Join(vol, "srv1", "x") { + t.Fatalf("relative anchor failed: (%q,%v)", got, ok) + } + if _, ok := a.safeUnderVolumes(vol); !ok { + t.Fatalf("expected root to be accepted") + } + for _, bad := range []string{ + filepath.Join(vol, "..", "etc", "passwd"), + "/etc/passwd", + filepath.Dir(vol), + "", + " ", + } { + if _, ok := a.safeUnderVolumes(bad); ok { + t.Fatalf("expected reject for %q", bad) + } + } + if r := a.volumeRootFor(in); r != filepath.Clean(vol) { + t.Fatalf("volumeRootFor primary: got %q want %q", r, vol) + } + roots := a.allDiskVolumeRoots() + if len(roots) != 1 || roots[0] != filepath.Clean(vol) { + t.Fatalf("expected single primary root, got %v", roots) + } +} + +func TestSafeUnderVolumes_SecondDisk(t *testing.T) { + a, vol := newTestAgent(t) + mount := t.TempDir() + registerTestDisk(t, a, mount, 50) + disk2 := a.diskLayoutVolumes(mount) + in := filepath.Join(disk2, "srvOnDisk2", "data.cfg") + got, ok := a.safeUnderVolumes(in) + if !ok || got != filepath.Clean(in) { + t.Fatalf("second-disk path rejected: (%q,%v)", got, ok) + } + if r := a.volumeRootFor(in); r != filepath.Clean(disk2) { + t.Fatalf("volumeRootFor disk2: got %q want %q", r, disk2) + } + prim := filepath.Join(vol, "srv1", "x") + if r := a.volumeRootFor(prim); r != filepath.Clean(vol) { + t.Fatalf("volumeRootFor primary with extra disk: got %q want %q", r, vol) + } + if _, ok := a.safeUnderVolumes("/etc/passwd"); ok { + t.Fatalf("expected reject for path outside all roots") + } + roots := a.allDiskVolumeRoots() + if len(roots) != 2 || roots[0] != filepath.Clean(vol) || roots[1] != filepath.Clean(disk2) { + t.Fatalf("unexpected roots: %v", roots) + } +} + +func TestServerDirRoutingByDisk(t *testing.T) { + a, vol := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + if got := a.serverDir("alpha"); got != filepath.Join(vol, "alpha") { + t.Fatalf("primary serverDir: got %q", got) + } + a.setServerDiskMapping("beta", d.ID) + wantVol := filepath.Join(a.diskLayoutVolumes(mount), "beta") + if got := a.serverDir("beta"); got != wantVol { + t.Fatalf("disk2 serverDir: got %q want %q", got, wantVol) + } + wantBk := filepath.Join(a.diskLayoutBackups(mount), "beta") + if got := a.serverBackupsDir("beta"); got != wantBk { + t.Fatalf("disk2 serverBackupsDir: got %q want %q", got, wantBk) + } + if name := a.serverNameFromPath(filepath.Join(wantVol, "world", "level.dat")); name != "beta" { + t.Fatalf("serverNameFromPath disk2: got %q", name) + } +} + +func TestCheckDiskCapacity(t *testing.T) { + a, _ := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 1) + oneGiB := int64(1024 * 1024 * 1024) + if err := a.checkDiskCapacity(d, oneGiB-1); err != nil { + t.Fatalf("expected allow at limit-1, got %v", err) + } + if err := a.checkDiskCapacity(d, oneGiB+1); err == nil { + t.Fatalf("expected capacity rejection") + } + if err := a.checkDiskCapacity(a.primaryDisk(), oneGiB*1000); err != nil { + t.Fatalf("primary disk must be unlimited, got %v", err) + } +} + +func TestPathAllowedForDisk(t *testing.T) { + bad := []string{"", "relative/path", "/", "/etc", "/var/lib/node", "/var/lib/node/servers", "/proc/1", "/mnt/disk1/", "/mnt/./disk1"} + for _, p := range bad { + if _, err := pathAllowedForDisk(p); err == nil { + t.Fatalf("expected reject for %q", p) + } + } + good := []string{"/mnt/disk1", "/srv/storage/extra", "/data2"} + for _, p := range good { + if c, err := pathAllowedForDisk(p); err != nil || c != p { + t.Fatalf("expected allow for %q, got (%q,%v)", p, c, err) + } + } +} + +func TestAllDiskVolumeRoots_NoDuplicatePrimary(t *testing.T) { + a, vol := newTestAgent(t) + registerTestDisk(t, a, a.dataRoot, 10) + roots := a.allDiskVolumeRoots() + if len(roots) != 1 || roots[0] != filepath.Clean(vol) { + t.Fatalf("expected single primary root, got %v", roots) + } +} + +func TestEnumerateServerNamesAcrossDisks(t *testing.T) { + a, vol := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + if err := os.MkdirAll(filepath.Join(vol, "alpha"), 0o750); err != nil { + t.Fatalf("mkdir alpha: %v", err) + } + a.setServerDiskMapping("beta", d.ID) + if err := os.MkdirAll(a.serverDir("beta"), 0o750); err != nil { + t.Fatalf("mkdir beta: %v", err) + } + if err := os.MkdirAll(filepath.Join(vol, ".adpanel_meta"), 0o750); err != nil { + t.Fatalf("mkdir meta: %v", err) + } + names := a.enumerateServerNames() + found := map[string]bool{} + for _, n := range names { + if strings.HasPrefix(n, ".") { + t.Fatalf("dotfile leaked into enumeration: %q", n) + } + found[n] = true + } + if !found["alpha"] || !found["beta"] { + t.Fatalf("expected both alpha (primary) and beta (disk2), got %v", names) + } +} + +func TestSecondDiskDeleteRoutesToOwningDisk(t *testing.T) { + a, _ := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + a.setServerDiskMapping("beta", d.ID) + wantVolRoot := filepath.Clean(a.diskLayoutVolumes(mount)) + if got := a.serverVolumesRoot("beta"); got != wantVolRoot { + t.Fatalf("serverVolumesRoot disk2: got %q want %q", got, wantVolRoot) + } + wantBkRoot := filepath.Clean(a.diskLayoutBackups(mount)) + if got := a.serverBackupsRoot("beta"); got != wantBkRoot { + t.Fatalf("serverBackupsRoot disk2: got %q want %q", got, wantBkRoot) + } + if err := os.MkdirAll(a.serverDir("beta"), 0o750); err != nil { + t.Fatalf("mkdir srv: %v", err) + } + if err := os.MkdirAll(a.serverBackupsDir("beta"), 0o750); err != nil { + t.Fatalf("mkdir bk: %v", err) + } + if !isUnder(wantVolRoot, a.serverDir("beta")) { + t.Fatalf("server dir not under its volumes root") + } + if !isUnder(wantBkRoot, a.serverBackupsDir("beta")) { + t.Fatalf("backup dir not under its backups root") + } + if _, exists, err := a.detachPathForAsyncDelete(wantVolRoot, a.serverDir("beta"), "server", "beta"); err != nil || !exists { + t.Fatalf("detach second-disk server failed: exists=%v err=%v", exists, err) + } + if _, exists, err := a.detachPathForAsyncDelete(wantBkRoot, a.serverBackupsDir("beta"), "backups", "beta"); err != nil || !exists { + t.Fatalf("detach second-disk backups failed: exists=%v err=%v", exists, err) + } + if _, statErr := os.Stat(a.serverDir("beta")); !os.IsNotExist(statErr) { + t.Fatalf("expected second-disk server dir to be detached, stat err=%v", statErr) + } +} + +func TestDiskMonitorEnforcesSecondDiskQuota(t *testing.T) { + a, _ := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + a.setServerDiskMapping("beta", d.ID) + srvDir := a.serverDir("beta") + if err := os.MkdirAll(srvDir, 0o750); err != nil { + t.Fatalf("mkdir srv: %v", err) + } + meta := map[string]any{"resources": map[string]any{"storageMb": float64(20)}} + if err := a.saveMeta(srvDir, meta); err != nil { + t.Fatalf("saveMeta: %v", err) + } + names := a.enumerateServerNames() + if !contains(names, "beta") { + t.Fatalf("disk monitor would not see secondary-disk server: %v", names) + } + if got := a.getServerDiskLimitBytes(srvDir); got != 20*1024*1024 { + t.Fatalf("limit bytes: got %d want %d", got, 20*1024*1024) + } + big := filepath.Join(srvDir, "server.jar") + f, err := os.Create(big) + if err != nil { + t.Fatalf("create big: %v", err) + } + if err := f.Truncate(50 * 1024 * 1024); err != nil { + f.Close() + t.Skipf("sparse truncate unsupported: %v", err) + } + f.Close() + used, err := getDirSizeBytes(srvDir) + if err != nil { + t.Fatalf("size: %v", err) + } + if used <= a.getServerDiskLimitBytes(srvDir) { + t.Fatalf("expected usage %d to exceed limit %d", used, a.getServerDiskLimitBytes(srvDir)) + } +} + +func contains(ss []string, want string) bool { + for _, s := range ss { + if s == want { + return true + } + } + return false +} + +func TestResolveStructuredBindsKeepsSecondDiskBind(t *testing.T) { + a, _ := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + a.setServerDiskMapping("beta", d.ID) + serverDir := a.serverDir("beta") + if err := os.MkdirAll(serverDir, 0o750); err != nil { + t.Fatalf("mkdir srv: %v", err) + } + runtimeObj := map[string]any{ + "volumes": []any{"{SERVER_DIR}:/data"}, + } + binds, _ := a.resolveStructuredBinds("minecraft", runtimeObj, serverDir) + if len(binds) != 1 { + t.Fatalf("expected the secondary-disk bind to be kept, got %v", binds) + } + wantHost := filepath.Clean(serverDir) + if !strings.HasPrefix(binds[0], wantHost+":") { + t.Fatalf("bind host path not routed to second disk: %q (want prefix %q:)", binds[0], wantHost) + } +} + +func TestColdCacheDeleteRemovesSecondDiskFiles(t *testing.T) { + a, _ := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + a.setServerDiskMapping("beta", d.ID) + srvDir := a.serverDir("beta") + if err := os.MkdirAll(srvDir, 0o750); err != nil { + t.Fatalf("mkdir srv: %v", err) + } + bkDir := a.serverBackupsDir("beta") + if err := os.MkdirAll(bkDir, 0o750); err != nil { + t.Fatalf("mkdir bk: %v", err) + } + if err := a.saveMeta(srvDir, map[string]any{"__diskId": d.ID}); err != nil { + t.Fatalf("saveMeta: %v", err) + } + a.invalidateServerDiskCache("beta") + if got := a.serverDir("beta"); got != srvDir { + t.Fatalf("cold-cache serverDir: got %q want %q", got, srvDir) + } + a.invalidateServerDiskCache("beta") + volRoot := a.serverVolumesRoot("beta") + bkRoot := a.serverBackupsRoot("beta") + if _, exists, err := a.detachPathForAsyncDelete(volRoot, a.serverDir("beta"), "server", "beta"); err != nil || !exists { + t.Fatalf("cold-cache server detach failed: exists=%v err=%v", exists, err) + } + if _, exists, err := a.detachPathForAsyncDelete(bkRoot, a.serverBackupsDir("beta"), "backups", "beta"); err != nil || !exists { + t.Fatalf("cold-cache backups detach failed: exists=%v err=%v", exists, err) + } + if _, statErr := os.Stat(srvDir); !os.IsNotExist(statErr) { + t.Fatalf("expected disk2 server dir removed, stat err=%v", statErr) + } + if _, statErr := os.Stat(bkDir); !os.IsNotExist(statErr) { + t.Fatalf("expected disk2 backups dir removed, stat err=%v", statErr) + } +} + +func TestLegacyServerWithoutDiskIdResolvesByScan(t *testing.T) { + a, _ := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + legacyDir := filepath.Join(a.diskLayoutVolumes(mount), "legacy") + if err := os.MkdirAll(legacyDir, 0o750); err != nil { + t.Fatalf("mkdir legacy: %v", err) + } + got := a.diskForServer("legacy") + if got.ID != d.ID { + t.Fatalf("legacy server mis-routed: got disk %q want %q", got.ID, d.ID) + } + if a.serverDir("legacy") != legacyDir { + t.Fatalf("serverDir for legacy: got %q want %q", a.serverDir("legacy"), legacyDir) + } +} + +func TestPrimaryServerWithoutDiskIdStaysPrimary(t *testing.T) { + a, vol := newTestAgent(t) + mount := t.TempDir() + registerTestDisk(t, a, mount, 50) + if err := os.MkdirAll(filepath.Join(vol, "primaryonly"), 0o750); err != nil { + t.Fatalf("mkdir primaryonly: %v", err) + } + got := a.diskForServer("primaryonly") + if !(got.Primary || got.ID == primaryDiskID) { + t.Fatalf("primary-only server mis-routed to %q", got.ID) + } +} diff --git a/multidisk_security_test.go b/multidisk_security_test.go new file mode 100644 index 0000000..908bfeb --- /dev/null +++ b/multidisk_security_test.go @@ -0,0 +1,382 @@ +package main + +import ( + "bytes" + "crypto/hmac" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strconv" + "testing" + "time" +) + +// signedAdminRequest builds an HTTP request carrying a valid panel-admin HMAC +// signature for (action, subject), mirroring verifyNodeAdminRequest exactly. +func signedAdminRequest(a *Agent, method, path, action, subject string, body any) *http.Request { + var buf bytes.Buffer + if body != nil { + _ = json.NewEncoder(&buf).Encode(body) + } + req := httptest.NewRequest(method, path, &buf) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-panel-role", "admin") + + secret := a.panelHMAC + if secret == "" { + secret = a.token + } + ts := strconv.FormatInt(time.Now().UnixMilli(), 10) + base := fmt.Sprintf("%s|%s|%s|%s|%s", a.uuid, action, subject, "admin", ts) + m := hmac.New(sha256.New, []byte(secret)) + _, _ = m.Write([]byte(base)) + req.Header.Set("x-panel-ts", ts) + req.Header.Set("x-panel-sign", hex.EncodeToString(m.Sum(nil))) + return req +} + +func newSignedTestAgent(t *testing.T) (*Agent, string) { + t.Helper() + a, vol := newTestAgent(t) + a.uuid = "node-uuid-test" + a.token = "node-secret-token" + a.panelHMAC = "panel-hmac-secret" + return a, vol +} + +func decodeJSONBody(t *testing.T, rr *httptest.ResponseRecorder) map[string]any { + t.Helper() + var m map[string]any + if err := json.Unmarshal(rr.Body.Bytes(), &m); err != nil { + t.Fatalf("decode response: %v (body=%q)", err, rr.Body.String()) + } + return m +} + +// --- Path traversal / symlink escape rejection across all disk roots --- + +func TestSymlinkEscapeBlockedAcrossDisks(t *testing.T) { + a, vol := newSignedTestAgent(t) + mount := t.TempDir() + registerTestDisk(t, a, mount, 50) + disk2 := a.diskLayoutVolumes(mount) + + // A symlink inside disk2 that points outside every registered root. + outside := t.TempDir() + if err := os.WriteFile(filepath.Join(outside, "secret"), []byte("x"), 0o600); err != nil { + t.Fatalf("write secret: %v", err) + } + link := filepath.Join(disk2, "escape") + if err := os.Symlink(outside, link); err != nil { + t.Skipf("symlinks unsupported: %v", err) + } + + // The path itself is lexically under disk2 (passes safeUnderVolumes) but + // ensureResolvedUnder must reject it because it resolves outside. + target := filepath.Join(link, "secret") + if _, ok := a.safeUnderVolumes(target); !ok { + t.Fatalf("expected lexical accept under disk2") + } + if err := ensureResolvedUnder(a.volumeRootFor(target), target); err == nil { + t.Fatalf("expected symlink escape to be blocked on disk2") + } + + // Traversal strings are rejected on the primary root too. + for _, bad := range []string{ + filepath.Join(vol, "..", "..", "etc", "passwd"), + "/etc/shadow", + } { + if _, ok := a.safeUnderVolumes(bad); ok { + t.Fatalf("expected reject for %q", bad) + } + } +} + +// --- Admin guard: non-admin role -> 403 --- + +func TestDiskAdd_NonAdmin403(t *testing.T) { + a, _ := newSignedTestAgent(t) + mount := t.TempDir() + body := map[string]any{"mountPath": mount, "limitGb": 10} + buf, _ := json.Marshal(body) + req := httptest.NewRequest("POST", "/v1/disks", bytes.NewReader(buf)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-panel-role", "viewer") // not admin + + rr := httptest.NewRecorder() + a.handleDiskAdd(rr, req) + if rr.Code != 403 { + t.Fatalf("expected 403 for non-admin, got %d (%s)", rr.Code, rr.Body.String()) + } +} + +// --- Signature: missing -> 401, forged -> 401 --- + +func TestDiskAdd_MissingSignature401(t *testing.T) { + a, _ := newSignedTestAgent(t) + mount := t.TempDir() + body := map[string]any{"mountPath": mount, "limitGb": 10} + buf, _ := json.Marshal(body) + req := httptest.NewRequest("POST", "/v1/disks", bytes.NewReader(buf)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("x-panel-role", "admin") // admin but no signature headers + + rr := httptest.NewRecorder() + a.handleDiskAdd(rr, req) + if rr.Code != 401 { + t.Fatalf("expected 401 for missing signature, got %d (%s)", rr.Code, rr.Body.String()) + } +} + +func TestDiskAdd_ForgedSignature401(t *testing.T) { + a, _ := newSignedTestAgent(t) + mount := t.TempDir() + req := signedAdminRequest(a, "POST", "/v1/disks", "disk-add", mount, + map[string]any{"mountPath": mount, "limitGb": 10}) + // Tamper with the signature. + req.Header.Set("x-panel-sign", "deadbeef") + + rr := httptest.NewRecorder() + a.handleDiskAdd(rr, req) + if rr.Code != 401 { + t.Fatalf("expected 401 for forged signature, got %d (%s)", rr.Code, rr.Body.String()) + } +} + +func TestDiskAdd_ValidSignatureSucceeds(t *testing.T) { + a, _ := newSignedTestAgent(t) + mount := t.TempDir() // real, writable, allowlisted (TempDir is under /tmp) + req := signedAdminRequest(a, "POST", "/v1/disks", "disk-add", filepath.Clean(mount), + map[string]any{"mountPath": mount, "limitGb": 1}) + + rr := httptest.NewRecorder() + a.handleDiskAdd(rr, req) + if rr.Code != 200 { + t.Fatalf("expected 200 for valid add, got %d (%s)", rr.Code, rr.Body.String()) + } + got := decodeJSONBody(t, rr) + if ok, _ := got["ok"].(bool); !ok { + t.Fatalf("expected ok=true, got %v", got) + } + disks := a.registeredDisks() + if len(disks) != 1 || disks[0].MountPath != filepath.Clean(mount) { + t.Fatalf("disk not persisted: %v", disks) + } +} + +// --- Quota math: 49 GiB used + 2 GiB write > 50 GiB limit -> 507-style reject --- + +func TestPerDiskCapacityQuotaMath(t *testing.T) { + a, _ := newSignedTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) // 50 GiB ceiling + + gib := int64(1024 * 1024 * 1024) + + // Simulate 49 GiB already used by writing a sparse file in the disk's volumes. + used := filepath.Join(a.diskLayoutVolumes(mount), "srv", "big.bin") + if err := os.MkdirAll(filepath.Dir(used), 0o750); err != nil { + t.Fatalf("mkdir: %v", err) + } + f, err := os.Create(used) + if err != nil { + t.Fatalf("create: %v", err) + } + if err := f.Truncate(49 * gib); err != nil { + f.Close() + t.Skipf("sparse truncate unsupported: %v", err) + } + f.Close() + + // 49 + 2 = 51 > 50 -> reject. + if err := a.checkDiskCapacity(d, 2*gib); err == nil { + t.Fatalf("expected capacity rejection for 49+2>50 GiB") + } + // 49 + 0.5 = 49.5 <= 50 -> allow. + if err := a.checkDiskCapacity(d, gib/2); err != nil { + t.Fatalf("expected allow for 49+0.5<=50 GiB, got %v", err) + } +} + +// --- Backup over per-server limit -> 507-style disk_limit_exceeded --- + +func TestBackupOverServerLimitRejected(t *testing.T) { + a, vol := newSignedTestAgent(t) + + // Create a server on the primary disk with a 1 MB storage quota in meta. + srvDir := filepath.Join(vol, "qsrv") + if err := os.MkdirAll(srvDir, 0o750); err != nil { + t.Fatalf("mkdir srv: %v", err) + } + meta := map[string]any{"resources": map[string]any{"storageMb": float64(1)}} + if err := a.saveMeta(srvDir, meta); err != nil { + t.Fatalf("saveMeta: %v", err) + } + + // A 2 MB backup against a 1 MB limit must be rejected. + twoMB := int64(2 * 1024 * 1024) + if errPayload := a.checkDiskLimit(srvDir, twoMB); errPayload == nil { + t.Fatalf("expected backup-over-limit rejection") + } else if errPayload["error"] != "disk_limit_exceeded" { + t.Fatalf("expected disk_limit_exceeded, got %v", errPayload["error"]) + } + + // A 0-byte addition stays within limit. + if errPayload := a.checkDiskLimit(srvDir, 0); errPayload != nil { + t.Fatalf("expected allow within limit, got %v", errPayload) + } +} + +// --- Existing backups count toward the storage limit (adpanel:backup-storage) --- + +// Scenario from the field: small server files but backups saturate the quota. +// e.g. 20 MB of files, a 100 MB limit, and backups that already occupy ~85 MB. +// Even though the server FILES are well under the limit, the combined usage +// (files + backups) must be enforced so further writes/backups are rejected. +func TestBackupsCountTowardStorageLimit(t *testing.T) { + a, vol := newSignedTestAgent(t) + + name := "bsrv" + srvDir := filepath.Join(vol, name) + if err := os.MkdirAll(srvDir, 0o750); err != nil { + t.Fatalf("mkdir srv: %v", err) + } + // 100 MB limit. + meta := map[string]any{"resources": map[string]any{"storageMb": float64(100)}} + if err := a.saveMeta(srvDir, meta); err != nil { + t.Fatalf("saveMeta: %v", err) + } + + // 20 MB of server files. + writeNBytes(t, filepath.Join(srvDir, "world.dat"), 20*1024*1024) + + // With only 20 MB of files used, a 30 MB write fits under the 100 MB limit. + if errPayload := a.checkDiskLimit(srvDir, 30*1024*1024); errPayload != nil { + t.Fatalf("expected 30 MB write allowed with only files present, got %v", errPayload) + } + + // Now add 85 MB of backups (outside the server dir). + bkDir := a.serverBackupsDir(name) + if err := os.MkdirAll(bkDir, 0o750); err != nil { + t.Fatalf("mkdir backups: %v", err) + } + writeNBytes(t, filepath.Join(bkDir, "backup-1", "data", "world.dat"), 85*1024*1024) + + // Combined usage is now 20 + 85 = 105 MB, already over the 100 MB limit, so + // even a 0-byte addition (e.g. starting a new backup) must be rejected. + if errPayload := a.checkDiskLimit(srvDir, 0); errPayload == nil { + t.Fatalf("expected rejection: files + backups exceed limit") + } else if errPayload["error"] != "disk_limit_exceeded" { + t.Fatalf("expected disk_limit_exceeded, got %v", errPayload["error"]) + } + + // The reported total usage must include the backups. + if got, want := a.getServerTotalUsage(srvDir), int64(105*1024*1024); got != want { + t.Fatalf("getServerTotalUsage = %d, want %d", got, want) + } +} + +// writeNBytes creates parent dirs and writes exactly n zero bytes to path. +func writeNBytes(t *testing.T, path string, n int64) { + t.Helper() + if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil { + t.Fatalf("mkdir for %s: %v", path, err) + } + if err := os.WriteFile(path, make([]byte, n), 0o600); err != nil { + t.Fatalf("write %s: %v", path, err) + } +} + +// --- FS ops on a second-disk server succeed (safeUnderVolumes regression) --- + +func TestFSWriteOnSecondDiskSucceeds(t *testing.T) { + a, _ := newSignedTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + a.setServerDiskMapping("beta", d.ID) + + abs := filepath.Join(a.serverDir("beta"), "config", "app.cfg") + // The write path must accept this absolute path under the second disk root. + validated, ok := a.safeUnderVolumes(abs) + if !ok || validated != filepath.Clean(abs) { + t.Fatalf("second-disk write path rejected: (%q,%v)", validated, ok) + } + // Per-disk + per-server limit checks must not error for a small write. + if errPayload := a.checkDiskLimitForPath(abs, 1024); errPayload != nil { + t.Fatalf("expected small write allowed on second disk, got %v", errPayload) + } + // And the resolved root must be the second disk, not the primary. + if root := a.volumeRootFor(abs); root != filepath.Clean(a.diskLayoutVolumes(mount)) { + t.Fatalf("write routed to wrong disk: %q", root) + } +} + +// --- limitGb greater than free space is rejected at add time --- + +func TestDiskAdd_LimitExceedsFreeSpaceRejected(t *testing.T) { + a, _ := newSignedTestAgent(t) + mount := t.TempDir() + + // Determine current free space, then request a limit far above it. + freeGb := freeDiskMb(mount) / 1024 + if freeGb <= 0 { + t.Skip("could not determine free space for mount") + } + overGb := freeGb + 1_000_000 // 1 PB beyond free space + + req := signedAdminRequest(a, "POST", "/v1/disks", "disk-add", filepath.Clean(mount), + map[string]any{"mountPath": mount, "limitGb": overGb}) + rr := httptest.NewRecorder() + a.handleDiskAdd(rr, req) + if rr.Code != 400 { + t.Fatalf("expected 400 for limit>free, got %d (%s)", rr.Code, rr.Body.String()) + } + if len(a.registeredDisks()) != 0 { + t.Fatalf("disk should not be persisted when limit exceeds free space") + } +} + +// --- Disk delete blocked while referenced by a server -> 409 --- + +func TestDiskDeleteBlockedWhileReferenced(t *testing.T) { + a, _ := newSignedTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + + // Place a server directory under the disk's volumes root. + srvDir := filepath.Join(a.diskLayoutVolumes(mount), "tenant") + if err := os.MkdirAll(srvDir, 0o750); err != nil { + t.Fatalf("mkdir tenant: %v", err) + } + + req := signedAdminRequest(a, "DELETE", "/v1/disks", "disk-remove", d.ID, + map[string]any{"id": d.ID}) + rr := httptest.NewRecorder() + a.handleDiskDelete(rr, req) + if rr.Code != 409 { + t.Fatalf("expected 409 for referenced disk, got %d (%s)", rr.Code, rr.Body.String()) + } + if len(a.registeredDisks()) != 1 { + t.Fatalf("referenced disk must not be removed") + } + + // After the server dir is emptied, removal must succeed. + if err := os.RemoveAll(srvDir); err != nil { + t.Fatalf("cleanup: %v", err) + } + req2 := signedAdminRequest(a, "DELETE", "/v1/disks", "disk-remove", d.ID, + map[string]any{"id": d.ID}) + rr2 := httptest.NewRecorder() + a.handleDiskDelete(rr2, req2) + if rr2.Code != 200 { + t.Fatalf("expected 200 after emptying disk, got %d (%s)", rr2.Code, rr2.Body.String()) + } + if len(a.registeredDisks()) != 0 { + t.Fatalf("disk should be removed after cleanup") + } +} diff --git a/mysql-schema.sql b/mysql-schema.sql index fda9689..d5fbb7b 100644 --- a/mysql-schema.sql +++ b/mysql-schema.sql @@ -2,8 +2,11 @@ CREATE TABLE IF NOT EXISTS users ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, email VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL, - secret VARCHAR(255) NOT NULL, + secret VARCHAR(255) NULL, admin TINYINT(1) NOT NULL DEFAULT 0, + suspended TINYINT(1) NOT NULL DEFAULT 0, + suspended_at BIGINT UNSIGNED NULL, + suspended_by VARCHAR(255) NULL, avatar_url VARCHAR(2048) NULL, preferences JSON NULL, recovery_codes TEXT NULL, @@ -48,6 +51,9 @@ CREATE TABLE IF NOT EXISTS servers ( ip VARCHAR(255) NULL, port INT NULL, status VARCHAR(32) NULL, + suspended TINYINT(1) NOT NULL DEFAULT 0, + suspended_at BIGINT UNSIGNED NULL, + suspended_by VARCHAR(255) NULL, runtime JSON NULL, docker JSON NULL, acl JSON NULL, @@ -63,6 +69,23 @@ CREATE TABLE IF NOT EXISTS servers ( CONSTRAINT fk_servers_node FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE SET NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE IF NOT EXISTS server_delete_jobs ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + server_name VARCHAR(120) NOT NULL, + technical_name VARCHAR(120) NOT NULL, + node_id VARCHAR(64) NOT NULL, + status ENUM('queued','running','completed','failed') NOT NULL DEFAULT 'queued', + attempts INT UNSIGNED NOT NULL DEFAULT 0, + next_attempt_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + last_error TEXT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + UNIQUE KEY uniq_server_delete_jobs_server (server_name), + KEY idx_server_delete_jobs_status_next (status, next_attempt_at), + KEY idx_server_delete_jobs_node (node_id) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + CREATE TABLE IF NOT EXISTS user_access ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, user_id BIGINT UNSIGNED NOT NULL, @@ -72,6 +95,26 @@ CREATE TABLE IF NOT EXISTS user_access ( CONSTRAINT fk_user_access_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; +CREATE TABLE IF NOT EXISTS destructive_action_grants ( + grant_id CHAR(64) NOT NULL, + user_id BIGINT UNSIGNED NOT NULL, + email VARCHAR(255) NOT NULL, + session_hash CHAR(64) NOT NULL, + secret_hash CHAR(64) NOT NULL, + ip_hash CHAR(64) NOT NULL, + ua_hash CHAR(64) NOT NULL, + verified_at BIGINT UNSIGNED NOT NULL, + expires_at BIGINT UNSIGNED NOT NULL, + revoked_at BIGINT UNSIGNED NULL, + subject VARCHAR(190) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (grant_id), + KEY idx_destructive_grants_user_expires (user_id, expires_at), + KEY idx_destructive_grants_session (session_hash), + KEY idx_destructive_grants_expires (expires_at), + CONSTRAINT fk_destructive_grants_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + CREATE TABLE IF NOT EXISTS ai_chats ( id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, user_email VARCHAR(255) NOT NULL DEFAULT '', @@ -187,3 +230,18 @@ CREATE TABLE IF NOT EXISTS subdomains ( KEY idx_subdomains_server (server_id), CONSTRAINT fk_subdomains_server FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +-- Round-robin style panel monitoring history. One averaged row per minute, +-- pruned to a fixed retention window (default ~31 days) so the table stays at a +-- small, predictable size. bucket_ts is the UTC epoch (ms) truncated to the +-- minute, used as a stable upsert key. +CREATE TABLE IF NOT EXISTS panel_metrics ( + bucket_ts BIGINT UNSIGNED NOT NULL, + cpu_percent DECIMAL(5,1) NOT NULL DEFAULT 0, + mem_percent DECIMAL(5,1) NOT NULL DEFAULT 0, + disk_percent DECIMAL(5,1) NOT NULL DEFAULT 0, + net_rx_bps BIGINT UNSIGNED NOT NULL DEFAULT 0, + net_tx_bps BIGINT UNSIGNED NOT NULL DEFAULT 0, + rps DECIMAL(8,1) NOT NULL DEFAULT 0, + PRIMARY KEY (bucket_ts) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; diff --git a/nodes.js b/nodes.js index 97a862f..738cb00 100644 --- a/nodes.js +++ b/nodes.js @@ -173,11 +173,15 @@ function sanitizeConsoleCommand(rawValue) { let _getEffectivePermsForUserOnServer = null; let _isAdmin = null; let _userHasAccessToServer = null; +let _serverActionObserver = null; function setPermissionCheckers(getPerms, isAdminFn, hasAccessFn) { _getEffectivePermsForUserOnServer = getPerms; _isAdmin = isAdminFn; _userHasAccessToServer = hasAccessFn || null; } +function setServerActionObserver(fn) { + _serverActionObserver = typeof fn === "function" ? fn : null; +} async function checkUserPerm(req, serverName, permKey) { if (!_getEffectivePermsForUserOnServer || !_isAdmin) { @@ -191,6 +195,31 @@ async function checkUserPerm(req, serverName, permKey) { return !!(perms && perms[permKey]); } +// resolveFsWriteMode decides which write operations a user may perform and the +// constraint to hand the node so it can enforce create-vs-overwrite atomically +// (no panel-side TOCTOU). Returns: +// { ok:true, mode:"" } -> may create new AND overwrite existing (admin / both perms) +// { ok:true, mode:"create" } -> may only create new files (node 409s if it exists) +// { ok:true, mode:"update" } -> may only overwrite existing files (node 404s if missing) +// { ok:false, permission } -> no write capability at all +// Back-compat: an existing files_create grant continues to allow creating files; +// files_write is the new, separate capability for overwriting existing files. +async function resolveFsWriteMode(req, serverName) { + if (!_getEffectivePermsForUserOnServer || !_isAdmin) { + return { ok: false, permission: "files_create" }; + } + const userEmail = req.session?.user; + if (!userEmail) return { ok: false, permission: "files_create" }; + if (await _isAdmin(req)) return { ok: true, mode: "" }; + const perms = await _getEffectivePermsForUserOnServer(userEmail, serverName); + const canCreate = !!(perms && perms.files_create); + const canWrite = !!(perms && perms.files_write); + if (canCreate && canWrite) return { ok: true, mode: "" }; + if (canCreate) return { ok: true, mode: "create" }; + if (canWrite) return { ok: true, mode: "update" }; + return { ok: false, permission: "files_create" }; +} + async function checkServerAccess(req, serverName) { const userEmail = req.session?.user; if (!userEmail) return { ok: false, status: 401, error: "not authenticated" }; @@ -210,6 +239,9 @@ const UPLOAD_TIMEOUT_MS = 3600_000; const NODE_BOOTSTRAP_TOKEN = (process.env.NODE_BOOTSTRAP_TOKEN || "").trim(); const PANEL_PUBLIC_URL = (process.env.PANEL_PUBLIC_URL || "").trim(); const PANEL_HMAC_SECRET = (process.env.PANEL_HMAC_SECRET || "").trim(); +const DAEMON_INSTALL_SCRIPT_PATH = path.join(__dirname, "install-daemon.sh"); +const NODE_INSTALLER_TOKEN_TTL_MS = parseInt(process.env.NODE_INSTALLER_TOKEN_TTL_MS || "", 10) || 60 * 60 * 1000; +const NODE_INSTALLER_TOKEN_SECRET = (process.env.NODE_INSTALLER_TOKEN_SECRET || process.env.SESSION_SECRET || "").trim(); (async () => { try { @@ -244,6 +276,25 @@ function safeCompare(a, b) { return crypto.timingSafeEqual(bufA, bufB); } +function b64urlEncode(input) { + const buf = Buffer.isBuffer(input) ? input : Buffer.from(String(input)); + return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ""); +} + +function b64urlDecode(input) { + const value = String(input || "").trim().replace(/-/g, "+").replace(/_/g, "/"); + const pad = value.length % 4 ? "=".repeat(4 - (value.length % 4)) : ""; + return Buffer.from(value + pad, "base64"); +} + +function safeDecodeURIComponent(value) { + try { + return decodeURIComponent(String(value || "")); + } catch { + return String(value || ""); + } +} + function parseDbJson(value, fallback) { if (value === undefined || value === null || value === "") return fallback; if (typeof value === "object") return value; @@ -985,6 +1036,108 @@ function defaultNodeTlsPaths(node) { function yamlDoubleQuote(value) { return `"${String(value || "").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; } +function replaceAllLiteral(value, search, replacement) { + return String(value).split(search).join(replacement); +} +function shellSingleQuote(value) { + return `'${String(value == null ? "" : value).replace(/'/g, `'\\''`)}'`; +} + +function buildPanelPublicUrl(req) { + if (PANEL_PUBLIC_URL) return PANEL_PUBLIC_URL.replace(/\/+$/, ""); + console.warn("[SECURITY] PANEL_PUBLIC_URL not set - node installer/config URLs are derived from request headers. Set PANEL_PUBLIC_URL for production."); + const host = req?.get?.("x-forwarded-host") || req?.get?.("host") || "localhost"; + const proto = (req?.get?.("x-forwarded-proto") || req?.protocol || "http"); + return `${proto}://${host}`.replace(/\/+$/, ""); +} + +function nodeInstallerSigningKey(node) { + return [ + NODE_INSTALLER_TOKEN_SECRET, + node?.uuid || "", + node?.id || "", + node?.token_id || "", + node?.token || "", + ].join("\n"); +} + +function signNodeInstallerPayload(payloadB64, node) { + return b64urlEncode(crypto.createHmac("sha256", nodeInstallerSigningKey(node)).update(payloadB64).digest()); +} + +function issueNodeInstallerToken(node) { + const payload = { + v: 1, + typ: "node-installer", + node: String(node?.uuid || node?.id || ""), + exp: Date.now() + NODE_INSTALLER_TOKEN_TTL_MS, + }; + const payloadB64 = b64urlEncode(JSON.stringify(payload)); + return `${payloadB64}.${signNodeInstallerPayload(payloadB64, node)}`; +} + +function verifyNodeInstallerToken(token, node) { + const parts = String(token || "").trim().split("."); + if (parts.length !== 2) return false; + const expectedSig = signNodeInstallerPayload(parts[0], node); + if (!safeCompare(parts[1], expectedSig)) return false; + + let payload; + try { + payload = JSON.parse(b64urlDecode(parts[0]).toString("utf8")); + } catch { + return false; + } + + const allowedNodeIds = new Set([String(node?.uuid || ""), String(node?.id || "")].filter(Boolean)); + return payload + && payload.v === 1 + && payload.typ === "node-installer" + && allowedNodeIds.has(String(payload.node || "")) + && Number(payload.exp || 0) >= Date.now(); +} + +function getNodeInstallerTokenFromRequest(req) { + return String(req?.get?.("x-node-installer") || req?.query?.installer || "").trim(); +} + +function buildNodeInstallerUrl(node, req) { + const id = encodeURIComponent(String(node?.uuid || node?.id || "")); + const base = buildPanelPublicUrl(req); + const url = new URL(`/api/nodes/${id}/install-daemon.sh`, base); + url.searchParams.set("installer", issueNodeInstallerToken(node)); + return url.toString(); +} + +function buildNodeConfigRestartCommand(configYml) { + const config = String(configYml || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\n*$/, "\n"); + return [ + `if [ "$(id -u)" -eq 0 ]; then SUDO=""; elif command -v sudo >/dev/null 2>&1; then SUDO="sudo"; else echo "Run as root or install sudo, then retry." >&2; exit 1; fi`, + `$SUDO install -d -m 0750 /var/lib/node`, + `$SUDO tee /var/lib/node/config.yml >/dev/null <<'ADPANEL_CONFIG_YML'`, + config, + `ADPANEL_CONFIG_YML`, + `$SUDO chown adaemon:adaemon /var/lib/node/config.yml 2>/dev/null || true`, + `$SUDO chmod 0640 /var/lib/node/config.yml`, + `if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then`, + ` $SUDO systemctl restart adaemon || $SUDO systemctl restart ADaemon`, + `elif command -v rc-service >/dev/null 2>&1; then`, + ` $SUDO rc-service adaemon restart || $SUDO rc-service adaemon start`, + `else`, + ` $SUDO service adaemon restart || $SUDO service adaemon start`, + `fi`, + ].join("\n"); +} + +async function isOpenNodeInstallerRoute(req) { + if (String(req?.method || "GET").toUpperCase() !== "GET") return false; + const match = /^\/api\/nodes\/([^/]+)\/install-daemon\.sh$/.exec(String(req?.path || "")); + if (!match) return false; + const node = await findNodeByIdOrName(safeDecodeURIComponent(match[1])); + if (!node) return false; + return verifyNodeInstallerToken(getNodeInstallerTokenFromRequest(req), node); +} + async function resolveNodeForServer(serverName) { const name = String(serverName || "").trim(); if (!name) return { server: null, node: null, nodeId: null }; @@ -1124,15 +1277,7 @@ async function activeCheckNode(node, opts = { force: false }) { } } function buildConfigYml(node, req) { - let panelUrl; - if (PANEL_PUBLIC_URL) { - panelUrl = PANEL_PUBLIC_URL; - } else { - console.warn("[SECURITY] PANEL_PUBLIC_URL not set - config.yml panel URL derived from request headers. Set PANEL_PUBLIC_URL for production."); - const host = req.get("x-forwarded-host") || req.get("host") || "localhost"; - const proto = (req.get("x-forwarded-proto") || req.protocol || "http"); - panelUrl = `${proto}://${host}`; - } + const panelUrl = buildPanelPublicUrl(req); const sslEnabled = !!node.ssl_enabled; const tlsPaths = defaultNodeTlsPaths(node); const lines = [ @@ -1153,8 +1298,6 @@ function buildConfigYml(node, req) { ` upload_limit: ${node.max_upload_mb || 10240}`, `system:`, ` data: /var/lib/node`, - ` sftp:`, - ` bind_port: ${node.sftp_port || 2022}`, `allowed_mounts: []`, `panel:`, ` url: ${panelUrl}`, @@ -1165,34 +1308,30 @@ function buildConfigYml(node, req) { } return lines.join("\n") + "\n"; } -function oneTimeCommand(node, req) { - let base; - if (PANEL_PUBLIC_URL) { - base = PANEL_PUBLIC_URL; - } else { - const host = req.get("x-forwarded-host") || req.get("host") || "localhost"; - const proto = (req.get("x-forwarded-proto") || req.protocol || "http"); - base = `${proto}://${host}`; +function buildDaemonInstallScript(node, req) { + const configB64 = Buffer.from(buildConfigYml(node, req), "utf8").toString("base64"); + if (!fs.existsSync(DAEMON_INSTALL_SCRIPT_PATH)) { + throw new Error("install-daemon.sh not found"); } - const url = `${base}/api/nodes/${encodeURIComponent(node.uuid)}/config.yml`; - const header = NODE_BOOTSTRAP_TOKEN ? `-H "X-Node-Bootstrap: ${NODE_BOOTSTRAP_TOKEN}" ` : ""; - return `set -e -mkdir -p /var/lib/node -curl -fsSL ${header}"${url}" -o /var/lib/node/config.yml -restart_adaemon() { - if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then - systemctl restart ADaemon 2>/dev/null || systemctl restart adaemon 2>/dev/null || systemctl restart adpanel-daemon 2>/dev/null - elif command -v rc-service >/dev/null 2>&1; then - rc-service adaemon restart 2>/dev/null || rc-service ADaemon restart 2>/dev/null || rc-service adpanel-daemon restart 2>/dev/null - elif command -v service >/dev/null 2>&1; then - service adaemon restart 2>/dev/null || service ADaemon restart 2>/dev/null || service adpanel-daemon restart 2>/dev/null - else - echo "No supported service manager found; start ADaemon manually." >&2 - return 1 - fi + let script = fs.readFileSync(DAEMON_INSTALL_SCRIPT_PATH, "utf8"); + + if (script.includes("__ADPANEL_NODE_CONFIG_B64__")) { + return [ + ["__ADPANEL_NODE_CONFIG_B64__", configB64], + ["__ADPANEL_NODE_API_PORT__", String(node.api_port || 8080)], + ["__ADPANEL_NODE_SFTP_PORT__", String(node.sftp_port || 2022)], + ].reduce((out, [search, replacement]) => replaceAllLiteral(out, search, replacement), script); + } + + return [ + "export ADPANEL_NODE_CONFIG_B64=" + shellSingleQuote(configB64), + "export ADPANEL_NODE_API_PORT=" + shellSingleQuote(String(node.api_port || 8080)), + "export ADPANEL_NODE_SFTP_PORT=" + shellSingleQuote(String(node.sftp_port || 2022)), + script, + ].join("\n"); } -restart_adaemon -echo "Config saved to /var/lib/node/config.yml and ADaemon restarted"`; +function oneTimeCommand(node, req) { + return buildNodeConfigRestartCommand(buildConfigYml(node, req)); } const app = express(); app.use(express.json({ limit: "2mb" })); @@ -1240,22 +1379,28 @@ const NODES_PUBLIC_ROUTES = new Set([ const NODES_SERVER_ROUTES_PATTERN = /^\/api\/nodes\/server\/[^/]+\/(info|entries|file|logs|stats|action|command|delete|delete-batch|rename|upload|upload-url|create|extract|archive|backups(\/[^/]+)?(\/restore)?)$/; -app.use((req, res, next) => { - const path = req.path || ""; +app.use(async (req, res, next) => { + try { + const path = req.path || ""; - if (path === "/health") return next(); + if (path === "/health") return next(); - if (/^\/api\/nodes\/[^/]+\/heartbeat$/.test(path)) return next(); + if (/^\/api\/nodes\/[^/]+\/heartbeat$/.test(path)) return next(); - if (NODES_SERVER_ROUTES_PATTERN.test(path)) return next(); + if (NODES_SERVER_ROUTES_PATTERN.test(path)) return next(); - if (path.startsWith("/api/nodes")) { - if (!req.isAdmin) { - return res.status(403).json({ error: "admin required" }); + if (await isOpenNodeInstallerRoute(req)) return next(); + + if (path.startsWith("/api/nodes")) { + if (!req.isAdmin) { + return res.status(403).json({ error: "admin required" }); + } } - } - next(); + return next(); + } catch (err) { + return next(err); + } }); app.get("/health", (_req, res) => res.json({ ok: true })); @@ -1322,6 +1467,19 @@ app.post("/api/nodes/:id/servers/create", async (req, res) => { if (!name) return res.status(400).json({ error: "missing_name" }); if (!hostPort) return res.status(400).json({ error: "invalid_host_port" }); + // adpanel:multidisk - resolve and verify the requested target disk belongs to + // this node before forwarding. Empty/"primary" => default primary disk. + let diskId = String(req.body?.diskId || "").trim(); + if (diskId && diskId !== "primary") { + const diskRes = await callNodeApi(node, "/v1/disks", "GET", null, 8000); + const disks = (diskRes.status === 200 && diskRes.json?.ok && Array.isArray(diskRes.json.disks)) ? diskRes.json.disks : []; + if (!disks.some((d) => String(d.id) === diskId)) { + return res.status(400).json({ error: "invalid_disk", detail: "Target disk does not belong to this node." }); + } + } else { + diskId = ""; + } + if (hostPort > 0 && !isPortInNodeAllocation(node, hostPort)) { const alloc = node.ports || {}; let allocDesc = "none"; @@ -1339,7 +1497,7 @@ app.post("/api/nodes/:id/servers/create", async (req, res) => { const { status, json } = await callNodeApi( node, "/v1/servers/create", "POST", - { name, templateId, mcFork, mcVersion, hostPort, autoStart }, + { name, templateId, mcFork, mcVersion, hostPort, autoStart, ...(diskId ? { diskId } : {}) }, LONG_NODE_TIMEOUT_MS ); if (status === 200 && json && json.ok) return res.json(json); @@ -1532,10 +1690,35 @@ app.get("/api/nodes/:id/config.yml", async (req, res) => { res.setHeader("Content-Type", "text/yaml; charset=utf-8"); res.send(yml); }); +app.get("/api/nodes/:id/install-daemon.sh", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).send("not found"); + if (!req.isAdmin && !verifyNodeInstallerToken(getNodeInstallerTokenFromRequest(req), node)) { + return res.status(401).send("authentication required"); + } + + let script; + try { + script = buildDaemonInstallScript(node, req); + } catch (err) { + console.error("[nodes] Failed to build daemon installer:", err?.message || err); + return res.status(500).send("failed to build installer"); + } + + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); + res.setHeader("Pragma", "no-cache"); + res.setHeader("Content-Type", "text/x-shellscript; charset=utf-8"); + res.send(script); +}); app.get("/api/nodes/:id/one-time-command", async (req, res) => { + if (!req.isAdmin) { + return res.status(403).json({ error: "admin required" }); + } const node = await findNodeByIdOrName(req.params.id); if (!node) return res.status(404).json({ error: "not found" }); - res.json({ command: oneTimeCommand(node, req) }); + res.json({ + command: oneTimeCommand(node, req), + }); }); app.post("/api/nodes/:id/heartbeat", async (req, res) => { try { @@ -1781,7 +1964,7 @@ async function fetchRemoteReplacementBytes(ctx, absDir, originalName, timeoutMs return size && size > 0 ? size : 0; } -function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb) { +function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb, serverName) { return new Promise((resolve) => { let settled = false; let nodeReq = null; @@ -1798,6 +1981,13 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, const boundary = `----ADPanelUpload${crypto.randomBytes(16).toString("hex")}`; const safeOriginalName = String(originalName || "upload.bin").replace(/[\r\n"]/g, "_"); + const safeServerName = String(serverName || "").replace(/[\r\n"]/g, "_"); + + const serverPart = safeServerName + ? `--${boundary}\r\n` + + `Content-Disposition: form-data; name="server"\r\n\r\n` + + `${safeServerName}\r\n` + : ""; const dirPart = `--${boundary}\r\n` + @@ -1811,7 +2001,7 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, const fileFooter = `\r\n--${boundary}--\r\n`; - const preamble = Buffer.from(dirPart + fileHeader, "utf8"); + const preamble = Buffer.from(serverPart + dirPart + fileHeader, "utf8"); const epilogue = Buffer.from(fileFooter, "utf8"); const headers = { @@ -1890,9 +2080,22 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, } function safeJoinUnix(base, rel) { + // Reject NUL bytes outright: they can truncate paths in some syscalls and + // must never reach the node. (#3 hardening) + if (String(base || "").includes("\0") || String(rel || "").includes("\0")) { + throw new Error("path traversal"); + } const b = base.endsWith("/") ? base.slice(0, -1) : base; const raw = String(rel || "").replace(/\\/g, "/"); + // Reject traversal segments in the raw value before normalization collapses + // them, so we never depend solely on the post-join prefix check. + if (raw.split("/").includes("..")) { + throw new Error("path traversal"); + } const norm = path.posix.normalize("/" + raw).replace(/^\/+/, ""); + if (norm.split("/").includes("..")) { + throw new Error("path traversal"); + } const joined = `${b}/${norm}`; if (!joined.startsWith(b + "/") && joined !== b) throw new Error("path traversal"); return joined; @@ -1914,6 +2117,55 @@ function mapFsEntries(entries) { }); return out; } +// adpanel:multidisk - per-server base-dir cache (server may be on a secondary disk). +const _nodeServerBaseDirCache = new Map(); // key `${nodeKey}:${name}` -> { baseDir, at } +const NODE_SERVER_BASEDIR_TTL_MS = 5 * 60 * 1000; + +// validateResolvedBaseDir hardens the node-reported base dir before the panel uses +// it as a prefix for safeJoinUnix. The node already enforces disk-root containment, +// but the panel independently rejects anything that is not a clean, absolute path +// whose final segment is exactly the sanitized server name. This prevents a +// compromised/spoofed node response from steering FS operations elsewhere and +// blocks traversal/NUL injection at the panel boundary. +function validateResolvedBaseDir(baseDir, expectedName) { + if (typeof baseDir !== "string" || !baseDir) return null; + if (baseDir.includes("\0")) return null; + // Reject traversal in the raw value *before* normalization collapses it. + if (baseDir.split("/").includes("..")) return null; + // POSIX-normalize; the node filesystem is always Unix. + const normalized = require("path").posix.normalize(baseDir).replace(/\/+$/, ""); + if (!normalized.startsWith("/")) return null; + if (normalized === "/" || normalized === "") return null; + if (normalized.split("/").includes("..")) return null; + const safeName = sanitizeName(expectedName); + if (!safeName) return null; + // The directory that holds the server files must be named exactly after the + // sanitized server name (…//). No suffix tricks, no parent. + const segments = normalized.split("/"); + if (segments[segments.length - 1] !== safeName) return null; + return normalized; +} + +async function resolveNodeServerBaseDir(node, nodeServerName) { + const nodeKey = String(node.uuid || node.id || node.name || ""); + const safeName = sanitizeName(nodeServerName); + if (!nodeKey || !safeName) return null; + const cacheKey = `${nodeKey}:${safeName}`; + const cached = _nodeServerBaseDirCache.get(cacheKey); + if (cached && Date.now() - cached.at < NODE_SERVER_BASEDIR_TTL_MS) { + return cached.baseDir; + } + const { status, json } = await httpJson( + nodeUrl(node, `/v1/servers/${encodeURIComponent(safeName)}`), + { method: "GET", headers: nodeHeaders(node), timeoutMs: 5000 } + ); + if (status !== 200 || !json || json.ok !== true) return null; + const validated = validateResolvedBaseDir(json.baseDir, safeName); + if (!validated) return null; + _nodeServerBaseDirCache.set(cacheKey, { baseDir: validated, at: Date.now() }); + return validated; +} + async function remoteContext(serverName) { const srv = await findServerByNameOrId(serverName); if (!srv) return { exists: false }; @@ -1923,7 +2175,15 @@ async function remoteContext(serverName) { if (!node) return { exists: true, remote: false, info: buildServerInfo(srv) }; const volRoot = getNodeVolumesDir(node); const nodeServerName = sanitizeName(srv.name || serverName); - const baseDir = `${volRoot}/${nodeServerName}`; + // adpanel:multidisk - the server may live on a secondary disk. Resolve its real + // base directory from the node (disk-aware) and fall back to the primary volumes + // root for older/unreachable nodes. The node remains the source of truth and + // re-validates every path, so this only affects which root the panel prefixes. + let baseDir = `${volRoot}/${nodeServerName}`; + try { + const resolved = await resolveNodeServerBaseDir(node, nodeServerName); + if (resolved) baseDir = resolved; + } catch (_) { /* fall back to primary path */ } return { exists: true, remote: true, @@ -1987,17 +2247,12 @@ app.get("/api/nodes/server/:name/entries", async (req, res) => { const ctx = await remoteContext(serverName); if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); - if (!_nodeVolumeDirCache.has(String(ctx.node.uuid || ctx.node.id || ""))) { - try { await activeCheckNode(ctx.node, { force: true }); } catch { } - const volRoot = getNodeVolumesDir(ctx.node); - ctx.baseDir = `${volRoot}/${sanitizeName(serverName)}`; - } const rel = String(req.query.path || ""); try { const full = safeJoinUnix(ctx.baseDir, rel); const { status, json } = await httpJson( nodeUrl(ctx.node, "/v1/fs/list"), - { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, depth: 1 } } + { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, depth: 1 } } ); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_list_failed" }); return res.json({ path: rel, entries: mapFsEntries(json.entries || []) }); @@ -2025,7 +2280,7 @@ app.get("/api/nodes/server/:name/file", async (req, res) => { const full = safeJoinUnix(ctx.baseDir, rel); const { status, json } = await httpJson( nodeUrl(ctx.node, "/v1/fs/read"), - { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, encoding: "utf8" } } + { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, encoding: "utf8" } } ); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_read_failed" }); return res.json({ path: rel, content: typeof json.content === "string" ? json.content : "" }); @@ -2052,7 +2307,7 @@ app.get("/api/nodes/server/:name/download", async (req, res) => { try { const full = safeJoinUnix(ctx.baseDir, rel); const lib = nodeUrl(ctx.node, "").startsWith("https:") ? require("https") : require("http"); - const postData = JSON.stringify({ path: full }); + const postData = JSON.stringify({ path: full, server: ctx.nodeServerName }); const url = new URL(nodeUrl(ctx.node, "/v1/fs/download")); const reqOpts = { hostname: url.hostname, @@ -2090,8 +2345,9 @@ app.post("/api/nodes/server/:name/file", async (req, res) => { return res.status(accessCheck.status).json({ error: accessCheck.error }); } - if (!(await checkUserPerm(req, serverName, "files_create"))) { - return res.status(403).json({ error: "permission denied", permission: "files_create" }); + const writeMode = await resolveFsWriteMode(req, serverName); + if (!writeMode.ok) { + return res.status(403).json({ error: "permission denied", permission: writeMode.permission }); } const ctx = await remoteContext(serverName); @@ -2103,15 +2359,23 @@ app.post("/api/nodes/server/:name/file", async (req, res) => { const full = safeJoinUnix(ctx.baseDir, rel); const { status, json } = await httpJson( nodeUrl(ctx.node, "/v1/fs/write"), - { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, content, encoding: "utf8" } } + { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, content, encoding: "utf8", mode: writeMode.mode } } ); if (status === 507 && json?.error === "disk_limit_exceeded") { return res.status(507).json(json); } + // The node enforces create-vs-overwrite atomically. Surface those as a 403 + // so the user understands it is a permission boundary, not a generic failure. + if (status === 409) { + return res.status(403).json({ error: "permission denied", permission: "files_write", detail: "overwriting existing files requires the files_write permission" }); + } + if (status === 404 && json && json.existed === false) { + return res.status(403).json({ error: "permission denied", permission: "files_create", detail: "creating new files requires the files_create permission" }); + } if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_write_failed" }); const userEmail = req.session?.user || "unknown"; - recordActivity(req.params.name, "file_edit", { path: rel }, userEmail, getRequestIp(req)); + recordActivity(req.params.name, "file_edit", { path: rel, created: json.existed === false }, userEmail, getRequestIp(req)); return res.json({ ok: true }); } catch (e) { @@ -2135,7 +2399,7 @@ app.post("/api/nodes/server/:name/delete", async (req, res) => { const full = safeJoinUnix(ctx.baseDir, rel); const { status, json } = await httpJson( nodeUrl(ctx.node, "/v1/fs/delete"), - { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, isDir } } + { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, isDir } } ); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_delete_failed" }); @@ -2179,7 +2443,7 @@ app.post("/api/nodes/server/:name/delete-batch", async (req, res) => { { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), - body: { items: fullItems }, + body: { items: fullItems, server: ctx.nodeServerName }, timeoutMs: 120000 } ); @@ -2220,7 +2484,7 @@ app.post("/api/nodes/server/:name/rename", async (req, res) => { const full = safeJoinUnix(ctx.baseDir, rel); const { status, json } = await httpJson( nodeUrl(ctx.node, "/v1/fs/rename"), - { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, newName } } + { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, newName } } ); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_rename_failed" }); @@ -2248,7 +2512,7 @@ app.post("/api/nodes/server/:name/extract", async (req, res) => { const full = safeJoinUnix(ctx.baseDir, rel); const { status, json } = await httpJson( nodeUrl(ctx.node, "/v1/fs/extract"), - { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full } } + { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName } } ); if (status === 507 && json?.error === "disk_limit_exceeded") { return res.status(507).json(json); @@ -2281,11 +2545,36 @@ app.post("/api/nodes/server/:name/archive", async (req, res) => { if (!Array.isArray(paths) || paths.length === 0) { return res.status(400).json({ error: "missing paths" }); } + if (paths.length > 1000) { + return res.status(400).json({ error: "too many paths (max 1000)" }); + } + + // #4 belt-and-suspenders: the per-server node endpoint already re-confines + // every path under the server root, but we also validate at the panel boundary + // so traversal/NUL/absolute inputs are rejected here regardless of which node + // endpoint they are ever routed to. We forward the original RELATIVE paths + // (the node prefixes its own server root); we only use safeJoinUnix as a + // throw-on-violation validator against the resolved baseDir. + const cleanPaths = []; + try { + for (const p of paths) { + const rel = String(p || ""); + if (!rel) continue; + safeJoinUnix(ctx.baseDir, rel); // throws on traversal / NUL / absolute + cleanPaths.push(rel); + } + if (destDir) safeJoinUnix(ctx.baseDir, destDir); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } + if (cleanPaths.length === 0) { + return res.status(400).json({ error: "missing paths" }); + } try { const { status, json } = await httpJson( nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(req.params.name)}/files/archive`), - { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { paths, destDir }, timeoutMs: 300000 } + { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { paths: cleanPaths, destDir }, timeoutMs: 300000 } ); if (status === 507 && json?.error === "disk_limit_exceeded") { return res.status(507).json(json); @@ -2363,7 +2652,7 @@ app.post("/api/nodes/server/:name/upload", async (req, res) => { fileStream.resume(); return { status: 507, json: diskLimitError }; } - return streamUploadToNode(ctx.node, fileStream, originalName, full, nodeMaxBytes, nodeMaxMb); + return streamUploadToNode(ctx.node, fileStream, originalName, full, nodeMaxBytes, nodeMaxMb, ctx.nodeServerName); })(); uploadPromise.then((result) => { @@ -2504,7 +2793,7 @@ app.post("/api/nodes/server/:name/upload-url", async (req, res) => { { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), - body: { dir: full, url: validatedUrl.toString() }, + body: { dir: full, server: ctx.nodeServerName, url: validatedUrl.toString() }, timeoutMs: 30 * 60 * 1000 } ); @@ -2641,6 +2930,13 @@ async function performPanelServerAction(req, serverName, cmdRaw) { } const { status, json, error } = result; if ((status === 200 || status === 202) && json && (json.ok === true || json.ok === undefined)) { + if (_serverActionObserver && cmd !== "status") { + try { + await _serverActionObserver({ req, serverName: targetServer, action: cmd, result: json || { ok: true } }); + } catch (observerErr) { + console.warn("[nodes-action] observer failed:", observerErr?.message || observerErr); + } + } return { status: 200, body: json || { ok: true } }; } const detail = (json && (json.detail || json.error || json.message)) || error || `HTTP ${status}`; @@ -3087,11 +3383,14 @@ module.exports.nodeUrl = nodeUrl; module.exports.nodeHeaders = nodeHeaders; module.exports.nodeUnderCloudflare = nodeUnderCloudflare; module.exports.callNodeApi = callNodeApi; +module.exports.isOpenNodeInstallerRoute = isOpenNodeInstallerRoute; module.exports.resolveNodeForServer = resolveNodeForServer; module.exports.recordActivity = recordActivity; +module.exports.flushActivityLogs = flushActivityLogs; module.exports.seedRuntimeOnNode = seedRuntimeOnNode; module.exports.setWebhookDispatcher = setWebhookDispatcher; module.exports.setPermissionCheckers = setPermissionCheckers; +module.exports.setServerActionObserver = setServerActionObserver; module.exports.startPayloadFor = startPayloadFor; module.exports.sanitizeConsoleCommand = sanitizeConsoleCommand; module.exports.performPanelServerAction = performPanelServerAction; diff --git a/opencode.json b/opencode.json new file mode 100644 index 0000000..e60773d --- /dev/null +++ b/opencode.json @@ -0,0 +1,19 @@ +{ + "$schema": "https://opencode.ai/config.json", + "model": "openrouter/moonshotai/kimi-k2.6:free", + "provider": { + "openrouter": { + "npm": "@ai-sdk/openai-compatible", + "name": "OpenRouter", + "options": { + "baseURL": "https://openrouter.ai/api/v1", + "apiKey": "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" + }, + "models": { + "moonshotai/kimi-k2.6:free": { + "name": "Kimi K2.6 Free" + } + } + } + } +} diff --git a/optimize_sidebar2.js b/optimize_sidebar2.js new file mode 100644 index 0000000..b9809e5 --- /dev/null +++ b/optimize_sidebar2.js @@ -0,0 +1,202 @@ +const fs = require('fs'); + +let ejsContent = fs.readFileSync('views/bot.ejs', 'utf8'); + +const oldEjsStr = ` .sidebar-shell { + transition: + width 0.42s cubic-bezier(0.22, 1, 0.36, 1), + opacity 0.2s ease, + background-color 0.42s cubic-bezier(0.22, 1, 0.36, 1), + box-shadow 0.42s cubic-bezier(0.22, 1, 0.36, 1) !important; + will-change: width, background-color, box-shadow; + }`; + +const newEjsStr = ` .sidebar-shell { + transition: + width 0.3s cubic-bezier(0.4, 0, 0.2, 1), + opacity 0.2s ease, + background-color 0.3s cubic-bezier(0.4, 0, 0.2, 1), + box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important; + will-change: width, transform, opacity; + transform: translateZ(0); + backface-visibility: hidden; + perspective: 1000px; + }`; + +const oldEjsStr2 = ` .sidebar-shell.open .sidebar-item .label, + .sidebar-shell.open .profile-meta { + transition: + max-width 0.36s cubic-bezier(0.22, 1, 0.36, 1), + opacity 0.26s ease, + transform 0.36s cubic-bezier(0.22, 1, 0.36, 1); + transition-delay: 0s; + }`; + +const newEjsStr2 = ` .sidebar-shell.open .sidebar-item .label, + .sidebar-shell.open .profile-meta { + transition: + opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1), + transform 0.25s cubic-bezier(0.4, 0, 0.2, 1); + transition-delay: 0s; + transform: translateZ(0); + backface-visibility: hidden; + }`; + +if (ejsContent.includes(oldEjsStr)) { + ejsContent = ejsContent.replace(oldEjsStr, newEjsStr); + console.log('Replaced sidebar-shell transitions'); +} else { + console.log('Could not find old sidebar-shell transitions'); +} + +if (ejsContent.includes(oldEjsStr2)) { + ejsContent = ejsContent.replace(oldEjsStr2, newEjsStr2); + console.log('Replaced sidebar-item label transitions'); +} else { + console.log('Could not find old sidebar-item label transitions'); +} +fs.writeFileSync('views/bot.ejs', ejsContent); + + +let cssContent = fs.readFileSync('public/css/bot.css', 'utf8'); + +const oldCssStr = `.sidebar-shell.open .sidebar-item .label { + display: inline-block; + max-width: 0; + opacity: 0; + overflow: hidden; + transition: max-width .25s ease, opacity .25s ease, transform .25s ease; +}`; + +const newCssStr = `.sidebar-shell.open .sidebar-item .label { + display: inline-block; + width: 0; + opacity: 0; + overflow: hidden; + transition: opacity .2s ease, transform .25s ease; + will-change: opacity, transform; + transform: translateZ(0); +}`; + +const oldCssStr2 = `.sidebar-shell.open:hover .sidebar-item .label { + max-width: 150px; + opacity: 1; + transform: translateX(0); +}`; + +const newCssStr2 = `.sidebar-shell.open:hover .sidebar-item .label { + width: 150px; + opacity: 1; + transform: translateX(0); +}`; + +const oldCssStr3 = `.sidebar-shell.open .profile-meta { + display: flex; + flex-direction: column; + max-width: 0; + opacity: 0; + overflow: hidden; + transition: max-width .25s ease, opacity .25s ease; + white-space: nowrap; +}`; + +const newCssStr3 = `.sidebar-shell.open .profile-meta { + display: flex; + flex-direction: column; + width: 0; + opacity: 0; + overflow: hidden; + transition: opacity .2s ease, transform .25s ease; + white-space: nowrap; + will-change: opacity, transform; + transform: translateZ(0); +}`; + +const oldCssStr4 = `.sidebar-shell.open:hover .profile-meta { + max-width: 200px; + opacity: 1; +}`; + +const newCssStr4 = `.sidebar-shell.open:hover .profile-meta { + width: 200px; + opacity: 1; +}`; + +const oldCssStr5 = `.sidebar-shell { + position: fixed; + --sidebar-top: 75px; + --sidebar-height: 480px; + top: var(--sidebar-top); + left: 12px; + transform: none; + transform: none; + width: 68px !important; + height: var(--sidebar-height); + backdrop-filter: blur(5px); + -webkit-backdrop-filter: blur(5px); + background-color: rgba(255, 255, 255, 0.047); + border-radius: 18px; + isolation: isolate; + box-shadow: 0px 6px var(--outer-shadow-blur) rgba(0, 0, 0, 0.2); + padding: 14px 0; + display: flex; + flex-direction: column; + gap: 10px; + opacity: 0; + pointer-events: none; + transition: width .22s ease, opacity .18s ease, transform .22s ease; + z-index: 2200; +}`; + +const newCssStr5 = `.sidebar-shell { + position: fixed; + --sidebar-top: 75px; + --sidebar-height: 480px; + top: var(--sidebar-top); + left: 12px; + transform: translateZ(0); + width: 68px !important; + height: var(--sidebar-height); + backdrop-filter: blur(5px); + -webkit-backdrop-filter: blur(5px); + background-color: rgba(255, 255, 255, 0.047); + border-radius: 18px; + isolation: isolate; + box-shadow: 0px 6px var(--outer-shadow-blur) rgba(0, 0, 0, 0.2); + padding: 14px 0; + display: flex; + flex-direction: column; + gap: 10px; + opacity: 0; + pointer-events: none; + transition: width .3s cubic-bezier(0.4, 0, 0.2, 1), opacity .2s ease, transform .3s cubic-bezier(0.4, 0, 0.2, 1); + z-index: 2200; + will-change: width, transform, opacity; + backface-visibility: hidden; + perspective: 1000px; +}`; + + +if (cssContent.includes(oldCssStr)) { + cssContent = cssContent.replace(oldCssStr, newCssStr); + console.log('Replaced bot.css label initial state'); +} +if (cssContent.includes(oldCssStr2)) { + cssContent = cssContent.replace(oldCssStr2, newCssStr2); + console.log('Replaced bot.css label hover state'); +} +if (cssContent.includes(oldCssStr3)) { + cssContent = cssContent.replace(oldCssStr3, newCssStr3); + console.log('Replaced bot.css profile initial state'); +} +if (cssContent.includes(oldCssStr4)) { + cssContent = cssContent.replace(oldCssStr4, newCssStr4); + console.log('Replaced bot.css profile hover state'); +} +if (cssContent.includes(oldCssStr5)) { + cssContent = cssContent.replace(oldCssStr5, newCssStr5); + console.log('Replaced bot.css sidebar main shell'); +} + +fs.writeFileSync('public/css/bot.css', cssContent); + diff --git a/package-lock.json b/package-lock.json index 0077da3..a23a634 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,11 +1,11 @@ { - "name": "adpanel-final-v12", + "name": "adpanel", "version": "1.0.0", "lockfileVersion": 3, "requires": true, "packages": { "": { - "name": "adpanel-final-v12", + "name": "adpanel", "version": "1.0.0", "license": "ISC", "dependencies": { @@ -14,13 +14,12 @@ "ansi_up": "^6.0.6", "bcrypt": "^6.0.0", "bcryptjs": "^3.0.3", - "busboy": "^1.6.0", "bullmq": "^5.66.7", + "busboy": "^1.6.0", "chalk": "^5.6.2", "compression": "^1.8.1", "connect-redis": "^9.0.0", "cookie-parser": "^1.4.7", - "csurf": "^1.11.0", "dotenv": "^17.2.3", "ejs": "^3.1.10", "express": "^4.19.2", @@ -35,7 +34,7 @@ "mysql2": "^3.11.5", "nodemon": "^3.1.14", "ora": "^9.3.0", - "pm2": "^6.0.14", + "pm2": "^7.0.1", "qrcode": "^1.5.4", "qrcode-terminal": "^0.12.0", "rate-limit-redis": "^4.3.1", @@ -44,7 +43,7 @@ "socket.io": "^4.8.3", "speakeasy": "^2.0.0", "tar": "^7.5.13", - "ws": "^8.19.0" + "ws": "^8.21.0" } }, "node_modules/@fortawesome/fontawesome-free": { @@ -422,9 +421,10 @@ } }, "node_modules/@ioredis/commands": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.0.tgz", - "integrity": "sha512-eUgLqrMf8nJkZxT24JvVRrQya1vZkQh8BBeYNwGDqa5I0VUi8ACx7uFvAaLxintokpTenkK6DASvo/bvNbBGow==" + "version": "1.5.1", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.1.tgz", + "integrity": "sha512-JH8ZL/ywcJyR9MmJ5BNqZllXNZQqQbnVZOqpPQqE1vHiFgAw4NHbvE0FOduNU8IX9babitBT46571OnPTT0Zcw==", + "license": "MIT" }, "node_modules/@isaacs/fs-minipass": { "version": "4.0.1", @@ -438,213 +438,83 @@ } }, "node_modules/@msgpackr-extract/msgpackr-extract-darwin-arm64": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.3.tgz", - "integrity": "sha512-QZHtlVgbAdy2zAqNA9Gu1UpIuI8Xvsd1v8ic6B2pZmeFnFcMWiPLfWXh7TVw4eGEZ/C9TH281KwhVoeQUKbyjw==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-arm64/-/msgpackr-extract-darwin-arm64-3.0.4.tgz", + "integrity": "sha512-LCkGo6JDfaBhgST7UpPWgNgLINpcpabaHfyz5OBx75nUYxBsaEPxjnyNjWpeb/xBup/682QnBfRBy2/LvPutZQ==", "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "darwin" ] }, "node_modules/@msgpackr-extract/msgpackr-extract-darwin-x64": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.3.tgz", - "integrity": "sha512-mdzd3AVzYKuUmiWOQ8GNhl64/IoFGol569zNRdkLReh6LRLHOXxU4U8eq0JwaD8iFHdVGqSy4IjFL4reoWCDFw==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-darwin-x64/-/msgpackr-extract-darwin-x64-3.0.4.tgz", + "integrity": "sha512-zExlW9zUJKZH/tOtVMttwjKa4Xm/3KcNjnE3dPN92uCktwavMxpgCA3MoJK/DOnTWsQgo224OaST27/mPNAf+w==", "cpu": [ "x64" ], + "license": "MIT", "optional": true, "os": [ "darwin" ] }, "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.3.tgz", - "integrity": "sha512-fg0uy/dG/nZEXfYilKoRe7yALaNmHoYeIoJuJ7KJ+YyU2bvY8vPv27f7UKhGRpY6euFYqEVhxCFZgAUNQBM3nw==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm/-/msgpackr-extract-linux-arm-3.0.4.tgz", + "integrity": "sha512-Tg3yX65f5GbtXLkrYEHE5oibZG9epyYWas7FogTTEJeDEF9JlXJzKgXaNhT3UXlTOeA+AfZpYZYZ0uPj7Cfquw==", "cpu": [ "arm" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@msgpackr-extract/msgpackr-extract-linux-arm64": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.3.tgz", - "integrity": "sha512-YxQL+ax0XqBJDZiKimS2XQaf+2wDGVa1enVRGzEvLLVFeqa5kx2bWbtcSXgsxjQB7nRqqIGFIcLteF/sHeVtQg==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-arm64/-/msgpackr-extract-linux-arm64-3.0.4.tgz", + "integrity": "sha512-dgX0P/9wGPJeHFBG+ZmhgE6bmtMt7NP5CRBGyyktpopdk/mW4POnrpQsSLtKI1dwpc+pPLuXHDh6vvskyQE/sw==", "cpu": [ "arm64" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@msgpackr-extract/msgpackr-extract-linux-x64": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.3.tgz", - "integrity": "sha512-cvwNfbP07pKUfq1uH+S6KJ7dT9K8WOE4ZiAcsrSes+UY55E/0jLYc+vq+DO7jlmqRb5zAggExKm0H7O/CBaesg==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-linux-x64/-/msgpackr-extract-linux-x64-3.0.4.tgz", + "integrity": "sha512-8TNXMEjJc3QEy7R/x1INhgiU+XakDAFUzBhaz7+Rbrs8NH5UQeHQxxmzsSBJGyV6I1jW79undiQm8tOI+D+8FQ==", "cpu": [ "x64" ], + "license": "MIT", "optional": true, "os": [ "linux" ] }, "node_modules/@msgpackr-extract/msgpackr-extract-win32-x64": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.3.tgz", - "integrity": "sha512-x0fWaQtYp4E6sktbsdAqnehxDgEc/VwM7uLsRCYWaiGu0ykYdZPiS8zCWdnjHwyiumousxfBm4SO31eXqwEZhQ==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/@msgpackr-extract/msgpackr-extract-win32-x64/-/msgpackr-extract-win32-x64-3.0.4.tgz", + "integrity": "sha512-CmCXPQrkbwExx3j946/PtHWHbYJiCRBRDl4BlkRQcJB/YOwQxJRTpoo7aTsortjgoJ1x7opzTSxn7C+ASSLVjQ==", "cpu": [ "x64" ], + "license": "MIT", "optional": true, "os": [ "win32" ] }, - "node_modules/@pm2/agent": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/@pm2/agent/-/agent-2.1.1.tgz", - "integrity": "sha512-0V9ckHWd/HSC8BgAbZSoq8KXUG81X97nSkAxmhKDhmF8vanyaoc1YXwc2KVkbWz82Rg4gjd2n9qiT3i7bdvGrQ==", - "dependencies": { - "async": "~3.2.0", - "chalk": "~3.0.0", - "dayjs": "~1.8.24", - "debug": "~4.3.1", - "eventemitter2": "~5.0.1", - "fast-json-patch": "^3.1.0", - "fclone": "~1.0.11", - "pm2-axon": "~4.0.1", - "pm2-axon-rpc": "~0.7.0", - "proxy-agent": "~6.4.0", - "semver": "~7.5.0", - "ws": "~7.5.10" - } - }, - "node_modules/@pm2/agent/node_modules/ansi-styles": { - "version": "4.3.0", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", - "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", - "dependencies": { - "color-convert": "^2.0.1" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/chalk/ansi-styles?sponsor=1" - } - }, - "node_modules/@pm2/agent/node_modules/chalk": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-3.0.0.tgz", - "integrity": "sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==", - "dependencies": { - "ansi-styles": "^4.1.0", - "supports-color": "^7.1.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@pm2/agent/node_modules/dayjs": { - "version": "1.8.36", - "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.8.36.tgz", - "integrity": "sha512-3VmRXEtw7RZKAf+4Tv1Ym9AGeo8r8+CjDi26x+7SYQil1UqtqdaokhzoEJohqlzt0m5kacJSDhJQkG/LWhpRBw==" - }, - "node_modules/@pm2/agent/node_modules/debug": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", - "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/@pm2/agent/node_modules/has-flag": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", - "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", - "engines": { - "node": ">=8" - } - }, - "node_modules/@pm2/agent/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@pm2/agent/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@pm2/agent/node_modules/supports-color": { - "version": "7.2.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", - "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", - "dependencies": { - "has-flag": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/@pm2/agent/node_modules/ws": { - "version": "7.5.10", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", - "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", - "license": "MIT", - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/@pm2/agent/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/@pm2/blessed": { "version": "0.1.81", "resolved": "https://registry.npmjs.org/@pm2/blessed/-/blessed-0.1.81.tgz", @@ -656,88 +526,6 @@ "node": ">= 0.8.0" } }, - "node_modules/@pm2/io": { - "version": "6.1.0", - "resolved": "https://registry.npmjs.org/@pm2/io/-/io-6.1.0.tgz", - "integrity": "sha512-IxHuYURa3+FQ6BKePlgChZkqABUKFYH6Bwbw7V/pWU1pP6iR1sCI26l7P9ThUEB385ruZn/tZS3CXDUF5IA1NQ==", - "dependencies": { - "async": "~2.6.1", - "debug": "~4.3.1", - "eventemitter2": "^6.3.1", - "require-in-the-middle": "^5.0.0", - "semver": "~7.5.4", - "shimmer": "^1.2.0", - "signal-exit": "^3.0.3", - "tslib": "1.9.3" - }, - "engines": { - "node": ">=6.0" - } - }, - "node_modules/@pm2/io/node_modules/async": { - "version": "2.6.4", - "resolved": "https://registry.npmjs.org/async/-/async-2.6.4.tgz", - "integrity": "sha512-mzo5dfJYwAn29PeiJ0zvwTo04zj8HDJj0Mn8TD7sno7q12prdbnasKJHhkm2c1LgrhlJ0teaea8860oxi51mGA==", - "dependencies": { - "lodash": "^4.17.14" - } - }, - "node_modules/@pm2/io/node_modules/debug": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", - "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/@pm2/io/node_modules/eventemitter2": { - "version": "6.4.9", - "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-6.4.9.tgz", - "integrity": "sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg==" - }, - "node_modules/@pm2/io/node_modules/lru-cache": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-6.0.0.tgz", - "integrity": "sha512-Jo6dJ04CmSjuznwJSS3pUeWmd/H0ffTlkXXgwZi+eq1UCmqQwCh+eLsYOYCwY991i2Fah4h1BEMCx4qThGbsiA==", - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@pm2/io/node_modules/semver": { - "version": "7.5.4", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.5.4.tgz", - "integrity": "sha512-1bCSESV6Pv+i21Hvpxp3Dx+pSD8lIPt8uVjRrxAUt/nbswYc+tK6Y2btiULjd4+fnq15PX+nqQDC7Oft7WkwcA==", - "dependencies": { - "lru-cache": "^6.0.0" - }, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/@pm2/io/node_modules/tslib": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-1.9.3.tgz", - "integrity": "sha512-4krF8scpejhaOgqzBEcGM7yDIEfi0/8+8zDRZhNZZ2kjmHJ4hv3zCbQWxoJGz1iw5U0Jl0nma13xzHXcncMavQ==" - }, - "node_modules/@pm2/io/node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==" - }, "node_modules/@pm2/js-api": { "version": "0.8.0", "resolved": "https://registry.npmjs.org/@pm2/js-api/-/js-api-0.8.0.tgz", @@ -777,32 +565,6 @@ } } }, - "node_modules/@pm2/js-api/node_modules/eventemitter2": { - "version": "6.4.9", - "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-6.4.9.tgz", - "integrity": "sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg==" - }, - "node_modules/@pm2/js-api/node_modules/ws": { - "version": "7.5.10", - "resolved": "https://registry.npmjs.org/ws/-/ws-7.5.10.tgz", - "integrity": "sha512-+dbF1tHwZpXcbOJdVOkzLDxZP1ailvSxM6ZweXTegylPny803bFhA+vqBYw4s31NSAk4S2Qz+AKXK9a4wkdjcQ==", - "license": "MIT", - "engines": { - "node": ">=8.3.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": "^5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, "node_modules/@pm2/pm2-version-check": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/@pm2/pm2-version-check/-/pm2-version-check-1.0.4.tgz", @@ -887,7 +649,8 @@ "node_modules/@tootallnate/quickjs-emscripten": { "version": "0.23.0", "resolved": "https://registry.npmjs.org/@tootallnate/quickjs-emscripten/-/quickjs-emscripten-0.23.0.tgz", - "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==" + "integrity": "sha512-C5Mc6rdnsaJDjO3UpGW/CQTHtCKaYlScZTly4JIu97Jxo/odCiH0ITnDXSJPTOrEKk/ycSZ0AOgTmkDtkOsvIA==", + "license": "MIT" }, "node_modules/@types/cors": { "version": "2.8.19", @@ -905,6 +668,15 @@ "undici-types": "~7.16.0" } }, + "node_modules/@types/ws": { + "version": "8.18.1", + "resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz", + "integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==", + "license": "MIT", + "dependencies": { + "@types/node": "*" + } + }, "node_modules/accepts": { "version": "1.3.8", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", @@ -930,6 +702,7 @@ "version": "7.1.4", "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "license": "MIT", "engines": { "node": ">= 14" } @@ -937,12 +710,14 @@ "node_modules/amp": { "version": "0.3.1", "resolved": "https://registry.npmjs.org/amp/-/amp-0.3.1.tgz", - "integrity": "sha512-OwIuC4yZaRogHKiuU5WlMR5Xk/jAcpPtawWL05Gj8Lvm2F6mwoJt4O/bHI+DHwG79vWd+8OFYM4/BzYqyRd3qw==" + "integrity": "sha512-OwIuC4yZaRogHKiuU5WlMR5Xk/jAcpPtawWL05Gj8Lvm2F6mwoJt4O/bHI+DHwG79vWd+8OFYM4/BzYqyRd3qw==", + "license": "MIT" }, "node_modules/amp-message": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/amp-message/-/amp-message-0.1.2.tgz", "integrity": "sha512-JqutcFwoU1+jhv7ArgW38bqrE+LQdcRv4NxNw0mp0JHQyB6tXesWRjtYKlDgHRY2o3JE5UTaBGUK8kSWUdxWUg==", + "license": "MIT", "dependencies": { "amp": "0.3.1" } @@ -956,14 +731,6 @@ "node": "*" } }, - "node_modules/ansi-colors": { - "version": "4.1.3", - "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.3.tgz", - "integrity": "sha512-/6w/C21Pm1A7aZitlI5Ni/2J6FFQN8i1Cvz3kHABAAbw93v/NlvKdVOqz7CCWz/3iv/JplRSEEZ83XION15ovw==", - "engines": { - "node": ">=6" - } - }, "node_modules/ansi-regex": { "version": "6.2.2", "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.2.2.tgz", @@ -1026,6 +793,7 @@ "version": "0.13.4", "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", + "license": "MIT", "dependencies": { "tslib": "^2.0.1" }, @@ -1075,9 +843,10 @@ } }, "node_modules/basic-ftp": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.0.5.tgz", - "integrity": "sha512-4Bcg1P8xhUuqcii/S0Z9wiHIrQVPMermM1any+MX5GeGD7faD3/msQUDGLol9wOcz4/jbg/WJnGqoJF6LiBdtg==", + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/basic-ftp/-/basic-ftp-5.3.1.tgz", + "integrity": "sha512-bopVNp6ugyA150DDuZfPFdt1KZ5a94ZDiwX4hMgZDzF+GttD80lEy8kj98kbyhLXnPvhtIo93mdnLIjpCAeeOw==", + "license": "MIT", "engines": { "node": ">=10.0.0" } @@ -1117,9 +886,10 @@ } }, "node_modules/bn.js": { - "version": "4.12.2", - "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.2.tgz", - "integrity": "sha512-n4DSx829VRTRByMRGdjQ9iqsN0Bh4OolPsFnaZBLcbi8iXcB+kJ9s7EnRt4wILZNV3kPLHkRVfOc/HvhC3ovDw==" + "version": "4.12.3", + "resolved": "https://registry.npmjs.org/bn.js/-/bn.js-4.12.3.tgz", + "integrity": "sha512-fGTi3gxV/23FTYdAoUtLYp6qySe2KE3teyZitipKNRuVYcBkoP/bB3guXN/XVKUe9mxCHXnc9C4ocyz8OmgN0g==", + "license": "MIT" }, "node_modules/bodec": { "version": "0.1.0", @@ -1127,9 +897,10 @@ "integrity": "sha512-Ylo+MAo5BDUq1KA3f3R/MFhh+g8cnHmo8bz3YPGhI1znrMaf77ol1sfvYJzsw3nTE+Y2GryfDxBaR+AqpAkEHQ==" }, "node_modules/body-parser": { - "version": "1.20.4", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", - "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", + "version": "1.20.5", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.5.tgz", + "integrity": "sha512-3grm+/2tUOvu2cjJkvsIxrv/wVpfXQW4PsQHYm7yk4vfpu7Ekl6nEsYBoJUL6qDwZUx8wUhQ8tR2qz+ad9c9OA==", + "license": "MIT", "dependencies": { "bytes": "~3.1.2", "content-type": "~1.0.5", @@ -1139,7 +910,7 @@ "http-errors": "~2.0.1", "iconv-lite": "~0.4.24", "on-finished": "~2.4.1", - "qs": "~6.14.0", + "qs": "~6.15.1", "raw-body": "~2.5.3", "type-is": "~1.6.18", "unpipe": "~1.0.0" @@ -1153,6 +924,7 @@ "version": "2.6.9", "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "license": "MIT", "dependencies": { "ms": "2.0.0" } @@ -1161,6 +933,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", @@ -1179,20 +952,23 @@ "node_modules/body-parser/node_modules/ms": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", - "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", + "license": "MIT" }, "node_modules/body-parser/node_modules/statuses": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", "engines": { "node": ">= 0.8" } }, "node_modules/brace-expansion": { - "version": "5.0.5", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.5.tgz", - "integrity": "sha512-VZznLgtwhn+Mact9tfiwx64fA9erHH/MCXEUfB/0bX/6Fz6ny5EGTXYltMocqg4xFAQZtnO3DHWWXi8RiuN7cQ==", + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", + "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "license": "MIT", "dependencies": { "balanced-match": "^4.0.2" }, @@ -1225,17 +1001,28 @@ "integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==" }, "node_modules/bullmq": { - "version": "5.66.7", - "resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.66.7.tgz", - "integrity": "sha512-X6YIjTXVN9fFjrMCKBppu74XZBnfWf0OgvwSVcpJE99irlszpGMKyyBcAOzd3126Lh9PwKygSfmHL4UfYrrIUQ==", + "version": "5.78.0", + "resolved": "https://registry.npmjs.org/bullmq/-/bullmq-5.78.0.tgz", + "integrity": "sha512-tT9jJmbobk9ueEfFc22egLmgwCcMGgOjZ5Y1cvgczBPv1JUmC7iHQVbQtqku2YBE5dE9uzdVpxIrBvL/YAjGwA==", + "license": "MIT", "dependencies": { "cron-parser": "4.9.0", - "ioredis": "5.9.2", - "msgpackr": "1.11.5", + "ioredis": "5.10.1", + "msgpackr": "2.0.2", "node-abort-controller": "3.1.1", - "semver": "7.7.3", - "tslib": "2.8.1", - "uuid": "11.1.0" + "semver": "7.8.0", + "tslib": "2.8.1" + }, + "engines": { + "node": ">=12.22.0" + }, + "peerDependencies": { + "redis": ">=5.0.0" + }, + "peerDependenciesMeta": { + "redis": { + "optional": true + } } }, "node_modules/busboy": { @@ -1273,6 +1060,7 @@ "version": "1.0.4", "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "license": "MIT", "dependencies": { "call-bind-apply-helpers": "^1.0.2", "get-intrinsic": "^1.3.0" @@ -1310,11 +1098,6 @@ "integrity": "sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==", "license": "MIT" }, - "node_modules/charm": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/charm/-/charm-0.1.2.tgz", - "integrity": "sha512-syedaZ9cPe7r3hoQA9twWYKu5AIyCswN5+szkmPBe9ccdLrj4bYaCnLVPTLd2kgVRc7+zoX4tyPgRnFKCj5YjQ==" - }, "node_modules/chokidar": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz", @@ -1670,6 +1453,7 @@ "version": "1.0.5", "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "license": "MIT", "engines": { "node": ">= 0.6" } @@ -1740,91 +1524,20 @@ "resolved": "https://registry.npmjs.org/croner/-/croner-4.1.97.tgz", "integrity": "sha512-/f6gpQuxDaqXu+1kwQYSckUglPaOrHdbIlBAu0YuW8/Cdb45XwXYNUBXg3r/9Mo6n540Kn/smKcZWko5x99KrQ==" }, - "node_modules/csrf": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/csrf/-/csrf-3.1.0.tgz", - "integrity": "sha512-uTqEnCvWRk042asU6JtapDTcJeeailFy4ydOQS28bj1hcLnYRiqi8SsD2jS412AY1I/4qdOwWZun774iqywf9w==", - "dependencies": { - "rndm": "1.2.0", - "tsscmp": "1.0.6", - "uid-safe": "2.1.5" - }, - "engines": { - "node": ">= 0.8" - } - }, - "node_modules/csurf": { - "version": "1.11.0", - "resolved": "https://registry.npmjs.org/csurf/-/csurf-1.11.0.tgz", - "integrity": "sha512-UCtehyEExKTxgiu8UHdGvHj4tnpE/Qctue03Giq5gPgMQ9cg/ciod5blZQ5a4uCEenNQjxyGuzygLdKUmee/bQ==", - "deprecated": "This package is archived and no longer maintained. For support, visit https://github.com/expressjs/express/discussions", - "dependencies": { - "cookie": "0.4.0", - "cookie-signature": "1.0.6", - "csrf": "3.1.0", - "http-errors": "~1.7.3" - }, - "engines": { - "node": ">= 0.8.0" - } - }, - "node_modules/csurf/node_modules/cookie": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.4.0.tgz", - "integrity": "sha512-+Hp8fLp57wnUSt0tY0tHEXh4voZRDnoIrZPqlo3DPiI4y9lwg/jqx+1Om94/W6ZaPDOUbnjOt/99w66zk+l1Xg==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/csurf/node_modules/depd": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/depd/-/depd-1.1.2.tgz", - "integrity": "sha512-7emPTl6Dpo6JRXOXjLRxck+FlLRX5847cLKEn00PLAgc3g2hTZZgr+e4c2v6QpSmLeFP3n5yUo7ft6avBK/5jQ==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/csurf/node_modules/http-errors": { - "version": "1.7.3", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-1.7.3.tgz", - "integrity": "sha512-ZTTX0MWrsQ2ZAhA1cejAwDLycFsd7I7nVtnkT3Ol0aqodaKW+0CTZDQ1uBv5whptCnc8e8HeRRJxRs0kmm/Qfw==", - "dependencies": { - "depd": "~1.1.2", - "inherits": "2.0.4", - "setprototypeof": "1.1.1", - "statuses": ">= 1.5.0 < 2", - "toidentifier": "1.0.0" - }, - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/csurf/node_modules/setprototypeof": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.1.1.tgz", - "integrity": "sha512-JvdAWfbXeIGaZ9cILp38HntZSFSo3mWg6xGcJJsd+d4aRMOqauag1C63dJfDw7OaMYwEbHMOxEZ1lqVRYP2OAw==" - }, - "node_modules/csurf/node_modules/statuses": { - "version": "1.5.0", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-1.5.0.tgz", - "integrity": "sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA==", - "engines": { - "node": ">= 0.6" - } - }, - "node_modules/csurf/node_modules/toidentifier": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.0.tgz", - "integrity": "sha512-yaOH/Pk/VEhBWWTlhI+qXxDFXlejDGcQipMlyxda9nthulaxLZUNcUqFxokp0vcYnvteJln5FNQDRrxj3YcbVw==", - "engines": { - "node": ">=0.6" - } - }, "node_modules/culvert": { "version": "0.1.2", "resolved": "https://registry.npmjs.org/culvert/-/culvert-0.1.2.tgz", "integrity": "sha512-yi1x3EAWKjQTreYWeSd98431AV+IEE0qoDyOoaHJ7KJ21gv6HtBXHVLX74opVSGqcR8/AbjJBHAHpcOy2bj5Gg==" }, + "node_modules/data-uri-to-buffer": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", + "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", + "license": "MIT", + "engines": { + "node": ">= 14" + } + }, "node_modules/dayjs": { "version": "1.11.15", "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.15.tgz", @@ -1858,6 +1571,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", + "license": "MIT", "dependencies": { "ast-types": "^0.13.4", "escodegen": "^2.1.0", @@ -1904,6 +1618,7 @@ "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", "optional": true, "engines": { "node": ">=8" @@ -1966,19 +1681,21 @@ } }, "node_modules/engine.io": { - "version": "6.6.4", - "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.4.tgz", - "integrity": "sha512-ZCkIjSYNDyGn0R6ewHDtXgns/Zre/NT6Agvq1/WobF7JXgFff4SeDroKiCO3fNJreU9YG429Sc81o4w5ok/W5g==", + "version": "6.6.8", + "resolved": "https://registry.npmjs.org/engine.io/-/engine.io-6.6.8.tgz", + "integrity": "sha512-2agL3ueZhqxoVrfmntO8yuVj+uNSlIOnhykYHk3Cq0ShYPdUjjUiSJrQvXjq01I9jAuI0Zl2YO8Evv5Mqytm5g==", + "license": "MIT", "dependencies": { "@types/cors": "^2.8.12", "@types/node": ">=10.0.0", + "@types/ws": "^8.5.12", "accepts": "~1.3.4", "base64id": "2.0.0", "cookie": "~0.7.2", "cors": "~2.8.5", - "debug": "~4.3.1", + "debug": "~4.4.1", "engine.io-parser": "~5.2.1", - "ws": "~8.17.1" + "ws": "~8.20.1" }, "engines": { "node": ">=10.2.0" @@ -2000,53 +1717,6 @@ "node": ">= 0.6" } }, - "node_modules/engine.io/node_modules/debug": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", - "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/engine.io/node_modules/ws": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", - "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/enquirer": { - "version": "2.3.6", - "resolved": "https://registry.npmjs.org/enquirer/-/enquirer-2.3.6.tgz", - "integrity": "sha512-yjNnPr315/FjS4zIsUxYguYUPP2e1NK4d7E7ZOLiyYCcbFBiTMyID+2wvm2w6+pZ/odMA7cRkjhsPbltwBOrLg==", - "dependencies": { - "ansi-colors": "^4.1.1" - }, - "engines": { - "node": ">=8.6" - } - }, "node_modules/es-define-property": { "version": "1.0.1", "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", @@ -2093,21 +1763,11 @@ "resolved": "https://registry.npmjs.org/escape-html/-/escape-html-1.0.3.tgz", "integrity": "sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow==" }, - "node_modules/escape-string-regexp": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", - "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", - "engines": { - "node": ">=10" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/escodegen": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/escodegen/-/escodegen-2.1.0.tgz", "integrity": "sha512-2NlIDTwUWJN0mRPQOdtQBzbUHvdGY2P1VXSyU83Q3xKxM7WHX2Ql8dKq782Q9TgQUNOLEzEYu9bzLNj1q88I5w==", + "license": "BSD-2-Clause", "dependencies": { "esprima": "^4.0.1", "estraverse": "^5.2.0", @@ -2128,6 +1788,7 @@ "version": "4.0.1", "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "license": "BSD-2-Clause", "bin": { "esparse": "bin/esparse.js", "esvalidate": "bin/esvalidate.js" @@ -2140,6 +1801,7 @@ "version": "5.3.0", "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "license": "BSD-2-Clause", "engines": { "node": ">=4.0" } @@ -2148,6 +1810,7 @@ "version": "2.0.3", "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "license": "BSD-2-Clause", "engines": { "node": ">=0.10.0" } @@ -2161,18 +1824,20 @@ } }, "node_modules/eventemitter2": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-5.0.1.tgz", - "integrity": "sha512-5EM1GHXycJBS6mauYAbVKT1cVs7POKWb2NXD4Vyt8dDqeZa7LaDK1/sjtL+Zb0lzTpSNil4596Dyu97hz37QLg==" + "version": "6.4.9", + "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-6.4.9.tgz", + "integrity": "sha512-JEPTiaOt9f04oa6NOkc4aH+nVp5I3wEjpHbIPqfgCdD5v5bUzy7xQqwcVO2aDQgOWhI28da57HksMrzK9HlRxg==", + "license": "MIT" }, "node_modules/express": { - "version": "4.22.1", - "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", - "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "version": "4.22.2", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.2.tgz", + "integrity": "sha512-IuL+Elrou2ZvCFHs18/CIzy2Nzvo25nZ1/D2eIZlz7c+QUayAcYoiM2BthCjs+EBHVpjYjcuLDAiCWgeIX3X1Q==", + "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "~1.20.3", + "body-parser": "~1.20.5", "content-disposition": "~0.5.4", "content-type": "~1.0.4", "cookie": "~0.7.1", @@ -2191,7 +1856,7 @@ "parseurl": "~1.3.3", "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", - "qs": "~6.14.0", + "qs": "~6.15.1", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", "send": "~0.19.0", @@ -2211,12 +1876,12 @@ } }, "node_modules/express-rate-limit": { - "version": "8.3.2", - "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.3.2.tgz", - "integrity": "sha512-77VmFeJkO0/rvimEDuUC5H30oqUC4EyOhyGccfqoLebB0oiEYfM7nwPrsDsBL1gsTpwfzX8SFy2MT3TDyRq+bg==", + "version": "8.5.2", + "resolved": "https://registry.npmjs.org/express-rate-limit/-/express-rate-limit-8.5.2.tgz", + "integrity": "sha512-5Kb34ipNX694DH48vN9irak1Qx30nb0PLYHXfJgw4YEjiC3ZEmZJhwOp+VfiCYwFzvFTdB9QkArYS5kXa2cx2A==", "license": "MIT", "dependencies": { - "ip-address": "10.1.0" + "ip-address": "^10.2.0" }, "engines": { "node": ">= 16" @@ -2301,7 +1966,8 @@ "node_modules/fast-json-patch": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/fast-json-patch/-/fast-json-patch-3.1.1.tgz", - "integrity": "sha512-vf6IHUX2SBcA+5/+4883dsIjpBTqmfBjmYiWK1savxQmFk4JfBMLa7ynTYOs1Rolp/T1betJxHiGD3g1Mn8lUQ==" + "integrity": "sha512-vf6IHUX2SBcA+5/+4883dsIjpBTqmfBjmYiWK1savxQmFk4JfBMLa7ynTYOs1Rolp/T1betJxHiGD3g1Mn8lUQ==", + "license": "MIT" }, "node_modules/fast-string-truncated-width": { "version": "3.0.3", @@ -2327,11 +1993,6 @@ "fast-string-width": "^3.0.2" } }, - "node_modules/fclone": { - "version": "1.0.11", - "resolved": "https://registry.npmjs.org/fclone/-/fclone-1.0.11.tgz", - "integrity": "sha512-GDqVQezKzRABdeqflsgMr7ktzgF9CyS+p2oe0jJqUY6izSSbhPIQJDpoU4PtGcD7VPM9xh/dVrTu6z1nwgmEGw==" - }, "node_modules/filelist": { "version": "1.0.4", "resolved": "https://registry.npmjs.org/filelist/-/filelist-1.0.4.tgz", @@ -2341,17 +2002,19 @@ } }, "node_modules/filelist/node_modules/brace-expansion": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", - "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.1.tgz", + "integrity": "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA==", + "license": "MIT", "dependencies": { "balanced-match": "^1.0.0" } }, "node_modules/filelist/node_modules/minimatch": { - "version": "5.1.6", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.6.tgz", - "integrity": "sha512-lKwV/1brpG6mBUFHtb7NUmtABCb2WZZmm2wNiOA5hAb8VdCS4B3dtMWyvcoViccwAW/COERjXLt0zP1zXUN26g==", + "version": "5.1.9", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.1.9.tgz", + "integrity": "sha512-7o1wEA2RyMP7Iu7GNba9vc0RWWGACJOCZBJX2GJWip0ikV+wcOsgVuY9uE8CPiyQhkGFSlhuSkZPavN7u1c2Fw==", + "license": "ISC", "dependencies": { "brace-expansion": "^2.0.1" }, @@ -2401,15 +2064,16 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" }, "node_modules/follow-redirects": { - "version": "1.15.11", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.11.tgz", - "integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==", + "version": "1.16.0", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.16.0.tgz", + "integrity": "sha512-y5rN/uOsadFT/JfYwhxRS5R7Qce+g3zG97+JrtFZlC9klX/W5hD7iiLzScI4nZqUS7DNUdhPgw4xI8W2LuXlUw==", "funding": [ { "type": "individual", "url": "https://github.com/sponsors/RubenVerborgh" } ], + "license": "MIT", "engines": { "node": ">=4.0" }, @@ -2551,6 +2215,7 @@ "version": "6.0.5", "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz", "integrity": "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==", + "license": "MIT", "dependencies": { "basic-ftp": "^5.0.2", "data-uri-to-buffer": "^6.0.2", @@ -2560,14 +2225,6 @@ "node": ">= 14" } }, - "node_modules/get-uri/node_modules/data-uri-to-buffer": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/data-uri-to-buffer/-/data-uri-to-buffer-6.0.2.tgz", - "integrity": "sha512-7hvf7/GW8e86rW0ptuwS3OcBGDjIi6SZva7hCyWC0yYry2cOPmLIjXAUHI6DK2HsnwJd9ifmt57i8eV2n4YNpw==", - "engines": { - "node": ">= 14" - } - }, "node_modules/git-node-fs": { "version": "1.0.0", "resolved": "https://registry.npmjs.org/git-node-fs/-/git-node-fs-1.0.0.tgz", @@ -2689,6 +2346,7 @@ "version": "7.0.2", "resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz", "integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==", + "license": "MIT", "dependencies": { "agent-base": "^7.1.0", "debug": "^4.3.4" @@ -2701,6 +2359,7 @@ "version": "7.0.6", "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "license": "MIT", "dependencies": { "agent-base": "^7.1.2", "debug": "4" @@ -2779,11 +2438,12 @@ } }, "node_modules/ioredis": { - "version": "5.9.2", - "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.9.2.tgz", - "integrity": "sha512-tAAg/72/VxOUW7RQSX1pIxJVucYKcjFjfvj60L57jrZpYCHC3XN0WCQ3sNYL4Gmvv+7GPvTAjc+KSdeNuE8oWQ==", + "version": "5.10.1", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.10.1.tgz", + "integrity": "sha512-HuEDBTI70aYdx1v6U97SbNx9F1+svQKBDo30o0b9fw055LMepzpOOd0Ccg9Q6tbqmBSJaMuY0fB7yw9/vjBYCA==", + "license": "MIT", "dependencies": { - "@ioredis/commands": "1.5.0", + "@ioredis/commands": "1.5.1", "cluster-key-slot": "^1.1.0", "debug": "^4.3.4", "denque": "^2.1.0", @@ -2802,9 +2462,9 @@ } }, "node_modules/ip-address": { - "version": "10.1.0", - "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.0.tgz", - "integrity": "sha512-XXADHxXmvT9+CRxhXg56LJovE+bmWnEWB78LB83VZTprKTmaC5QfruXocxzTZ2Kl0DNwKuBdlIhjL8LeY8Sf8Q==", + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz", + "integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==", "license": "MIT", "engines": { "node": ">= 12" @@ -2838,20 +2498,6 @@ "node": ">=8" } }, - "node_modules/is-core-module": { - "version": "2.16.1", - "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", - "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", - "dependencies": { - "hasown": "^2.0.2" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -2985,19 +2631,22 @@ } }, "node_modules/lodash": { - "version": "4.17.23", - "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", - "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==" + "version": "4.18.1", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.18.1.tgz", + "integrity": "sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==", + "license": "MIT" }, "node_modules/lodash.defaults": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", - "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==" + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==", + "license": "MIT" }, "node_modules/lodash.isarguments": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", - "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==" + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==", + "license": "MIT" }, "node_modules/log-symbols": { "version": "7.0.1", @@ -3020,6 +2669,15 @@ "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==" }, + "node_modules/lru-cache": { + "version": "7.18.3", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", + "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", + "license": "ISC", + "engines": { + "node": ">=12" + } + }, "node_modules/lru.min": { "version": "1.1.3", "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.3.tgz", @@ -3173,29 +2831,26 @@ "mkdirp": "bin/cmd.js" } }, - "node_modules/module-details-from-path": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/module-details-from-path/-/module-details-from-path-1.0.4.tgz", - "integrity": "sha512-EGWKgxALGMgzvxYF1UyGTy0HXX/2vHLkw6+NvDKW2jypWbHpjQuj4UMcqQWXHERJhVGKikolT06G3bcKe4fi7w==" - }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" }, "node_modules/msgpackr": { - "version": "1.11.5", - "resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-1.11.5.tgz", - "integrity": "sha512-UjkUHN0yqp9RWKy0Lplhh+wlpdt9oQBYgULZOiFhV3VclSF1JnSQWZ5r9gORQlNYaUKQoR8itv7g7z1xDDuACA==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/msgpackr/-/msgpackr-2.0.2.tgz", + "integrity": "sha512-c5hYOXFbP79Slh6Dzd2wzk+jnV7mX1UxfMYtilnY1NmalXPqG8DGb5cYCMBrW4AsH3zekBBZd4QrKz9NhtvYLQ==", + "license": "MIT", "optionalDependencies": { - "msgpackr-extract": "^3.0.2" + "msgpackr-extract": "^3.0.4" } }, "node_modules/msgpackr-extract": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.3.tgz", - "integrity": "sha512-P0efT1C9jIdVRefqjzOQ9Xml57zpOXnIuS+csaB4MdZbTdmGDLo8XhzBG1N7aO11gKDDkJvBLULeFTo46wwreA==", + "version": "3.0.4", + "resolved": "https://registry.npmjs.org/msgpackr-extract/-/msgpackr-extract-3.0.4.tgz", + "integrity": "sha512-4kmO/MdyUIkLIvTPr8VHLil4AtoKIoniWPIEk5+CDy0xnWC84azhSFmuJ7PxZdsYtiP5kEeQsORAVIeMgxT+Hw==", "hasInstallScript": true, + "license": "MIT", "optional": true, "dependencies": { "node-gyp-build-optional-packages": "5.2.2" @@ -3204,12 +2859,12 @@ "download-msgpackr-prebuilds": "bin/download-prebuilds.js" }, "optionalDependencies": { - "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.3", - "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.3", - "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.3", - "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.3", - "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.3", - "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.3" + "@msgpackr-extract/msgpackr-extract-darwin-arm64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-darwin-x64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-arm": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-arm64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-linux-x64": "3.0.4", + "@msgpackr-extract/msgpackr-extract-win32-x64": "3.0.4" } }, "node_modules/multer": { @@ -3230,11 +2885,6 @@ "node": ">= 6.0.0" } }, - "node_modules/mute-stream": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-0.0.8.tgz", - "integrity": "sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==" - }, "node_modules/mysql2": { "version": "3.16.0", "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.16.0.tgz", @@ -3280,30 +2930,6 @@ "node": ">=8.0.0" } }, - "node_modules/needle": { - "version": "2.4.0", - "resolved": "https://registry.npmjs.org/needle/-/needle-2.4.0.tgz", - "integrity": "sha512-4Hnwzr3mi5L97hMYeNl8wRW/Onhy4nUKR/lVemJ8gJedxxUyBLm9kkrDColJvoSfwi0jCNhD+xCdOtiGDQiRZg==", - "dependencies": { - "debug": "^3.2.6", - "iconv-lite": "^0.4.4", - "sax": "^1.2.4" - }, - "bin": { - "needle": "bin/needle" - }, - "engines": { - "node": ">= 4.4.x" - } - }, - "node_modules/needle/node_modules/debug": { - "version": "3.2.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", - "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", - "dependencies": { - "ms": "^2.1.1" - } - }, "node_modules/negotiator": { "version": "0.6.3", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.3.tgz", @@ -3313,9 +2939,10 @@ } }, "node_modules/netmask": { - "version": "2.0.2", - "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.0.2.tgz", - "integrity": "sha512-dBpDMdxv9Irdq66304OLfEmQ9tbNRFnFTuZiLo+bD+r332bBmMJ8GBLXklIXXgxd3+v9+KUnZaUR5PJMa75Gsg==", + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/netmask/-/netmask-2.1.1.tgz", + "integrity": "sha512-eonl3sLUha+S1GzTPxychyhnUzKyeQkZ7jLjKrBagJgPla13F+uQ71HgpFefyHgqrjEbCPkDArxYsjY8/+gLKA==", + "license": "MIT", "engines": { "node": ">= 0.4.0" } @@ -3347,6 +2974,7 @@ "version": "5.2.2", "resolved": "https://registry.npmjs.org/node-gyp-build-optional-packages/-/node-gyp-build-optional-packages-5.2.2.tgz", "integrity": "sha512-s+w+rBWnpTMwSFbaE0UXsRlg7hU4FjekKU4eyAih5T8nJuNZT1nNsskXpxmeqSK9UzkBl6UgRlnKc8hz8IEqOw==", + "license": "MIT", "optional": true, "dependencies": { "detect-libc": "^2.0.1" @@ -3404,6 +3032,7 @@ "version": "1.13.4", "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "license": "MIT", "engines": { "node": ">= 0.4" }, @@ -3479,6 +3108,7 @@ "version": "7.2.0", "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", + "license": "MIT", "dependencies": { "@tootallnate/quickjs-emscripten": "^0.23.0", "agent-base": "^7.1.2", @@ -3497,6 +3127,7 @@ "version": "7.0.1", "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", + "license": "MIT", "dependencies": { "degenerator": "^5.0.0", "netmask": "^2.0.2" @@ -3526,15 +3157,11 @@ "node": ">=8" } }, - "node_modules/path-parse": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", - "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==" - }, "node_modules/path-to-regexp": { - "version": "0.1.12", - "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.12.tgz", - "integrity": "sha512-RA1GjUVMnvYFxuqovrEqZoxxW5NUZqbwKtYz/Tt7nXerk0LbLblQmrsgdeOxV5SFHf0UDggjS/bSeOZwt1pmEQ==" + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-0.1.13.tgz", + "integrity": "sha512-A/AGNMFN3c8bOlvV9RreMdrv7jsmF9XIfDeCd87+I8RNg6s78BhJxMu69NEMHBSJFxKidViTEdruRwEk/WIKqA==", + "license": "MIT" }, "node_modules/picocolors": { "version": "1.1.1", @@ -3542,9 +3169,10 @@ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==" }, "node_modules/picomatch": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", - "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "version": "2.3.2", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.2.tgz", + "integrity": "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA==", + "license": "MIT", "engines": { "node": ">=8.6" }, @@ -3553,27 +3181,28 @@ } }, "node_modules/pidusage": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/pidusage/-/pidusage-3.0.2.tgz", - "integrity": "sha512-g0VU+y08pKw5M8EZ2rIGiEBaB8wrQMjYGFfW2QVIfyT8V+fq8YFLkvlz4bz5ljvFDJYNFCWT3PWqcRr2FKO81w==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/pidusage/-/pidusage-4.0.1.tgz", + "integrity": "sha512-yCH2dtLHfEBnzlHUJymR/Z1nN2ePG3m392Mv8TFlTP1B0xkpMQNHAnfkY0n2tAi6ceKO6YWhxYfZ96V4vVkh/g==", + "license": "MIT", "dependencies": { "safe-buffer": "^5.2.1" }, "engines": { - "node": ">=10" + "node": ">=18" } }, "node_modules/pm2": { - "version": "6.0.14", - "resolved": "https://registry.npmjs.org/pm2/-/pm2-6.0.14.tgz", - "integrity": "sha512-wX1FiFkzuT2H/UUEA8QNXDAA9MMHDsK/3UHj6Dkd5U7kxyigKDA5gyDw78ycTQZAuGCLWyUX5FiXEuVQWafukA==", + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pm2/-/pm2-7.0.1.tgz", + "integrity": "sha512-h/DI7WomfdAWDzDRtjhnNfsG4Do6kuOY+VGKbqffHW3yRZMUoWzwyBDkXjrOWvnBlwuY3lYBKkozDdCagfRI4Q==", "license": "AGPL-3.0", "dependencies": { - "@pm2/agent": "~2.1.1", "@pm2/blessed": "0.1.81", - "@pm2/io": "~6.1.0", - "@pm2/js-api": "~0.8.0", - "@pm2/pm2-version-check": "^1.0.4", + "@pm2/js-api": "0.8.0", + "@pm2/pm2-version-check": "1.0.4", + "amp": "0.3.1", + "amp-message": "0.1.2", "ansis": "4.0.0-node10", "async": "3.2.6", "chokidar": "3.6.0", @@ -3582,22 +3211,15 @@ "croner": "4.1.97", "dayjs": "1.11.15", "debug": "4.4.3", - "enquirer": "2.3.6", - "eventemitter2": "5.0.1", - "fclone": "1.0.11", + "eventemitter2": "6.4.9", + "fast-json-patch": "3.1.1", "js-yaml": "4.1.1", - "mkdirp": "1.0.4", - "needle": "2.4.0", - "pidusage": "3.0.2", - "pm2-axon": "~4.0.1", - "pm2-axon-rpc": "~0.7.1", - "pm2-deploy": "~1.0.2", - "pm2-multimeter": "^0.1.2", - "promptly": "2.2.0", + "pidusage": "4.0.1", + "pm2-deploy": "1.0.2", + "proxy-agent": "6.5.0", "semver": "7.7.2", - "source-map-support": "0.5.21", - "sprintf-js": "1.1.2", - "vizion": "~2.2.1" + "vizion": "2.2.1", + "ws": "8.20.0" }, "bin": { "pm2": "bin/pm2", @@ -3606,37 +3228,12 @@ "pm2-runtime": "bin/pm2-runtime" }, "engines": { - "node": ">=16.0.0" + "node": ">=18.0.0" }, "optionalDependencies": { "pm2-sysmonit": "^1.2.8" } }, - "node_modules/pm2-axon": { - "version": "4.0.1", - "resolved": "https://registry.npmjs.org/pm2-axon/-/pm2-axon-4.0.1.tgz", - "integrity": "sha512-kES/PeSLS8orT8dR5jMlNl+Yu4Ty3nbvZRmaAtROuVm9nYYGiaoXqqKQqQYzWQzMYWUKHMQTvBlirjE5GIIxqg==", - "dependencies": { - "amp": "~0.3.1", - "amp-message": "~0.1.1", - "debug": "^4.3.1", - "escape-string-regexp": "^4.0.0" - }, - "engines": { - "node": ">=5" - } - }, - "node_modules/pm2-axon-rpc": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/pm2-axon-rpc/-/pm2-axon-rpc-0.7.1.tgz", - "integrity": "sha512-FbLvW60w+vEyvMjP/xom2UPhUN/2bVpdtLfKJeYM3gwzYhoTEEChCOICfFzxkxuoEleOlnpjie+n1nue91bDQw==", - "dependencies": { - "debug": "^4.3.1" - }, - "engines": { - "node": ">=5" - } - }, "node_modules/pm2-deploy": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/pm2-deploy/-/pm2-deploy-1.0.2.tgz", @@ -3649,14 +3246,6 @@ "node": ">=4.0.0" } }, - "node_modules/pm2-multimeter": { - "version": "0.1.2", - "resolved": "https://registry.npmjs.org/pm2-multimeter/-/pm2-multimeter-0.1.2.tgz", - "integrity": "sha512-S+wT6XfyKfd7SJIBqRgOctGxaBzUOmVQzTAS+cg04TsEUObJVreha7lvCfX8zzGVr871XwCSnHUU7DQQ5xEsfA==", - "dependencies": { - "charm": "~0.1.1" - } - }, "node_modules/pm2-sysmonit": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/pm2-sysmonit/-/pm2-sysmonit-1.2.8.tgz", @@ -3687,17 +3276,6 @@ "resolved": "https://registry.npmjs.org/commander/-/commander-2.15.1.tgz", "integrity": "sha512-VlfT9F3V0v+jr4yxPc5gg9s62/fIVWsd2Bk2iD435um1NlGMYdVCq+MjcXnhYq2icNOizHr1kK+5TI6H0Hy0ag==" }, - "node_modules/pm2/node_modules/mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "bin": { - "mkdirp": "bin/cmd.js" - }, - "engines": { - "node": ">=10" - } - }, "node_modules/pm2/node_modules/semver": { "version": "7.7.2", "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz", @@ -3722,14 +3300,6 @@ "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==" }, - "node_modules/promptly": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/promptly/-/promptly-2.2.0.tgz", - "integrity": "sha512-aC9j+BZsRSSzEsXBNBwDnAxujdx19HycZoKgRgzWnS8eOHg1asuf9heuLprfbe739zY3IdUQx+Egv6Jn135WHA==", - "dependencies": { - "read": "^1.0.4" - } - }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -3743,35 +3313,29 @@ } }, "node_modules/proxy-agent": { - "version": "6.4.0", - "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.4.0.tgz", - "integrity": "sha512-u0piLU+nCOHMgGjRbimiXmA9kM/L9EHh3zL81xCdp7m+Y2pHIsnmbdDoEDoAz5geaonNR6q6+yOPQs6n4T6sBQ==", + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/proxy-agent/-/proxy-agent-6.5.0.tgz", + "integrity": "sha512-TmatMXdr2KlRiA2CyDu8GqR8EjahTG3aY3nXjdzFyoZbmB8hrBsTyMezhULIXKnC0jpfjlmiZ3+EaCzoInSu/A==", + "license": "MIT", "dependencies": { - "agent-base": "^7.0.2", + "agent-base": "^7.1.2", "debug": "^4.3.4", "http-proxy-agent": "^7.0.1", - "https-proxy-agent": "^7.0.3", + "https-proxy-agent": "^7.0.6", "lru-cache": "^7.14.1", - "pac-proxy-agent": "^7.0.1", + "pac-proxy-agent": "^7.1.0", "proxy-from-env": "^1.1.0", - "socks-proxy-agent": "^8.0.2" + "socks-proxy-agent": "^8.0.5" }, "engines": { "node": ">= 14" } }, - "node_modules/proxy-agent/node_modules/lru-cache": { - "version": "7.18.3", - "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz", - "integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==", - "engines": { - "node": ">=12" - } - }, "node_modules/proxy-from-env": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", - "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "license": "MIT" }, "node_modules/pstree.remy": { "version": "1.1.8", @@ -3804,9 +3368,10 @@ } }, "node_modules/qs": { - "version": "6.14.1", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.1.tgz", - "integrity": "sha512-4EK3+xJl8Ts67nLYNwqw/dsFVnCf+qR7RgXSK9jEEm9unao3njwMDdmsdvoKBKHzxd7tCYz5e5M+SnMjdtXGQQ==", + "version": "6.15.2", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.15.2.tgz", + "integrity": "sha512-Rzq0KEyX/w/tEybncDgdkZrJgVUsUMk3xjh3t5bv3S1HTAtg+uOYt72+ZfwiQwKdysThkTBdL/rTi6HDmX9Ddw==", + "license": "BSD-3-Clause", "dependencies": { "side-channel": "^1.1.0" }, @@ -3848,6 +3413,7 @@ "version": "2.5.3", "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "license": "MIT", "dependencies": { "bytes": "~3.1.2", "http-errors": "~2.0.1", @@ -3862,6 +3428,7 @@ "version": "2.0.1", "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "license": "MIT", "dependencies": { "depd": "~2.0.0", "inherits": "~2.0.4", @@ -3881,21 +3448,11 @@ "version": "2.0.2", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "license": "MIT", "engines": { "node": ">= 0.8" } }, - "node_modules/read": { - "version": "1.0.7", - "resolved": "https://registry.npmjs.org/read/-/read-1.0.7.tgz", - "integrity": "sha512-rSOKNYUmaxy0om1BNjMN4ezNT6VKK+2xF4GBhc81mkH7L60i6dp8qPYrkndNLT3QPphoII3maL9PVC9XmhHwVQ==", - "dependencies": { - "mute-stream": "~0.0.4" - }, - "engines": { - "node": ">=0.8" - } - }, "node_modules/readdirp": { "version": "3.6.0", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", @@ -3927,6 +3484,7 @@ "version": "1.2.0", "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "license": "MIT", "engines": { "node": ">=4" } @@ -3935,6 +3493,7 @@ "version": "3.0.0", "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "license": "MIT", "dependencies": { "redis-errors": "^1.0.0" }, @@ -3950,38 +3509,6 @@ "node": ">=0.10.0" } }, - "node_modules/require-in-the-middle": { - "version": "5.2.0", - "resolved": "https://registry.npmjs.org/require-in-the-middle/-/require-in-the-middle-5.2.0.tgz", - "integrity": "sha512-efCx3b+0Z69/LGJmm9Yvi4cqEdxnoGnxYxGxBghkkTTFeXRtTCmmhO0AnAfHz59k957uTSuy8WaHqOs8wbYUWg==", - "dependencies": { - "debug": "^4.1.1", - "module-details-from-path": "^1.0.3", - "resolve": "^1.22.1" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/require-in-the-middle/node_modules/resolve": { - "version": "1.22.11", - "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", - "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", - "dependencies": { - "is-core-module": "^2.16.1", - "path-parse": "^1.0.7", - "supports-preserve-symlinks-flag": "^1.0.0" - }, - "bin": { - "resolve": "bin/resolve" - }, - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/require-main-filename": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", @@ -4023,11 +3550,6 @@ "node": ">= 4" } }, - "node_modules/rndm": { - "version": "1.2.0", - "resolved": "https://registry.npmjs.org/rndm/-/rndm-1.2.0.tgz", - "integrity": "sha512-fJhQQI5tLrQvYIYFpOnFinzv9dwmR7hRnUz1XqP3OJ1jIweTNOd6aTO4jwQSgcBSFUB+/KHJxuGneime+FdzOw==" - }, "node_modules/run-async": { "version": "4.0.6", "resolved": "https://registry.npmjs.org/run-async/-/run-async-4.0.6.tgz", @@ -4089,15 +3611,11 @@ "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==" }, - "node_modules/sax": { - "version": "1.4.3", - "resolved": "https://registry.npmjs.org/sax/-/sax-1.4.3.tgz", - "integrity": "sha512-yqYn1JhPczigF94DMS+shiDMjDowYO6y9+wB/4WgO0Y19jWYk0lQ4tuG5KI7kj4FTp1wxPj5IFfcrz/s1c3jjQ==" - }, "node_modules/semver": { - "version": "7.7.3", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", - "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "version": "7.8.0", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.0.tgz", + "integrity": "sha512-AcM7dV/5ul4EekoQ29Agm5vri8JNqRyj39o0qpX6vDF2GZrtutZl5RwgD1XnZjiTAfncsJhMI48QQH3sN87YNA==", + "license": "ISC", "bin": { "semver": "bin/semver.js" }, @@ -4194,15 +3712,11 @@ "resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz", "integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==" }, - "node_modules/shimmer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/shimmer/-/shimmer-1.2.1.tgz", - "integrity": "sha512-sQTKC1Re/rM6XyFM6fIAGHRPVGvyXfgzIDvzoq608vM+jeyVD0Tu1E6Np0Kc2zAIFWIj963V2800iF/9LPieQw==" - }, "node_modules/side-channel": { "version": "1.1.0", "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "license": "MIT", "dependencies": { "es-errors": "^1.3.0", "object-inspect": "^1.13.3", @@ -4218,12 +3732,13 @@ } }, "node_modules/side-channel-list": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", - "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.1.tgz", + "integrity": "sha512-mjn/0bi/oUURjc5Xl7IaWi/OJJJumuoJFQJfDDyO46+hBWsfaVM65TBHq2eoZBhzl9EchxOijpkbRC8SVBQU0w==", + "license": "MIT", "dependencies": { "es-errors": "^1.3.0", - "object-inspect": "^1.13.3" + "object-inspect": "^1.13.4" }, "engines": { "node": ">= 0.4" @@ -4236,6 +3751,7 @@ "version": "1.0.1", "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "license": "MIT", "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", @@ -4253,6 +3769,7 @@ "version": "1.0.2", "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "license": "MIT", "dependencies": { "call-bound": "^1.0.2", "es-errors": "^1.3.0", @@ -4287,6 +3804,7 @@ "version": "4.2.0", "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", "engines": { "node": ">= 6.0.0", "npm": ">= 3.0.0" @@ -4310,84 +3828,35 @@ } }, "node_modules/socket.io-adapter": { - "version": "2.5.5", - "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.5.tgz", - "integrity": "sha512-eLDQas5dzPgOWCk9GuuJC2lBqItuhKI4uxGgo9aIV7MYbk2h9Q6uULEh8WBzThoI7l+qU9Ast9fVUmkqPP9wYg==", + "version": "2.5.7", + "resolved": "https://registry.npmjs.org/socket.io-adapter/-/socket.io-adapter-2.5.7.tgz", + "integrity": "sha512-e0LyK91f3cUxTmv95/KzoLg47+zF+s/sbxRGDNsyG4dmIP8ZSX8ax6byOxfJXeNNtS/8AZlfD+uP7gBeR7DLlg==", + "license": "MIT", "dependencies": { - "debug": "~4.3.4", - "ws": "~8.17.1" - } - }, - "node_modules/socket.io-adapter/node_modules/debug": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", - "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/socket.io-adapter/node_modules/ws": { - "version": "8.17.1", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", - "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } + "debug": "~4.4.1", + "ws": "~8.20.1" } }, "node_modules/socket.io-parser": { - "version": "4.2.4", - "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.4.tgz", - "integrity": "sha512-/GbIKmo8ioc+NIWIhwdecY0ge+qVBSMdgxGygevmdHj24bsfgtCmcUUcQ5ZzcylGFHsN3k4HB4Cgkl96KVnuew==", + "version": "4.2.6", + "resolved": "https://registry.npmjs.org/socket.io-parser/-/socket.io-parser-4.2.6.tgz", + "integrity": "sha512-asJqbVBDsBCJx0pTqw3WfesSY0iRX+2xzWEWzrpcH7L6fLzrhyF8WPI8UaeM4YCuDfpwA/cgsdugMsmtz8EJeg==", + "license": "MIT", "dependencies": { "@socket.io/component-emitter": "~3.1.0", - "debug": "~4.3.1" + "debug": "~4.4.1" }, "engines": { "node": ">=10.0.0" } }, - "node_modules/socket.io-parser/node_modules/debug": { - "version": "4.3.7", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.7.tgz", - "integrity": "sha512-Er2nc/H7RrMXZBFCEim6TCmMk02Z8vLC2Rbi1KEBggpo0fS6l0S1nnapwmIi3yW/+GOJap1Krg4w0Hg80oCqgQ==", - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, "node_modules/socks": { - "version": "2.8.7", - "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.7.tgz", - "integrity": "sha512-HLpt+uLy/pxB+bum/9DzAgiKS8CX1EvbWxI4zlmgGCExImLdiad2iCwXT5Z4c9c3Eq8rP2318mPW2c+QbtjK8A==", + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz", + "integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==", + "license": "MIT", "dependencies": { - "ip-address": "^10.0.1", + "ip-address": "^10.1.1", "smart-buffer": "^4.2.0" }, "engines": { @@ -4399,6 +3868,7 @@ "version": "8.0.5", "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "license": "MIT", "dependencies": { "agent-base": "^7.1.2", "debug": "^4.3.4", @@ -4412,19 +3882,12 @@ "version": "0.6.1", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "license": "BSD-3-Clause", + "optional": true, "engines": { "node": ">=0.10.0" } }, - "node_modules/source-map-support": { - "version": "0.5.21", - "resolved": "https://registry.npmjs.org/source-map-support/-/source-map-support-0.5.21.tgz", - "integrity": "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w==", - "dependencies": { - "buffer-from": "^1.0.0", - "source-map": "^0.6.0" - } - }, "node_modules/speakeasy": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/speakeasy/-/speakeasy-2.0.0.tgz", @@ -4437,11 +3900,6 @@ "node": ">= 0.10.0" } }, - "node_modules/sprintf-js": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.2.tgz", - "integrity": "sha512-VE0SOVEHCk7Qc8ulkWw3ntAzXuqf7S2lvwQaDLRnUeIEaKNQJzV6BwmLKhOqT61aGhfUMrXeaBk+oDGCzvhcug==" - }, "node_modules/sqlstring": { "version": "2.3.3", "resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz", @@ -4453,7 +3911,8 @@ "node_modules/standard-as-callback": { "version": "2.1.0", "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", - "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==" + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==", + "license": "MIT" }, "node_modules/statuses": { "version": "2.0.1", @@ -4525,21 +3984,11 @@ "node": ">=4" } }, - "node_modules/supports-preserve-symlinks-flag": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", - "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", - "engines": { - "node": ">= 0.4" - }, - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, "node_modules/systeminformation": { - "version": "5.27.14", - "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.27.14.tgz", - "integrity": "sha512-3DoNDYSZBLxBwaJtQGWNpq0fonga/VZ47HY1+7/G3YoIPaPz93Df6egSzzTKbEMmlzUpy3eQ0nR9REuYIycXGg==", + "version": "5.31.7", + "resolved": "https://registry.npmjs.org/systeminformation/-/systeminformation-5.31.7.tgz", + "integrity": "sha512-/8NC53e5nP9nmhn42/ncdOkyJnOoue/Vy+tJOyUGd1Yv66G069wK4rrziwhrqDETgk78CudTQupw5z19S5uoZw==", + "license": "MIT", "optional": true, "os": [ "darwin", @@ -4610,14 +4059,6 @@ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==" }, - "node_modules/tsscmp": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/tsscmp/-/tsscmp-1.0.6.tgz", - "integrity": "sha512-LxhtAkPDTkVCMQjt2h6eBVY28KCjikZqZfMcC15YBeNjkgUpdCfBu5HoiOTDu86v6smE8yOjyEktJ8hlbANHQA==", - "engines": { - "node": ">=0.6.x" - } - }, "node_modules/tv4": { "version": "1.3.0", "resolved": "https://registry.npmjs.org/tv4/-/tv4-1.3.0.tgz", @@ -4710,18 +4151,6 @@ "node": ">= 0.4.0" } }, - "node_modules/uuid": { - "version": "11.1.0", - "resolved": "https://registry.npmjs.org/uuid/-/uuid-11.1.0.tgz", - "integrity": "sha512-0/A9rDy9P7cJ+8w1c9WD9V//9Wj15Ce2MPz8Ri6032usz+NfePxx5AcN3bN+r6ZL6jEo066/yNYB3tn4pQEx+A==", - "funding": [ - "https://github.com/sponsors/broofa", - "https://github.com/sponsors/ctavan" - ], - "bin": { - "uuid": "dist/esm/bin/uuid" - } - }, "node_modules/vary": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/vary/-/vary-1.1.2.tgz", @@ -4769,9 +4198,9 @@ } }, "node_modules/ws": { - "version": "8.19.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", - "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "version": "8.21.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz", + "integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==", "license": "MIT", "engines": { "node": ">=10.0.0" diff --git a/package.json b/package.json index 44e7bd7..f05ca7e 100644 --- a/package.json +++ b/package.json @@ -14,13 +14,12 @@ "ansi_up": "^6.0.6", "bcrypt": "^6.0.0", "bcryptjs": "^3.0.3", - "busboy": "^1.6.0", "bullmq": "^5.66.7", + "busboy": "^1.6.0", "chalk": "^5.6.2", "compression": "^1.8.1", "connect-redis": "^9.0.0", "cookie-parser": "^1.4.7", - "csurf": "^1.11.0", "dotenv": "^17.2.3", "ejs": "^3.1.10", "express": "^4.19.2", @@ -35,7 +34,7 @@ "mysql2": "^3.11.5", "nodemon": "^3.1.14", "ora": "^9.3.0", - "pm2": "^6.0.14", + "pm2": "^7.0.1", "qrcode": "^1.5.4", "qrcode-terminal": "^0.12.0", "rate-limit-redis": "^4.3.1", @@ -44,7 +43,7 @@ "socket.io": "^4.8.3", "speakeasy": "^2.0.0", "tar": "^7.5.13", - "ws": "^8.19.0" + "ws": "^8.21.0" }, "description": "
\"ADPanel ", "repository": { @@ -57,5 +56,8 @@ "bugs": { "url": "https://github.com/antonndev/ADPanel/issues" }, - "homepage": "https://github.com/antonndev/ADPanel#readme" -} + "homepage": "https://github.com/antonndev/ADPanel#readme", + "overrides": { + "ws": "^8.21.0" + } +} \ No newline at end of file diff --git a/patch_bot_css.js b/patch_bot_css.js new file mode 100644 index 0000000..e6b8865 --- /dev/null +++ b/patch_bot_css.js @@ -0,0 +1,150 @@ +const fs = require('fs'); +const file = 'public/css/bot.css'; +let content = fs.readFileSync(file, 'utf8'); + +const oldStr = `.sidebar-middle { + flex: 1; + display: flex; + flex-direction: column; + gap: 8px; + justify-content: center; + position: relative; +} + +.sidebar-bottom { + padding-top: 6px; + border-top: 1px solid rgba(255, 255, 255, 0.05); + position: relative; + margin: 0 9px; +} + +.sidebar-item { + width: 100%; + display: flex; + align-items: center; + gap: 12px; + padding: 9px 19px; + border-radius: 12px; + background: transparent; + border: none; + color: #e3e9f3; + cursor: pointer; + justify-content: flex-start; + transition: background .15s ease, transform .15s ease, color .15s ease, padding .15s ease; +} + +.sidebar-shell.open:not(:hover) .sidebar-item { + justify-content: center !important; + padding-left: 0 !important; + padding-right: 0 !important; + gap: 0 !important; +} + +.sidebar-item .icon { + width: 28px; + height: 28px; + border-radius: 10px; + display: grid; + place-items: center; + background: transparent; + box-shadow: none; + font-size: 16px; + flex-shrink: 0; +} + +.sidebar-item .label { + opacity: 0; + transform: translateX(-6px); + white-space: nowrap; + transition: opacity .12s ease, transform .12s ease; +} + +.sidebar-shell.open .sidebar-item .label { + display: inline-block; + max-width: 0; + opacity: 0; + overflow: hidden; + transition: max-width .25s ease, opacity .25s ease, transform .25s ease; +} + +.sidebar-shell.open:hover .sidebar-item { + padding: 9px 20px; +} + +.sidebar-shell.open:hover .sidebar-item .label { + max-width: 150px; + opacity: 1; + transform: translateX(0); +}`; + +const newStr = `.sidebar-middle { + flex: 1; + display: flex; + flex-direction: column; + gap: 8px; + justify-content: center; + position: relative; + margin: 0 9px; +} + +.sidebar-bottom { + padding-top: 6px; + border-top: 1px solid rgba(255, 255, 255, 0.05); + position: relative; + margin: 0 9px; +} + +.sidebar-item { + width: 100%; + display: flex; + align-items: center; + gap: 12px; + padding: 9px 11px; + border-radius: 12px; + background: transparent; + border: none; + color: #e3e9f3; + cursor: pointer; + justify-content: flex-start; + transition: background .15s ease, transform .15s ease, color .15s ease; +} + +.sidebar-item .icon { + width: 28px; + height: 28px; + border-radius: 10px; + display: grid; + place-items: center; + background: transparent; + box-shadow: none; + font-size: 16px; + flex-shrink: 0; +} + +.sidebar-item .label { + opacity: 0; + transform: translateX(-6px); + white-space: nowrap; + transition: opacity .12s ease, transform .12s ease; +} + +.sidebar-shell.open .sidebar-item .label { + display: inline-block; + max-width: 0; + opacity: 0; + overflow: hidden; + transition: max-width .25s ease, opacity .25s ease, transform .25s ease; +} + +.sidebar-shell.open:hover .sidebar-item .label { + max-width: 150px; + opacity: 1; + transform: translateX(0); +}`; + +if (content.includes(oldStr)) { + fs.writeFileSync(file, content.replace(oldStr, newStr)); + console.log('Successfully patched bot.css sidebar item'); +} else { + console.log('Old string not found in bot.css!'); +} diff --git a/patch_rest.js b/patch_rest.js new file mode 100644 index 0000000..0f374af --- /dev/null +++ b/patch_rest.js @@ -0,0 +1,100 @@ +const fs = require('fs'); +let cssContent = fs.readFileSync('public/css/bot.css', 'utf8'); + +const oldProfileStr = `.sidebar-shell.open .profile-card { + justify-content: flex-start; + padding: 9px 16px; +} + +.sidebar-shell.open:not(:hover) .profile-card { + justify-content: center !important; + padding-left: 0 !important; + padding-right: 0 !important; + gap: 0 !important; +} + +.sidebar-shell.open:hover .profile-card { + justify-content: flex-start; + padding: 9px 17px; +}`; + +const newProfileStr = `.sidebar-shell.open .profile-card { + justify-content: flex-start; + padding: 9px 8px; +}`; + +if (cssContent.includes(oldProfileStr)) { + fs.writeFileSync('public/css/bot.css', cssContent.replace(oldProfileStr, newProfileStr)); + console.log('Successfully patched bot.css profile card'); +} else { + console.log('Old string not found in bot.css profile card!'); +} + +let ejsContent = fs.readFileSync('views/bot.ejs', 'utf8'); +const oldEjsStr = ` .sidebar-shell.open .sidebar-item, + .sidebar-shell.open .profile-card { + transition: + background 0.2s ease, + transform 0.2s ease, + color 0.2s ease, + padding 0.38s cubic-bezier(0.22, 1, 0.36, 1); + } + + .sidebar-shell.open .sidebar-item .label, + .sidebar-shell.open .profile-meta { + transition: + max-width 0.36s cubic-bezier(0.22, 1, 0.36, 1), + opacity 0.26s ease, + transform 0.36s cubic-bezier(0.22, 1, 0.36, 1); + transition-delay: 0s; + }`; + +const newEjsStr = ` .sidebar-shell.open .sidebar-item, + .sidebar-shell.open .profile-card { + transition: + background 0.2s ease, + transform 0.2s ease, + color 0.2s ease; + } + + .sidebar-shell.open .sidebar-item .label, + .sidebar-shell.open .profile-meta { + transition: + max-width 0.36s cubic-bezier(0.22, 1, 0.36, 1), + opacity 0.26s ease, + transform 0.36s cubic-bezier(0.22, 1, 0.36, 1); + transition-delay: 0s; + }`; + +if (ejsContent.includes(oldEjsStr)) { + fs.writeFileSync('views/bot.ejs', ejsContent.replace(oldEjsStr, newEjsStr)); + console.log('Successfully patched bot.ejs transitions'); +} else { + console.log('Old string not found in bot.ejs transitions!'); +} + +const oldEjsStr2 = ` .sidebar-shell.open:hover .sidebar-item .label, + .sidebar-shell.open:hover .profile-meta { + transition-delay: 0.08s; + } + + .sidebar-shell.open:not(:hover) .sidebar-item .label, + .sidebar-shell.open:not(:hover) .profile-meta { + transition-delay: 0s; + } + + #cmdInput,`; + +const newEjsStr2 = ` .sidebar-shell.open:hover .sidebar-item .label, + .sidebar-shell.open:hover .profile-meta { + transition-delay: 0.08s; + } + + .sidebar-shell.open:not(:hover) .sidebar-item .label, + .sidebar-shell.open:not(:hover) .profile-meta { + transition-delay: 0s; + } + + #cmdInput,`; + +// Just to check everything is fine diff --git a/public/css/bot.css b/public/css/bot.css index 7050ac3..6da0ad1 100644 --- a/public/css/bot.css +++ b/public/css/bot.css @@ -1,5 +1,5 @@ :root { - --ui-bg: url("/images/waves.png?v=1776616961314"); + --ui-bg: url("/images/waves.png?v=1780686309159"); } .ptero-flash-bar { @@ -229,7 +229,7 @@ } .progress-file-name { - min-width: 0; + min-max-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -365,7 +365,7 @@ textarea, overflow: auto; padding: 12px; border-radius: 8px; - background: #0b0c0e; + background: #0b0f19; white-space: pre-wrap; position: relative; width: 1100px; @@ -690,7 +690,7 @@ textarea, } .store-pref-copy { - min-width: 0; + min-max-width: 0; } .store-pref-title { @@ -907,11 +907,11 @@ textarea, display: flex; align-items: center; gap: 14px; - min-width: 0; + min-max-width: 0; } .entry-text-wrap { - min-width: 0; + min-max-width: 0; } .entry-icon { @@ -946,7 +946,7 @@ textarea, font-weight: 600; color: var(--text); letter-spacing: -0.01em; - min-width: 0; + min-max-width: 0; } .entry.renaming { @@ -962,7 +962,7 @@ textarea, .entry-rename-input { width: 100%; - min-width: 150px; + min-max-width: 150px; max-width: 320px; height: 30px; border-radius: 8px; @@ -1110,6 +1110,248 @@ textarea, scrollbar-width: none; } +/* ============ Mini File Manager (inside Monaco editor) ============ */ +.code-shell-editor { + flex: 1 1 0; + min-width: 0; + position: relative; + display: flex; + align-items: stretch; +} + +.mini-fm { + flex: 0 0 auto; + width: 280px; + max-width: 60%; + display: flex; + flex-direction: column; + min-height: 0; + background: rgba(20, 23, 30, 0.96); + border-left: 0.5px solid rgba(255, 255, 255, 0.08); + box-shadow: -8px 0 30px rgba(0, 0, 0, 0.28); + transition: width 0.28s cubic-bezier(0.22, 1, 0.36, 1), + opacity 0.2s ease, transform 0.28s cubic-bezier(0.22, 1, 0.36, 1); + overflow: hidden; + resize: horizontal; +} + +.code-shell.mini-fm-collapsed .mini-fm { + width: 0 !important; + opacity: 0; + pointer-events: none; + transform: translateX(12px); + border-left-color: transparent; +} + +.mini-fm-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + padding: 10px 12px; + border-bottom: 0.5px solid rgba(255, 255, 255, 0.06); + background: rgba(255, 255, 255, 0.02); + flex: 0 0 auto; +} + +.mini-fm-header-main { + display: flex; + align-items: center; + gap: 9px; + min-width: 0; +} + +.mini-fm-header-icon { + width: 28px; + height: 28px; + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: center; + border-radius: 8px; + background: rgba(80, 140, 255, 0.14); + color: #6ea8ff; + font-size: 13px; +} + +.mini-fm-header-text { + min-width: 0; +} + +.mini-fm-title { + font-weight: 700; + font-size: 12px; + letter-spacing: 0.02em; + color: #eef2f7; +} + +.mini-fm-breadcrumbs { + font-size: 11px; + color: var(--muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 170px; +} + +.mini-fm-breadcrumbs .file-crumb { + color: var(--muted); + text-decoration: none; +} + +.mini-fm-breadcrumbs .file-crumb:hover { + color: #6ea8ff; +} + +.mini-fm-breadcrumbs .file-crumb-separator { + color: rgba(255, 255, 255, 0.25); + margin: 0 2px; +} + +.mini-fm-header-actions { + display: flex; + align-items: center; + gap: 4px; + flex: 0 0 auto; +} + +.mini-fm-icon-btn { + width: 28px; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 8px; + border: 0.5px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + color: var(--muted); + cursor: pointer; + font-size: 12px; + transition: background 0.18s ease, color 0.18s ease, border-color 0.18s ease; +} + +.mini-fm-icon-btn:hover { + background: rgba(255, 255, 255, 0.08); + color: #eef2f7; + border-color: rgba(255, 255, 255, 0.16); +} + +.mini-fm-entries { + list-style: none; + margin: 0; + padding: 6px; + overflow-y: auto; + flex: 1 1 0; + min-height: 0; + scrollbar-width: thin; +} + +.mini-fm-entry { + display: flex; + align-items: center; + gap: 10px; + padding: 7px 9px; + border-radius: 9px; + cursor: pointer; + color: var(--text); + transition: background 0.15s ease; + user-select: none; +} + +.mini-fm-entry:hover { + background: rgba(255, 255, 255, 0.06); +} + +.mini-fm-entry.active { + background: rgba(80, 140, 255, 0.16); +} + +.mini-fm-entry-icon { + width: 26px; + height: 26px; + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: center; + border-radius: 7px; + background: rgba(255, 255, 255, 0.05); + color: #9aa4b2; + font-size: 12px; +} + +.mini-fm-entry-icon.folder { + background: rgba(255, 196, 84, 0.14); + color: #ffc454; +} + +.mini-fm-entry-icon.up { + background: rgba(255, 255, 255, 0.06); + color: #9aa4b2; +} + +.mini-fm-entry-text { + min-width: 0; + flex: 1 1 auto; +} + +.mini-fm-entry-name { + font-size: 12.5px; + font-weight: 600; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + color: #e6eaf0; +} + +.mini-fm-entry-meta { + font-size: 10.5px; + color: var(--muted); +} + +.mini-fm-empty { + padding: 14px 10px; + color: var(--muted); + font-size: 12px; + text-align: center; +} + +.mini-fm-toggle { + position: absolute; + top: 12px; + right: 292px; + z-index: 6; + width: 32px; + height: 32px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 9px; + border: 0.5px solid rgba(255, 255, 255, 0.1); + background: rgba(20, 23, 30, 0.85); + backdrop-filter: blur(8px); + color: #cdd5e0; + cursor: pointer; + font-size: 13px; + transition: background 0.18s ease, color 0.18s ease, right 0.28s cubic-bezier(0.22, 1, 0.36, 1); +} + +.mini-fm-toggle:hover { + background: rgba(40, 44, 54, 0.95); + color: #fff; +} + +.mini-fm-toggle i { + transition: transform 0.28s cubic-bezier(0.22, 1, 0.36, 1); +} + +.code-shell.mini-fm-collapsed .mini-fm-toggle { + right: 12px; +} + +.code-shell.mini-fm-collapsed .mini-fm-toggle i { + transform: rotate(180deg); +} + #monacoContainer { background: #1e1e1e; isolation: isolate; @@ -1180,7 +1422,7 @@ textarea, } .code-shell::-webkit-scrollbar { - width: 0; + max-width: 0; height: 0; } @@ -1208,7 +1450,7 @@ textarea, .line-gutter::-webkit-scrollbar { display: none; - width: 0; + max-width: 0; height: 0; } @@ -1229,7 +1471,7 @@ textarea, } .code-pane::-webkit-scrollbar { - width: 0; + max-width: 0; height: 0; } @@ -1369,6 +1611,24 @@ textarea { max-width: calc(100vw - 36px); display: flex; justify-content: center; + backdrop-filter: blur(15px) saturate(150%) !important; + -webkit-backdrop-filter: blur(15px) saturate(150%) !important; + background: transparent !important; + border-radius: 16px; +} + +@media (max-height: 300px) { + .dock-wrap, + .dock-wrap *, + .dock, + .dock *, + .dock-item, + .dock-item * { + display: none !important; + visibility: hidden !important; + opacity: 0 !important; + pointer-events: none !important; + } } .dock { @@ -1381,8 +1641,9 @@ textarea { max-width: 100%; border: none; box-shadow: 0 8px 26px rgba(0, 0, 0, 0.45); - backdrop-filter: blur(14px) saturate(150%); - background: transparent; + backdrop-filter: blur(15px) saturate(150%) !important; + -webkit-backdrop-filter: blur(15px) saturate(150%) !important; + background: transparent !important; align-items: center; } @@ -1754,7 +2015,7 @@ textarea { .store-provider-body { flex: 1; - min-width: 0; + min-max-width: 0; } .store-provider-name { @@ -1789,7 +2050,7 @@ textarea { align-items: center; gap: 12px; flex: 1; - min-width: 0; + min-max-width: 0; padding: 10px 12px; border-radius: 14px; background: rgba(255, 255, 255, 0.04); @@ -1869,7 +2130,7 @@ textarea { } .store-version-meta { - min-width: 0; + min-max-width: 0; } .store-version-name { @@ -1909,7 +2170,7 @@ textarea { .store-custom-version-input { width: 210px; - min-width: 0; + min-max-width: 0; height: 38px; border: 0; border-radius: 10px; @@ -2074,7 +2335,7 @@ textarea { } .mr-plugin-body { - min-width: 0; + min-max-width: 0; } .mr-plugin-title { @@ -2241,7 +2502,7 @@ textarea { } #mrPluginModal .activity-header-left { - min-width: 0; + min-max-width: 0; gap: 14px; } @@ -2481,9 +2742,10 @@ textarea { .icon-btn { border-radius: 10px; border: none; - background: rgba(255, 255, 255, 0.04); + background: transparent !important; color: #e6eef8; - backdrop-filter: blur(10px); + backdrop-filter: blur(15px) saturate(150%) !important; + -webkit-backdrop-filter: blur(15px) saturate(150%) !important; padding: 8px 12px; font-weight: 400; cursor: pointer; @@ -2494,7 +2756,48 @@ textarea { .icon-btn:hover { background: rgba(255, 255, 255, 0.10); - transform: translateY(-1px); + transform: scale(1.05); +} + +.topbar .icon-btn { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.topbar .icon-btn:hover { + transform: scale(1.05); +} + +.top-action-hidden { + display: none; + opacity: 0; + transform: translateX(20px); +} + +.top-actions.expanded { + margin-right: 20px !important; + gap: 8px; +} + +.top-actions.expanded .top-action-hidden { + display: inline-flex; + animation: slideInFromRight 0.3s ease forwards; +} + +.top-actions.expanded .top-action-visible#moreBtn { + display: none; +} + +@keyframes slideInFromRight { + from { + opacity: 0; + transform: translateX(20px); + } + to { + opacity: 1; + transform: translateX(0); + } } .modal { @@ -2616,6 +2919,63 @@ textarea { box-shadow: none; } +.cmd-arrows { + position: absolute; + left: 14px; + top: 50%; + transform: translateY(-50%); + color: #5a5a5a; + font-size: 16px; + font-weight: 900; + user-select: none; + line-height: 1; + pointer-events: none; + z-index: 1; +} + +#sendBtn, +#clearBtn { + position: relative; + background: transparent !important; + border-color: transparent !important; + display: inline-flex; + align-items: center; + gap: 6px; + color: #e6eef8 !important; + font-weight: 400 !important; + font-size: 13px !important; + z-index: 1; +} + +#sendBtn::before, +#clearBtn::before { + content: ""; + position: absolute; + top: 0; left: 0; right: 0; bottom: 0; + background: rgba(255, 255, 255, 0.04); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + border: 1px solid rgba(255, 255, 255, 0.03); + border-radius: inherit; + z-index: -1; + pointer-events: none; + transition: transform 0.15s ease, background 0.15s ease, box-shadow 0.15s ease; +} + +#sendBtn:hover, +#clearBtn:hover { + transform: none !important; + background: transparent !important; + box-shadow: none; +} + +#sendBtn:hover::before, +#clearBtn:hover::before { + transform: scale(1.04); + background: rgba(255, 255, 255, 0.10); + box-shadow: 0 10px 30px rgba(2, 6, 23, 0.5); +} + .sidebar-toggle { position: fixed; left: 25px; @@ -2653,8 +3013,7 @@ textarea { --sidebar-height: 480px; top: var(--sidebar-top); left: 12px; - transform: none; - transform: none; + transform: translate3d(0, 0, 0); width: 68px !important; height: var(--sidebar-height); backdrop-filter: blur(5px); @@ -2669,8 +3028,14 @@ textarea { gap: 10px; opacity: 0; pointer-events: none; - transition: width .22s ease, opacity .18s ease, transform .22s ease; + transition: + width 0.6s cubic-bezier(0.4, 0, 0.2, 1), + opacity 0.5s cubic-bezier(0.4, 0, 0.2, 1), + box-shadow 0.6s cubic-bezier(0.4, 0, 0.2, 1), + background-color 0.6s cubic-bezier(0.4, 0, 0.2, 1); z-index: 2200; + will-change: width, opacity; + overflow: visible; } .sidebar-shell * { @@ -2687,14 +3052,29 @@ textarea { pointer-events: auto; } +@media (max-width: 941px) { + .sidebar-shell.open { + display: none !important; + } +} + .sidebar-shell.open:hover { width: 220px !important; + box-shadow: + 0 18px 44px rgba(0, 0, 0, 0.34), + inset 0 1px 0 rgba(255, 255, 255, 0.08); + background-color: rgba(255, 255, 255, 0.062); + transition: + width 0.6s cubic-bezier(0.4, 0, 0.2, 1), + box-shadow 0.6s cubic-bezier(0.4, 0, 0.2, 1), + background-color 0.6s cubic-bezier(0.4, 0, 0.2, 1); } .sidebar-top { padding-bottom: 6px; border-bottom: 1px solid rgba(255, 255, 255, 0.05); margin: 0 9px; + overflow: visible; } .sidebar-middle { @@ -2704,6 +3084,8 @@ textarea { gap: 8px; justify-content: center; position: relative; + margin: 0 9px; + overflow: visible; } .sidebar-bottom { @@ -2711,6 +3093,7 @@ textarea { border-top: 1px solid rgba(255, 255, 255, 0.05); position: relative; margin: 0 9px; + overflow: visible; } .sidebar-item { @@ -2718,21 +3101,15 @@ textarea { display: flex; align-items: center; gap: 12px; - padding: 9px 19px; + padding: 9px 11px; border-radius: 12px; background: transparent; border: none; color: #e3e9f3; cursor: pointer; justify-content: flex-start; - transition: background .15s ease, transform .15s ease, color .15s ease, padding .15s ease; -} - -.sidebar-shell.open:not(:hover) .sidebar-item { - justify-content: center !important; - padding-left: 0 !important; - padding-right: 0 !important; - gap: 0 !important; + transition: background 0.15s ease; + contain: layout style paint; } .sidebar-item .icon { @@ -2749,9 +3126,10 @@ textarea { .sidebar-item .label { opacity: 0; - transform: translateX(-6px); white-space: nowrap; - transition: opacity .12s ease, transform .12s ease; + transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1); + will-change: opacity; + pointer-events: none; } .sidebar-shell.open .sidebar-item .label { @@ -2759,22 +3137,19 @@ textarea { max-width: 0; opacity: 0; overflow: hidden; - transition: max-width .25s ease, opacity .25s ease, transform .25s ease; -} - -.sidebar-shell.open:hover .sidebar-item { - padding: 9px 20px; + transition: max-width 0.6s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.5s cubic-bezier(0.4, 0, 0.2, 1); + will-change: opacity; } .sidebar-shell.open:hover .sidebar-item .label { max-width: 150px; opacity: 1; - transform: translateX(0); + transition: max-width 0.6s cubic-bezier(0.4, 0, 0.2, 1) 0.1s, opacity 0.5s cubic-bezier(0.4, 0, 0.2, 1) 0.1s; + pointer-events: auto; } .sidebar-shell.open:hover .sidebar-item:hover { background: rgba(255, 255, 255, 0.05); - transform: translateY(-1px); } .sidebar-item.active { @@ -2792,7 +3167,8 @@ textarea { border: 1px solid rgba(255, 255, 255, 0.05); color: #e3e9f3; cursor: pointer; - transition: background .15s ease, border-color .15s ease; + transition: background 0.15s ease, border-color 0.15s ease; + contain: layout style paint; } .profile-card:hover { @@ -2824,13 +3200,15 @@ textarea { flex-direction: column; gap: 4px; text-align: left; + transition: opacity 0.3s cubic-bezier(0.4, 0, 0.2, 1); + will-change: opacity; } .profile-email { font-weight: 700; font-size: 13px; color: #e9eef7; - max-width: 150px; + max-max-width: 150px; overflow: hidden; text-overflow: ellipsis; } @@ -2856,6 +3234,7 @@ textarea { left: 70px; bottom: 6px; width: 220px; + max-height: 400px; background: rgba(8, 12, 18, 0.98); border: 1px solid rgba(255, 255, 255, 0.08); border-radius: 12px; @@ -2865,6 +3244,7 @@ textarea { flex-direction: column; gap: 10px; z-index: 2400; + overflow-y: auto; } .status-popover.show { @@ -3038,9 +3418,10 @@ textarea { visibility: hidden; pointer-events: none; transition: opacity 0.22s ease, visibility 0.22s ease, transform 0.22s ease, left 0.22s ease; - z-index: 9999; + z-index: 9999999; isolation: isolate; transform: translateY(10px); + position: fixed; } .resource-stats-popup.visible { @@ -3117,7 +3498,7 @@ textarea { .resource-stat-row { display: flex; - align-items: center; + align-items: flex-start; gap: 12px; background: rgba(255, 255, 255, 0.03); border: 1px solid rgba(255, 255, 255, 0.05); @@ -3140,6 +3521,7 @@ textarea { font-size: 16px; flex-shrink: 0; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); + margin-top: 4px; } .resource-stat-icon.memory-icon { @@ -3172,9 +3554,18 @@ textarea { color: #fbbf24; } -.resource-stat-info { +.resource-stat-content { flex: 1; min-width: 0; + display: flex; + flex-direction: column; + gap: 4px; +} + +.resource-stat-label-line { + display: flex; + align-items: center; + gap: 8px; } .resource-stat-label { @@ -3183,7 +3574,7 @@ textarea { text-transform: uppercase; letter-spacing: 0.8px; font-weight: 600; - margin-bottom: 4px; + white-space: nowrap; } .resource-stat-value { @@ -3191,17 +3582,15 @@ textarea { font-weight: 600; color: #f1f5f9; white-space: nowrap; - overflow: hidden; - text-overflow: ellipsis; text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2); } .resource-stat-bar { - width: 54px; height: 6px; background: rgba(255, 255, 255, 0.08); border-radius: 3px; overflow: hidden; + width: 60px; flex-shrink: 0; } @@ -3233,30 +3622,20 @@ textarea { max-width: 0; opacity: 0; overflow: hidden; - transition: max-width .25s ease, opacity .25s ease; + transition: max-width 0.6s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.5s cubic-bezier(0.4, 0, 0.2, 1); white-space: nowrap; + will-change: opacity; } .sidebar-shell.open .profile-card { justify-content: flex-start; - padding: 9px 16px; -} - -.sidebar-shell.open:not(:hover) .profile-card { - justify-content: center !important; - padding-left: 0 !important; - padding-right: 0 !important; - gap: 0 !important; -} - -.sidebar-shell.open:hover .profile-card { - justify-content: flex-start; - padding: 9px 17px; + padding: 9px 8px; } .sidebar-shell.open:hover .profile-meta { max-width: 200px; opacity: 1; + transition: max-width 0.6s cubic-bezier(0.4, 0, 0.2, 1) 0.1s, opacity 0.5s cubic-bezier(0.4, 0, 0.2, 1) 0.1s; } .notfound-modal { @@ -3417,7 +3796,7 @@ textarea { body>svg:first-child { position: absolute; - width: 0; + max-width: 0; height: 0; pointer-events: none; } @@ -4026,7 +4405,7 @@ body { .activity-entry-content { flex: 1; - min-width: 0; + min-max-width: 0; } .activity-entry-action { @@ -4437,7 +4816,7 @@ body { .info-card-content { flex: 1; - min-width: 0; + min-max-width: 0; } .info-card-label { @@ -5075,7 +5454,7 @@ body { .scheduler-task-info { flex: 1; - min-width: 0; + min-max-width: 0; } .scheduler-task-name { @@ -5389,7 +5768,7 @@ body { .scheduler-ai-model-selector { width: 100%; - min-width: 0; + min-max-width: 0; max-width: none; flex: 0 1 auto; z-index: 80; @@ -5561,7 +5940,7 @@ body { display: flex; align-items: center; gap: 18px; - min-width: 0; + min-max-width: 0; } .planner-icon-wrap { @@ -5603,7 +5982,7 @@ body { display: flex; flex-direction: column; gap: 2px; - min-width: 0; + min-max-width: 0; opacity: 0; animation: textFadeIn 0.4s ease 0.2s forwards; } @@ -5910,7 +6289,7 @@ body { .planner-item-main { flex: 1; - min-width: 0; + min-max-width: 0; background: none; border: none; padding: 0; @@ -5938,7 +6317,7 @@ body { } .planner-item-title-wrap { - min-width: 0; + min-max-width: 0; } .planner-item-title { @@ -6363,7 +6742,7 @@ body { #backupsModal .backup-item-main { flex: 1; - min-width: 0; + min-max-width: 0; display: flex; align-items: flex-start; gap: 16px; @@ -6389,7 +6768,7 @@ body { #backupsModal .backup-item-info { flex: 1; - min-width: 0; + min-max-width: 0; } #backupsModal .backup-item-name { @@ -6709,7 +7088,7 @@ body { align-items: center; gap: 14px; flex: 1; - min-width: 0; + min-max-width: 0; } .backup-item-icon { @@ -6728,7 +7107,7 @@ body { .backup-item-info { flex: 1; - min-width: 0; + min-max-width: 0; } .backup-item-name { @@ -7544,7 +7923,7 @@ body { .ai-provider-info { flex: 1; - min-width: 0; + min-max-width: 0; } .ai-provider-name { @@ -7749,7 +8128,7 @@ body { display: flex; flex-direction: row; min-height: 0; - min-width: 0; + min-max-width: 0; overflow-x: hidden; } @@ -7766,8 +8145,8 @@ body { } .ai-chat-sidebar.collapsed { - width: 0; - min-width: 0; + max-width: 0; + min-max-width: 0; overflow: hidden; border-right: none; } @@ -7848,7 +8227,7 @@ body { text-align: left; box-sizing: border-box; width: 100%; - min-width: 0; + min-max-width: 0; gap: 8px; position: relative; } @@ -7981,7 +8360,7 @@ body { flex: 1; display: flex; flex-direction: column; - min-width: 0; + min-max-width: 0; position: relative; overflow-x: hidden; } @@ -8119,7 +8498,7 @@ body { position: relative; z-index: 1; width: 100%; - min-width: 0; + min-max-width: 0; padding: 13px 42px 13px 16px; background: rgba(255, 255, 255, 0.04); border: 1px solid rgba(255, 255, 255, 0.1); @@ -8166,7 +8545,7 @@ body { .ai-model-current { display: block; width: 100%; - min-width: 0; + min-max-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; @@ -8304,7 +8683,7 @@ body { } .ai-model-option-name { - min-width: 0; + min-max-width: 0; white-space: normal; line-height: 1.35; word-break: break-word; @@ -9574,7 +9953,7 @@ body { .ai-file-change-info { flex: 1; - min-width: 0; + min-max-width: 0; } .ai-file-change-path { @@ -10247,7 +10626,7 @@ body { } .access-denied-decor-2 { - width: 200px; + max-width: 200px; height: 200px; background: radial-gradient(circle, rgba(168, 85, 247, 0.25), transparent); bottom: -100px; @@ -10866,7 +11245,7 @@ button, .switch input { opacity: 0; - width: 0; + max-width: 0; height: 0; } @@ -11085,7 +11464,7 @@ button, .switch input { opacity: 0; - width: 0; + max-width: 0; height: 0; } @@ -11778,7 +12157,7 @@ button, } #filesModal .file-toolbar-left { - min-width: 0; + min-max-width: 0; } #filesModal .file-toolbar-icon { @@ -11963,12 +12342,12 @@ button, } #filesModal .entry-left { - min-width: 0; + min-max-width: 0; gap: 12px; } #filesModal .entry-text-wrap { - min-width: 0; + min-max-width: 0; } #filesModal .entry-icon { @@ -12069,7 +12448,7 @@ button, } #filesModal .entry-rename-input { - min-width: 0; + min-max-width: 0; max-width: none; height: 32px; letter-spacing: 0; @@ -12332,7 +12711,7 @@ button, } #filesModal .file-toolbar-meta { - min-width: 0; + min-max-width: 0; } #filesModal .file-toolbar-actions { @@ -12503,7 +12882,7 @@ button, .file-breadcrumbs { display: flex; align-items: center; - min-width: 0; + min-max-width: 0; gap: 6px; overflow: hidden; white-space: nowrap; @@ -12511,7 +12890,7 @@ button, .file-crumb, .file-crumb:visited { - min-width: 0; + min-max-width: 0; max-width: 220px; display: inline-flex; align-items: center; @@ -12828,7 +13207,7 @@ button, backface-visibility: hidden; isolation: isolate; transform-origin: center center; - will-change: opacity, transform; + will-change: opacity, max-width; } .modal-overlay.show > .modal, @@ -12885,7 +13264,7 @@ button, .dock-wrap { transform: translate3d(-50%, 0, 0); transition: opacity 0.22s ease, transform 0.22s ease; - will-change: opacity, transform; + will-change: opacity, max-width; } .dock-wrap.dock-hidden { @@ -13040,7 +13419,7 @@ button, animation-timing-function: var(--adp-modal-ease); backdrop-filter: blur(48px) saturate(135%) brightness(1.03); -webkit-backdrop-filter: blur(48px) saturate(135%) brightness(1.03); - will-change: opacity, transform; + will-change: opacity, max-width; } @keyframes storePanelScaleIn { @@ -13105,7 +13484,7 @@ button, .store-custom-version-form { width: 100%; - min-width: 0; + min-max-width: 0; flex-direction: column; align-items: stretch; } @@ -13261,3 +13640,96 @@ button, transition-duration: 1ms !important; } } + +/* Store progress bar */ +#storeModal .ptero-flash-bar { + border-radius: 18px 18px 0 0; +} + +/* Store toast */ +.store-toast { + position: fixed; + bottom: 28px; + left: 50%; + transform: translateX(-50%) translateY(20px); + background: rgba(15, 20, 30, 0.92); + border: 1px solid rgba(255,255,255,0.10); + backdrop-filter: blur(18px); + -webkit-backdrop-filter: blur(18px); + color: #e6eef8; + font-size: 13px; + font-weight: 500; + padding: 10px 20px; + border-radius: 12px; + box-shadow: 0 8px 32px rgba(0,0,0,0.45); + z-index: 999999; + pointer-events: none; + opacity: 0; + transition: opacity 0.2s ease, transform 0.2s ease; + white-space: nowrap; + display: flex; + align-items: center; + gap: 8px; +} +.store-toast.show { + opacity: 1; + transform: translateX(-50%) translateY(0); +} +.store-toast.toast-error { + border-color: rgba(239,68,68,0.35); + color: #fca5a5; +} +.store-toast.toast-success { + border-color: rgba(96,165,250,0.35); + color: #93c5fd; +} + +/* Store confirm overlay */ +.store-confirm-overlay { + position: fixed; + inset: 0; + background: rgba(0,0,0,0.55); + backdrop-filter: blur(4px); + -webkit-backdrop-filter: blur(4px); + z-index: 999998; + display: flex; + align-items: center; + justify-content: center; + opacity: 0; + pointer-events: none; + transition: opacity 0.18s ease; +} +.store-confirm-overlay.show { + opacity: 1; + pointer-events: all; +} +.store-confirm-box { + background: rgba(12, 16, 24, 0.96); + border: 1px solid rgba(255,255,255,0.10); + border-radius: 16px; + padding: 28px 28px 22px; + max-width: 380px; + width: 90%; + box-shadow: 0 20px 60px rgba(0,0,0,0.5); + display: flex; + flex-direction: column; + align-items: center; + gap: 14px; + text-align: center; +} +.store-confirm-icon { + font-size: 28px; + color: #f59e0b; +} +.store-confirm-msg { + color: #e6eef8; + font-size: 14px; + line-height: 1.55; +} +.store-confirm-actions { + display: flex; + gap: 10px; + margin-top: 4px; + width: 100%; + justify-content: center; +} diff --git a/public/css/dashboard.css b/public/css/dashboard.css index 851b9a4..b5877be 100644 --- a/public/css/dashboard.css +++ b/public/css/dashboard.css @@ -1,5 +1,5 @@ :root { - --ui-bg: url("/images/waves.png?v=1776616961314"); + --ui-bg: url("/images/waves.png?v=1780686309159"); } .btn-primary { @@ -32,6 +32,43 @@ filter: brightness(0.96); } + /* ── Navbar Create pill — overrides for the later-loaded stylesheet ── + This file is loaded AFTER dashboard.css, so the pill animation rules + must be restated here or .btn-primary above would cancel them + (its `transition` omits width/border-radius/padding/gap, which made the + expand/collapse look instant). Open state is toggled via JS (.is-open). */ + .btn-primary.create-btn { + position: relative; + overflow: hidden; + width: 44px; + height: 44px; + min-height: 44px; + padding: 0; + gap: 0; + border: none; + border-radius: 50%; + justify-content: center; + transition: + width 0.4s cubic-bezier(0.65, 0, 0.35, 1), + border-radius 0.4s cubic-bezier(0.65, 0, 0.35, 1), + padding 0.4s cubic-bezier(0.65, 0, 0.35, 1), + gap 0.4s cubic-bezier(0.65, 0, 0.35, 1), + filter 0.4s ease; + } + + .btn-primary.create-btn:hover { + transform: none; + } + + .btn-primary.create-btn.is-open, + .btn-primary.create-btn:focus-visible { + width: 124px; + padding: 0 18px; + gap: 9px; + border-radius: 999px; + filter: brightness(1.06); + } + .btn-ghost { background: rgba(15, 23, 42, 0.85); border: none; @@ -781,10 +818,6 @@ align-items: center; } - .faplusbutton { - margin-right: 6px; - } - .footer-inner { align-items: center; gap: 16px; @@ -812,6 +845,10 @@ background: var(--ui-bg) center/cover no-repeat fixed !important; } + body.modal-open { + overflow: hidden; + } + /* Quick Action Custom Scale Animation - Independent Element Scaling */ .quick-action.qa-anim-scale { position: relative; @@ -909,11 +946,14 @@ } #topbar-spacer { - height: 104px; + height: 73px; + min-height: 73px; + flex-shrink: 0; } .dashboard { - margin-top: 46px; + margin-top: 20px; + min-height: auto; } .top-bar { @@ -972,6 +1012,8 @@ } .brand-title { + font-family: 'Inter', sans-serif; + font-weight: 700; letter-spacing: -0.012em; } @@ -1019,13 +1061,6 @@ object-fit: cover; } - .btn-primary.create-btn { - border-radius: 999px; - padding-inline: 18px; - min-height: 42px; - outline: none; - } - .top-bar .btn-primary.create-btn:focus, .top-bar .btn-primary.create-btn:focus-visible, .top-bar .btn-primary.create-btn:active { diff --git a/public/css/ssh-terminal-window.css b/public/css/ssh-terminal-window.css new file mode 100644 index 0000000..c854847 --- /dev/null +++ b/public/css/ssh-terminal-window.css @@ -0,0 +1,399 @@ +.adp-ssh-terminal-window { + position: fixed; + left: 0; + top: 0; + width: min(var(--adp-ssh-w, 960px), calc(100vw - 16px)); + height: min(var(--adp-ssh-h, 640px), calc(100vh - 16px)); + min-width: min(360px, calc(100vw - 16px)); + min-height: 260px; + display: flex; + flex-direction: column; + overflow: hidden; + border-radius: 14px; + border: 1px solid rgba(148, 163, 184, 0.24); + background: #020617; + box-shadow: 0 18px 52px rgba(0, 0, 0, 0.48), 0 0 0 1px rgba(15, 23, 42, 0.64); + z-index: 2147483000; + opacity: 0; + transform: translate3d(var(--adp-ssh-x, 24px), var(--adp-ssh-y, 24px), 0) scale(0.985); + transform-origin: top left; + transition: opacity 140ms ease, transform 180ms cubic-bezier(0.2, 0.8, 0.2, 1); + contain: layout paint style; + isolation: isolate; + backface-visibility: hidden; +} + +.adp-ssh-terminal-window::before, +.adp-ssh-terminal-window::after { + content: ""; + position: absolute; + pointer-events: none; + border-radius: inherit; +} + +.adp-ssh-terminal-window::before { + inset: 0; + z-index: 2; + background: + radial-gradient(circle at 18% 0%, rgba(255, 255, 255, 0.17), transparent 28%), + linear-gradient(145deg, rgba(255, 255, 255, 0.12), transparent 32%, rgba(45, 212, 191, 0.08) 72%, transparent); + opacity: 0.28; +} + +.adp-ssh-terminal-window::after { + inset: -58%; + z-index: 6; + opacity: 0; + background: + radial-gradient(ellipse at 50% 50%, rgba(255, 255, 255, 0.34), rgba(45, 212, 191, 0.16) 28%, transparent 58%), + linear-gradient(105deg, transparent 34%, rgba(255, 255, 255, 0.42) 48%, transparent 62%); + transform: translate3d(-42%, -22%, 0) rotate(9deg) scale(0.78); +} + +.adp-ssh-terminal-window.is-ready { + opacity: 1; + transform: translate3d(var(--adp-ssh-x, 24px), var(--adp-ssh-y, 24px), 0) scale(1); +} + +.adp-ssh-terminal-window.is-liquid-motion { + will-change: transform, opacity; +} + +.adp-ssh-terminal-window.is-liquid-motion::before { + opacity: 0.5; +} + +.adp-ssh-terminal-window.is-liquid-motion::after { + animation: adp-ssh-tahoe-sheen 520ms cubic-bezier(0.16, 1, 0.3, 1) both; + will-change: transform, opacity; +} + +.adp-ssh-terminal-window.is-motion-minimize::after { + animation-duration: 460ms; +} + +.adp-ssh-terminal-window.is-motion-close::after { + animation-duration: 260ms; + animation-timing-function: cubic-bezier(0.4, 0, 1, 1); +} + +.adp-ssh-terminal-window.is-motion-lite::after { + display: none; +} + +.adp-ssh-terminal-window.is-interacting { + transition: none; + user-select: none; + will-change: transform, width, height; +} + +.adp-ssh-terminal-window.is-interacting .adp-ssh-terminal-frame { + pointer-events: none; +} + +.adp-ssh-terminal-window.is-minimized { + width: min(380px, calc(100vw - 24px)); + height: 38px; + min-height: 38px; + border-radius: 12px; + border-color: rgba(45, 212, 191, 0.38); +} + +.adp-ssh-terminal-titlebar { + position: relative; + z-index: 4; + height: 34px; + flex: 0 0 34px; + display: grid; + grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr); + align-items: center; + gap: 8px; + padding: 0 8px 0 11px; + border-bottom: 1px solid rgba(148, 163, 184, 0.15); + background: linear-gradient(180deg, rgba(15, 23, 42, 0.98), rgba(2, 6, 23, 0.98)); + color: #d1d5db; + cursor: grab; + touch-action: none; +} + +.adp-ssh-terminal-window.is-dragging .adp-ssh-terminal-titlebar { + cursor: grabbing; +} + +.adp-ssh-terminal-title { + min-width: 0; + display: flex; + align-items: center; + gap: 8px; + font: 600 12px/1 Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; + color: rgba(226, 232, 240, 0.92); + letter-spacing: 0; +} + +.adp-ssh-terminal-title i { + color: #2dd4bf; + font-size: 12px; +} + +.adp-ssh-terminal-title span { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.adp-ssh-terminal-grip { + width: 58px; + height: 4px; + border-radius: 999px; + background: rgba(148, 163, 184, 0.42); + justify-self: center; +} + +.adp-ssh-terminal-controls { + position: relative; + z-index: 7; + justify-self: end; + display: flex; + align-items: center; + gap: 6px; +} + +.adp-ssh-terminal-control { + width: 24px; + height: 24px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 6px; + border: 1px solid rgba(148, 163, 184, 0.18); + background: rgba(15, 23, 42, 0.78); + color: rgba(226, 232, 240, 0.92); + cursor: pointer; + padding: 0; + transition: background-color 120ms ease, border-color 120ms ease, color 120ms ease; +} + +.adp-ssh-terminal-control:hover { + background: rgba(51, 65, 85, 0.82); + border-color: rgba(148, 163, 184, 0.34); +} + +.adp-ssh-terminal-control[data-adp-ssh-close]:hover { + background: rgba(239, 68, 68, 0.88); + border-color: rgba(248, 113, 113, 0.96); + color: #fff; +} + +.adp-ssh-terminal-frame-wrap { + position: relative; + z-index: 1; + min-height: 0; + flex: 1 1 auto; + overflow: hidden; + background: #000; +} + +.adp-ssh-terminal-window.is-minimized .adp-ssh-terminal-frame-wrap { + width: 1px; + height: 1px; + min-height: 0; + flex: 0 0 1px; + overflow: hidden; + opacity: 0; + pointer-events: none; +} + +.adp-ssh-terminal-frame { + width: 100%; + height: 100%; + border: 0; + display: block; + background: #000; +} + +.adp-ssh-terminal-resize { + position: absolute; + z-index: 5; + display: block; + touch-action: none; +} + +@keyframes adp-ssh-tahoe-sheen { + 0% { + opacity: 0; + transform: translate3d(-42%, -22%, 0) rotate(9deg) scale(0.78); + } + + 34% { + opacity: 0.95; + } + + 100% { + opacity: 0; + transform: translate3d(34%, 18%, 0) rotate(9deg) scale(1.14); + } +} + +.adp-ssh-terminal-window.is-minimized .adp-ssh-terminal-resize { + display: none; +} + +.adp-ssh-terminal-resize-n { + top: 0; + left: 16px; + right: 16px; + height: 7px; + cursor: ns-resize; +} + +.adp-ssh-terminal-resize-e { + top: 16px; + right: 0; + bottom: 16px; + width: 7px; + cursor: ew-resize; +} + +.adp-ssh-terminal-resize-s { + right: 16px; + bottom: 0; + left: 16px; + height: 7px; + cursor: ns-resize; +} + +.adp-ssh-terminal-resize-w { + top: 16px; + bottom: 16px; + left: 0; + width: 7px; + cursor: ew-resize; +} + +.adp-ssh-terminal-resize-ne, +.adp-ssh-terminal-resize-nw, +.adp-ssh-terminal-resize-se, +.adp-ssh-terminal-resize-sw { + width: 16px; + height: 16px; +} + +.adp-ssh-terminal-resize-ne { + top: 0; + right: 0; + cursor: nesw-resize; +} + +.adp-ssh-terminal-resize-nw { + top: 0; + left: 0; + cursor: nwse-resize; +} + +.adp-ssh-terminal-resize-se { + right: 0; + bottom: 0; + cursor: nwse-resize; +} + +.adp-ssh-terminal-resize-sw { + bottom: 0; + left: 0; + cursor: nesw-resize; +} + +.adp-ssh-terminal-launcher { + position: fixed; + right: 18px; + bottom: 18px; + z-index: 2147482500; + width: 42px; + height: 42px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 8px; + border: none; + background: rgba(2, 6, 23, 0.86); + color: #d1d5db; + box-shadow: 0 10px 26px rgba(0, 0, 0, 0.34); + cursor: pointer; + transition: transform 140ms ease, color 140ms ease, box-shadow 140ms ease; +} + +.adp-ssh-terminal-launcher:hover { + transform: translateY(-1px) scale(1.03); + color: #f8fafc; + box-shadow: 0 12px 30px rgba(0, 0, 0, 0.42); +} + +.adp-ssh-terminal-launcher.is-hidden { + display: none; +} + +@media (max-width: 640px) { + .adp-ssh-terminal-window { + min-width: 280px; + min-height: 220px; + border-radius: 12px; + } + + .adp-ssh-terminal-window.is-minimized { + width: min(340px, calc(100vw - 16px)); + } + + .adp-ssh-terminal-grip { + width: 42px; + } +} + +@media (pointer: coarse) { + .adp-ssh-terminal-titlebar { + height: 38px; + flex-basis: 38px; + } + + .adp-ssh-terminal-resize-n, + .adp-ssh-terminal-resize-s { + height: 12px; + } + + .adp-ssh-terminal-resize-e, + .adp-ssh-terminal-resize-w { + width: 12px; + } + + .adp-ssh-terminal-resize-ne, + .adp-ssh-terminal-resize-nw, + .adp-ssh-terminal-resize-se, + .adp-ssh-terminal-resize-sw { + width: 22px; + height: 22px; + } +} + +@media (prefers-reduced-motion: reduce), (update: slow) { + .adp-ssh-terminal-window, + .adp-ssh-terminal-launcher { + transition-duration: 60ms; + } + + .adp-ssh-terminal-window { + box-shadow: 0 12px 34px rgba(0, 0, 0, 0.42), 0 0 0 1px rgba(15, 23, 42, 0.58); + } + + .adp-ssh-terminal-window::before { + opacity: 0.28; + } + + .adp-ssh-terminal-window::after { + display: none; + } +} + +@media (prefers-reduced-transparency: reduce) { + .adp-ssh-terminal-window::before, + .adp-ssh-terminal-window::after { + display: none; + } +} diff --git a/public/css/status-monitor.css b/public/css/status-monitor.css new file mode 100644 index 0000000..b57b463 --- /dev/null +++ b/public/css/status-monitor.css @@ -0,0 +1,567 @@ +/* Admin /status monitoring page styles. + * Apple 2026 + Dieter Rams aesthetic. + * Less, but better. Honest materials. Tabular numerics. No decoration without purpose. + */ + +:root { + --monitor-font: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text", + "Inter", "Manrope", "Segoe UI", system-ui, sans-serif; + --monitor-mono: ui-monospace, "SF Mono", "JetBrains Mono", "Menlo", "Consolas", monospace; + --monitor-surface: rgba(255, 255, 255, 0.035); + --monitor-surface-strong: rgba(255, 255, 255, 0.05); + --monitor-border: rgba(255, 255, 255, 0.07); + --monitor-border-soft: rgba(255, 255, 255, 0.045); + --monitor-text: rgba(255, 255, 255, 0.95); + --monitor-text-muted: rgba(255, 255, 255, 0.55); + --monitor-text-faint: rgba(255, 255, 255, 0.38); + --monitor-accent: #22d3ee; + --monitor-accent-soft: rgba(34, 211, 238, 0.18); + --monitor-radius-card: 22px; + --monitor-radius-row: 14px; +} + +/* ===== Page shell ===== */ +.monitor { + width: min(1180px, calc(100% - 48px)); + margin: 0 auto; + padding: 8px 0 40px; + display: flex; + flex-direction: column; + gap: 22px; + font-family: var(--monitor-font); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; +} + +/* ===== Page header ===== */ +.monitor-head { + display: flex; + align-items: flex-end; + justify-content: space-between; + flex-wrap: wrap; + gap: 16px; + padding: 4px 2px 0; +} +.monitor-head h2 { + font-size: clamp(1.6rem, 3.2vh, 2.1rem); + font-weight: 600; + letter-spacing: -0.02em; + color: var(--monitor-text); + line-height: 1.15; +} +.monitor-head p { + color: var(--monitor-text-muted); + font-size: 14px; + margin-top: 6px; + line-height: 1.5; + max-width: 56ch; +} +.monitor-head__meta { + display: flex; + gap: 10px; + flex-wrap: wrap; +} +.monitor-chip { + display: inline-flex; + align-items: center; + gap: 9px; + padding: 9px 14px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.06); + border: 1px solid rgba(255, 255, 255, 0.12); + color: var(--monitor-text-muted); + font-size: 13px; + font-weight: 500; + letter-spacing: 0.005em; + font-variant-numeric: tabular-nums; + -webkit-backdrop-filter: blur(24px) saturate(180%); + backdrop-filter: blur(24px) saturate(180%); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.12) inset, + 0 -1px 0 rgba(0, 0, 0, 0.18) inset, + 0 8px 22px rgba(0, 0, 0, 0.28); + transition: transform 0.22s cubic-bezier(0.22, 0.61, 0.36, 1), + background 0.22s ease, border-color 0.22s ease; +} +.monitor-chip:hover { + background: rgba(255, 255, 255, 0.09); + border-color: rgba(255, 255, 255, 0.16); + transform: translateY(-1px); +} +.monitor-chip strong { + color: var(--monitor-text); + font-weight: 600; +} +.monitor-chip i { + color: var(--monitor-accent); + font-size: 12.5px; + width: 14px; + text-align: center; +} + +/* ===== Card surface ===== */ +.monitor-card { + background: var(--monitor-surface); + border: 1px solid var(--monitor-border-soft); + border-radius: var(--monitor-radius-card); + padding: 24px 26px; + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.04) inset, + 0 18px 40px rgba(0, 0, 0, 0.22); + -webkit-backdrop-filter: blur(14px) saturate(140%); + backdrop-filter: blur(14px) saturate(140%); +} +.monitor-card__title { + display: flex; + align-items: center; + gap: 9px; + font-size: 12.5px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: none; + color: var(--monitor-text-muted); + margin-bottom: 22px; +} +.monitor-card__title i { + color: var(--monitor-accent); + font-size: 13px; + width: 16px; + text-align: center; +} + +/* ===== Metrics Hero Grid (Apple-inspired circular cards) ===== */ +.metrics-hero { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + gap: 20px; + margin-bottom: 8px; +} + +.metric-card { + position: relative; + background: var(--monitor-surface); + border: 1px solid var(--monitor-border-soft); + border-radius: var(--monitor-radius-card); + padding: 36px 28px 28px; + display: flex; + flex-direction: column; + align-items: center; + min-height: 260px; + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.04) inset, + 0 18px 40px rgba(0, 0, 0, 0.22); + -webkit-backdrop-filter: blur(14px) saturate(140%); + backdrop-filter: blur(14px) saturate(140%); + transition: transform 0.3s cubic-bezier(0.22, 0.61, 0.36, 1), + box-shadow 0.3s ease, + border-color 0.3s ease; + overflow: visible; +} + +.metric-card:hover { + transform: translateY(-2px); + border-color: rgba(255, 255, 255, 0.12); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.06) inset, + 0 24px 48px rgba(0, 0, 0, 0.3); +} + +.metric-card__ring { + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + width: 240px; + height: 240px; + opacity: 0.5; + pointer-events: none; + z-index: 0; +} + +.metric-card__ring svg { + width: 100%; + height: 100%; + transform: rotate(0deg); +} + +.metric-card__ring-fill { + transition: stroke-dasharray 0.8s cubic-bezier(0.22, 0.61, 0.36, 1); +} + +.metric-card__icon { + width: 28px; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + font-size: 24px; + color: rgba(255, 255, 255, 0.5); + margin-bottom: 14px; + position: relative; + z-index: 1; +} + +.metric-card__label { + font-size: 13px; + font-weight: 500; + color: var(--monitor-text-muted); + letter-spacing: 0.01em; + text-align: center; + margin-bottom: 20px; + position: relative; + z-index: 1; +} + +.metric-card__value { + font-size: 48px; + font-weight: 700; + color: var(--monitor-text); + font-variant-numeric: tabular-nums; + letter-spacing: -0.03em; + line-height: 1; + margin-bottom: 8px; + position: relative; + z-index: 1; +} + +.metric-card__detail { + font-size: 12px; + color: var(--monitor-text-muted); + font-variant-numeric: tabular-nums; + text-align: center; + letter-spacing: 0.01em; + display: flex; + align-items: center; + gap: 2px; + position: relative; + z-index: 1; +} + +/* ===== Stats Row (Live metrics) ===== */ +.stats-row { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); + gap: 16px; + margin-bottom: 6px; +} + +.stat-pill { + display: flex; + align-items: center; + gap: 16px; + padding: 20px 24px; + background: var(--monitor-surface); + border: 1px solid var(--monitor-border-soft); + border-radius: var(--monitor-radius-card); + box-shadow: + 0 1px 0 rgba(255, 255, 255, 0.04) inset, + 0 12px 30px rgba(0, 0, 0, 0.18); + -webkit-backdrop-filter: blur(14px) saturate(140%); + backdrop-filter: blur(14px) saturate(140%); + transition: transform 0.25s cubic-bezier(0.22, 0.61, 0.36, 1), + border-color 0.25s ease; +} + +.stat-pill:hover { + transform: translateY(-1px); + border-color: rgba(255, 255, 255, 0.1); +} + +.stat-pill__icon { + font-size: 24px; + line-height: 1; + color: rgba(255, 255, 255, 0.5); + display: flex; + align-items: center; + justify-content: center; + width: 32px; + flex-shrink: 0; +} + +.stat-pill__body { + display: flex; + flex-direction: column; + gap: 4px; + min-width: 0; +} + +.stat-pill__label { + font-size: 12px; + color: var(--monitor-text-muted); + letter-spacing: 0.01em; + font-weight: 500; +} + +.stat-pill__value { + font-size: 24px; + font-weight: 600; + color: var(--monitor-text); + font-variant-numeric: tabular-nums; + letter-spacing: -0.02em; + line-height: 1.1; +} + +/* ===== Services grid ===== */ +.svc-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); + gap: 10px; +} +.svc-row { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 14px; + border-radius: var(--monitor-radius-row); + background: var(--monitor-surface-strong); + border: 1px solid var(--monitor-border-soft); +} +.svc-row__dot { + width: 8px; + height: 8px; + border-radius: 50%; + flex: none; + background: var(--monitor-text-faint); + transition: background 0.3s ease, box-shadow 0.3s ease; +} +.svc-row[data-state="ok"] .svc-row__dot { + background: #22c55e; + box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.12); +} +.svc-row[data-state="warn"] .svc-row__dot { + background: #f59e0b; + box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.14); +} +.svc-row[data-state="bad"] .svc-row__dot { + background: #ef4444; + box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.14); +} +.svc-row__body { min-width: 0; } +.svc-row__name { + font-size: 13.5px; + font-weight: 500; + color: var(--monitor-text); + letter-spacing: -0.005em; +} +.svc-row__val { + font-size: 12px; + color: var(--monitor-text-muted); + margin-top: 2px; + font-variant-numeric: tabular-nums; +} + +/* ===== History graph + calendar ===== */ +.graph-wrap { + display: flex; + flex-direction: column; + gap: 18px; +} +.graph-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; +} +.graph-legend { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 4px; + border-radius: 999px; + background: var(--monitor-surface); + border: 1px solid var(--monitor-border-soft); +} +.graph-legend span { + display: inline-flex; + align-items: center; + gap: 7px; + font-size: 12px; + color: var(--monitor-text-muted); + font-variant-numeric: tabular-nums; + padding: 5px 11px; + border-radius: 999px; + font-weight: 500; +} +.graph-legend i { + width: 8px; + height: 8px; + border-radius: 50%; + display: inline-block; +} +#graphLabel { + font-size: 12.5px; + color: var(--monitor-text-muted); + font-variant-numeric: tabular-nums; + font-weight: 500; + letter-spacing: 0.01em; +} +#metricsGraph { + width: 100%; + height: 220px; + display: block; + border-radius: 14px; + background: var(--monitor-surface); + border: 1px solid var(--monitor-border-soft); + padding: 14px; + box-sizing: border-box; +} + +/* Calendar */ +.calendar { margin-top: 4px; } +.calendar-head { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 14px; + gap: 12px; + flex-wrap: wrap; +} +.calendar-nav { + display: inline-flex; + align-items: center; + gap: 4px; + padding: 4px; + border-radius: 999px; + background: var(--monitor-surface); + border: 1px solid var(--monitor-border-soft); +} +.calendar-nav-btn { + width: 30px; + height: 30px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 999px; + border: none; + background: transparent; + color: var(--monitor-text-muted); + font-size: 11px; + cursor: pointer; + transition: background 0.18s ease, color 0.18s ease, transform 0.18s ease; +} +.calendar-nav-btn:hover:not(:disabled) { + background: var(--monitor-surface-strong); + color: var(--monitor-text); +} +.calendar-nav-btn:active:not(:disabled) { + transform: scale(0.94); +} +.calendar-nav-btn:disabled { + opacity: 0.3; + cursor: not-allowed; +} +.calendar-head__month { + font-size: 14.5px; + font-weight: 600; + color: var(--monitor-text); + letter-spacing: -0.01em; + padding: 0 10px; + min-width: 130px; + text-align: center; + font-variant-numeric: tabular-nums; +} +.calendar-head__hint { + font-size: 12px; + color: var(--monitor-text-faint); +} + +.cal-grid { + display: grid; + grid-template-columns: repeat(7, 1fr); + gap: 6px; +} +.cal-weekday { + text-align: center; + font-size: 10.5px; + font-weight: 600; + color: var(--monitor-text-faint); + text-transform: uppercase; + letter-spacing: 0.08em; + padding: 8px 0 10px; +} +.cal-cell { + position: relative; + aspect-ratio: 1 / 1; + border-radius: 12px; + border: 1px solid var(--monitor-border-soft); + background: var(--monitor-surface); + color: var(--monitor-text); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + padding: 0; + font-family: var(--monitor-font); + transition: + transform 0.2s cubic-bezier(0.22, 0.61, 0.36, 1), + box-shadow 0.2s ease, + background 0.2s ease, + border-color 0.2s ease; + overflow: hidden; +} +.cal-cell:hover:not(.cal-cell--blank):not(.cal-cell--active) { + transform: translateY(-1px); + background: var(--monitor-surface-strong); + border-color: rgba(255, 255, 255, 0.1); +} +.cal-cell--blank { + background: transparent; + border-color: transparent; + cursor: default; +} +.cal-cell--blank:hover { transform: none; } + +.cal-cell__num { + font-size: 13.5px; + font-weight: 500; + font-variant-numeric: tabular-nums; + letter-spacing: -0.01em; + line-height: 1; +} + +/* Active/selected day: same look as unselected, just "pressed" (sunken). */ +.cal-cell--active { + transform: scale(0.9); + background: rgba(0, 0, 0, 0.28); + border-color: rgba(255, 255, 255, 0.04); + box-shadow: + inset 0 2px 4px rgba(0, 0, 0, 0.45), + inset 0 -1px 0 rgba(255, 255, 255, 0.03); +} +.cal-cell--active .cal-cell__num { color: var(--monitor-text); } + +/* Heat indicator + today dot are intentionally hidden — minimal cells. */ +.cal-cell__heat, +.cal-cell--today .cal-cell__num::after { display: none; } + +/* ===== Responsive ===== */ +@media (max-width: 920px) { + .metrics-hero { + grid-template-columns: repeat(2, 1fr); + } +} + +@media (max-width: 720px) { + .monitor-head { align-items: flex-start; } + .monitor-head__meta { width: 100%; } + .monitor-chip { font-size: 12.5px; padding: 8px 12px; } + .calendar-head { flex-direction: column; align-items: flex-start; gap: 8px; } + .stats-row { + grid-template-columns: 1fr; + } +} + +@media (max-width: 640px) { + .monitor { width: calc(100% - 28px); } + .monitor-card { padding: 20px 18px; } + .metric-card { padding: 32px 24px 28px; min-height: 240px; } + .metric-card__value { font-size: 40px; } + .metric-card__ring { width: 210px; height: 210px; } + .metrics-hero { grid-template-columns: 1fr; gap: 16px; } + .cal-cell { padding: 4px 2px 6px; gap: 3px; } + .cal-cell__num { font-size: 12.5px; } + .cal-cell__heat { height: 2.5px; } + .monitor-chip { font-size: 12px; padding: 7px 11px; } + .stat-pill { padding: 16px 20px; } +} diff --git a/public/dashboard.css b/public/dashboard.css index 3833fb2..670ebae 100644 --- a/public/dashboard.css +++ b/public/dashboard.css @@ -38,8 +38,8 @@ body { background: url("https://cdn.pixabay.com/photo/2024/07/19/08/16/waves-8905720_1280.png") center/cover no-repeat; background-attachment: fixed; padding: 32px clamp(20px, 6vw, 72px); - scroll-snap-type: y mandatory; overflow-y: scroll; + overscroll-behavior: none; } ::-webkit-scrollbar { @@ -193,14 +193,14 @@ html.skip-dashboard-splash #splash-screen { width: 44px; height: 44px; border-radius: 50%; - border: none; - outline: none; + border: none !important; + outline: none !important; background: rgba(255, 255, 255, 0.08); color: var(--color-text); display: grid; place-items: center; cursor: pointer; - transition: transform var(--transition-base), background var(--transition-base), border var(--transition-base); + transition: transform var(--transition-base), background var(--transition-base); } .icon-button:hover { @@ -217,6 +217,13 @@ html.skip-dashboard-splash #splash-screen { background: rgb(0, 140, 254); } +.icon-button:focus, +.icon-button:focus-visible, +.icon-button:active { + border: none !important; + outline: none !important; +} + .icon-button:disabled { cursor: not-allowed; opacity: 0.6; @@ -280,12 +287,12 @@ html.skip-dashboard-splash #splash-screen { display: grid; place-items: center; cursor: pointer; - transition: transform var(--transition-base), background var(--transition-base), border var(--transition-base); + transition: transform var(--transition-base), background var(--transition-base); } .icon-butt { - border: none; - outline: none; + border: none !important; + outline: none !important; } .icon-butt i { @@ -295,7 +302,15 @@ html.skip-dashboard-splash #splash-screen { .icon-butt:hover:not(:disabled) { transform: translateY(-2px) scale(1.03); background: rgba(255, 0, 0, 0.841); - border-color: rgba(0, 255, 213, 0); + border: none !important; + outline: none !important; +} + +.icon-butt:focus, +.icon-butt:focus-visible, +.icon-butt:active { + border: none !important; + outline: none !important; } .icon-butt:disabled { @@ -306,7 +321,7 @@ html.skip-dashboard-splash #splash-screen { .dashboard { margin-top: 32px; display: grid; - gap: clamp(28px, 4vw, 48px); + gap: 30px; } .hero { @@ -314,16 +329,32 @@ html.skip-dashboard-splash #splash-screen { grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); gap: clamp(24px, 4vw, 44px); align-items: stretch; - scroll-snap-align: start; } .hero-copy { - background: var(--color-surface); - border: 1px solid var(--color-border); + position: relative; + background: rgba(30, 30, 35, 0.7); + border: 1px solid rgba(255, 255, 255, 0.08); border-radius: var(--radius-lg); padding: clamp(28px, 4vw, 40px); - box-shadow: var(--shadow-lg); - backdrop-filter: blur(18px); + box-shadow: var(--shadow-lg), inset 0 1px 0 rgba(255, 255, 255, 0.06); + backdrop-filter: blur(40px) saturate(180%); + -webkit-backdrop-filter: blur(40px) saturate(180%); + transition: background var(--transition-base), border-color var(--transition-base); +} + +.hero-copy::before { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + pointer-events: none; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 25%); +} + +.hero-copy:hover { + background: rgba(30, 30, 35, 0.78); + border-color: rgba(255, 255, 255, 0.14); } .hero-copy h2 { @@ -345,40 +376,57 @@ html.skip-dashboard-splash #splash-screen { } .pill { - border-top: 20px solid black; - border-right: 5px solid black; - border-bottom: 20px solid black; - border-left: 5px solid black; - border-radius: 5px; + border: none; + border-radius: 999px; padding: 10px 22px; - font-weight: 600; + font-weight: 500; + font-size: 14px; cursor: pointer; background: linear-gradient(135deg, #7c5cff, #4f46e5); color: white; - transition: transform var(--transition-base), box-shadow var(--transition-base); + transition: background 0.25s ease; + transition: filter 0.2s ease-in-out; + display: inline-flex; + align-items: center; + gap: 8px; } .pill--outline { background: transparent; color: var(--color-text); - border: 2px solid rgba(255, 255, 255, 0.088); + border: 1px solid rgba(255, 255, 255, 0.2); +} + +.pill--outline:hover { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.3); +} + +/* Buton Create independent cu hover gri */ +.pill.pill--create-hero { + font-weight: 500; + font-size: 14px; +} + +.pill.pill--create-hero:hover { + background: rgba(255, 255, 255, 0.12) !important; + border-color: rgba(255, 255, 255, 0.35) !important; } .pill:hover { - transform: translateY(-1px); - border: 2px solid rgba(255, 255, 255, 0.168); - box-shadow: 0 12px 24px rgba(78, 70, 229, 0.129); + background: linear-gradient(135deg, #7c5dff, #4f46e6); } .pills { border: none; border-radius: 999px; padding: 10px 22px; - font-weight: 600; + font-weight: 500; + font-size: 14px; cursor: pointer; background: linear-gradient(135deg, #7c5cff, #4f46e5); color: white; - transition: transform var(--transition-base), box-shadow var(--transition-base); + transition: background 0.25s ease; } .pills--outline { @@ -388,8 +436,7 @@ html.skip-dashboard-splash #splash-screen { } .pills:hover { - transform: translateY(-1px); - box-shadow: 0 12px 24px rgba(79, 70, 229, 0.28); + background: linear-gradient(135deg, #8c6cff, #6356f5); } .hero-stats { @@ -398,55 +445,89 @@ html.skip-dashboard-splash #splash-screen { } .stat-card { + position: relative; display: flex; align-items: center; - gap: 18px; - background: var(--color-surface); + gap: 22px; + background: rgba(30, 30, 35, 0.7); + border: 1px solid rgba(255, 255, 255, 0.08); border-radius: var(--radius-lg); padding: 20px; - box-shadow: var(--shadow-md); - backdrop-filter: blur(20px); + box-shadow: var(--shadow-md), inset 0 1px 0 rgba(255, 255, 255, 0.05); + backdrop-filter: blur(40px) saturate(180%); + -webkit-backdrop-filter: blur(40px) saturate(180%); + transition: background var(--transition-base), border-color var(--transition-base); +} + +.stat-card::before { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + pointer-events: none; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 30%); +} + +.stat-card:hover { + background: rgba(30, 30, 35, 0.78); + border-color: rgba(255, 255, 255, 0.14); } .stat-card__icon { - width: 56px; - height: 56px; - border-radius: 18px; - display: grid; - place-items: center; - font-size: 1.3rem; - color: white; + font-size: 2.2rem; + color: #818cf8; + flex-shrink: 0; } -.stat-card__icon--active { - background: linear-gradient(135deg, #34d399, #059669); +.stat-card:first-child .stat-card__icon { + font-size: 2.5rem; } -.stat-card__icon--uptime { - background: linear-gradient(135deg, #38bdf8, #1d4ed8); -} - -.stat-card__icon--deploy { - background: linear-gradient(135deg, #ffa600, #da4500); +.stat-card__content { + display: flex; + flex-direction: column; + gap: 2px; + justify-content: center; } .stat-card__label { font-size: 0.9rem; color: var(--color-text-muted); + margin: 0; + line-height: 1.1; } .stat-card__value { font-size: 1.7rem; font-weight: 700; + margin: 0; + line-height: 1.1; } .quick-actions { - background: var(--color-surface); + position: relative; + background: rgba(30, 30, 35, 0.7); border-radius: var(--radius-lg); - border: 1px solid var(--color-border); - box-shadow: var(--shadow-md); + border: 1px solid rgba(255, 255, 255, 0.08); + box-shadow: var(--shadow-md), inset 0 1px 0 rgba(255, 255, 255, 0.05); padding: clamp(24px, 4vw, 36px); - backdrop-filter: blur(14px); + backdrop-filter: blur(40px) saturate(180%); + -webkit-backdrop-filter: blur(40px) saturate(180%); + transition: background var(--transition-base), border-color var(--transition-base); +} + +.quick-actions::before { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + pointer-events: none; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 30%); +} + +.quick-actions:hover { + background: rgba(30, 30, 35, 0.78); + border-color: rgba(255, 255, 255, 0.14); } .quick-actions h3 { @@ -579,7 +660,7 @@ html.skip-dashboard-splash #splash-screen { align-items: flex-end; justify-content: space-between; gap: 16px; - margin-bottom: 20px; + margin-bottom: 40px; } .section-heading h3 { @@ -627,21 +708,73 @@ html.skip-dashboard-splash #splash-screen { .bot-grid { display: grid; - gap: 18px; - grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); + gap: 20px; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 360px), 360px)); + justify-content: center; + row-gap: 40px; + margin-top: 32px; } .bots .bot-grid { display: grid; - grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); - gap: 16px; + grid-template-columns: repeat(auto-fit, minmax(min(100%, 360px), 360px)); + gap: 20px; + row-gap: 40px; + justify-content: center; + margin-top: 32px; +} - justify-items: center; +.bot-card:only-child { + justify-self: center; + max-width: 360px; +} + +@media (max-width: 400px) { + .bot-grid, + .bots .bot-grid { + grid-template-columns: 1fr; + } +} + +@media (min-width: 401px) and (max-width: 800px) { + .bot-grid, + .bots .bot-grid { + grid-template-columns: repeat(auto-fit, minmax(320px, 360px)); + } +} + +@media (min-width: 801px) and (max-width: 1200px) { + .bot-grid, + .bots .bot-grid { + grid-template-columns: repeat(auto-fit, minmax(340px, 360px)); + max-width: 760px; + margin-left: auto; + margin-right: auto; + } +} + +@media (min-width: 1201px) and (max-width: 1600px) { + .bot-grid, + .bots .bot-grid { + grid-template-columns: repeat(auto-fit, minmax(350px, 360px)); + max-width: 1140px; + margin-left: auto; + margin-right: auto; + } +} + +@media (min-width: 1601px) { + .bot-grid, + .bots .bot-grid { + grid-template-columns: repeat(auto-fit, minmax(360px, 360px)); + max-width: 1520px; + margin-left: auto; + margin-right: auto; + } } .bots, .quick-actions { - scroll-snap-align: start; scroll-margin-top: 20px; } @@ -651,48 +784,21 @@ html.skip-dashboard-splash #splash-screen { flex-direction: column; border-radius: 20px; overflow: hidden; - background: radial-gradient(circle at 10% -10%, rgba(34, 211, 238, 0.08), transparent 26%), - radial-gradient(circle at 80% -20%, rgba(124, 92, 255, 0.12), transparent 32%), - linear-gradient(160deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.02)); + background: linear-gradient(160deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.02)); border: 1px solid rgba(255, 255, 255, 0.14); cursor: pointer; box-shadow: 0 18px 42px rgba(0, 0, 0, 0.45); - isolation: isolate; - transition: transform 0.25s ease, box-shadow 0.25s ease, border-color 0.25s ease; -} - -.bot-card::before, -.bot-card::after { - content: ""; - position: absolute; - inset: 0; - pointer-events: none; - transition: opacity 0.25s ease; -} - -.bot-card::before { - border-radius: inherit; - background: linear-gradient(135deg, rgba(34, 211, 238, 0.2), rgba(29, 78, 216, 0.12)); - opacity: 0.35; -} - -.bot-card::after { - border-radius: inherit; - background: radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.12), transparent 36%), - radial-gradient(circle at 80% 10%, rgba(14, 165, 233, 0.22), transparent 38%); - mix-blend-mode: screen; - opacity: 0.45; + will-change: transform; + transform: translateZ(0); + backface-visibility: hidden; + transition: transform 0.2s ease, box-shadow 0.2s ease; } .bot-card:hover { - transform: translateY(-1px) scale(1.005); + transform: translateY(-1px) translateZ(0); box-shadow: 0 22px 52px rgba(0, 0, 0, 0.55); } -.bot-card:hover::after { - opacity: 0.75; -} - .bot-card__hero { position: relative; min-height: 210px; @@ -705,7 +811,9 @@ html.skip-dashboard-splash #splash-screen { background: var(--bot-cover); background-size: cover; background-position: center; - filter: saturate(1.5) brightness(1); + opacity: 0.85; + will-change: transform; + transform: translateZ(0); -webkit-mask-image: linear-gradient(180deg, #fff 0%, #fff 70%, rgba(255, 255, 255, 0.65) 82%, transparent 100%); mask-image: linear-gradient(180deg, #fff 0%, #fff 70%, rgba(255, 255, 255, 0.65) 82%, transparent 100%); } @@ -713,9 +821,7 @@ html.skip-dashboard-splash #splash-screen { .bot-card__hero-overlay { position: absolute; inset: 0; - background: linear-gradient(180deg, rgba(2, 6, 23, 0.02) 0%, rgba(2, 6, 23, 0.373) 20%, rgba(2, 6, 23, 0.581) 20%), - radial-gradient(circle at 30% 20%, rgba(34, 211, 238, 0.26), transparent 70%); - mix-blend-mode: lighten; + background: linear-gradient(180deg, rgba(2, 6, 23, 0.02) 0%, rgba(2, 6, 23, 0.45) 100%); } .bot-card__hero-content { @@ -810,20 +916,20 @@ html.skip-dashboard-splash #splash-screen { .bot-card.status-online .bot-card__status-dot { color: #34d399; - background: radial-gradient(circle at 35% 35%, #e6fff2 0%, #c1ffd7 30%, #34d399 70%); - box-shadow: 0 0 0 5px rgba(52, 211, 153, 0.16), 0 0 22px rgba(52, 211, 153, 0.45); + background: #34d399; + box-shadow: 0 0 0 5px rgba(52, 211, 153, 0.16), 0 0 12px rgba(52, 211, 153, 0.45); } .bot-card.status-stopped .bot-card__status-dot { color: #e64747; - background: radial-gradient(circle at 35% 35%, #ffe4e8 0%, #ffc2cb 30%, #e64747 70%); - box-shadow: 0 0 0 5px rgba(239, 68, 68, 0.18), 0 0 22px rgba(239, 68, 68, 0.45); + background: #e64747; + box-shadow: 0 0 0 5px rgba(239, 68, 68, 0.18), 0 0 12px rgba(239, 68, 68, 0.45); } .bot-card.status-unknown .bot-card__status-dot { color: #f59e0b; - background: radial-gradient(circle at 35% 35%, #fef3c7 0%, #fde68a 30%, #f59e0b 70%); - box-shadow: 0 0 0 5px rgba(245, 158, 11, 0.16), 0 0 22px rgba(245, 158, 11, 0.35); + background: #f59e0b; + box-shadow: 0 0 0 5px rgba(245, 158, 11, 0.16), 0 0 12px rgba(245, 158, 11, 0.35); } .bot-card.status-unknown .bot-card__status-dot::before, @@ -841,7 +947,6 @@ html.skip-dashboard-splash #splash-screen { background: rgba(2, 6, 23, 0.6); border-radius: 14px; box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05); - backdrop-filter: blur(10px); } .bot-card__meta-row span { @@ -862,7 +967,6 @@ html.skip-dashboard-splash #splash-screen { background: linear-gradient(180deg, rgba(2, 6, 23, 0.86), rgba(2, 6, 23, 0.96)); border-top: 1px solid rgba(255, 255, 255, 0.1); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04); - backdrop-filter: blur(18px); } .bot-card__stat { @@ -1060,11 +1164,12 @@ html.skip-dashboard-splash #splash-screen { .footer { margin-top: 40px; - background: var(--color-surface); - border: 1px solid var(--color-border); + background: rgba(255, 255, 255, 0.06); + border: 1px solid rgba(255, 255, 255, 0.08); border-radius: var(--radius-lg); box-shadow: var(--shadow-md); - backdrop-filter: blur(14px); + backdrop-filter: blur(14px) saturate(160%); + -webkit-backdrop-filter: blur(14px) saturate(160%); } .footer-inner { @@ -1230,6 +1335,12 @@ html.skip-dashboard-splash #splash-screen { transform: none; } +.footer .btn-primary:hover { + background: linear-gradient(135deg, #10aff0, #1f52dc); + filter: none; + transform: none; +} + .btn-primary.create-btn:hover { transform: none; } @@ -1239,6 +1350,102 @@ html.skip-dashboard-splash #splash-screen { filter: brightness(0.96); } +/* ── Navbar Create pill — circle → pill expand ────────────────────────── */ +/* Open/close is driven by JS (.is-open class on mouseenter/leave + focus) so + the collapse animation always plays, even after the cursor leaves. */ +.create-btn { + position: relative; + overflow: hidden; + width: 44px; + height: 44px; + /* No horizontal padding in the circle state: the icon is centred purely by + flexbox, so the "+" sits dead-centre regardless of the (collapsed) label. */ + padding: 0; + border-radius: 50%; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 0; + /* 0.4s smooth expand / collapse */ + transition: + width 0.4s cubic-bezier(0.65, 0, 0.35, 1), + border-radius 0.4s cubic-bezier(0.65, 0, 0.35, 1), + padding 0.4s cubic-bezier(0.65, 0, 0.35, 1), + gap 0.4s cubic-bezier(0.65, 0, 0.35, 1), + filter 0.4s ease; +} + +.create-btn__icon { + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: center; + width: 14px; + height: 14px; + font-size: 14px; + line-height: 1; + /* Centred in the circle (no offset); only opacity eases when opening, + so the "+" stays dead-centre while still animating like the label. */ + opacity: 0.9; + transition: opacity 0.25s cubic-bezier(0.65, 0, 0.35, 1); +} + +.create-btn__label { + flex: 0 0 auto; + overflow: hidden; + white-space: nowrap; + /* Collapsed: pulled out of normal flow so it never offsets the centred icon */ + position: absolute; + left: 100%; + max-width: 0; + opacity: 0; + font-family: 'Inter', 'Manrope', system-ui, sans-serif; + font-size: 14px; + font-weight: 500; + line-height: 1; + letter-spacing: 0.01em; + transform: translateX(8px); + pointer-events: none; + /* Closing: label fades/slides out while the box collapses */ + transition: + max-width 0.25s cubic-bezier(0.65, 0, 0.35, 1), + opacity 0.2s cubic-bezier(0.65, 0, 0.35, 1), + transform 0.25s cubic-bezier(0.65, 0, 0.35, 1); +} + +/* Open state — toggled by JS (.is-open) and mirrored on :focus-visible */ +.create-btn.is-open, +.create-btn:focus-visible { + width: 124px; + border-radius: 999px; + /* Even left/right padding centres the icon+label group inside the pill */ + padding: 0 18px; + gap: 9px; + filter: brightness(1.06); +} + +.create-btn.is-open .create-btn__icon, +.create-btn:focus-visible .create-btn__icon { + opacity: 1; + transition: opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1) 0.08s; +} + +.create-btn.is-open .create-btn__label, +.create-btn:focus-visible .create-btn__label { + /* Back into normal flow when open, so it sits next to the icon */ + position: static; + left: auto; + max-width: 64px; + opacity: 1; + transform: translateX(0); + pointer-events: auto; + /* Opening: text eases in just after the box starts expanding */ + transition: + max-width 0.35s cubic-bezier(0.16, 1, 0.3, 1) 0.08s, + opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1) 0.12s, + transform 0.35s cubic-bezier(0.16, 1, 0.3, 1) 0.08s; +} + .btn-ghost { background: rgba(15, 23, 42, 0.85); border: none; @@ -2735,7 +2942,7 @@ html.skip-dashboard-splash #splash-screen { .account-page { max-width: 800px; margin: 0 auto; - padding: 40px 24px; + padding: 80px 24px 40px; animation: fadeInUp 0.4s ease; } diff --git a/public/images/login-background-remote-e8193864dfde27d9.jpeg b/public/images/login-background-remote-e8193864dfde27d9.jpeg new file mode 100644 index 0000000..9adfeff Binary files /dev/null and b/public/images/login-background-remote-e8193864dfde27d9.jpeg differ diff --git a/public/images/logo-ebf271a4ea9cc80f.png b/public/images/logo-ebf271a4ea9cc80f.png new file mode 100644 index 0000000..34a1d4c Binary files /dev/null and b/public/images/logo-ebf271a4ea9cc80f.png differ diff --git a/public/index-real.html b/public/index-real.html new file mode 100644 index 0000000..17a747d --- /dev/null +++ b/public/index-real.html @@ -0,0 +1,1739 @@ + + + + + + + + ADPanel + + + + + + + + + + + + + + +
+ + + + + + + + + + + + + + + + + +
+
+
+ +
+ +
+
+
+
+
+
+
+

+ t +

+

Node: +

+
+
+ +
+
+
+ + 1.2.3.4:22 + + + Custom + +
+
+
+ +
+
+
+
+
+
Memory
+
+ N/A +
+
+
+ +
+
+
+
+
+
+
Disk
+
+ N/A +
+
+
+
+
+
+
+
+
CPU
+
+ N/A +
+
+
+
+
+ + +
+
+ +
+ +
+ +
+ + + + + + + +
+
+
+
+
+ Recovery +
+
+

Recovery Code

+

Use a one-time recovery code

+
+
+ +
+ +
+
+
+ 1 + Enter one of your recovery codes +
+ +
+ +
+ Recovery codes were provided when you created your account. Each code can only be used once. +
+ +
+
+ + +
+
+ +
+
+
+
+
+ Status +
+
+

Update Status

+

Set a custom status message

+
+
+ +
+ +
+
+
+ 1 + Enter your status +
+ +
+ +
+
+ 2 + Clear after +
+ +
+ +
+
+ + +
+
+ +
+
+
+
+
+ Password +
+
+

Change Password

+

Update your account password

+
+
+ +
+ +
+
+
+
+ 1 + Enter your current password +
+
+ + +
+
+ +
+
+ 2 + Enter your 2FA code +
+ + +
+
+ + + +
+
+ Password has been successfully changed! +
+
+ + +
+
+ + +
+
+
+
+
+ 2FA +
+
+

Change 2FA Code

+

Update your authenticator app

+
+
+ +
+ +
+
+
+ 1 + Enter your current 2FA code +
+ + +
+ + + + + +
+
+ 2FA has been successfully updated! +
+
+ + +
+
+ + + + + + + + + +
+
+
+
+ +
+
+ + ADPanel +
+

Wish you merry christmas!

+
+
+
+ +
+
+
+
+ +
+
+ + ADPanel +
+

You are here to build amazing things 1 more year with ADPanel

+
+
+
+ + + + + +
+ © 2026-2026 ADPanel Dashboard +
+ + + + + + + diff --git a/public/js/bot.js b/public/js/bot.js index 3988338..aabf227 100644 --- a/public/js/bot.js +++ b/public/js/bot.js @@ -181,6 +181,82 @@ function flashFilesBar() { flashBar('filesFlashFill'); } function flashEditorBar() { flashBar('editorFlashFill'); } + // Store progress bar helpers + let _storeBarTimer = null; + function storeBarStart(msg) { + const fill = document.getElementById('storeFlashFill'); + if (!fill) return; + fill.classList.remove('complete'); + fill.style.transition = 'none'; + fill.style.width = '0%'; + void fill.offsetWidth; + fill.style.transition = ''; + fill.style.width = '30%'; + setTimeout(() => { if (fill.style.width !== '0%') fill.style.width = '65%'; }, 400); + setTimeout(() => { if (fill.style.width !== '0%') fill.style.width = '85%'; }, 1200); + } + function storeBarDone(success) { + const fill = document.getElementById('storeFlashFill'); + if (!fill) return; + fill.style.width = '100%'; + if (!success) { + fill.style.background = 'linear-gradient(90deg,#ef4444,#b91c1c,#ef4444)'; + } + setTimeout(() => { + fill.classList.add('complete'); + setTimeout(() => { + fill.classList.remove('complete'); + fill.style.width = '0%'; + fill.style.background = ''; + }, 600); + }, 200); + } + + // Store toast helper + let _storeToastTimer = null; + function showStoreToast(msg, type = 'success', duration = 3000) { + const el = document.getElementById('storeToast'); + if (!el) return; + clearTimeout(_storeToastTimer); + el.className = 'store-toast'; + const icon = type === 'error' ? '' + : type === 'success' ? '' + : ''; + el.innerHTML = icon + ' ' + msg; + el.classList.add('show', type === 'error' ? 'toast-error' : type === 'success' ? 'toast-success' : ''); + _storeToastTimer = setTimeout(() => { + el.classList.remove('show'); + }, duration); + } + + // Store confirm helper (replaces confirm()) + function storeConfirm(msg) { + return new Promise(resolve => { + const overlay = document.getElementById('storeConfirmOverlay'); + const msgEl = document.getElementById('storeConfirmMsg'); + const okBtn = document.getElementById('storeConfirmOk'); + const cancelBtn = document.getElementById('storeConfirmCancel'); + if (!overlay || !msgEl || !okBtn || !cancelBtn) { resolve(window.confirm(msg)); return; } + msgEl.textContent = msg; + overlay.setAttribute('aria-hidden', 'false'); + overlay.classList.add('show'); + function cleanup(result) { + overlay.classList.remove('show'); + overlay.setAttribute('aria-hidden', 'true'); + okBtn.removeEventListener('click', onOk); + cancelBtn.removeEventListener('click', onCancel); + overlay.removeEventListener('click', onBg); + resolve(result); + } + function onOk() { cleanup(true); } + function onCancel() { cleanup(false); } + function onBg(e) { if (e.target === overlay) cleanup(false); } + okBtn.addEventListener('click', onOk); + cancelBtn.addEventListener('click', onCancel); + overlay.addEventListener('click', onBg); + }); + } + const sio = window.io; let socket; @@ -373,8 +449,8 @@ const version = btn.getAttribute("data-version") || ""; const kind = btn.getAttribute("data-kind") || ""; if (!version) return; - if (kind === "node") changeNodeVersion(version).catch((err) => alert(err?.message || err)); - else changeVersion(version).catch((err) => alert(err?.message || err)); + if (kind === "node") changeNodeVersion(version).catch((err) => showStoreToast(err?.message || err, 'error')); + else changeVersion(version).catch((err) => showStoreToast(err?.message || err, 'error')); }); } @@ -498,9 +574,13 @@ loadStatus(); let REMOTE_MODE = false; let NODE_ONLINE = true; + let SERVER_MISSING = false; function setNodeOnline(isOnline) { NODE_ONLINE = !!isOnline; - updateOfflineState(!NODE_ONLINE); + // The overlay must reflect BOTH conditions: a node that is offline, or a node + // that is online but reports the server as missing. Keying only on offline made + // the popup stick around after the node restarted. + updateOfflineState(!NODE_ONLINE || SERVER_MISSING); } let NODE_ID = null; let NODE_API_BASE = `/api/nodes/server/${encodeURIComponent(bot)}`; @@ -509,13 +589,39 @@ let SERVER_DISK_USED_BYTES = null; let SERVER_DISK_LIMIT_BYTES = null; const currentExplorerEntryMeta = new Map(); - const remoteLogTransportMode = String(new URLSearchParams(window.location.search || '').get('logTransport') || '').trim().toLowerCase(); - const PREFER_SOCKET_REMOTE_LOGS = remoteLogTransportMode === 'socket'; let logSource = null; let activeRemoteLogUrl = ''; let remoteLogTransport = 'none'; let remoteLogFallbackTimer = null; let topoInfoPromise = null; + const INITIAL_CONSOLE_HISTORY_LIMIT = 5000; + const REMOTE_LOG_SNAPSHOT_TAIL = 5000; + // Marker prefix the node embeds to carry a console command inline in the same + // log stream as its output (single source of truth for ordering). Keep in sync + // with consoleCommandMarkerPrefix in main.go / CONSOLE_COMMAND_MARKER_PREFIX in + // index.js. When seen in the live stream, render it as a plain "> " + // line (Pterodactyl-style) instead of raw output. + const CONSOLE_COMMAND_MARKER_PREFIX = 'ADPANELCMD>> '; + function extractConsoleCommandMarker(rawLine) { + const raw = String(rawLine || ''); + const idx = raw.indexOf(CONSOLE_COMMAND_MARKER_PREFIX); + if (idx === -1) return null; + const command = raw.slice(idx + CONSOLE_COMMAND_MARKER_PREFIX.length).replace(/[\r\n]+/g, ' ').trim(); + return command || null; + } + // Render a single live stream payload, converting an embedded command marker + // into a formatted "> " line (deduplicated against the optimistic + // local echo), otherwise appending it as normal output. + function appendLiveConsoleLine(rawLine, ts = Date.now()) { + const markerCommand = extractConsoleCommandMarker(rawLine); + if (markerCommand) { + rememberConsoleCommandEcho(markerCommand, ts); + if (recentlyRenderedConsoleCommand(markerCommand, ts)) return; + appendConsoleCommandLine(markerCommand, ts); + return; + } + appendToConsole(rawLine, { live: true }); + } function clearRemoteLogFallbackTimer() { if (remoteLogFallbackTimer) { clearTimeout(remoteLogFallbackTimer); @@ -553,7 +659,7 @@ if (Number.isFinite(explicitTail) && explicitTail >= 0) { return Math.max(0, Math.trunc(explicitTail)); } - return 0; + return REMOTE_LOG_SNAPSHOT_TAIL; } function buildRemoteLogsUrl(tailCount = null) { const params = new URLSearchParams(); @@ -567,14 +673,6 @@ closeRemoteLogEventSource(); return; } - if (PREFER_SOCKET_REMOTE_LOGS) { - if (forceReconnect || remoteLogTransport !== 'socket') { - enableRemoteSocketLogFallback(); - } else { - ensureSocketConsoleJoin(); - } - return; - } const url = buildRemoteLogsUrl(tail); if (!forceReconnect && remoteLogTransport === 'eventsource' && logSource && activeRemoteLogUrl) { return; @@ -584,31 +682,24 @@ const es = new EventSource(url); logSource = es; activeRemoteLogUrl = url; - remoteLogFallbackTimer = window.setTimeout(() => { - if (remoteLogTransport === 'eventsource') { - console.debug('[remote-logs] SSE did not become active in time, falling back to socket transport'); - enableRemoteSocketLogFallback(); - } - }, 8000); - es.addEventListener('hello', (e) => { }); - es.addEventListener('keepalive', () => { }); + es.addEventListener('hello', () => { clearRemoteLogFallbackTimer(); }); + es.addEventListener('keepalive', () => { clearRemoteLogFallbackTimer(); }); es.onmessage = (ev) => { if (remoteLogTransport !== 'eventsource') return; clearRemoteLogFallbackTimer(); try { const j = JSON.parse(ev.data); if (j && typeof j.line === 'string') { - appendToConsole(j.line, { live: true }); + const messageTs = Number(j.ts || j.time || j.timestamp || 0) || 0; + if (messageTs > 0 && consoleHistoryResetAt > 0 && messageTs < consoleHistoryResetAt) return; + appendLiveConsoleLine(j.line, messageTs || Date.now()); } } catch { - appendToConsole(ev.data || "", { live: true }); + appendLiveConsoleLine(ev.data || "", Date.now()); } }; es.onerror = () => { - if (remoteLogTransport === 'eventsource') { - console.warn('[remote-logs] SSE stream failed, falling back to socket transport'); - enableRemoteSocketLogFallback(); - } + clearRemoteLogFallbackTimer(); }; } window.addEventListener('beforeunload', () => { @@ -1149,7 +1240,7 @@ ? { bot, command: trimmed, requestId: commandRequestId } : { bot, command: trimmed }; - if (!REMOTE_MODE) { + if (!REMOTE_MODE || (socket && socket.connected)) { const ack = await socketRequest('command', commandPayload); if (!ack || ack.ok === false) { const msg = String((ack && (ack.error || ack.detail)) || 'command_failed'); @@ -1159,6 +1250,12 @@ return true; } + await fetch(`/api/servers/${encodeURIComponent(bot)}/console-history/command`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ command: trimmed }) + }).catch(() => { }); + const r = await fetch(`${NODE_API_BASE}/command`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(commandRequestId ? { command: trimmed, requestId: commandRequestId } : { command: trimmed }) @@ -1416,7 +1513,7 @@ id: 'minecraft', title: 'Minecraft Servers', description: 'Choose Minecraft cores and browse plugins/mods like Paper, Spigot, or Purpur.', - logo: 'https://cdn.freebiesupply.com/logos/large/2x/minecraft-1-logo-png-transparent.png' + logo: 'https://cdn.jsdelivr.net/gh/antonndev/ADCDn/minecraft-logo.webp' }, { id: 'fivem', @@ -1688,6 +1785,156 @@ return null; } } + const CONSOLE_COMMAND_HISTORY_LIMIT = 32; + const consoleCommandHistoryKey = `adpanel:${bot}:command_history`; + const CONSOLE_COMMAND_ECHO_HISTORY_LIMIT = 80; + const consoleCommandEchoHistoryKey = `adpanel:${bot}:command_echo_history`; + const consoleHistoryResetKey = `adpanel:${bot}:console_history_reset_at`; + const RECENT_SUBMITTED_COMMAND_TTL_MS = 2 * 60 * 1000; + const recentSubmittedConsoleCommands = new Map(); + let consoleCommandHistory = loadConsoleCommandHistory(); + let consoleCommandHistoryIndex = -1; + let consoleCommandEchoHistory = loadConsoleCommandEchoHistory(); + let consoleHistoryResetAt = loadConsoleHistoryResetAt(); + + function normalizeConsoleCommandText(value) { + return visibleConsoleText(String(value || '')) + .replace(/[\r\n]+/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + } + + function normalizeConsoleCommandKey(value) { + let text = normalizeConsoleCommandText(value); + if ( + text.length >= 2 && + ((text.startsWith('"') && text.endsWith('"')) || (text.startsWith("'") && text.endsWith("'"))) + ) { + text = text.slice(1, -1).trim(); + } + return text; + } + + function firstConsoleCommandToken(value) { + const text = normalizeConsoleCommandKey(value); + if (!text) return ''; + if (text.startsWith('"') || text.startsWith("'")) { + const quote = text[0]; + const end = text.indexOf(quote, 1); + return end > 1 ? text.slice(1, end).trim() : ''; + } + return text.split(/\s+/, 1)[0] || ''; + } + + function pruneRecentSubmittedConsoleCommands(now = Date.now()) { + for (const [key, ts] of recentSubmittedConsoleCommands.entries()) { + if ((now - ts) > RECENT_SUBMITTED_COMMAND_TTL_MS) { + recentSubmittedConsoleCommands.delete(key); + } + } + } + + function rememberSubmittedConsoleCommand(commandText, sentAt = Date.now()) { + const key = normalizeConsoleCommandKey(commandText); + if (!key) return; + pruneRecentSubmittedConsoleCommands(sentAt); + recentSubmittedConsoleCommands.set(key, sentAt); + if (recentSubmittedConsoleCommands.size > 80) { + const oldest = recentSubmittedConsoleCommands.keys().next().value; + if (oldest) recentSubmittedConsoleCommands.delete(oldest); + } + } + + function knownConsoleCommandSets() { + pruneRecentSubmittedConsoleCommands(); + const exact = new Set(); + const first = new Set(); + const duplicated = new Set(); + const commands = []; + const addCommand = (value) => { + const key = normalizeConsoleCommandKey(value); + if (!key) return; + exact.add(key); + commands.push(key); + const token = firstConsoleCommandToken(key); + if (token) first.add(token); + const duplicate = duplicatedFirstConsoleCommandEcho(key); + if (duplicate) duplicated.add(duplicate); + }; + for (const key of recentSubmittedConsoleCommands.keys()) { + addCommand(key); + } + if (Array.isArray(consoleCommandHistory)) { + for (const entry of consoleCommandHistory) { + addCommand(entry); + } + } + if (Array.isArray(consoleCommandEchoHistory)) { + for (const entry of consoleCommandEchoHistory) { + addCommand(entry && entry.command); + } + } + return { exact, first, duplicated, commands }; + } + + function isKnownConsoleCommandText(value, sets = knownConsoleCommandSets(), allowFirstToken = false) { + const key = normalizeConsoleCommandKey(value); + if (!key) return false; + return sets.exact.has(key) || (allowFirstToken && sets.first.has(key)); + } + + function duplicatedFirstConsoleCommandEcho(value) { + const command = normalizeConsoleCommandKey(value); + if (!command) return ''; + const chars = Array.from(command); + return chars.length ? chars[0] + command : ''; + } + + function isPrefixedConsoleCommandEchoArtifact(value, commandValue) { + const text = normalizeConsoleCommandKey(value); + const command = normalizeConsoleCommandKey(commandValue); + if (!text || !command || text === command) return false; + if (!text.endsWith(command)) return false; + const prefix = text.slice(0, text.length - command.length); + return !!prefix && command.startsWith(prefix); + } + + function isRecentDuplicatedConsoleCommandEcho(value) { + const key = normalizeConsoleCommandKey(value); + if (!key) return false; + const now = Date.now(); + pruneRecentSubmittedConsoleCommands(now); + for (const [command, ts] of recentSubmittedConsoleCommands.entries()) { + if ((now - Number(ts || 0)) > 15000) continue; + if (key === duplicatedFirstConsoleCommandEcho(command)) return true; + } + return false; + } + + function shouldDropConsoleCommandArtifact(visibleLine) { + const text = normalizeConsoleCommandText(visibleLine); + if (!text) return false; + if (isRecentDuplicatedConsoleCommandEcho(text)) return true; + const known = knownConsoleCommandSets(); + if (isKnownConsoleCommandText(text, known, false)) return true; + if (known.duplicated && known.duplicated.has(text)) return true; + if (Array.isArray(known.commands) && known.commands.some((command) => isPrefixedConsoleCommandEchoArtifact(text, command))) return true; + + let match = text.match(/^\$\s+(.+)$/); + if (match && isKnownConsoleCommandText(match[1], known, false)) return true; + + match = text.match(/^(?:\/bin\/)?sh:\s+\d+:\s+(.+?):\s+not found$/i); + if (match && isKnownConsoleCommandText(match[1], known, true)) return true; + + match = text.match(/^(?:\/bin\/)?bash:\s+line\s+\d+:\s+(.+?):\s+command not found$/i); + if (match && isKnownConsoleCommandText(match[1], known, true)) return true; + + match = text.match(/^(?:\/bin\/)?bash:\s+(.+?):\s+command not found$/i); + if (match && isKnownConsoleCommandText(match[1], known, true)) return true; + + return false; + } + function clientClean(raw) { if (!raw) return ""; let s = decodeHtmlEntities(raw); @@ -1721,6 +1968,7 @@ if (/Error response from daemon:\s*No such container/i.test(t)) continue; if (/^\s*\[init\]\s/i.test(t)) continue; if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d+Z,?version=.*$/i.test(t)) continue; + if (shouldDropConsoleCommandArtifact(t)) continue; out.push(line); } let joined = out.join("\n"); @@ -1747,7 +1995,11 @@ function ansiToHtml(text) { if (!text) return ""; - let result = getAnsiUp().ansi_to_html(text); + // Strip all ANSI color codes EXCEPT the sent command color (38;5;75m) and reset code (0m) + let result = text.replace(/\x1b\[(?!(?:38;5;75|0)m)[0-9;]*m/g, ''); + + // Process remaining codes (only light blue for sent commands + reset) with ansi_up + result = getAnsiUp().ansi_to_html(result); result = result.replace( /(https?:\/\/[^\s<>"']+)/gi, @@ -1765,10 +2017,6 @@ let lastCommandRequestId = ""; let pendingConsoleHistoryResyncTimer = null; let lastConsoleLiveAt = 0; - const CONSOLE_COMMAND_HISTORY_LIMIT = 32; - const consoleCommandHistoryKey = `adpanel:${bot}:command_history`; - let consoleCommandHistory = loadConsoleCommandHistory(); - let consoleCommandHistoryIndex = -1; function loadConsoleCommandHistory() { try { @@ -1789,6 +2037,138 @@ } catch { } } + function loadConsoleCommandEchoHistory() { + try { + const parsed = JSON.parse(localStorage.getItem(consoleCommandEchoHistoryKey) || '[]'); + if (!Array.isArray(parsed)) return []; + return parsed + .map((entry) => ({ + command: normalizeConsoleCommandKey(entry && entry.command), + ts: Number(entry && entry.ts) || Date.now() + })) + .filter((entry) => entry.command) + .slice(0, CONSOLE_COMMAND_ECHO_HISTORY_LIMIT); + } catch { + return []; + } + } + + function persistConsoleCommandEchoHistory() { + try { + localStorage.setItem(consoleCommandEchoHistoryKey, JSON.stringify(consoleCommandEchoHistory.slice(0, CONSOLE_COMMAND_ECHO_HISTORY_LIMIT))); + } catch { } + } + + function loadConsoleHistoryResetAt() { + try { + const value = Number(localStorage.getItem(consoleHistoryResetKey) || 0); + return Number.isFinite(value) && value > 0 ? value : 0; + } catch { + return 0; + } + } + + function persistConsoleHistoryResetAt() { + try { + if (consoleHistoryResetAt > 0) { + localStorage.setItem(consoleHistoryResetKey, String(consoleHistoryResetAt)); + } else { + localStorage.removeItem(consoleHistoryResetKey); + } + } catch { } + } + + function applyConsoleHistoryReset(resetAt = Date.now(), options = {}) { + const ts = Number(resetAt || Date.now()) || Date.now(); + const previous = consoleHistoryResetAt || 0; + consoleHistoryResetAt = Math.max(previous, ts); + if (consoleHistoryResetAt !== previous && options.persist !== false) { + persistConsoleHistoryResetAt(); + } + consoleCommandEchoHistory = consoleCommandEchoHistory + .filter((entry) => (Number(entry && entry.ts) || 0) >= consoleHistoryResetAt); + persistConsoleCommandEchoHistory(); + recentSubmittedConsoleCommands.clear(); + if (options.resetBuffer !== false) resetConsoleBuffer(); + } + + function resetLocalConsoleHistorySession() { + applyConsoleHistoryReset(Date.now()); + try { + closeRemoteLogEventSource(); + attachLogStreamIfRemote({ tail: 0, forceReconnect: true }); + } catch { } + return true; + } + + function rememberConsoleCommandEcho(commandText, sentAt = Date.now()) { + const command = normalizeConsoleCommandKey(commandText); + if (!command) return; + rememberSubmittedConsoleCommand(command, sentAt); + const ts = Number(sentAt) || Date.now(); + consoleCommandEchoHistory = [ + { command, ts }, + ...consoleCommandEchoHistory.filter((entry) => normalizeConsoleCommandKey(entry && entry.command) !== command) + ].slice(0, CONSOLE_COMMAND_ECHO_HISTORY_LIMIT); + persistConsoleCommandEchoHistory(); + } + + // Stable ordering for console history entries: prefer the server-assigned + // monotonic sequence (seq); fall back to timestamp only when seq is absent. + // This mirrors the server ordering and prevents commands/output from being + // jumbled by clock skew between the panel and the node. + function consoleHistoryEntryComparator(a, b) { + const sa = Number(a && a.seq) || 0; + const sb = Number(b && b.seq) || 0; + if (sa && sb && sa !== sb) return sa - sb; + const ta = Number(a && a.ts) || 0; + const tb = Number(b && b.ts) || 0; + if (ta !== tb) return ta - tb; + return sa - sb; + } + + function mergeLocalConsoleCommandEchoHistory(lines, limit = 80, resetAt = consoleHistoryResetAt) { + const cutoff = Number(resetAt || 0) || 0; + const remote = (Array.isArray(lines) ? lines.slice() : []) + .filter((item) => (Number(item && item.ts) || 0) >= cutoff); + const hasRemoteOutput = remote.some((item) => String(item && item.source || 'output') !== 'command' && String(item && item.line || '').trim()); + if (!hasRemoteOutput) { + return remote + .sort(consoleHistoryEntryComparator) + .slice(-Math.max(1, Number(limit) || 80)); + } + const seen = new Set(); + for (const item of remote) { + if (String(item && item.source || 'output') !== 'command') continue; + const key = normalizeConsoleCommandKey(item && item.line); + if (key) seen.add(key); + } + for (const entry of consoleCommandEchoHistory) { + const command = normalizeConsoleCommandKey(entry && entry.command); + const ts = Number(entry && entry.ts) || Date.now(); + if (!command || seen.has(command) || ts < cutoff) continue; + seen.add(command); + // Position the locally-recalled command echo just before the first + // remote entry that happened after it (by timestamp), borrowing a seq + // slightly below that entry's seq so it renders immediately before its + // output instead of being dumped at the end. + let anchorSeq = 0; + for (const item of remote) { + const itemTs = Number(item && item.ts) || 0; + const itemSeq = Number(item && item.seq) || 0; + if (!itemSeq) continue; + if (itemTs >= ts) { + anchorSeq = itemSeq - 0.5; + break; + } + } + remote.push({ line: command, ts, source: 'command', seq: anchorSeq }); + } + return remote + .sort(consoleHistoryEntryComparator) + .slice(-Math.max(1, Number(limit) || 80)); + } + function rememberConsoleCommandForInput(commandText) { const command = String(commandText || '').trim(); if (!command) return; @@ -1884,6 +2264,7 @@ let lastConsoleAppendText = ""; let lastConsoleAppendAt = 0; let lastConsoleHistorySyncTs = 0; + let lastHydratedConsoleOutputCount = 0; const seenConsoleHistoryEntries = new Set(); const recentConsoleLineFingerprints = new Map(); @@ -1960,7 +2341,74 @@ function appendCommandEcho(commandText, sentAt = Date.now()) { const safe = String(commandText || '').replace(/[\r\n]+/g, ' ').trim(); if (!safe) return; - appendToConsole(`[${formatConsoleClock(sentAt)} CMD] ${safe}\n`); + rememberConsoleCommandEcho(safe, sentAt); + appendConsoleCommandLine(safe); + } + + // Pterodactyl/Wings-style command echo. The command is rendered on its own + // line in a distinct color so it visually leads its output, with NO panel + // wall-clock (the old "[HH:MM:SS CMD]" format mixed the panel clock with the + // server's own log clock, e.g. 21:09 next to 18:08). Ordering is purely by + // position in the node stream, so it stays put across refreshes. + // + // CRITICAL: command lines must NOT go through clientClean()/appendToConsole(), + // because that pipeline strips a leading "> " and drops bare known-command + // lines as "echo artifacts" - which previously made the command disappear + // entirely. appendConsoleCommandLine() writes a pre-styled, already-clean line + // straight into the render buffer, bypassing those filters. + const CONSOLE_COMMAND_ANSI_COLOR = '\x1b[38;5;75m'; // light blue, like Pterodactyl + function formatConsoleHistoryCommand(commandText) { + const safe = String(commandText || '').replace(/[\r\n]+/g, ' ').trim(); + if (!safe) return ''; + return `${CONSOLE_COMMAND_ANSI_COLOR}> ${safe}\x1b[0m\n`; + } + function appendConsoleCommandLine(commandText, ts = Date.now()) { + const styled = formatConsoleHistoryCommand(commandText); + if (!styled) return; + const now = Date.now(); + rememberConsoleCommandRendered(commandText, ts); + lastConsoleLiveAt = now; + _pendingConsoleText += styled; + if (!_flushRaf) { + _flushRaf = requestAnimationFrame(_flushConsole); + } + } + + // Dedicated dedup for rendered command lines. We CANNOT reuse + // recentlySawConsoleLine()/rememberRecentConsoleChunk() here because those run + // clientClean(), which strips the leading "> " and drops bare commands as + // artifacts - producing an empty fingerprint that never matches. + // + // Dedup is keyed on the command text PLUS a coarse time bucket of the source + // timestamp. This is important: a command that is genuinely sent again (e.g. + // running "pl" three times) carries a different source timestamp each time and + // MUST render each time, while the SAME single keypress arriving from two + // channels (inline EventSource marker + socket "console:command", or a history + // resync) shares the same timestamp bucket and collapses to one line. + const recentRenderedConsoleCommands = new Map(); + const CONSOLE_COMMAND_RENDER_BUCKET_MS = 2500; + function normalizedConsoleCommandFingerprint(commandText, ts = 0) { + const text = String(commandText || '').replace(/[\r\n]+/g, ' ').trim().toLowerCase(); + if (!text) return ''; + const bucket = Number(ts) > 0 ? Math.round(Number(ts) / CONSOLE_COMMAND_RENDER_BUCKET_MS) : 0; + return `${text}\u0000${bucket}`; + } + function rememberConsoleCommandRendered(commandText, ts = Date.now()) { + const key = normalizedConsoleCommandFingerprint(commandText, ts); + if (!key) return; + const now = Date.now(); + recentRenderedConsoleCommands.set(key, now); + if (recentRenderedConsoleCommands.size > 400) { + for (const [k, seenAt] of recentRenderedConsoleCommands.entries()) { + if ((now - seenAt) > RECENT_CONSOLE_DEDUPE_MS) recentRenderedConsoleCommands.delete(k); + } + } + } + function recentlyRenderedConsoleCommand(commandText, ts = 0) { + const key = normalizedConsoleCommandFingerprint(commandText, ts); + if (!key) return false; + const seenAt = recentRenderedConsoleCommands.get(key) || 0; + return seenAt > 0 && (Date.now() - seenAt) <= RECENT_CONSOLE_DEDUPE_MS; } function createCommandRequestId() { @@ -2027,33 +2475,97 @@ _flushRaf = requestAnimationFrame(_flushConsole); } } + + function prependToConsole(rawChunk) { + const cleaned = clientClean(rawChunk); + if (!cleaned) return false; + if (_flushRaf) { + cancelAnimationFrame(_flushRaf); + _flushRaf = 0; + _flushConsole(); + } + const wasNearBottom = isNearBottom(consoleEl); + _consoleRawChunks.unshift(cleaned); + _consoleVisibleChars += getConsoleVisibleLength(cleaned); + while (_consoleVisibleChars > MAX_CONSOLE_CHARS && _consoleRawChunks.length > 1) { + const dropped = _consoleRawChunks.pop(); + _consoleVisibleChars -= getConsoleVisibleLength(dropped); + } + consoleContentEl.innerHTML = ansiToHtml(_consoleRawChunks.join('')); + rememberRecentConsoleChunk(cleaned, Date.now()); + if (!suppressAutoScroll && wasNearBottom) { + scrollConsoleToBottom(false); + } + updateJumpBtnVisibility(); + return true; + } + async function fetchConsoleHistory(limit = 80) { - const r = await fetch(`/api/servers/${encodeURIComponent(bot)}/console-history?limit=${encodeURIComponent(limit)}`); + const params = new URLSearchParams(); + params.set('limit', String(limit)); + params.set('includeCommands', '1'); + if (consoleHistoryResetAt > 0) params.set('clientResetAt', String(consoleHistoryResetAt)); + const r = await fetch(`/api/servers/${encodeURIComponent(bot)}/console-history?${params.toString()}`); const payload = await r.json().catch(() => ({})); if (!r.ok || !payload || payload.ok === false || !Array.isArray(payload.lines)) { throw new Error((payload && (payload.error || payload.detail)) || `history_http_${r.status}`); } - return payload.lines; + const resetAt = Number(payload.resetAt || 0) || 0; + if (resetAt > consoleHistoryResetAt) { + applyConsoleHistoryReset(resetAt, { resetBuffer: false }); + } + // Do NOT re-filter the server response by consoleHistoryResetAt here. We + // already pass clientResetAt to the server, which is authoritative: it + // returns exactly the lines that belong to the current run (the node's + // persisted console is truncated per container start, and the server gates + // stale history via its canUseNode logic). Re-applying a local wall-clock + // cutoff on top of that deleted legitimate current-run startup lines whose + // node-assigned timestamps fell just below the local reset time (clock skew + // / synthetic snapshot timestamps) — the "only the last few startup lines + // survive a refresh" bug. Trust the server's result and just order it. + return payload.lines + .slice() + .sort(consoleHistoryEntryComparator) + .slice(-Math.max(1, Number(limit) || 80)); } - async function resetServerConsoleHistorySession() { + async function resetServerConsoleHistorySession(options = {}) { try { const response = await fetch(`/api/servers/${encodeURIComponent(bot)}/console-history/reset`, { method: 'POST' }); + const payload = await response.json().catch(() => ({})); + applyConsoleHistoryReset(Number(payload.resetAt || Date.now()) || Date.now(), { + resetBuffer: options.resetBuffer !== false + }); return response.ok; } catch { + applyConsoleHistoryReset(Date.now(), { resetBuffer: options.resetBuffer !== false }); return false; } } async function hydrateInitialConsoleHistory(limit = 120) { if (!hasConsoleReadAccess()) return 0; - if (_consoleVisibleChars > 0 || _pendingConsoleText || (consoleContentEl && consoleContentEl.textContent.trim())) return 0; let appendedCount = 0; + let outputCount = 0; try { - const lines = await fetchConsoleHistory(limit); + const remoteLines = await fetchConsoleHistory(limit); + // The first command after a (re)start can race the panel's log tail: + // its output is captured but the matching command echo may be missing + // from the server-side snapshot. Re-inject locally remembered command + // echoes so the "[HH:MM:SS CMD] ..." line shows up alongside its output + // after a browser refresh. + const lines = mergeLocalConsoleCommandEchoHistory(remoteLines, limit, consoleHistoryResetAt); + const historyChunks = []; for (const item of lines) { const ts = Number(item && item.ts) || 0; const source = String(item && item.source || 'output'); const line = String(item && item.line || ''); if (!line) continue; + // NOTE: we intentionally do NOT skip output lines just because the + // console already has text. The whole persisted history (the full + // server startup log, up to the cap) must always be rendered when + // entering the console, exactly like Pterodactyl. Duplicates against + // any live text are prevented per-line below via the stable + // seenConsoleHistoryEntries key (stable synthetic ts from the node) and + // recentlySawConsoleLine() content dedup, not by dropping history wholesale. const key = `${ts}:${source}:${line}`; if (seenConsoleHistoryEntries.has(key)) continue; seenConsoleHistoryEntries.add(key); @@ -2061,11 +2573,37 @@ const first = seenConsoleHistoryEntries.values().next().value; if (first) seenConsoleHistoryEntries.delete(first); } - appendToConsole(line.endsWith('\n') ? line : `${line}\n`); + if (source === 'command') { + // Flush any pending output first so the command renders in order, + // then write it through the bypass (clientClean would strip "> " and + // drop it as a known-command artifact). + if (historyChunks.length) { + appendToConsole(historyChunks.join('')); + historyChunks.length = 0; + } + if (!recentlyRenderedConsoleCommand(line, ts)) { + appendConsoleCommandLine(line, ts || Date.now()); + } + if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; + appendedCount += 1; + continue; + } + const historyLine = line.endsWith('\n') ? line : `${line}\n`; + if (recentlySawConsoleLine(historyLine, 0)) { + if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; + continue; + } + historyChunks.push(historyLine); if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; + outputCount += 1; appendedCount += 1; } + if (historyChunks.length) { + const historyText = historyChunks.join(''); + appendToConsole(historyText); + } } catch { } + lastHydratedConsoleOutputCount = outputCount; return appendedCount; } function scheduleConsoleHistoryResync(commandText, sentAt = Date.now()) { @@ -2079,14 +2617,13 @@ pendingConsoleHistoryResyncTimer = null; if (remoteLogTransport === 'eventsource' && lastConsoleLiveAt >= sentAt) return; try { - const lines = await fetchConsoleHistory(120); + const lines = await fetchConsoleHistory(Math.max(160, Math.min(INITIAL_CONSOLE_HISTORY_LIMIT, 240))); for (const item of lines) { const ts = Number(item && item.ts) || 0; const source = String(item && item.source || 'output'); const line = String(item && item.line || ''); if (!line) continue; if (ts < baselineTs) continue; - if (ts <= lastConsoleHistorySyncTs) continue; const key = `${ts}:${source}:${line}`; if (seenConsoleHistoryEntries.has(key)) continue; seenConsoleHistoryEntries.add(key); @@ -2094,9 +2631,17 @@ const first = seenConsoleHistoryEntries.values().next().value; if (first) seenConsoleHistoryEntries.delete(first); } - if (source === 'command' && line.trim() === String(commandText || '').trim()) continue; + if (source === 'command') { + if (recentlyRenderedConsoleCommand(line, ts)) { + if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; + continue; + } + appendConsoleCommandLine(line, ts || Date.now()); + if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; + continue; + } const historyLine = line.endsWith('\n') ? line : `${line}\n`; - if (source !== 'command' && recentlySawConsoleLine(historyLine, baselineTs)) { + if (recentlySawConsoleLine(historyLine, Math.max(0, baselineTs - 5000))) { if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; continue; } @@ -2203,7 +2748,33 @@ if (REMOTE_MODE && remoteLogTransport === 'eventsource') return; syncPowerStateFromPanelMessage(data); if (!hasConsoleReadAccess()) return; - appendToConsole(data, { live: true }); + appendLiveConsoleLine(data, Date.now()); + }); + + socket.off("console:reset"); + socket.on("console:reset", (payload) => { + const target = String(payload && payload.server || '').trim().toLowerCase(); + if (target && target !== String(bot || '').trim().toLowerCase()) return; + applyConsoleHistoryReset(Number(payload && payload.resetAt || Date.now()) || Date.now(), { resetBuffer: false }); + }); + + socket.off("console:command"); + socket.on("console:command", (payload) => { + const target = String(payload && payload.server || '').trim().toLowerCase(); + if (target && target !== String(bot || '').trim().toLowerCase()) return; + // When the live console is on the EventSource transport, the command marker + // already arrives inline in that stream (appendLiveConsoleLine -> marker -> + // appendConsoleCommandLine). Handling the socket "console:command" event too + // would render the same command twice. Ignore it on EventSource, exactly + // like the "output" handler does, so there is a single source per transport. + if (REMOTE_MODE && remoteLogTransport === 'eventsource') return; + if (!hasConsoleReadAccess()) return; + const command = String(payload && payload.command || '').trim(); + if (!command) return; + const ts = Number(payload && payload.ts) || Date.now(); + rememberConsoleCommandEcho(command, ts); + if (recentlyRenderedConsoleCommand(command, ts)) return; + appendConsoleCommandLine(command, ts); }); socket.off("nodeStatus"); @@ -2213,7 +2784,14 @@ powerNodeOnline = nodeOnline; updatePowerControlsInteractivity(); setNodeOnline(nodeOnline); - updateOfflineState(!nodeOnline); + // serverMissing means the node is reachable but the server no longer exists + // on it. Show the 404 overlay for that case too, but key it on a real signal + // (not a flapping connection failure) so it clears the moment the server is + // present again or is intentionally removed. + if (typeof data.serverMissing !== 'undefined') { + SERVER_MISSING = data.serverMissing === true; + } + updateOfflineState(!nodeOnline || SERVER_MISSING); }); if (socket.connected) socket.emit("join", bot); @@ -2350,7 +2928,7 @@ const saved = await persistStoreTemplateChoice(opt.id); closeStorePrefModal(); updateStoreVisibility(); - if (!saved) alert('Saved locally but failed to persist template for this server.'); + if (!saved) showStoreToast('Saved locally but failed to persist template for this server.', 'error'); if (pendingStoreOpen) { pendingStoreOpen = false; openStoreModal(); @@ -2459,7 +3037,7 @@ }); async function openStoreModal() { if (!storeModal) return; - if (!hasPerm('store_access')) { alert('You do not have permission to access the store'); return; } + if (!hasPerm('store_access')) { showStoreToast('You do not have permission to access the store', 'error'); return; } if (!serverInfo) await loadServerInfo(); updateStoreVisibility(); const { template: tpl } = resolveStoreTemplate(); @@ -3265,8 +3843,9 @@ } = opts; if (!hasPerm('store_access')) throw new Error('Unauthorized'); - if (!skipConfirm && confirmMessage && !confirm(confirmMessage)) return { cancelled: true }; + if (!skipConfirm && confirmMessage && !(await storeConfirm(confirmMessage))) return { cancelled: true }; + storeBarStart(progressMessage); showProgressWheel(3, progressMessage); try { const response = await applyServerVersionWithActionToken(bot, payload); @@ -3278,9 +3857,11 @@ throw new Error(result?.detail || result?.error || `HTTP ${response.status}`); } try { await loadServerInfo(); updateStoreVisibility(); } catch { } - if (!silentSuccess) alert(result.message || successMessage); + storeBarDone(true); + if (!silentSuccess) showStoreToast(result.message || successMessage, 'success'); return result; } catch (e) { + storeBarDone(false); throw new Error(`${errorPrefix}: ${e?.message || e}`); } finally { setTimeout(hideProgressWheel, 450); @@ -3504,23 +4085,23 @@ }); row.appendChild(meta); row.appendChild(tags); - row.addEventListener('click', () => { + row.addEventListener('click', async () => { const id = v.id || v.name || v.version || ''; const label = v.label || v.name || id; const downloadUrl = v.downloadUrl || v.url || null; if (isFivemProvider) { applyVersion(provider.id || provider.provider || '', id, label, downloadUrl, { template: 'fivem' }) - .catch((err) => alert(err?.message || err)); + .catch((err) => showStoreToast(err?.message || err, 'error')); return; } const { template: tpl } = resolveStoreTemplate(); if (tpl) { const friendly = templateDisplayName(tpl); - const proceed = confirm(`Please note your server will switch to ${friendly} template, do you want to continue?`); + const proceed = await storeConfirm(`Please note your server will switch to ${friendly} template, do you want to continue?`); if (!proceed) return; } applyVersion(provider.id || provider.provider || '', id, label, downloadUrl) - .catch((err) => alert(err?.message || err)); + .catch((err) => showStoreToast(err?.message || err, 'error')); }); list.appendChild(row); }); @@ -3542,11 +4123,11 @@ const submitCustom = () => { const version = (input?.value || '').trim(); if (!version) { - alert('Enter a FiveM artifact version first.'); + showStoreToast('Enter a FiveM artifact version first.', 'error'); return; } applyVersion(provider.id || provider.provider || '', version, `FiveM artifact ${version}`, null, { template: 'fivem' }) - .catch((err) => alert(err?.message || err)); + .catch((err) => showStoreToast(err?.message || err, 'error')); }; button.addEventListener('click', (event) => { event.preventDefault(); @@ -3835,13 +4416,13 @@ v.game_versions.includes(mrSelectedMcVersion) ); if (!match) { - alert("No matching Modrinth version found for this platform / Minecraft version."); + showStoreToast("No matching Modrinth version found for this platform / Minecraft version.", 'error'); return; } const files = match.files || []; const file = files.find(f => f.primary) || files[0]; if (!file || !file.url) { - alert("This Modrinth version does not expose a downloadable file."); + showStoreToast("This Modrinth version does not expose a downloadable file.", 'error'); return; } const label = `${mrPluginName.textContent} (${mrSelectedPlatform.toUpperCase()} ${mrSelectedMcVersion})`; @@ -3852,10 +4433,9 @@ mrPluginInstallBtn.innerHTML = `Installing...`; try { await applyVersion("modrinth-plugin", match.id || `${mrCurrentProjectId}-${mrSelectedPlatform}-${mrSelectedMcVersion}`, label, file.url, { destPath: `plugins/${pluginFileName}` }); - alert("Plugin installed successfully"); closeModrinthPluginModal(); } catch (e) { - alert("Failed to trigger plugin install: " + (e && e.message ? e.message : e)); + showStoreToast("Failed to trigger plugin install: " + (e && e.message ? e.message : e), 'error'); } finally { mrPluginInstallBtn.classList.remove("is-loading"); mrPluginInstallBtn.innerHTML = installButtonHtml; @@ -4715,6 +5295,23 @@ } } + function formatActivityActionLabel(entry) { + const action = String(entry && entry.action || 'unknown'); + if (action === 'console_command') return 'Sent command'; + return action.replace(/_/g, ' '); + } + + function formatActivityDetails(entry) { + const details = entry && entry.details; + const action = String(entry && entry.action || '').toLowerCase(); + if (!details) return ''; + if (action === 'console_command' && typeof details === 'object' && details.command) { + const source = details.source ? ` (${String(details.source)})` : ''; + return `Command${source}: ${String(details.command)}`; + } + return typeof details === 'string' ? details : JSON.stringify(details); + } + function renderActivityList() { const query = (activitySearchInput?.value || '').toLowerCase(); let filtered = activityData.filter(e => { @@ -4736,12 +5333,12 @@ } activityList.innerHTML = filtered.map(e => { const ts = e.ts ? new Date(e.ts).toLocaleString() : '—'; - const action = escapeHtml(e.action || 'unknown'); + const action = escapeHtml(formatActivityActionLabel(e)); const user = escapeHtml(e.user || 'unknown'); const ip = escapeHtml(e.ip || ''); - const details = e.details ? escapeHtml(typeof e.details === 'string' ? e.details : JSON.stringify(e.details)) : ''; + const details = escapeHtml(formatActivityDetails(e)); let icon = 'fa-circle-info'; - const actionLower = action.toLowerCase(); + const actionLower = String(e.action || action).toLowerCase(); if (actionLower.includes('start') || actionLower.includes('run')) icon = 'fa-play'; else if (actionLower.includes('stop') || actionLower.includes('kill')) icon = 'fa-stop'; else if (actionLower.includes('restart')) icon = 'fa-rotate'; @@ -6200,7 +6797,7 @@ if (clearConsoleConfirm) { clearConsoleConfirm.addEventListener('click', async function () { - resetConsoleBuffer(); + resetLocalConsoleHistorySession(); var cb = document.getElementById('clearConsoleNoAsk'); if (cb && cb.checked) { @@ -6303,9 +6900,18 @@ } SERVER_DISK_USED_BYTES = Math.max(0, usedGb * 1073741824); SERVER_DISK_LIMIT_BYTES = limitGb > 0 ? Math.max(0, limitGb * 1073741824) : 0; - if (resDiskLabel) resDiskLabel.textContent = limitGb > 0 + // adpanel:backup-storage - storage shown as the combined total (server + // files + backups). When backups exist, append the breakdown so it is + // clear how much of the quota the backups occupy. + const serverMb = (data.disk && typeof data.disk === 'object') ? data.disk.serverMb : null; + const backupsMb = (data.disk && typeof data.disk === 'object') ? data.disk.backupsMb : null; + let diskText = limitGb > 0 ? `${formatBytes(usedGb * 1073741824)} / ${formatBytes(limitGb * 1073741824)} (${Math.round(pct)}%)` : `${formatBytes(usedGb * 1073741824)} / Unlimited`; + if (Number.isFinite(backupsMb) && backupsMb > 0 && Number.isFinite(serverMb)) { + diskText += ` — files ${formatBytes(serverMb * 1048576)} + backups ${formatBytes(backupsMb * 1048576)}`; + } + if (resDiskLabel) resDiskLabel.textContent = diskText; if (resDiskBar) resDiskBar.style.width = `${pct}%`; } else { if (resDiskLabel) resDiskLabel.textContent = '—'; @@ -7315,6 +7921,13 @@ textArea.dataset.original = normalized; textArea.focus(); } + // Populate the mini file manager with the folder containing the open file. + try { + const dir = currentEditorPath.includes('/') + ? currentEditorPath.slice(0, currentEditorPath.lastIndexOf('/')) + : ""; + renderMiniFm(dir); + } catch (_) { } } function closeEditorModal() { if (!editorModal) return; @@ -7355,11 +7968,13 @@ ? 'Saving...' : 'Save'; } - async function performSave() { - if (editorSaving) return; - if (!hasPerm('files_create')) return alert('Unauthorized'); + async function performSave(opts = {}) { + const closeAfter = opts.closeAfter !== false; // default: close editor after a manual save + if (editorSaving) return false; + if (!hasPerm('files_create')) { alert('Unauthorized'); return false; } const path = document.getElementById('editorPath').textContent; - if (!path) return alert('No file open'); + if (!path) { alert('No file open'); return false; } + let editorSaveSucceeded = false; let contentToSave = ""; if (monacoEditor && monacoEditor.getModel && monacoEditor.getModel()) { contentToSave = monacoEditor.getValue(); @@ -7384,9 +7999,12 @@ if (codeInput) codeInput.dataset.original = contentToSave; if (editorModal && editorModal.classList.contains('show')) flashEditorBar(); loadExplorer(currentPath); + refreshMiniFm(); + editorSaveSucceeded = true; } catch (err) { flashEditorBar(); alert('Save failed: ' + (err && err.message ? err.message : err)); + return false; } finally { editorSaving = false; if (editorSave) { @@ -7395,6 +8013,10 @@ editorSave.classList.toggle("disabled", !hasPerm("files_create")); } } + if (closeAfter && editorSaveSucceeded) { + closeEditorModal(); + } + return editorSaveSucceeded; } if (editorSave) { editorSave.onclick = (e) => { @@ -7402,6 +8024,190 @@ performSave(); }; } + + // ============= Mini File Manager (inside Monaco editor) ============= + const miniFm = document.getElementById('miniFm'); + const miniFmEntries = document.getElementById('miniFmEntries'); + const miniFmBreadcrumbs = document.getElementById('miniFmBreadcrumbs'); + const miniFmToggle = document.getElementById('miniFmToggle'); + const miniFmRefresh = document.getElementById('miniFmRefresh'); + const miniFmUpload = document.getElementById('miniFmUpload'); + let miniFmPath = ""; + + function getCurrentEditorValue() { + if (monacoEditor && monacoEditor.getModel && monacoEditor.getModel()) return monacoEditor.getValue(); + if (aceEditor && aceContainer && aceContainer.style.display !== 'none') return aceEditor.getValue(); + if (textArea && textArea.style.display !== 'none') return textArea.value; + if (codeInput) return codeInput.value; + return ""; + } + + function isEditorDirty() { + if (!currentEditorPath) return false; + return normalizeInput(getCurrentEditorValue()) !== normalizeInput(editorOriginalContent || ""); + } + + function refreshMiniFm() { + if (!miniFm || !codeShell || codeShell.style.display === 'none') return; + renderMiniFm(miniFmPath); + } + + function renderMiniFmBreadcrumb(pathValue) { + if (!miniFmBreadcrumbs) return; + const clean = String(pathValue || "").replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""); + const parts = clean ? clean.split("/").filter(Boolean) : []; + const crumbs = [`${escapeHtml(String(bot || "server"))}`]; + let acc = ""; + parts.forEach((part) => { + acc = acc ? `${acc}/${part}` : part; + crumbs.push('/'); + crumbs.push(`${escapeHtml(part)}`); + }); + miniFmBreadcrumbs.innerHTML = crumbs.join(""); + } + + async function renderMiniFm(path = "") { + if (!miniFmEntries) return; + if (!hasPerm('files_read')) { + miniFmEntries.innerHTML = `
  • Unauthorized
  • `; + return; + } + miniFmEntries.innerHTML = `
  • `; + try { + const data = await apiExplore(path); + miniFmPath = data.path || ""; + renderMiniFmBreadcrumb(miniFmPath); + const entries = (Array.isArray(data.entries) ? data.entries : []) + .map(normalizeExplorerEntry) + .filter((e) => e.name) + .sort(compareExplorerEntries); + miniFmEntries.innerHTML = ""; + + if (miniFmPath) { + const up = document.createElement("li"); + up.className = "mini-fm-entry"; + up.innerHTML = `
    ` + + `
    ..
    `; + up.addEventListener('click', () => { + const parent = miniFmPath.includes('/') ? miniFmPath.slice(0, miniFmPath.lastIndexOf('/')) : ""; + renderMiniFm(parent); + }); + miniFmEntries.appendChild(up); + } + + if (!entries.length) { + const empty = document.createElement("li"); + empty.className = "mini-fm-empty"; + empty.textContent = "Empty folder"; + miniFmEntries.appendChild(empty); + } + + entries.forEach((e) => { + const rel = miniFmPath ? miniFmPath + "/" + e.name : e.name; + const li = document.createElement("li"); + li.className = "mini-fm-entry"; + if (!e.isDir && rel === currentEditorPath) li.classList.add('active'); + const icon = `
    ` + + `
    `; + const meta = e.isDir ? 'Folder' : (typeof e.size === 'number' ? formatFileSize(e.size) : 'File'); + li.innerHTML = icon + + `
    ${escapeHtml(e.name)}
    ` + + `
    `; + li.addEventListener('click', () => { + if (e.isDir) { + renderMiniFm(rel); + } else { + switchEditorFile(rel, e.size); + } + }); + miniFmEntries.appendChild(li); + }); + } catch (err) { + console.error("[MiniFM] Load failed:", err); + miniFmEntries.innerHTML = `
  • Failed to load
  • `; + } + } + + async function openFileInEditor(rel, size) { + if (typeof size === 'number' && size > FILE_SIZE_EDITOR_LIMIT) { + if (confirm(`This file is ${formatFileSize(size)} which exceeds the 5 MB editor limit.\n\nDownload instead?`)) { + apiDownloadFile(rel); + } + return; + } + if (!hasPerm('files_read')) return alert('Unauthorized'); + try { + const content = await apiReadFile(rel); + if (content !== null) { + await openEditorModal(rel, content); + refreshMiniFm(); + } + } catch (err) { + flashEditorBar(); + } + } + + // Switch to another file from the mini file manager. + // If the current file has unsaved changes, the browser asks to save or not, + // then the selected file is opened. + async function switchEditorFile(rel, size) { + if (rel === currentEditorPath) return; + if (isEditorDirty()) { + const save = confirm('You have unsaved changes.\n\nClick OK to save them before opening the other file, or Cancel to discard them.'); + if (save) { + const ok = await performSave({ closeAfter: false }); + if (!ok) return; // save failed; stay on current file + } + } + await openFileInEditor(rel, size); + } + + if (miniFmBreadcrumbs) { + miniFmBreadcrumbs.addEventListener('click', (e) => { + const a = e.target.closest('a[data-mini-path]'); + if (!a) return; + e.preventDefault(); + renderMiniFm(a.getAttribute('data-mini-path') || ""); + }); + } + if (miniFmRefresh) { + miniFmRefresh.addEventListener('click', (e) => { e.preventDefault(); renderMiniFm(miniFmPath); }); + } + if (miniFmToggle && codeShell) { + miniFmToggle.addEventListener('click', (e) => { + e.preventDefault(); + const collapsed = codeShell.classList.toggle('mini-fm-collapsed'); + miniFmToggle.setAttribute('aria-expanded', String(!collapsed)); + // Monaco uses automaticLayout, but nudge a relayout for instant resize feel. + setTimeout(() => { + if (monacoEditor && monacoEditor.layout) monacoEditor.layout(); + if (aceEditor && aceEditor.resize) aceEditor.resize(true); + }, 300); + }); + } + if (miniFmUpload) { + miniFmUpload.addEventListener('change', () => { + if (!hasPerm('files_upload')) return alert('Unauthorized'); + const files = Array.from(miniFmUpload.files || []); + if (!files.length) return; + if (typeof fileListHasDirectory === 'function' && fileListHasDirectory(files)) { + if (typeof blockFolderUpload === 'function') blockFolderUpload(); + miniFmUpload.value = ''; + return; + } + const savedCurrentPath = currentPath; + currentPath = miniFmPath; // upload into the folder shown in the mini manager + uploadFilesSequential(files) + .then(() => { renderMiniFm(miniFmPath); loadExplorer(savedCurrentPath); }) + .catch((err) => { + if (typeof hideProgressWheel === 'function') hideProgressWheel(); + flashEditorBar(); + alert('Upload failed: ' + ((err && err.message) ? err.message : 'upload failed')); + }) + .finally(() => { currentPath = savedCurrentPath; miniFmUpload.value = ''; }); + }); + } + editorDiscard.addEventListener('click', () => { if (monacoEditor && monacoEditor.getModel && monacoEditor.getModel()) { monacoEditor.setValue(editorOriginalContent || ""); @@ -7443,7 +8249,6 @@ if (!hasPerm('server_start')) return alert('Unauthorized'); if (!isPowerActionAllowed('run')) return; resetConsoleBuffer(); - resetServerConsoleHistorySession(); appendConsoleNotice('[ADaemon] Starting server...'); setPowerState(POWER_STATE.STARTING); attachLogStreamIfRemote({ tail: 0, forceReconnect: true }); @@ -7470,7 +8275,7 @@ setPowerState(POWER_STATE.STOPPING); appendConsoleNotice('[ADaemon] Stopping server...'); apiAction({ bot, cmd: 'stop' }) - .then(() => { + .then(async () => { appendConsoleNotice('[ADaemon] Stop request accepted.'); return refreshPowerState({ force: true }).catch(() => { }); }) @@ -7487,7 +8292,7 @@ setPowerState(POWER_STATE.STOPPING); appendConsoleNotice('[ADaemon] Sending kill signal...'); apiAction({ bot, cmd: 'kill' }) - .then(() => { + .then(async () => { appendConsoleNotice('[ADaemon] Kill request accepted.'); return refreshPowerState({ force: true }).catch(() => { }); }) @@ -7689,7 +8494,7 @@ setCommandSendingState(true); cmdInput.value = ''; rememberConsoleCommandForInput(cmd); - appendCommandEcho(cmd, now); + rememberConsoleCommandEcho(cmd, now); try { await apiCommand(cmd, now, requestId); } catch (err) { @@ -7723,7 +8528,7 @@ function clearConsole() { if (currentUserPreferences.clear_console_no_ask || loadClearConsoleNoAskFromStorage()) { currentUserPreferences.clear_console_no_ask = true; - resetConsoleBuffer(); + resetLocalConsoleHistorySession(); return; } if (typeof openClearConsoleModal === 'function') { @@ -7867,7 +8672,7 @@ }); let initialConsoleHistoryCount = 0; await runBootstrapStep('hydrate-console-history', async () => { - initialConsoleHistoryCount = await hydrateInitialConsoleHistory(120); + initialConsoleHistoryCount = await hydrateInitialConsoleHistory(INITIAL_CONSOLE_HISTORY_LIMIT); }); startPowerStatePolling(); await runBootstrapStep('refresh-power-state-initial', async () => { @@ -7877,7 +8682,10 @@ await loadServerInfo(); }); await runBootstrapStep('attach-log-stream', async () => { - attachLogStreamIfRemote({ tail: initialConsoleHistoryCount > 0 ? 0 : 100 }); + const initialTail = consoleHistoryResetAt > 0 || lastHydratedConsoleOutputCount > 0 + ? 0 + : REMOTE_LOG_SNAPSHOT_TAIL; + attachLogStreamIfRemote({ tail: initialTail }); }); window.setTimeout(() => { loadMonaco().catch(() => { }); @@ -7885,9 +8693,6 @@ await runBootstrapStep('refresh-power-state-post-server-info', async () => { await refreshPowerState({ force: true }); }); - if (powerState === POWER_STATE.STOPPED && consoleContentEl && !consoleContentEl.textContent.trim()) { - appendConsoleNotice('[ADaemon] Server is currently stopped.'); - } await runBootstrapStep('load-explorer', async () => { await loadExplorer(); }); @@ -9764,7 +10569,9 @@ if (action === 'start' || action === 'restart') { resetConsoleBuffer(); - resetServerConsoleHistorySession(); + } + if (action === 'stop' || action === 'kill') { + resetServerConsoleHistorySession({ resetBuffer: false }); } if (action === 'start') setPowerState(POWER_STATE.STARTING); if (action === 'stop' || action === 'kill') setPowerState(POWER_STATE.STOPPING); @@ -9805,7 +10612,7 @@ const commandText = String(action.command || '').trim(); const sentAt = Number(action.sentAt) || Date.now(); if (commandText && hasConsoleReadAccess()) { - appendCommandEcho(commandText, sentAt); + rememberConsoleCommandEcho(commandText, sentAt); } scheduleConsoleHistoryResync(commandText, sentAt); } diff --git a/public/js/dashboard-assistant.js b/public/js/dashboard-assistant.js index d2322ba..b6055de 100644 --- a/public/js/dashboard-assistant.js +++ b/public/js/dashboard-assistant.js @@ -908,22 +908,64 @@ return els.messages.querySelectorAll(".dashboard-assistant-message--assistant").length; } + // Minimum viewport height (in CSS pixels) required to safely open the + // assistant. Below this the UI is too cramped to be usable (matches a + // phone-sized window or an extreme browser zoom-in). + const MIN_OPEN_HEIGHT = 480; + // Minimum viewport width. Below this the layout would clip horizontally. + const MIN_OPEN_WIDTH = 360; + + function canOpenMenu() { + const h = window.innerHeight; + const w = window.innerWidth; + return h >= MIN_OPEN_HEIGHT && w >= MIN_OPEN_WIDTH; + } + function positionMenu() { if (!state.open || !els.menu || !els.trigger) return; const triggerRect = els.trigger.getBoundingClientRect(); + + const margin = 12; + const topGap = 10; + + // Width: keep the designed width, never scale it. Clamp to viewport. const preferredWidth = state.configured ? 580 : 430; - const menuWidth = Math.min(preferredWidth, window.innerWidth - 24); - const leftBias = 150; + const visualW = Math.min(preferredWidth, window.innerWidth - margin * 2); - // Center on trigger, then keep the panel fully visible in viewport. - const idealLeft = triggerRect.left + (triggerRect.width / 2) - (menuWidth / 2) - leftBias; - const left = Math.max(12, Math.min(idealLeft, window.innerWidth - menuWidth - 12)); + // Height: whatever fits between the trigger bottom and the viewport bottom. + // The messages area has `flex: 1` + `overflow-y: auto`, so it scrolls + // naturally when content is taller than this — no clipping at the bottom. + const availableBelow = window.innerHeight - triggerRect.bottom - topGap - margin; + const availableAbove = triggerRect.top - topGap - margin; + // Prefer placing it below the trigger; fall back to above if no room. + const useAbove = availableBelow < 260 && availableAbove > availableBelow; + const visualH = Math.max( + 260, + useAbove ? availableAbove : availableBelow + ); - els.menu.style.width = `${menuWidth}px`; + // Center horizontally on the trigger, then clamp to viewport. + const desiredLeft = triggerRect.left + (triggerRect.width / 2) - (visualW / 2) - 150; + const left = Math.max(margin, Math.min(desiredLeft, window.innerWidth - visualW - margin)); + const top = useAbove + ? Math.max(margin, triggerRect.top - visualH - topGap) + : Math.max(margin, triggerRect.bottom + topGap); + + els.menu.style.width = `${visualW}px`; + els.menu.style.height = `${visualH}px`; els.menu.style.left = `${left}px`; - els.menu.style.right = 'auto'; - els.menu.style.top = `${triggerRect.bottom + 20}px`; - els.menu.style.bottom = 'auto'; + els.menu.style.right = "auto"; + els.menu.style.top = `${top}px`; + els.menu.style.bottom = "auto"; + els.menu.style.transform = "none"; + els.menu.style.setProperty("--assistant-scale", "1"); + + // Relax the messages area's min-height when the viewport is tight, + // so the menu can shrink to fit without clipping the composer. + if (els.messages) { + const tight = visualH < 520; + els.messages.style.minHeight = tight ? "0px" : ""; + } } function stopSpeaking() { @@ -1168,6 +1210,10 @@ } function openMenu() { + if (!canOpenMenu()) { + showTooSmallNotice(); + return; + } state.open = true; primeSpeechSynthesis(); updateButtons(); @@ -1178,6 +1224,24 @@ }); } + function showTooSmallNotice() { + // Flash a transient inline notice near the trigger so the user understands + // why the assistant didn't open. Uses the existing status pipeline. + if (els.status) { + const prevState = els.status.dataset.state; + const prevText = els.status.textContent; + els.status.dataset.state = "warning"; + els.status.textContent = "Screen too small to open the assistant. Try a larger window."; + els.status.classList.remove("is-hidden"); + setTimeout(() => { + if (!state.open && els.status) { + els.status.dataset.state = prevState || "idle"; + els.status.textContent = prevText || ""; + } + }, 3500); + } + } + function closeMenu() { state.open = false; updateButtons(); @@ -4696,6 +4760,11 @@ els.trigger?.addEventListener("click", (event) => { event.stopPropagation(); if (!state.open) { + if (!canOpenMenu()) { + event.preventDefault(); + showTooSmallNotice(); + return; + } openMenu(); return; } @@ -4860,14 +4929,61 @@ }; } - window.addEventListener("resize", positionMenu); - window.addEventListener("scroll", positionMenu, true); + // Re-position on window resize, scroll, AND browser zoom. + // `window.resize` doesn't always fire on Ctrl+/Ctrl- zoom, so we also + // listen to `visualViewport.resize` (covers pinch-zoom and most browser + // zoom cases) and fall back to a DPR poll for the rest. + let lastDpr = window.devicePixelRatio || 1; + const refit = () => { + if (!state.open) return; + if (!canOpenMenu()) { + // Viewport shrunk below the safe threshold (e.g. extreme zoom-in). + // Auto-close and inform the user. + closeMenu(); + showTooSmallNotice(); + return; + } + positionMenu(); + }; + window.addEventListener("resize", refit); + window.addEventListener("scroll", refit, true); + if (window.visualViewport) { + window.visualViewport.addEventListener("resize", refit); + window.visualViewport.addEventListener("scroll", refit); + } + // DPR poll: catches the few browsers/configs where neither resize nor + // visualViewport fires on zoom. Cheap (rAF-throttled). + const dprTick = () => { + const dpr = window.devicePixelRatio || 1; + if (dpr !== lastDpr) { + lastDpr = dpr; + refit(); + } + requestAnimationFrame(dprTick); + }; + requestAnimationFrame(dprTick); + window.addEventListener("beforeunload", () => { stopSpeaking(); stopActiveStream(); cleanupAudioGraph(); cleanupRecognition(); }); + + // Re-position when the menu's intrinsic size changes (e.g. messages streaming, + // config panel toggling, transcript appearing). Debounced with rAF. + if (typeof ResizeObserver !== "undefined" && els.menu) { + let rafId = 0; + const ro = new ResizeObserver(() => { + if (!state.open) return; + if (rafId) cancelAnimationFrame(rafId); + rafId = requestAnimationFrame(() => { + rafId = 0; + positionMenu(); + }); + }); + ro.observe(els.menu); + } } function init() { diff --git a/public/js/dashboard.js b/public/js/dashboard.js index 26a2f03..4ed3e57 100644 --- a/public/js/dashboard.js +++ b/public/js/dashboard.js @@ -94,19 +94,29 @@ window.addEventListener('DOMContentLoaded', () => { const showSplashForFirstCacheMiss = () => { if (!splash) return; const displayTime = 5000; + const hardTimeout = 7000; const preload = new Image(); let hideScheduled = false; + const hardTimer = window.setTimeout(() => { + if (hideScheduled) return; + markSplashCached(); + hideSplash(); + }, hardTimeout); const scheduleHide = () => { if (hideScheduled) return; hideScheduled = true; + window.clearTimeout(hardTimer); markSplashCached(); window.setTimeout(hideSplash, displayTime); }; preload.decoding = 'async'; preload.onload = scheduleHide; - preload.onerror = removeSplash; + preload.onerror = () => { + window.clearTimeout(hardTimer); + removeSplash(); + }; preload.src = splashImage; if (preload.complete) { @@ -317,76 +327,19 @@ window.addEventListener('DOMContentLoaded', () => { document.querySelectorAll('[data-href]').forEach(el => { el.addEventListener('click', (event) => { + event.preventDefault(); + event.stopPropagation(); const href = el.getAttribute('data-href'); if (!href) return; const target = el.getAttribute('data-target'); if (target === '_blank') { - window.open(href, '_blank'); + window.open(href, '_blank', 'noopener,noreferrer'); } else { window.location.href = href; } - event.preventDefault(); }); }); - function ensureSshTerminalModal() { - let overlay = document.getElementById('sshTerminalOverlay'); - if (overlay) return overlay; - - overlay = document.createElement('div'); - overlay.id = 'sshTerminalOverlay'; - overlay.className = 'ssh-terminal-overlay'; - overlay.innerHTML = ` - - `; - document.body.appendChild(overlay); - - const closeBtn = overlay.querySelector('#sshTerminalCloseBtn'); - const closeModal = () => { - overlay.classList.remove('show'); - const frame = overlay.querySelector('#sshTerminalFrame'); - if (frame) frame.src = 'about:blank'; - }; - - closeBtn?.addEventListener('click', closeModal); - overlay.addEventListener('click', (e) => { - if (e.target === overlay) closeModal(); - }); - document.addEventListener('keydown', (e) => { - if (e.key === 'Escape' && overlay.classList.contains('show')) closeModal(); - }); - - return overlay; - } - - const sshTerminalBtn = document.getElementById('openSshTerminalBtn'); - sshTerminalBtn?.addEventListener('click', async () => { - sshTerminalBtn.disabled = true; - try { - const res = await fetch('/api/ssh-terminal/session', { credentials: 'include' }); - const data = await res.json().catch(() => ({})); - if (!res.ok || !data?.launchUrl) { - throw new Error(data?.error || 'Unable to open terminal'); - } - const overlay = ensureSshTerminalModal(); - const frame = overlay.querySelector('#sshTerminalFrame'); - if (!frame) throw new Error('Terminal frame unavailable'); - frame.src = data.launchUrl; - overlay.classList.add('show'); - } catch (err) { - alert(err?.message || 'Failed to open SSH terminal.'); - } finally { - sshTerminalBtn.disabled = false; - } - }); - document.querySelectorAll('[data-bot-card]').forEach(card => { const cover = card.dataset.cover; if (cover) card.style.setProperty('--bot-cover', `url("${cover.replace(/"/g, '\\"')}")`); @@ -415,6 +368,7 @@ window.addEventListener('DOMContentLoaded', () => { _searchTimer = setTimeout(() => navigateDashboard(1, (searchInput?.value || '').trim()), 500); return; } + if (!botGrid) return; const term = (searchInput?.value || '').trim().toLowerCase(); const botCards = Array.from(botGrid.querySelectorAll('[data-bot-card]')); let visible = 0; @@ -437,7 +391,7 @@ window.addEventListener('DOMContentLoaded', () => { clearTimeout(_searchTimer); _searchTimer = setTimeout(updateBotVisibility, dashPagination ? 500 : 150); }); - if (!dashPagination) updateBotVisibility(); + if (botGrid && !dashPagination) updateBotVisibility(); const urlParams = new URLSearchParams(window.location.search); if (searchInput && urlParams.get('search')) { @@ -455,6 +409,7 @@ window.addEventListener('DOMContentLoaded', () => { const topBar = document.getElementById('topBar'); const spacer = document.getElementById('topbar-spacer'); + const spacerExtraOffset = spacer ? parseInt(spacer.getAttribute('data-topbar-extra-offset') || '0', 10) || 0 : 0; function measureExpandedHeight() { const hadCompact = topBar.classList.contains('top-bar--compact'); topBar.classList.remove('top-bar--compact'); @@ -462,19 +417,23 @@ window.addEventListener('DOMContentLoaded', () => { if (hadCompact) topBar.classList.add('top-bar--compact'); return h; } + function applySpacerHeight() { + if (!spacer) return; + spacer.style.height = Math.max(0, expandedHeight - spacerExtraOffset) + 'px'; + } let expandedHeight = measureExpandedHeight(); - spacer.style.height = expandedHeight + 'px'; + applySpacerHeight(); let resizeRAF = null; window.addEventListener('resize', () => { if (resizeRAF) cancelAnimationFrame(resizeRAF); resizeRAF = requestAnimationFrame(() => { expandedHeight = measureExpandedHeight(); - spacer.style.height = expandedHeight + 'px'; + applySpacerHeight(); }); }); new ResizeObserver(() => { expandedHeight = measureExpandedHeight(); - spacer.style.height = expandedHeight + 'px'; + applySpacerHeight(); fitHero(); }).observe(topBar); @@ -603,6 +562,7 @@ window.addEventListener('DOMContentLoaded', () => { if (statusTextEl) statusTextEl.textContent = data.status || 'Available'; window._accountData = data; + syncAccountSecurityUi(); if (cooldownEl && data.usernameChangeCooldown) { const days = Math.ceil(data.usernameChangeCooldown / (24 * 60 * 60 * 1000)); @@ -840,10 +800,85 @@ window.addEventListener('DOMContentLoaded', () => { const newSecretDisplay = document.getElementById('newSecretDisplay'); const twofaError = document.getElementById('twofaError'); const twofaSuccess = document.getElementById('twofaSuccess'); + const twofaStep1Text = document.getElementById('twofaStep1Text'); let pendingNewSecret = null; let twoFaModalStep = 1; + function accountHas2FA() { + return !window._accountData || window._accountData.has2FA !== false; + } + + function setStepVisibility(input, visible) { + const step = input?.closest('.password-step, .email-step, .twofa-step'); + if (step) step.style.display = visible ? '' : 'none'; + } + + function setStepNumber(input, number) { + const step = input?.closest('.password-step, .email-step, .twofa-step'); + const badge = step?.querySelector('.password-step-num, .email-step-num, .twofa-step-num'); + if (badge) badge.textContent = String(number); + } + + function syncTwofaCard() { + const has2FA = accountHas2FA(); + if (change2faBtn) { + change2faBtn.innerHTML = has2FA + ? ' Change 2FA' + : ' Enable 2FA'; + } + } + + function configureTwofaModalSecurity() { + const has2FA = accountHas2FA(); + const title = twofaModal?.querySelector('.twofa-modal-title'); + const subtitle = twofaModal?.querySelector('.twofa-modal-subtitle'); + if (title) title.textContent = has2FA ? 'Change 2FA Code' : 'Enable 2FA'; + if (subtitle) subtitle.textContent = has2FA ? 'Update your authenticator app' : 'Add an authenticator app to this account'; + if (twofaStep1Text) { + twofaStep1Text.textContent = has2FA ? 'Enter your current 2FA code' : 'Enter your current password'; + } + if (currentCodeInput) { + currentCodeInput.type = has2FA ? 'text' : 'password'; + currentCodeInput.placeholder = has2FA ? '000000' : 'Current password'; + currentCodeInput.maxLength = has2FA ? 6 : 1024; + currentCodeInput.inputMode = has2FA ? 'numeric' : ''; + currentCodeInput.autocomplete = has2FA ? 'one-time-code' : 'current-password'; + currentCodeInput.classList.toggle('twofa-password-input', !has2FA); + } + const twofaForgotLink = document.getElementById('twofaForgotLink'); + if (twofaForgotLink) twofaForgotLink.style.display = has2FA ? '' : 'none'; + } + + function configurePasswordModalSecurity() { + const has2FA = accountHas2FA(); + const passwordCodeInput = document.getElementById('password2faInput'); + const passwordNewInput = document.getElementById('newPasswordInput'); + const passwordConfirmInput = document.getElementById('confirmPasswordInput'); + setStepVisibility(passwordCodeInput, has2FA); + setStepNumber(passwordNewInput, has2FA ? 3 : 2); + setStepNumber(passwordConfirmInput, has2FA ? 4 : 3); + const passwordForgotLink = document.getElementById('passwordForgotLink'); + if (passwordForgotLink) passwordForgotLink.style.display = has2FA ? '' : 'none'; + } + + function configureEmailModalSecurity() { + const has2FA = accountHas2FA(); + const emailCodeInput = document.getElementById('email2faInput'); + const emailNewInput = document.getElementById('newEmailInput'); + setStepVisibility(emailCodeInput, has2FA); + setStepNumber(emailNewInput, has2FA ? 3 : 2); + const emailForgotLink = document.getElementById('emailForgotLink'); + if (emailForgotLink) emailForgotLink.style.display = has2FA ? '' : 'none'; + } + + function syncAccountSecurityUi() { + syncTwofaCard(); + configureTwofaModalSecurity(); + configurePasswordModalSecurity(); + configureEmailModalSecurity(); + } + function resetTwofaModal() { twoFaModalStep = 1; pendingNewSecret = null; @@ -854,7 +889,7 @@ window.addEventListener('DOMContentLoaded', () => { if (twofaError) twofaError.classList.remove('show'); if (twofaSuccess) twofaSuccess.classList.remove('show'); if (twofaConfirmBtn) { - twofaConfirmBtn.textContent = 'Verify Current Code'; + twofaConfirmBtn.textContent = accountHas2FA() ? 'Verify Current Code' : 'Verify Password'; twofaConfirmBtn.disabled = false; twofaConfirmBtn.style.display = ''; } @@ -862,8 +897,7 @@ window.addEventListener('DOMContentLoaded', () => { const twofaStep1 = document.getElementById('twofaStep1'); if (twofaStep1) twofaStep1.style.display = ''; - const twofaForgotLink = document.getElementById('twofaForgotLink'); - if (twofaForgotLink) twofaForgotLink.style.display = ''; + configureTwofaModalSecurity(); const qrStepNum = qrCodeSection?.querySelector('.twofa-step-num'); const confirmStepNum = confirmSection?.querySelector('.twofa-step-num'); @@ -903,11 +937,16 @@ window.addEventListener('DOMContentLoaded', () => { hideTwofaError(); if (twoFaModalStep === 1) { - const currentCode = currentCodeInput?.value.trim() || ''; - if (!currentCode || currentCode.length !== 6 || !/^\d+$/.test(currentCode)) { + const has2FA = accountHas2FA(); + const currentCredential = currentCodeInput?.value.trim() || ''; + if (has2FA && (!currentCredential || currentCredential.length !== 6 || !/^\d+$/.test(currentCredential))) { showTwofaError('Please enter a valid 6-digit code'); return; } + if (!has2FA && !currentCredential) { + showTwofaError('Please enter your current password'); + return; + } twofaConfirmBtn.disabled = true; twofaConfirmBtn.textContent = 'Verifying...'; @@ -915,10 +954,10 @@ window.addEventListener('DOMContentLoaded', () => { try { const res = await fetch('/api/account/2fa/generate', { method: 'POST', - headers: { 'Content-Type': 'application/json' }, - credentials: 'include', - body: JSON.stringify({ currentCode }) - }); + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify(has2FA ? { currentCode: currentCredential } : { currentPassword: currentCredential }) + }); const data = await res.json(); if (!res.ok) throw new Error(data.error || 'Verification failed'); @@ -934,7 +973,7 @@ window.addEventListener('DOMContentLoaded', () => { twofaConfirmBtn.disabled = false; } catch (err) { showTwofaError(err.message); - twofaConfirmBtn.textContent = 'Verify Current Code'; + twofaConfirmBtn.textContent = accountHas2FA() ? 'Verify Current Code' : 'Verify Password'; twofaConfirmBtn.disabled = false; } } else if (twoFaModalStep === 2) { @@ -958,8 +997,10 @@ window.addEventListener('DOMContentLoaded', () => { const data = await res.json(); if (!res.ok) throw new Error(data.error || 'Failed to update 2FA'); - if (twofaSuccess) twofaSuccess.classList.add('show'); - twofaConfirmBtn.style.display = 'none'; + if (twofaSuccess) twofaSuccess.classList.add('show'); + if (window._accountData) window._accountData.has2FA = true; + syncAccountSecurityUi(); + twofaConfirmBtn.style.display = 'none'; if (twofaCancelBtn) twofaCancelBtn.textContent = 'Done'; setTimeout(() => { @@ -974,10 +1015,13 @@ window.addEventListener('DOMContentLoaded', () => { } }); - [currentCodeInput, newCodeInput].forEach(input => { - input?.addEventListener('input', (e) => { + currentCodeInput?.addEventListener('input', (e) => { + if (accountHas2FA()) { e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6); - }); + } + }); + newCodeInput?.addEventListener('input', (e) => { + e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6); }); const passwordModal = document.getElementById('passwordModal'); @@ -1012,6 +1056,7 @@ window.addEventListener('DOMContentLoaded', () => { passwordConfirmBtn.style.display = ''; } if (passwordCancelBtn) passwordCancelBtn.textContent = 'Cancel'; + configurePasswordModalSecurity(); } function showPasswordError(msg) { @@ -1053,7 +1098,7 @@ window.addEventListener('DOMContentLoaded', () => { showPasswordError('Please enter your current password'); return; } - if (!code || code.length !== 6 || !/^\d+$/.test(code)) { + if (accountHas2FA() && (!code || code.length !== 6 || !/^\d+$/.test(code))) { showPasswordError('Please enter a valid 6-digit 2FA code'); return; } @@ -1066,7 +1111,7 @@ window.addEventListener('DOMContentLoaded', () => { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', - body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: code }) + body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: accountHas2FA() ? code : '' }) }); const data = await res.json(); @@ -1105,7 +1150,7 @@ window.addEventListener('DOMContentLoaded', () => { credentials: 'include', body: JSON.stringify({ currentPassword: currentPasswordInput?.value || '', - twoFactorCode: password2faInput?.value.trim() || '', + twoFactorCode: accountHas2FA() ? (password2faInput?.value.trim() || '') : '', newPassword: newPw }) }); @@ -1180,6 +1225,7 @@ window.addEventListener('DOMContentLoaded', () => { emailConfirmBtn.style.display = ''; } if (emailCancelBtn) emailCancelBtn.textContent = 'Cancel'; + configureEmailModalSecurity(); } function showEmailError(msg) { @@ -1221,7 +1267,7 @@ window.addEventListener('DOMContentLoaded', () => { showEmailError('Please enter your password'); return; } - if (!code || code.length !== 6 || !/^\d+$/.test(code)) { + if (accountHas2FA() && (!code || code.length !== 6 || !/^\d+$/.test(code))) { showEmailError('Please enter a valid 6-digit 2FA code'); return; } @@ -1234,7 +1280,7 @@ window.addEventListener('DOMContentLoaded', () => { method: 'POST', headers: { 'Content-Type': 'application/json' }, credentials: 'include', - body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: code }) + body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: accountHas2FA() ? code : '' }) }); const data = await res.json(); @@ -1269,7 +1315,7 @@ window.addEventListener('DOMContentLoaded', () => { credentials: 'include', body: JSON.stringify({ currentPassword: emailPasswordInput?.value || '', - twoFactorCode: email2faInput?.value.trim() || '', + twoFactorCode: accountHas2FA() ? (email2faInput?.value.trim() || '') : '', newEmail: newEmail }) }); @@ -1562,6 +1608,8 @@ window.addEventListener('DOMContentLoaded', () => { const nodeRamLimitEl = document.getElementById('nodeRamLimit'); const nodeCpuLimitEl = document.getElementById('nodeCpuLimit'); const nodeStorageLimitEl = document.getElementById('nodeStorageLimit'); + const resourceDiskEl = document.getElementById('resourceDisk'); + const resourceDiskHintEl = document.getElementById('resourceDiskHint'); const liveNodeCapacityCache = new Map(); const RESOURCE_NETWORK_LIMIT_MAX_MB = 1073741824; const RESOURCE_NETWORK_RESET_MAX_MINUTES = 43200; @@ -1650,6 +1698,52 @@ window.addEventListener('DOMContentLoaded', () => { return resolveEffectiveNodeCapacity(node, liveCapacity); } + function formatDiskOptionUsage(disk) { + const used = Number(disk?.usedGb || 0); + const limit = Number(disk?.limitGb || 0); + const usedStr = (used >= 10 ? used.toFixed(0) : used.toFixed(1)).replace(/\.0$/, ''); + return limit > 0 ? `${usedStr}/${limit} GB` : `${usedStr} GB used`; + } + + async function populateNodeDiskOptions(node) { + if (!resourceDiskEl) return; + const primaryOpt = ''; + resourceDiskEl.innerHTML = primaryOpt; + resourceDiskEl.value = 'primary'; + if (resourceDiskHintEl) resourceDiskHintEl.textContent = 'Server files are stored on the selected disk.'; + const id = node && (node.id || node.uuid || node.name); + if (!id) return; + try { + const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/disks`, { cache: 'no-store' }); + const data = await res.json().catch(() => ({})); + if (!res.ok || !Array.isArray(data.disks)) return; + // Keep the modal in sync only if the same node is still selected. + const current = getSelectedNode(); + if (!current || resolveNodeCacheKey(current) !== resolveNodeCacheKey(node)) return; + const options = []; + const additional = []; + for (const d of data.disks) { + const isPrimary = !!d.primary || String(d.id) === 'primary'; + if (isPrimary) continue; + additional.push(d); + } + options.push(primaryOpt); + for (const d of additional) { + const label = `${d.mountPath} (${formatDiskOptionUsage(d)})`; + options.push(``); + } + resourceDiskEl.innerHTML = options.join(''); + resourceDiskEl.value = 'primary'; + if (resourceDiskHintEl) { + resourceDiskHintEl.textContent = additional.length + ? 'Primary is used by default. Select an additional disk to place this server elsewhere.' + : 'This node has only the primary disk available.'; + } + } catch { + // Leave the primary-only default in place on failure. + } + } + if (resourceStorageEl) { resourceStorageEl.addEventListener('input', () => { const hint = resourceStorageEl.closest('.enterprise-field')?.querySelector('.enterprise-hint'); @@ -1711,7 +1805,7 @@ window.addEventListener('DOMContentLoaded', () => { let nodes = []; let selectedTemplateId = null; let selectedForkId = null; - let selectedNodeId = "local"; + let selectedNodeId = ""; let portBackTarget = "create"; let selectedStartupCommand = ""; let selectedStartupCommandMode = ""; @@ -1750,6 +1844,13 @@ window.addEventListener('DOMContentLoaded', () => { function getDefaultPortForTemplate(templateId) { const id = (templateId || '').toString().toLowerCase(); if (!id) return 25565; + const configuredTemplate = (templates || []).find(t => String(t?.id || '').trim().toLowerCase() === id); + const configuredPort = parseStrictPortValue( + configuredTemplate?.defaultPort || + configuredTemplate?.default_port || + configuredTemplate?.docker?.ports?.[0] + ); + if (configuredPort) return configuredPort; if (id.includes('minecraft') || id === 'mc') return 25565; if (id.includes('node') || id.includes('discord')) return 3000; if (id.includes('http') || id.includes('web') || id.includes('proxy')) return 80; @@ -1774,7 +1875,7 @@ window.addEventListener('DOMContentLoaded', () => { } function getSelectedNode() { - if (!selectedNodeId || selectedNodeId === 'local') return null; + if (!selectedNodeId) return null; return (nodes || []).find(x => (x.uuid === selectedNodeId) || (x.id === selectedNodeId) || @@ -2034,11 +2135,16 @@ window.addEventListener('DOMContentLoaded', () => { function startupCommandSourceLabel(source, imageRef) { const normalized = String(source || '').trim().toLowerCase(); - if (normalized === 'adpanel-startup') return 'Using ADPanel STARTUP from this template. Edit it in the template settings.'; + if (normalized === 'adpanel-startup') return 'Using the startup command defined by this template.'; + if (normalized === 'image-default') { + return imageRef + ? `Using Docker image default ENTRYPOINT/CMD (${imageRef}); ADPanel will not override it.` + : 'Using Docker image default ENTRYPOINT/CMD; ADPanel will not override it.'; + } if (normalized === 'image-inspect') { return imageRef - ? `Detected from Docker image inspect (${imageRef}).` - : 'Detected from Docker image inspect.'; + ? `Detected from Docker image inspect (${imageRef}); ADPanel will use the image default.` + : 'Detected from Docker image inspect; ADPanel will use the image default.'; } if (normalized === 'template-command') return 'Using process command defined by this template.'; if (normalized === 'template-default') return 'Using template default process command.'; @@ -2200,7 +2306,7 @@ window.addEventListener('DOMContentLoaded', () => { async function resolveStartupCommandForSelection(options = {}) { const templateId = String(options.templateId ?? selectedTemplateId ?? '').trim(); - const nodeId = String(options.nodeId ?? selectedNodeId ?? 'local').trim() || 'local'; + const nodeId = String(options.nodeId ?? selectedNodeId ?? 'none').trim() || 'none'; const forceRefresh = !!options.forceRefresh; const showLoading = !!options.showLoading; setStartupCommandValidationError(''); @@ -2222,6 +2328,15 @@ window.addEventListener('DOMContentLoaded', () => { template?.docker?.pterodactyl_startup || '' ).trim(); + const templateStartupDisplay = String( + template?.docker?.startupDisplay || + template?.docker?.startup_display || + template?.docker?.startupPreview || + template?.docker?.startup_preview || + template?.docker?.imageDefaultStartup || + template?.docker?.image_default_startup || + '' + ).trim(); if (startupCommandEl) startupCommandEl.readOnly = false; if (templateADPanelStartup) { selectedStartupCommand = templateADPanelStartup; @@ -2231,7 +2346,21 @@ window.addEventListener('DOMContentLoaded', () => { startupCommandEl.readOnly = true; } setStartupCommandValidationError(''); - setStartupCommandSource('Using ADPanel STARTUP from this template. Edit it in template settings if needed.'); + setStartupCommandSource('Using the startup command defined by this template.'); + setStartupCommandLoading(false); + return selectedStartupCommand; + } + if (templateStartupDisplay) { + selectedStartupCommand = templateStartupDisplay; + selectedStartupCommandMode = 'image-default'; + if (startupCommandEl && startupModal?.classList.contains('show')) { + startupCommandEl.value = selectedStartupCommand; + startupCommandEl.readOnly = true; + } + setStartupCommandValidationError(''); + setStartupCommandSource(startupCommandSourceLabel('image-default', template?.docker?.image && template?.docker?.tag + ? `${template.docker.image}:${template.docker.tag}` + : '')); setStartupCommandLoading(false); return selectedStartupCommand; } @@ -2275,23 +2404,34 @@ window.addEventListener('DOMContentLoaded', () => { if (detected?.ok) { const data = detected.data || {}; + const sourceMode = String(data.source || '').trim().toLowerCase(); + const usesDockerImageDefault = sourceMode === 'image-default' || sourceMode === 'image-inspect'; let detectedCommand = String(data.command || '').trim(); if (!detectedCommand && data.inspect) { detectedCommand = inferStartupFromInspectMeta(template, data.inspect, fallbackCommand, { allowUnsafe: false }); } - const detectedError = validateRuntimeProcessCommandInput(detectedCommand); - if (detectedCommand && !detectedError) { - const activeNodeId = String(selectedNodeId ?? 'local').trim() || 'local'; + if (!detectedCommand && usesDockerImageDefault && data.inspect) { + const entrypoint = Array.isArray(data.inspect.entrypoint) + ? data.inspect.entrypoint.map((item) => String(item || '').trim()).filter(Boolean) + : []; + const cmd = Array.isArray(data.inspect.cmd) + ? data.inspect.cmd.map((item) => String(item || '').trim()).filter(Boolean) + : []; + detectedCommand = joinStartupArgs([...entrypoint, ...cmd]); + } + const detectedError = usesDockerImageDefault ? null : validateRuntimeProcessCommandInput(detectedCommand); + if (detectedCommand && (!detectedError || usesDockerImageDefault)) { + const activeNodeId = String(selectedNodeId ?? 'none').trim() || 'none'; if (String(selectedTemplateId || '').trim() !== templateId || activeNodeId !== nodeId) { return selectedStartupCommand; } selectedStartupCommand = detectedCommand; - selectedStartupCommandMode = String(data.source || '').trim().toLowerCase() === 'adpanel-startup' + selectedStartupCommandMode = sourceMode === 'adpanel-startup' ? 'adpanel-startup' - : ''; + : (usesDockerImageDefault ? 'image-default' : ''); if (startupCommandEl && startupModal?.classList.contains('show')) { startupCommandEl.value = selectedStartupCommand; - startupCommandEl.readOnly = selectedStartupCommandMode === 'adpanel-startup'; + startupCommandEl.readOnly = selectedStartupCommandMode === 'adpanel-startup' || selectedStartupCommandMode === 'image-default'; } setStartupCommandSource(startupCommandSourceLabel(data.source, data.imageRef)); return selectedStartupCommand; @@ -2313,12 +2453,17 @@ window.addEventListener('DOMContentLoaded', () => { } function openCreate() { + if (!createModal) { + window.location.href = '/status'; + return; + } + document.body.classList.add('modal-open'); createModal.classList.add('show'); createModal.setAttribute('aria-hidden', 'false'); selectedTemplateId = null; selectedForkId = null; - selectedNodeId = 'local'; + selectedNodeId = ''; portBackTarget = 'create'; selectedStartupCommand = ''; selectedImportUrl = ''; @@ -2331,7 +2476,7 @@ window.addEventListener('DOMContentLoaded', () => { if (summaryNameEl) summaryNameEl.textContent = '—'; if (summaryTemplateEl) summaryTemplateEl.textContent = '—'; - if (summaryNodeEl) summaryNodeEl.textContent = 'Local node'; + if (summaryNodeEl) summaryNodeEl.textContent = '—'; if (templateInfo2) templateInfo2.textContent = ''; setStartupCommandSource('Using startup command from template.'); @@ -2340,6 +2485,8 @@ window.addEventListener('DOMContentLoaded', () => { } function closeCreate() { + if (!createModal) return; + document.body.classList.remove('modal-open'); createModal.classList.remove('show'); createModal.setAttribute('aria-hidden', 'true'); } @@ -2356,6 +2503,19 @@ window.addEventListener('DOMContentLoaded', () => { }; createBtns.forEach(btn => btn.addEventListener('click', openCreate)); + + // Navbar Create pill: expand to a pill on hover/focus, collapse back to a + // circle on leave. Driven by JS so the collapse animation always plays. + const navCreateBtn = document.getElementById('createBtn'); + if (navCreateBtn) { + const openPill = () => navCreateBtn.classList.add('is-open'); + const closePill = () => navCreateBtn.classList.remove('is-open'); + navCreateBtn.addEventListener('mouseenter', openPill); + navCreateBtn.addEventListener('mouseleave', closePill); + navCreateBtn.addEventListener('focus', openPill); + navCreateBtn.addEventListener('blur', closePill); + } + createClose?.addEventListener('click', closeCreate); createCancel?.addEventListener('click', closeCreate); document.addEventListener('keydown', (e) => { @@ -2449,16 +2609,19 @@ window.addEventListener('DOMContentLoaded', () => { if (!nodes.length) { const empty = document.createElement('div'); empty.className = 'enterprise-hint'; - empty.textContent = 'No remote nodes configured. Using local node.'; + empty.textContent = 'No nodes configured. Add a node in Settings before creating a server.'; nodeGrid.appendChild(empty); - if (summaryNodeEl) summaryNodeEl.textContent = 'Local node'; + selectedNodeId = ''; + if (summaryNodeEl) summaryNodeEl.textContent = 'No node available'; + if (createConfirm) createConfirm.disabled = true; return; } const autoNode = nodes.find(n => n && n.online) || nodes[0]; - if ((!selectedNodeId || selectedNodeId === 'local') && autoNode) { + if (!selectedNodeId && autoNode) { selectedNodeId = autoNode.uuid || autoNode.id || autoNode.name || selectedNodeId; } + if (createConfirm) createConfirm.disabled = false; nodes.forEach(n => { const online = !!n.online; @@ -2502,6 +2665,7 @@ window.addEventListener('DOMContentLoaded', () => { } function openForkModal() { + document.body.classList.add('modal-open'); if (!forkModal) return; if (forkGrid) forkGrid.innerHTML = ''; selectedForkId = null; @@ -2538,6 +2702,7 @@ window.addEventListener('DOMContentLoaded', () => { } function closeForkModal() { + document.body.classList.remove('modal-open'); forkModal.classList.remove('show'); forkModal.setAttribute('aria-hidden', 'true'); } @@ -2554,29 +2719,28 @@ window.addEventListener('DOMContentLoaded', () => { function openPortModal(backFrom) { portBackTarget = backFrom || 'create'; + const selectedNode = getSelectedNode(); + if (!selectedNode) { + alert('Please choose a node before configuring ports.'); + return; + } + document.body.classList.add('modal-open'); if (serverPortEl) { let defPort = getDefaultPortForTemplate(selectedTemplateId); - if (selectedNodeId && selectedNodeId !== 'local') { - const node = (nodes || []).find(x => - (x.uuid === selectedNodeId) || - (x.id === selectedNodeId) || - (x.name === selectedNodeId) - ); - if (node && node.ports) { - const alloc = node.ports; - let inRange = true; - let firstPort = defPort; - if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { - inRange = defPort >= alloc.start && defPort < alloc.start + alloc.count; - firstPort = alloc.start; - } else if (alloc.mode === 'list' && Array.isArray(alloc.ports) && alloc.ports.length > 0) { - inRange = alloc.ports.includes(defPort); - firstPort = alloc.ports[0]; - } - if (!inRange) defPort = firstPort; + if (selectedNode.ports) { + const alloc = selectedNode.ports; + let inRange = true; + let firstPort = defPort; + if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { + inRange = defPort >= alloc.start && defPort < alloc.start + alloc.count; + firstPort = alloc.start; + } else if (alloc.mode === 'list' && Array.isArray(alloc.ports) && alloc.ports.length > 0) { + inRange = alloc.ports.includes(defPort); + firstPort = alloc.ports[0]; } + if (!inRange) defPort = firstPort; } serverPortEl.value = String(defPort); @@ -2588,22 +2752,6 @@ window.addEventListener('DOMContentLoaded', () => { serverIpEl.textContent = 'detecting…'; } - const ipv4Re = /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/; - function extractIP(s) { - if (!s) return null; - const str = String(s).trim(); - const m = str.match(ipv4Re); - if (m) return m[0]; - if (str.includes(':')) return str.replace(/^\[|\]$/g, ''); - return null; - } - function pickIpFromJSON(j) { - return extractIP(j?.publicIp) || - extractIP(j?.ip) || - extractIP(j?.address) || - extractIP(j?.host) || - extractIP(j?.hostname); - } function setIp(ip) { if (serverIpEl) serverIpEl.textContent = ip || 'unknown'; } @@ -2613,26 +2761,14 @@ window.addEventListener('DOMContentLoaded', () => { if (portTitleTextEl) portTitleTextEl.textContent = 'Expose public port'; if (portSubtitleEl) portSubtitleEl.textContent = `Choose the public port for ${templateLabel}.`; - if (selectedNodeId && selectedNodeId !== 'local') { - const node = (nodes || []).find(x => - (x.uuid === selectedNodeId) || - (x.id === selectedNodeId) || - (x.name === selectedNodeId) - ); - const ip = node && (node.address || node.host || node.hostname); - setIp(ip); - } else { - fetch('/api/server-info') - .then(r => r.ok ? r.json() : Promise.reject()) - .then(j => setIp(pickIpFromJSON(j))) - .catch(() => setIp(null)); - } + setIp(selectedNode.address || selectedNode.host || selectedNode.hostname); portModal.classList.add('show'); portModal.setAttribute('aria-hidden', 'false'); } function closePortModal() { + document.body.classList.remove('modal-open'); portModal.classList.remove('show'); portModal.setAttribute('aria-hidden', 'true'); } @@ -2684,20 +2820,19 @@ window.addEventListener('DOMContentLoaded', () => { return; } - if (selectedNodeId !== 'local') { - const node = (nodes || []).find(x => - (x.uuid === selectedNodeId) || - (x.id === selectedNodeId) || - (x.name === selectedNodeId) - ); - if (!node) { - alert('The chosen node no longer exists.'); - return; - } - if (!node.online) { - alert('The chosen node is offline.'); - return; - } + if (!nodes.length) { + alert('No nodes are configured. Add a node in Settings before creating a server.'); + return; + } + + const node = getSelectedNode(); + if (!node) { + alert('Please choose a node.'); + return; + } + if (!node.online) { + alert('The chosen node is offline.'); + return; } if (selectedTemplateId === 'minecraft') { @@ -2726,27 +2861,25 @@ window.addEventListener('DOMContentLoaded', () => { return; } - if (selectedNodeId && selectedNodeId !== 'local') { - const node = (nodes || []).find(x => - (x.uuid === selectedNodeId) || - (x.id === selectedNodeId) || - (x.name === selectedNodeId) - ); - if (node && node.ports) { - const alloc = node.ports; - let allowed = true; - if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { - allowed = portVal >= alloc.start && portVal < alloc.start + alloc.count; - } else if (alloc.mode === 'list' && Array.isArray(alloc.ports) && alloc.ports.length > 0) { - allowed = alloc.ports.includes(portVal); - } - if (!allowed) { - let desc = ''; - if (alloc.mode === 'range') desc = `${alloc.start} \u2013 ${alloc.start + alloc.count - 1}`; - else if (alloc.mode === 'list') desc = alloc.ports.slice(0, 10).join(', ') + (alloc.ports.length > 10 ? '\u2026' : ''); - alert(`Port ${portVal} is not in this node's allocated ports (${desc}). Please choose a port within the node's allocation.`); - return; - } + const selectedNode = getSelectedNode(); + if (!selectedNode) { + alert('Please choose a node.'); + return; + } + if (selectedNode.ports) { + const alloc = selectedNode.ports; + let allowed = true; + if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { + allowed = portVal >= alloc.start && portVal < alloc.start + alloc.count; + } else if (alloc.mode === 'list' && Array.isArray(alloc.ports) && alloc.ports.length > 0) { + allowed = alloc.ports.includes(portVal); + } + if (!allowed) { + let desc = ''; + if (alloc.mode === 'range') desc = `${alloc.start} \u2013 ${alloc.start + alloc.count - 1}`; + else if (alloc.mode === 'list') desc = alloc.ports.slice(0, 10).join(', ') + (alloc.ports.length > 10 ? '\u2026' : ''); + alert(`Port ${portVal} is not in this node's allocated ports (${desc}). Please choose a port within the node's allocation.`); + return; } } @@ -2764,6 +2897,7 @@ window.addEventListener('DOMContentLoaded', () => { }); async function openStartupModal() { + document.body.classList.add('modal-open'); if (!startupModal) return; startupModal.classList.add('show'); @@ -2778,6 +2912,7 @@ window.addEventListener('DOMContentLoaded', () => { } function closeStartupModal() { + document.body.classList.remove('modal-open'); if (!startupModal) return; startupModal.classList.remove('show'); startupModal.setAttribute('aria-hidden', 'true'); @@ -2809,6 +2944,12 @@ window.addEventListener('DOMContentLoaded', () => { openImportModal(); return; } + if (selectedStartupCommandMode === 'image-default') { + setStartupCommandValidationError(''); + closeStartupModal(); + openImportModal(); + return; + } selectedStartupCommandMode = ''; const startupCommandError = validateRuntimeProcessCommandInput(selectedStartupCommand); if (startupCommandError && selectedStartupCommand) { @@ -2853,6 +2994,7 @@ window.addEventListener('DOMContentLoaded', () => { } function openImportModal() { + document.body.classList.add('modal-open'); if (!importModal) { openResourcesModal(); return; @@ -2876,6 +3018,7 @@ window.addEventListener('DOMContentLoaded', () => { } function closeImportModal() { + document.body.classList.remove('modal-open'); if (!importModal) return; importModal.classList.remove('show'); importModal.setAttribute('aria-hidden', 'true'); @@ -2932,6 +3075,13 @@ window.addEventListener('DOMContentLoaded', () => { }); function openResourcesModal() { + const node = getSelectedNode(); + if (!node) { + alert('Please choose a node.'); + return; + } + + document.body.classList.add('modal-open'); if (resourceRamEl) resourceRamEl.value = ''; if (resourceCpuCoresEl) resourceCpuCoresEl.value = ''; if (resourceSwapEl) resourceSwapEl.value = ''; @@ -2946,35 +3096,23 @@ window.addEventListener('DOMContentLoaded', () => { if (resourceNetworkOutboundLimitEl) resourceNetworkOutboundLimitEl.value = ''; if (resourceNetworkResetMinutesEl) resourceNetworkResetMinutesEl.value = ''; - const node = (nodes || []).find(x => - (x.uuid === selectedNodeId) || - (x.id === selectedNodeId) || - (x.name === selectedNodeId) - ); - - if (node) { - const cacheKey = resolveNodeCacheKey(node); - applyNodeCapacityToResourceModal(resolveEffectiveNodeCapacity(node, null)); - fetchLiveNodeCapacity(node).then((liveCapacity) => { - if (!liveCapacity) return; - if (!resourcesModal?.classList.contains('show')) return; - const selectedNode = (nodes || []).find(x => - (x.uuid === selectedNodeId) || - (x.id === selectedNodeId) || - (x.name === selectedNodeId) - ); - if (!selectedNode || resolveNodeCacheKey(selectedNode) !== cacheKey) return; - applyNodeCapacityToResourceModal(resolveEffectiveNodeCapacity(selectedNode, liveCapacity)); - }); - } else { - applyNodeCapacityToResourceModal({ ramMb: 0, cpuCores: 0, diskGb: 0 }); - } + const cacheKey = resolveNodeCacheKey(node); + applyNodeCapacityToResourceModal(resolveEffectiveNodeCapacity(node, null)); + populateNodeDiskOptions(node); + fetchLiveNodeCapacity(node).then((liveCapacity) => { + if (!liveCapacity) return; + if (!resourcesModal?.classList.contains('show')) return; + const selectedNode = getSelectedNode(); + if (!selectedNode || resolveNodeCacheKey(selectedNode) !== cacheKey) return; + applyNodeCapacityToResourceModal(resolveEffectiveNodeCapacity(selectedNode, liveCapacity)); + }); resourcesModal.classList.add('show'); resourcesModal.setAttribute('aria-hidden', 'false'); } function closeResourcesModal() { + document.body.classList.remove('modal-open'); resourcesModal.classList.remove('show'); resourcesModal.setAttribute('aria-hidden', 'true'); } @@ -3004,42 +3142,36 @@ window.addEventListener('DOMContentLoaded', () => { return; } - if (selectedNodeId !== 'local') { - const node = (nodes || []).find(x => - (x.uuid === selectedNodeId) || - (x.id === selectedNodeId) || - (x.name === selectedNodeId) - ); - if (!node) { - alert('The chosen node no longer exists.'); - return; - } - if (!node.online) { - alert('The chosen node is offline.'); - return; - } + const node = getSelectedNode(); + if (!node) { + alert('Please choose a node.'); + return; + } + if (!node.online) { + alert('The chosen node is offline.'); + return; + } - const effectiveCapacity = await getEffectiveNodeCapacity(node); - const ramMb = effectiveCapacity.ramMb; - const cpuCores = effectiveCapacity.cpuCores; - const diskMb2 = effectiveCapacity.diskGb > 0 ? Math.trunc(effectiveCapacity.diskGb * 1024) : 0; + const effectiveCapacity = await getEffectiveNodeCapacity(node); + const ramMb = effectiveCapacity.ramMb; + const cpuCores = effectiveCapacity.cpuCores; + const diskMb2 = effectiveCapacity.diskGb > 0 ? Math.trunc(effectiveCapacity.diskGb * 1024) : 0; - const inputRam = resourceRamEl && resourceRamEl.value ? parseInt(resourceRamEl.value, 10) : 0; - const inputCpuCores = resourceCpuCoresEl && resourceCpuCoresEl.value ? parseFloat(resourceCpuCoresEl.value) : 0; - const inputStorage = resourceStorageEl && resourceStorageEl.value ? parseInt(resourceStorageEl.value, 10) : 0; + const inputRam = resourceRamEl && resourceRamEl.value ? parseInt(resourceRamEl.value, 10) : 0; + const inputCpuCores = resourceCpuCoresEl && resourceCpuCoresEl.value ? parseFloat(resourceCpuCoresEl.value) : 0; + const inputStorage = resourceStorageEl && resourceStorageEl.value ? parseInt(resourceStorageEl.value, 10) : 0; - if (ramMb > 0 && inputRam > ramMb) { - alert(`RAM limit cannot exceed node maximum (${ramMb} MB).`); - return; - } - if (cpuCores > 0 && inputCpuCores > cpuCores) { - alert(`CPU cores cannot exceed node maximum (${cpuCores} cores).`); - return; - } - if (diskMb2 > 0 && inputStorage > diskMb2) { - alert(`Storage limit cannot exceed node maximum (${diskMb2.toLocaleString()} MB).`); - return; - } + if (ramMb > 0 && inputRam > ramMb) { + alert(`RAM limit cannot exceed node maximum (${ramMb} MB).`); + return; + } + if (cpuCores > 0 && inputCpuCores > cpuCores) { + alert(`CPU cores cannot exceed node maximum (${cpuCores} cores).`); + return; + } + if (diskMb2 > 0 && inputStorage > diskMb2) { + alert(`Storage limit cannot exceed node maximum (${diskMb2.toLocaleString()} MB).`); + return; } const portVal = parseStrictPortValue(serverPortEl?.value); @@ -3048,27 +3180,20 @@ window.addEventListener('DOMContentLoaded', () => { return; } - if (selectedNodeId && selectedNodeId !== 'local') { - const node = (nodes || []).find(x => - (x.uuid === selectedNodeId) || - (x.id === selectedNodeId) || - (x.name === selectedNodeId) - ); - if (node && node.ports) { - const alloc = node.ports; - let allowed = true; - if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { - allowed = portVal >= alloc.start && portVal < alloc.start + alloc.count; - } else if (alloc.mode === 'list' && Array.isArray(alloc.ports) && alloc.ports.length > 0) { - allowed = alloc.ports.includes(portVal); - } - if (!allowed) { - let desc = ''; - if (alloc.mode === 'range') desc = `${alloc.start} \u2013 ${alloc.start + alloc.count - 1}`; - else if (alloc.mode === 'list') desc = alloc.ports.slice(0, 10).join(', ') + (alloc.ports.length > 10 ? '\u2026' : ''); - alert(`Port ${portVal} is not in this node's allocated ports (${desc}). Please choose a port within the node's allocation.`); - return; - } + if (node.ports) { + const alloc = node.ports; + let allowed = true; + if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { + allowed = portVal >= alloc.start && portVal < alloc.start + alloc.count; + } else if (alloc.mode === 'list' && Array.isArray(alloc.ports) && alloc.ports.length > 0) { + allowed = alloc.ports.includes(portVal); + } + if (!allowed) { + let desc = ''; + if (alloc.mode === 'range') desc = `${alloc.start} \u2013 ${alloc.start + alloc.count - 1}`; + else if (alloc.mode === 'list') desc = alloc.ports.slice(0, 10).join(', ') + (alloc.ports.length > 10 ? '\u2026' : ''); + alert(`Port ${portVal} is not in this node's allocated ports (${desc}). Please choose a port within the node's allocation.`); + return; } } @@ -3088,7 +3213,11 @@ window.addEventListener('DOMContentLoaded', () => { nodeId: selectedNodeId, hostPort: portVal }; - if (selectedStartupCommand && selectedStartupCommandMode !== 'adpanel-startup') { + const selectedDiskId = resourceDiskEl ? String(resourceDiskEl.value || '').trim() : ''; + if (selectedDiskId && selectedDiskId !== 'primary') { + payload.diskId = selectedDiskId; + } + if (selectedStartupCommand && selectedStartupCommandMode !== 'adpanel-startup' && selectedStartupCommandMode !== 'image-default') { const payloadCommandError = validateRuntimeProcessCommandInput(selectedStartupCommand); if (!payloadCommandError) { payload.command = selectedStartupCommand; diff --git a/public/js/resource-popup.js b/public/js/resource-popup.js index 9a2d5ca..c6f3006 100644 --- a/public/js/resource-popup.js +++ b/public/js/resource-popup.js @@ -94,9 +94,17 @@ } else { usedGb = data.disk / 1024; limitGb = 0; pct = 0; } - resDiskLabel.textContent = limitGb > 0 + // adpanel:backup-storage - combined storage (server files + backups); + // show the breakdown when backups occupy part of the quota. + const serverMb = (typeof data.disk === 'object') ? data.disk.serverMb : null; + const backupsMb = (typeof data.disk === 'object') ? data.disk.backupsMb : null; + let diskText = limitGb > 0 ? `${formatBytes(usedGb * 1073741824)} / ${formatBytes(limitGb * 1073741824)} (${Math.round(pct)}%)` : `${formatBytes(usedGb * 1073741824)} / Unlimited`; + if (Number.isFinite(backupsMb) && backupsMb > 0 && Number.isFinite(serverMb)) { + diskText += ` — files ${formatBytes(serverMb * 1048576)} + backups ${formatBytes(backupsMb * 1048576)}`; + } + resDiskLabel.textContent = diskText; resDiskBar.style.width = `${pct}%`; } else { resDiskLabel.textContent = '—'; diff --git a/public/js/settings.js b/public/js/settings.js index d73697a..960e380 100644 --- a/public/js/settings.js +++ b/public/js/settings.js @@ -2,6 +2,11 @@ const BG_KEY = 'ui-background'; const ACCENT_KEY = 'ui-accent'; const DENSITY_KEY = 'ui-density'; const ANIM_KEY = 'ui-animations'; +const SETTINGS_PANEL_SESSION_KEY = 'adpanel-settings-active-panel'; +const currentUserSecurity = window.__ADPANEL_CURRENT_USER__ || {}; +const currentUserHas2FA = Object.prototype.hasOwnProperty.call(currentUserSecurity, 'has2FA') + ? !!currentUserSecurity.has2FA + : true; const body = document.body; const sidebarNav = document.getElementById('sidebarNav'); const sections = document.querySelectorAll('.panel-section'); @@ -28,6 +33,13 @@ const permSave = document.getElementById('permSave'); const templatesFeedbackEl = document.getElementById('templatesFeedback'); const templatesListEl = document.getElementById('templatesList'); const openCreateTemplateBtn = document.getElementById('openCreateTemplate'); +const openTemplateStoreBtn = document.getElementById('openTemplateStore'); +const templateStoreOverlay = document.getElementById('templateStoreOverlay'); +const templateStoreModal = document.getElementById('templateStoreModal'); +const templateStoreClose = document.getElementById('templateStoreClose'); +const templateStoreSearch = document.getElementById('templateStoreSearch'); +const templateStoreGrid = document.getElementById('templateStoreGrid'); +const templateStoreFeedback = document.getElementById('templateStoreFeedback'); const createTemplateOverlay = document.getElementById('createTemplateOverlay'); const createTemplateModal = document.getElementById('createTemplateModal'); const createTemplateModalTitle = document.getElementById('createTemplateModalTitle'); @@ -46,13 +58,11 @@ const ct_tag = document.getElementById('ct_tag'); const ct_startup_command = document.getElementById('ct_startup_command'); const ct_workdir = document.getElementById('ct_workdir'); const ct_env_json = document.getElementById('ct_env_json'); -const ct_adpanel_startup = document.getElementById('ct_adpanel_startup'); const ct_install_image = document.getElementById('ct_install_image'); -const ct_install_entrypoint = document.getElementById('ct_install_entrypoint'); const ct_install_mount = document.getElementById('ct_install_mount'); const ct_install_runtime = document.getElementById('ct_install_runtime'); -const ct_install_timeout = document.getElementById('ct_install_timeout'); const ct_install_script = document.getElementById('ct_install_script'); +const ct_advanced_settings = document.getElementById('ct_advanced_settings'); const ct_import_json = document.getElementById('ct_import_json'); const createTemplateImportBtn = document.getElementById('createTemplateImportBtn'); const serversListEl = document.getElementById('serversList'); @@ -89,7 +99,6 @@ const cn_port_list = document.getElementById('cn_port_list'); const cn_cpu_cores = document.getElementById('cn_cpu_cores'); const cn_max_upload_mb = document.getElementById('cn_max_upload_mb'); const cn_daemon_port = document.getElementById('cn_daemon_port'); -const cn_sftp_port = document.getElementById('cn_sftp_port'); const cn_ssl_enabled = document.getElementById('cn_ssl_enabled'); const cn_ssl_row = document.getElementById('cn_ssl_row'); const cn_connection_label = document.getElementById('cn_connection_label'); @@ -156,12 +165,12 @@ function tryOpenRequestedAssistantSettingsAction(action) { return clickAssistantSettingsButton('addQuickActionBtn'); case 'quick_action_user': return clickAssistantSettingsButton('addUserQuickActionBtn'); - case 'database_setup': - if (typeof openSetupModal === 'function') { - openSetupModal(); - return true; - } - return false; + case 'database_setup': + if (typeof window.openSetupModal === 'function') { + window.openSetupModal(); + return true; + } + return false; case 'create_node': return clickAssistantSettingsButton('openCreateNode'); case 'create_template': @@ -177,6 +186,163 @@ function tryOpenRequestedAssistantSettingsAction(action) { return false; } } + +const STEP_UP_GRACE_CREDENTIAL = '__ADPANEL_STEP_UP_GRACE_ACTIVE__'; +const stepUpSecurityState = { + twoFactorEnabled: currentUserHas2FA, + authMethod: currentUserHas2FA ? '2fa' : 'password', + graceExpiresAt: 0, + _timer: null, +}; + +function normalizeStepUpSecurity(security) { + if (!security || typeof security !== 'object') return null; + const twoFactorEnabled = Object.prototype.hasOwnProperty.call(security, 'twoFactorEnabled') + ? !!security.twoFactorEnabled + : currentUserHas2FA; + const authMethod = security.authMethod === 'password' ? 'password' : (twoFactorEnabled ? '2fa' : 'password'); + const graceExpiresAt = Math.max(0, Number(security.graceExpiresAt || 0)); + return { + twoFactorEnabled, + authMethod, + graceExpiresAt: graceExpiresAt > Date.now() ? graceExpiresAt : 0, + }; +} + +function isStepUpGraceActive() { + const expiresAt = Number(stepUpSecurityState.graceExpiresAt || 0); + if (!expiresAt) return false; + if (expiresAt <= Date.now()) { + stepUpSecurityState.graceExpiresAt = 0; + return false; + } + return true; +} + +function getCurrentStepUpMode() { + return stepUpSecurityState.authMethod === 'password' ? 'password' : '2fa'; +} + +function getStepUpCredentialContainer(input) { + if (!input) return null; + return ( + input.closest('[data-step-up-field]') || + input.closest('.node-delete-security-field') || + input.closest('.password-field') || + input.closest('.node-form-section') || + input.parentElement + ); +} + +function refreshStepUpCredentialFields() { + const fields = [ + ['adminChangePasswordCredential', 'adminChangePasswordCredentialLabel', 'adminChangePasswordCredentialHint'], + ['maintenanceCredentialInput', 'maintenanceCredentialLabel', 'maintenanceCredentialHint'], + ['nm_deleteCredential', 'nm_deleteCredentialLabel', 'nm_deleteCredentialHint'], + ['webhookCredentialInput', 'webhookCredentialLabel', 'webhookCredentialHint'], + ['webhookDeleteCredentialInput', 'webhookDeleteCredentialLabel', 'webhookDeleteCredentialHint'], + ]; + fields.forEach(([inputId, labelId, hintId]) => { + const input = document.getElementById(inputId); + if (!input) return; + configureStepUpCredentialField(input, document.getElementById(labelId), document.getElementById(hintId)); + }); +} + +function scheduleStepUpGraceRefresh() { + if (stepUpSecurityState._timer) { + window.clearTimeout(stepUpSecurityState._timer); + stepUpSecurityState._timer = null; + } + if (!isStepUpGraceActive()) return; + const delay = Math.max(250, Math.min(Number(stepUpSecurityState.graceExpiresAt || 0) - Date.now() + 250, 2147483000)); + stepUpSecurityState._timer = window.setTimeout(() => { + stepUpSecurityState.graceExpiresAt = 0; + refreshStepUpCredentialFields(); + }, delay); +} + +function applyGlobalStepUpSecurityFromPayload(security) { + const normalized = normalizeStepUpSecurity(security); + if (!normalized) return stepUpSecurityState; + stepUpSecurityState.twoFactorEnabled = normalized.twoFactorEnabled; + stepUpSecurityState.authMethod = normalized.authMethod; + stepUpSecurityState.graceExpiresAt = normalized.graceExpiresAt; + refreshStepUpCredentialFields(); + scheduleStepUpGraceRefresh(); + return stepUpSecurityState; +} + +window.applyRevokeSecurityFromPayload = applyGlobalStepUpSecurityFromPayload; +applyGlobalStepUpSecurityFromPayload(currentUserSecurity.revokeSecurity); + +function configureStepUpCredentialField(input, label, hint) { + if (!input) return; + const trustedMode = isStepUpGraceActive(); + const container = getStepUpCredentialContainer(input); + if (container) container.style.display = trustedMode ? 'none' : ''; + input.required = !trustedMode; + if (trustedMode) { + input.value = ''; + return; + } + const passwordMode = getCurrentStepUpMode() === 'password'; + if (label) label.textContent = passwordMode ? 'Current Password' : '2FA Code'; + if (hint) { + hint.textContent = passwordMode + ? 'Enter your current password to confirm this action.' + : 'Enter the code from your authenticator app.'; + } + input.type = passwordMode ? 'password' : 'text'; + input.placeholder = passwordMode ? 'Current password' : '000000'; + input.autocomplete = passwordMode ? 'current-password' : 'one-time-code'; + input.maxLength = passwordMode ? 1024 : 6; + input.inputMode = passwordMode ? '' : 'numeric'; + input.pattern = passwordMode ? '' : '[0-9]*'; +} + +function bindStepUpCredentialInput(input) { + if (!input || input.dataset.stepUpBound === 'true') return; + input.dataset.stepUpBound = 'true'; + input.addEventListener('input', () => { + if (getCurrentStepUpMode() !== '2fa') return; + input.value = String(input.value || '').replace(/\D/g, '').slice(0, 6); + }); +} + +function getStepUpCredentialValue(input) { + if (!input) return ''; + if (getCurrentStepUpMode() === 'password') return String(input.value || ''); + return String(input.value || '').replace(/\D/g, '').slice(0, 6); +} + +function validateStepUpCredential(input, showFeedback) { + if (isStepUpGraceActive()) return STEP_UP_GRACE_CREDENTIAL; + const passwordMode = getCurrentStepUpMode() === 'password'; + const credential = getStepUpCredentialValue(input); + if (passwordMode) { + if (!credential) { + showFeedback?.('Enter your current password.', true); + input?.focus(); + return ''; + } + } else if (!/^\d{6}$/.test(credential)) { + showFeedback?.('Enter a valid 6-digit code.', true); + input?.focus(); + return ''; + } + return credential; +} + +function appendStepUpCredentialPayload(body, credential) { + if (credential === STEP_UP_GRACE_CREDENTIAL) return body; + if (getCurrentStepUpMode() === 'password') { + body.currentPassword = credential; + } else { + body.twoFactorCode = credential; + } + return body; +} const nodeModal = document.getElementById('nodeModal'); const nodeModalClose = document.getElementById('nodeModalClose'); const nodeModalCancelBtn = document.getElementById('nodeModalCancelBtn'); @@ -199,9 +365,13 @@ const nm_port_count = document.getElementById('nm_port_count'); const nm_port_list = document.getElementById('nm_port_list'); const nm_max_upload_mb = document.getElementById('nm_max_upload_mb'); const nm_daemon_port = document.getElementById('nm_daemon_port'); -const nm_sftp_port = document.getElementById('nm_sftp_port'); const nm_save = document.getElementById('nm_save'); const nm_saveFeedback = document.getElementById('nm_saveFeedback'); +const nm_disks_list = document.getElementById('nm_disks_list'); +const nm_disks_feedback = document.getElementById('nm_disks_feedback'); +const nm_disk_mount = document.getElementById('nm_disk_mount'); +const nm_disk_limit = document.getElementById('nm_disk_limit'); +const nm_disk_add = document.getElementById('nm_disk_add'); const nm_configYml = document.getElementById('nm_configYml'); const nm_copyConfig = document.getElementById('nm_copyConfig'); const nm_downloadConfig = document.getElementById('nm_downloadConfig'); @@ -211,6 +381,9 @@ const nm_cmdActions = document.getElementById('nm_cmdActions'); const nm_copyCmd = document.getElementById('nm_copyCmd'); const nm_delete = document.getElementById('nm_delete'); const nm_deleteFeedback = document.getElementById('nm_deleteFeedback'); +const nm_deleteCredential = document.getElementById('nm_deleteCredential'); +const nm_deleteCredentialLabel = document.getElementById('nm_deleteCredentialLabel'); +const nm_deleteCredentialHint = document.getElementById('nm_deleteCredentialHint'); const nm_ssl_enabled = document.getElementById('nm_ssl_enabled'); const nm_ssl_row = document.getElementById('nm_ssl_row'); const nm_connection_label = document.getElementById('nm_connection_label'); @@ -218,12 +391,14 @@ const nm_connection_help = document.getElementById('nm_connection_help'); const nm_under_cloudflare = document.getElementById('nm_under_cloudflare'); const nm_under_cloudflare_row = document.getElementById('nm_under_cloudflare_row'); const PERM_KEYS = [ - "files_read", "files_delete", "files_rename", "files_archive", "console_read", "console_write", "server_stop", "server_start", "files_upload", "files_create", "activity_logs", "backups_view", "backups_create", "backups_delete", "scheduler_access", "scheduler_create", "scheduler_delete", "store_access", "subdomain_show", "subdomain_add", "server_reinstall" + "files_read", "files_write", "files_delete", "files_rename", "files_archive", "console_read", "console_write", "server_stop", "server_start", "files_upload", "files_create", "activity_logs", "backups_view", "backups_create", "backups_delete", "scheduler_access", "scheduler_create", "scheduler_delete", "store_access", "subdomain_show", "subdomain_add", "server_reinstall" ]; const templateExportMap = new Map(); const templateEditorState = { mode: 'create', - editTemplateId: '' + editTemplateId: '', + startupSource: '', + startupValue: '' }; const ACL_PREFIX = 'acl:'; const THEME_KEY = 'ui-theme'; @@ -535,13 +710,39 @@ function summarizePerms(perms) { const enabled = PERM_KEYS.filter(k => perms && perms[k]); return enabled.length ? enabled.join(', ') : 'none'; } -sidebarNav.addEventListener('click', (e) => { - const btn = e.target.closest('button'); if (!btn) return; +function escapeSettingsPanelSelectorValue(value) { + if (window.CSS && typeof window.CSS.escape === 'function') return window.CSS.escape(value); + return String(value || '').replace(/["\\]/g, '\\$&'); +} +function isValidSettingsPanel(panel) { + if (!panel || typeof panel !== 'string') return false; + const safePanel = escapeSettingsPanelSelectorValue(panel); + return !!document.getElementById(panel) && !!sidebarNav?.querySelector(`button[data-panel="${safePanel}"]`); +} +function getSavedSettingsPanel() { + try { + const savedPanel = sessionStorage.getItem(SETTINGS_PANEL_SESSION_KEY); + return isValidSettingsPanel(savedPanel) ? savedPanel : null; + } catch (e) { + return null; + } +} +function saveSettingsPanel(panel) { + if (!isValidSettingsPanel(panel)) return; + try { + sessionStorage.setItem(SETTINGS_PANEL_SESSION_KEY, panel); + } catch (e) { + } +} +function activateSettingsPanel(panel, options = {}) { + if (!isValidSettingsPanel(panel)) return false; + const btn = sidebarNav.querySelector(`button[data-panel="${escapeSettingsPanelSelectorValue(panel)}"]`); sidebarNav.querySelectorAll('button').forEach(b => b.classList.remove('active')); btn.classList.add('active'); - const panel = btn.dataset.panel; sections.forEach(s => s.classList.remove('active')); - const target = document.getElementById(panel); if (target) target.classList.add('active'); + const target = document.getElementById(panel); + target.classList.add('active'); + if (options.save !== false) saveSettingsPanel(panel); if (panel === 'servers') { loadServers(); } @@ -559,6 +760,11 @@ sidebarNav.addEventListener('click', (e) => { if (panel === 'panelinfo') { loadPanelInfo(); } + return true; +} +sidebarNav.addEventListener('click', (e) => { + const btn = e.target.closest('button'); if (!btn) return; + activateSettingsPanel(btn.dataset.panel); }); function deleteAllClientCookies() { const cookies = document.cookie.split("; "); @@ -601,23 +807,40 @@ const densitySelect = document.getElementById('densitySelect'); const animationsToggle = document.getElementById('animationsToggle'); const accentPicker = document.getElementById('accentPicker'); const savedBg = document.getElementById('savedBg'); +let currentBackground = null; +let backgroundSaveInFlight = false; +let lastBackgroundFingerprint = ''; async function sendBackgroundToServer(obj) { try { const res = await fetch('/api/settings/background', { method: 'POST', headers: { 'Content-Type': 'application/json' }, + credentials: 'include', body: JSON.stringify(obj) }); if (!res.ok) { const err = await res.json().catch(() => ({ error: 'failed' })); console.warn("Server returned error:", err); + throw new Error(err.error || 'Failed to save background'); } else { + const data = await res.json().catch(() => ({})); console.log("Background updated on server"); + return data.background || obj; } } catch (e) { console.error("Failed to send background to server", e); + throw e; } } +async function loadBackgroundFromServer(preferInjected = true) { + const injectedBackground = window.__ADPANEL_DASHBOARD_BACKGROUND__; + if (preferInjected && injectedBackground && injectedBackground.value) return injectedBackground; + + const res = await fetch('/api/settings/background', { credentials: 'include' }); + if (!res.ok) throw new Error('Failed to load background'); + const data = await res.json(); + return data.background || null; +} presets.forEach(p => { const el = document.createElement('div'); el.className = 'thumb'; @@ -626,19 +849,56 @@ presets.forEach(p => { el.addEventListener('click', () => selectThumb(el)); thumbsEl.appendChild(el); }); -function selectThumb(el) { +function markSelectedThumb(value) { document.querySelectorAll('.thumb').forEach(t => t.classList.remove('selected')); - el.classList.add('selected'); - const url = el.dataset.url; - bgPreview.style.backgroundImage = `url(${url})`; - bgPreview.style.backgroundSize = 'cover'; - bgPreview.style.backgroundPosition = 'center'; - const obj = { type: 'image', value: url }; - localStorage.setItem(BG_KEY, JSON.stringify(obj)); - updateSavedBgText(); - sendBackgroundToServer(obj); + if (!value) return; + const selected = Array.from(document.querySelectorAll('.thumb')).find(t => t.dataset.url === value); + if (selected) selected.classList.add('selected'); } -function setColor(hex) { +function getBackgroundFingerprint(obj) { + return obj && obj.type && obj.value ? `${obj.type}:${obj.value}` : ''; +} +function applyBackgroundLocally(obj, options = {}) { + if (!obj || !obj.type || !obj.value) return; + currentBackground = obj; + lastBackgroundFingerprint = getBackgroundFingerprint(obj); + const shouldCache = options.cache !== false; + if (shouldCache) localStorage.setItem(BG_KEY, JSON.stringify(obj)); + + if (obj.type === 'image' || obj.type === 'url' || obj.type === 'upload') { + bgPreview.style.backgroundImage = `url(${obj.value})`; + bgPreview.style.backgroundSize = 'cover'; + bgPreview.style.backgroundPosition = 'center'; + if (bgHex) bgHex.textContent = obj.type === 'upload' ? 'Uploaded image' : 'Image'; + markSelectedThumb(obj.value); + } else { + bgPreview.style.backgroundImage = 'none'; + bgPreview.style.backgroundColor = obj.value; + colorPicker.value = obj.value; + hexInput.value = obj.value; + colorDot.style.background = obj.value; + bgHex.textContent = obj.value; + markSelectedThumb(null); + } + updateSavedBgText(); +} +async function persistAndApplyBackground(obj) { + applyBackgroundLocally(obj); + try { + backgroundSaveInFlight = true; + const saved = await sendBackgroundToServer(obj); + applyBackgroundLocally(saved || obj); + } catch (err) { + alert(err.message || 'Failed to save background on server'); + } finally { + backgroundSaveInFlight = false; + } +} +function selectThumb(el) { + const url = el.dataset.url; + persistAndApplyBackground({ type: 'image', value: url }); +} +function setColor(hex, persist = true) { colorPicker.value = hex; hexInput.value = hex; colorDot.style.background = hex; @@ -655,9 +915,14 @@ function setColor(hex) { bgPreview.style.backgroundColor = hex; bgHex.textContent = hex; const obj = { type: 'color', value: hex }; - localStorage.setItem(BG_KEY, JSON.stringify(obj)); - updateSavedBgText(); - sendBackgroundToServer(obj); + applyBackgroundLocally(obj); + if (persist) { + backgroundSaveInFlight = true; + sendBackgroundToServer(obj) + .then((saved) => applyBackgroundLocally(saved || obj)) + .catch((err) => alert(err.message || 'Failed to save background on server')) + .finally(() => { backgroundSaveInFlight = false; }); + } } @@ -673,32 +938,50 @@ if (hexInput && colorPicker) { }); hexInput.style.cursor = 'pointer'; } -const bgSaved = localStorage.getItem(BG_KEY); -if (bgSaved) { +async function initializeBackgroundSelection() { try { - const v = JSON.parse(bgSaved); - if (v.type === 'image' || v.type === 'url' || v.type === 'upload') { - bgPreview.style.backgroundImage = `url(${v.value})`; - bgPreview.style.backgroundSize = 'cover'; - bgPreview.style.backgroundPosition = 'center'; - } else { - bgPreview.style.backgroundImage = 'none'; - bgPreview.style.backgroundColor = v.value; - colorPicker.value = v.value; - hexInput.value = v.value; - colorDot.style.background = v.value; - bgHex.textContent = v.value; + const serverBackground = await loadBackgroundFromServer(false); + if (serverBackground && serverBackground.value) { + applyBackgroundLocally(serverBackground); + return; } } catch (e) { - console.warn('invalid bg saved'); + console.warn('Failed to load server background, using local cache if present', e); } -} else { setColor('#ffffff'); } -function updateSavedBgText() { - const raw = localStorage.getItem(BG_KEY); - if (!raw) { savedBg.textContent = 'None'; return; } - try { const v = JSON.parse(raw); savedBg.textContent = v.type + ' — ' + (typeof v.value === 'string' && v.value.length > 40 ? v.value.slice(0, 40) + '...' : v.value); } catch (e) { savedBg.textContent = 'None' } + + const bgSaved = localStorage.getItem(BG_KEY); + if (bgSaved) { + try { + applyBackgroundLocally(JSON.parse(bgSaved)); + return; + } catch (e) { + console.warn('invalid bg saved'); + } + } + setColor('#ffffff', false); } -updateSavedBgText(); +async function refreshBackgroundSelectionFromServer() { + if (backgroundSaveInFlight || document.hidden) return; + try { + const serverBackground = await loadBackgroundFromServer(false); + if (!serverBackground || !serverBackground.value) return; + const nextFingerprint = getBackgroundFingerprint(serverBackground); + if (nextFingerprint && nextFingerprint !== lastBackgroundFingerprint) { + applyBackgroundLocally(serverBackground); + } + } catch (e) { + console.warn('Failed to refresh server background', e); + } +} +function updateSavedBgText() { + const v = currentBackground; + if (!v) { savedBg.textContent = 'None'; return; } + savedBg.textContent = v.type + ' — ' + (typeof v.value === 'string' && v.value.length > 40 ? v.value.slice(0, 40) + '...' : v.value); +} +initializeBackgroundSelection(); +window.addEventListener('focus', refreshBackgroundSelectionFromServer); +document.addEventListener('visibilitychange', refreshBackgroundSelectionFromServer); +setInterval(refreshBackgroundSelectionFromServer, 15000); colorPicker.addEventListener('input', (e) => setColor(e.target.value)); hexInput.addEventListener('change', (e) => { const v = e.target.value.trim(); if (/^#([0-9A-Fa-f]{3}){1,2}$/.test(v)) setColor(v); else alert('Please enter a valid hex, e.g. #282c34'); }); applyColorBtn.addEventListener('click', () => { const h = hexInput.value.trim(); if (/^#([0-9A-Fa-f]{3}){1,2}$/.test(h)) { setColor(h); console.log('Applied color selection:', h); } else alert('Invalid hex'); }); @@ -713,12 +996,7 @@ uploadFile.addEventListener('change', async (e) => { reader.onload = async () => { const dataUrl = reader.result; const obj = { type: 'upload', name: file.name, value: dataUrl }; - localStorage.setItem(BG_KEY, JSON.stringify(obj)); - bgPreview.style.backgroundImage = `url(${dataUrl})`; - bgPreview.style.backgroundSize = 'cover'; - bgPreview.style.backgroundPosition = 'center'; - updateSavedBgText(); - await sendBackgroundToServer({ type: 'upload', value: dataUrl }); + await persistAndApplyBackground(obj); }; reader.readAsDataURL(file); }); @@ -727,12 +1005,7 @@ useUrlBtn.addEventListener('click', async () => { if (!url) return alert('Enter a valid link'); if (!/^https?:\/\//i.test(url)) return alert('URL must start with http:// or https://'); const obj = { type: 'image', value: url }; - localStorage.setItem(BG_KEY, JSON.stringify(obj)); - bgPreview.style.backgroundImage = `url(${url})`; - bgPreview.style.backgroundSize = 'cover'; - bgPreview.style.backgroundPosition = 'center'; - updateSavedBgText(); - await sendBackgroundToServer(obj); + await persistAndApplyBackground(obj); }); if (colorDot && colorPicker) { @@ -757,11 +1030,27 @@ if (animationsToggleEl) { const savedAccent = localStorage.getItem(ACCENT_KEY); if (savedAccent) document.documentElement.style.setProperty('--accent', savedAccent); if (accentPicker) accentPicker.addEventListener('input', (e) => { document.documentElement.style.setProperty('--accent', e.target.value); localStorage.setItem(ACCENT_KEY, e.target.value); }); -if (changePassCard) changePassCard.addEventListener('click', () => { modalOverlay?.classList.add('show'); changeModal?.classList.add('show'); }); +function configureSettingsPasswordModalSecurity() { + const twoFactorField = document.getElementById('twoFactorField'); + const twoFactorInput = document.getElementById('modalTwoFactor'); + if (twoFactorField) twoFactorField.style.display = currentUserHas2FA ? 'block' : 'none'; + if (twoFactorInput) { + twoFactorInput.value = ''; + twoFactorInput.required = currentUserHas2FA; + } +} +if (changePassCard) { + changePassCard.addEventListener('click', () => { + configureSettingsPasswordModalSecurity(); + modalOverlay?.classList.add('show'); + changeModal?.classList.add('show'); + }); +} const closePasswordModal = () => { modalOverlay?.classList.remove('show'); changeModal?.classList.remove('show'); }; if (modalCancel) modalCancel.addEventListener('click', closePasswordModal); if (modalCancelBtn) modalCancelBtn.addEventListener('click', closePasswordModal); -if (modalOverlay) modalOverlay.addEventListener('click', (e) => { if (e.target === modalOverlay) closePasswordModal(); }); +// Click outside disabled — user must use close/cancel button +// if (modalOverlay) modalOverlay.addEventListener('click', (e) => { if (e.target === modalOverlay) closePasswordModal(); }); document.querySelectorAll('.password-toggle').forEach(btn => { if (btn.dataset.listenerAdded) return; @@ -831,6 +1120,12 @@ modalSave.addEventListener('click', async () => { showFeedback('Passwords do not match', true); return; } + if (currentUserHas2FA && !/^\d{6}$/.test(String(twoFactorCode || '').replace(/\s+/g, ''))) { + configureSettingsPasswordModalSecurity(); + showFeedback('Please enter a valid 6-digit 2FA code', true); + document.getElementById('modalTwoFactor')?.focus(); + return; + } try { modalSave.disabled = true; @@ -839,7 +1134,7 @@ modalSave.addEventListener('click', async () => { const res = await fetch('/api/settings/change-password', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ current: cur, newPassword: nw, confirm: cf, twoFactorCode: twoFactorCode }) + body: JSON.stringify({ current: cur, newPassword: nw, confirm: cf, twoFactorCode: currentUserHas2FA ? twoFactorCode : '' }) }); const data = await res.json().catch(() => ({ error: 'Invalid server response' })); @@ -862,7 +1157,7 @@ modalSave.addEventListener('click', async () => { document.getElementById('modalNew').value = ''; document.getElementById('modalConfirm').value = ''; if (document.getElementById('modalTwoFactor')) document.getElementById('modalTwoFactor').value = ''; - if (document.getElementById('twoFactorField')) document.getElementById('twoFactorField').style.display = 'none'; + if (!currentUserHas2FA && document.getElementById('twoFactorField')) document.getElementById('twoFactorField').style.display = 'none'; modalOverlay.classList.remove('show'); changeModal.classList.remove('show'); window.location.reload(); }, 1500); @@ -875,6 +1170,7 @@ modalSave.addEventListener('click', async () => { } }); async function loadServers(page, search) { + if (!serversListEl) return; if (typeof page === 'undefined') page = _serversPage; if (typeof search === 'undefined') search = _serversSearch; _serversPage = page; @@ -886,7 +1182,7 @@ async function loadServers(page, search) { try { const params = new URLSearchParams({ page: String(page), limit: String(_serversLimit) }); if (search) params.set('search', search); - const res = await fetch('/api/settings/servers?' + params.toString()); + const res = await fetchWithTimeout('/api/settings/servers?' + params.toString(), {}, 15000); if (!res.ok) { const err = await res.json().catch(() => ({ error: 'failed' })); serversListEl.innerHTML = `
    Failed to load servers
    `; @@ -894,6 +1190,10 @@ async function loadServers(page, search) { return; } const data = await res.json(); + serversListEl._actionTokens = data.actionTokens || {}; + try { + window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); + } catch (_) { } const items = Array.isArray(data.items) ? data.items : (Array.isArray(data.names) ? data.names.map(n => ({ name: n, isLocal: true, nodeId: null })) : []); @@ -912,21 +1212,37 @@ function shortId(id) { } function renderServers(list) { if (!Array.isArray(list) || list.length === 0) { + serversListEl._deleteTokensByName = new Map(); + serversListEl._suspensionTokensByName = new Map(); serversListEl.innerHTML = `
    No servers found.
    `; return; } serversListEl.innerHTML = ''; + serversListEl._deleteTokensByName = new Map(); + serversListEl._suspensionTokensByName = new Map(); list.forEach(item => { - const name = item.name || String(item); + const name = String(item.name || String(item) || '').trim(); const visibleName = item.displayName || name; const isLocal = (item && typeof item.isLocal === 'boolean') ? item.isLocal : (!item.nodeId); const chipText = isLocal ? 'ID: localhost' : `ID: ${item.nodeId}`; const templateLabel = displayTemplateName(item?.template); + const deleteToken = String(item?.deleteToken || '').trim(); + const suspensionToken = String(item?.suspensionToken || '').trim(); + const isSuspendedServer = item?.suspended === true || item?.suspended === 1 || String(item?.suspended || '').toLowerCase() === 'true'; + if (name && deleteToken) { + serversListEl._deleteTokensByName.set(name, deleteToken); + serversListEl._deleteTokensByName.set(name.toLowerCase(), deleteToken); + } + if (name && suspensionToken) { + serversListEl._suspensionTokensByName.set(name, suspensionToken); + serversListEl._suspensionTokensByName.set(name.toLowerCase(), suspensionToken); + } const row = document.createElement('div'); - row.className = 'server-row clickable-card'; + row.className = `server-row clickable-card${isSuspendedServer ? ' server-row-suspended' : ''}`; row.dataset.name = name; row.dataset.template = item?.template || ''; row.dataset.nodeId = item?.nodeId ? String(item.nodeId) : ''; + row.dataset.suspended = isSuspendedServer ? '1' : '0'; row.innerHTML = `
    @@ -935,28 +1251,70 @@ function renderServers(list) {
    ${escapeHtml(chipText)} Template: ${escapeHtml(templateLabel)} + ${isSuspendedServer ? ' Suspended' : ''}
    - - - - - +
    `; + const deleteButton = row.querySelector('.delete-server'); + if (deleteButton) deleteButton.dataset.deleteToken = deleteToken; + const suspensionButton = row.querySelector('.server-suspension-action'); + if (suspensionButton) suspensionButton.dataset.suspensionToken = suspensionToken; serversListEl.appendChild(row); }); } +function getServerDeleteToken(serverName, sourceButton = null) { + const directToken = String(sourceButton?.dataset?.deleteToken || '').trim(); + if (directToken) return directToken; + const name = String(serverName || '').trim(); + if (!name) return ''; + const tokens = serversListEl?._deleteTokensByName; + if (tokens && typeof tokens.get === 'function') { + return String(tokens.get(name) || tokens.get(name.toLowerCase()) || '').trim(); + } + return ''; +} +async function refreshServerDeleteToken(serverName) { + const name = String(serverName || '').trim(); + if (!name) return ''; + await loadServers(_serversPage, _serversSearch); + return getServerDeleteToken(name); +} +function getServerSuspensionToken(serverName, sourceButton = null) { + const directToken = String(sourceButton?.dataset?.suspensionToken || '').trim(); + if (directToken) return directToken; + const name = String(serverName || '').trim(); + if (!name) return ''; + const tokens = serversListEl?._suspensionTokensByName; + if (tokens && typeof tokens.get === 'function') { + return String(tokens.get(name) || tokens.get(name.toLowerCase()) || '').trim(); + } + return ''; +} +async function refreshServerSuspensionToken(serverName) { + const name = String(serverName || '').trim(); + if (!name) return ''; + await loadServers(_serversPage, _serversSearch); + return getServerSuspensionToken(name); +} function renderServersPagination(currentPage, totalPages, total) { const el = document.getElementById('serversPagination'); if (!el) return; @@ -1174,6 +1532,541 @@ function renderTemplatesPagination(currentPage, totalPages, total) { }); }); } + +const TEMPLATE_STORE_API = '/api/settings/template-store'; +const TEMPLATE_STORE_CATEGORIES = [ + { id: 'games', label: 'Games' }, + { id: 'communication', label: 'Communication' }, + { id: 'development', label: 'Development' }, + { id: 'hosting', label: 'Hosting' }, + { id: 'media', label: 'Media' }, +]; +const templateStoreCategoryCache = new Map(); +const templateStoreFileCache = new Map(); +const templateStoreItemCache = new Map(); +const templateStoreState = { + activeCategory: 'games', + query: '', + renderToken: 0, + searchTimer: null, + closeTimer: null, + installedTemplateIds: new Set(), +}; + +function getTemplateStoreCategory(categoryId) { + return TEMPLATE_STORE_CATEGORIES.find(category => category.id === categoryId) || TEMPLATE_STORE_CATEGORIES[0]; +} + +function getTemplateStoreCategoryCache(categoryId) { + if (!templateStoreCategoryCache.has(categoryId)) { + templateStoreCategoryCache.set(categoryId, { items: null, promise: null, error: null }); + } + return templateStoreCategoryCache.get(categoryId); +} + +function setTemplateStoreFeedback(message, type = '') { + if (!templateStoreFeedback) return; + templateStoreFeedback.textContent = message || ''; + templateStoreFeedback.classList.toggle('is-error', type === 'error'); + templateStoreFeedback.classList.toggle('is-success', type === 'success'); +} + +function renderTemplateStoreLoading(message) { + if (!templateStoreGrid) return; + templateStoreGrid.innerHTML = ` +
    + +
    ${escapeHtml(message || 'Loading templates...')}
    +
    + `; +} + +function renderTemplateStoreEmpty() { + if (!templateStoreGrid) return; + templateStoreGrid.innerHTML = ` +
    +
    :(
    +
    Nothing found
    +
    + `; +} + +function renderTemplateStoreError(message) { + if (!templateStoreGrid) return; + templateStoreGrid.innerHTML = ` +
    + +
    ${escapeHtml(message || 'Unable to load store templates.')}
    +
    + `; +} + +async function mapTemplateStoreWithConcurrency(list, limit, worker) { + const entries = Array.isArray(list) ? list : []; + const results = new Array(entries.length); + let index = 0; + const size = Math.max(1, Math.min(limit || 4, entries.length || 1)); + const runners = Array.from({ length: size }, async () => { + while (index < entries.length) { + const currentIndex = index; + index += 1; + results[currentIndex] = await worker(entries[currentIndex], currentIndex); + } + }); + await Promise.all(runners); + return results; +} + +async function fetchTemplateStoreJsonFile(file) { + const cacheKey = file?.url || file?.download_url || file?.path || file?.name; + if (!cacheKey) return null; + if (templateStoreFileCache.has(cacheKey)) return templateStoreFileCache.get(cacheKey); + + const promise = (async () => { + if (file && Object.prototype.hasOwnProperty.call(file, 'payload')) { + return file.payload; + } + const raw = typeof file?.raw === 'string' ? file.raw : ''; + if (!raw.trim()) return null; + return JSON.parse(raw); + })().catch((err) => { + templateStoreFileCache.delete(cacheKey); + throw err; + }); + + templateStoreFileCache.set(cacheKey, promise); + return promise; +} + +function getStoreTemplateImage(payload) { + return String( + payload?.templateImage || + payload?.template_image || + payload?.image || + payload?.icon || + payload?.logo || + '' + ).trim(); +} + +function sanitizeTemplateStoreAssetUrl(value) { + const raw = String(value || '').trim(); + if (!raw || raw.length > 2048 || /[\u0000-\u001f"\\]/.test(raw)) return ''; + if (raw.startsWith('/') && !raw.startsWith('//')) return raw; + try { + const parsed = new URL(raw); + return (parsed.protocol === 'https:' || parsed.protocol === 'http:') ? parsed.href : ''; + } catch { + return ''; + } +} + +function getStoreTemplateDockerImage(payload) { + return String( + payload?.docker?.image || + payload?.dockerImage || + payload?.docker_image || + '' + ).trim(); +} + +function normalizeStoreTemplateEntry(payload, file, category, index = 0) { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null; + const fallbackId = String(file?.name || 'template').replace(/\.json$/i, ''); + const rawId = String(payload.id || payload.template_id || fallbackId).trim(); + const id = slugifyTemplateId(rawId || fallbackId); + const name = String(payload.name || payload.template_name || rawId || fallbackId).trim(); + const description = String(payload.description || payload.shortDescription || payload.summary || 'No description').trim(); + const image = sanitizeTemplateStoreAssetUrl(getStoreTemplateImage(payload)); + const dockerImage = getStoreTemplateDockerImage(payload); + const cacheKey = `${category.id}:${file?.path || file?.name || id}:${index}:${id}`; + const searchText = [ + id, + name, + description, + category.label, + category.id, + dockerImage, + file?.name, + file?.path, + ].join(' ').toLowerCase(); + + const item = { + cacheKey, + id, + name, + description, + image, + dockerImage, + categoryId: category.id, + categoryLabel: category.label, + fileName: file?.name || `${id}.json`, + sourceUrl: file?.html_url || file?.download_url || '', + payload, + searchText, + }; + templateStoreItemCache.set(cacheKey, item); + return item; +} + +function extractStoreTemplateEntries(parsed, file, category) { + const payloads = Array.isArray(parsed) ? parsed : [parsed]; + return payloads + .map((payload, index) => normalizeStoreTemplateEntry(payload, file, category, index)) + .filter(Boolean); +} + +function compareTemplateStoreItems(a, b) { + return String(a?.name || a?.id || '').localeCompare(String(b?.name || b?.id || ''), undefined, { + sensitivity: 'base', + numeric: true, + }); +} + +async function fetchTemplateStoreCategory(categoryId) { + const category = getTemplateStoreCategory(categoryId); + const cache = getTemplateStoreCategoryCache(category.id); + if (Array.isArray(cache.items)) return cache.items; + if (cache.promise) return cache.promise; + + cache.promise = (async () => { + try { + const res = await fetch(`${TEMPLATE_STORE_API}/${encodeURIComponent(category.id)}`, { + headers: { Accept: 'application/json' }, + }); + if (res.status === 404) { + cache.items = []; + cache.error = null; + return cache.items; + } + const data = await res.json().catch(() => null); + if (!res.ok) { + throw new Error(data?.error || `Template store returned ${res.status}`); + } + + const files = Array.isArray(data?.files) ? data.files : []; + const jsonFiles = files + .filter(file => file && file.type === 'file' && /\.json$/i.test(String(file.name || ''))) + .slice(0, 120); + + const groups = await mapTemplateStoreWithConcurrency(jsonFiles, 4, async (file) => { + try { + const parsed = await fetchTemplateStoreJsonFile(file); + return extractStoreTemplateEntries(parsed, file, category); + } catch (err) { + console.warn('[template-store] Failed to load template JSON:', file?.path || file?.name, err); + return []; + } + }); + + cache.items = groups.flat().sort(compareTemplateStoreItems); + cache.error = null; + return cache.items; + } catch (err) { + cache.items = null; + cache.error = err; + throw err; + } finally { + cache.promise = null; + } + })(); + + return cache.promise; +} + +async function fetchAllTemplateStoreCategories() { + const groups = await mapTemplateStoreWithConcurrency(TEMPLATE_STORE_CATEGORIES, 2, async (category) => { + try { + return await fetchTemplateStoreCategory(category.id); + } catch (err) { + console.warn('[template-store] Failed to load category:', category.id, err); + return []; + } + }); + return groups.flat().sort(compareTemplateStoreItems); +} + +function setTemplateStoreActiveCategory(categoryId) { + templateStoreState.activeCategory = getTemplateStoreCategory(categoryId).id; + document.querySelectorAll('.template-store-tab').forEach(tab => { + tab.classList.toggle('active', tab.dataset.storeCategory === templateStoreState.activeCategory); + }); +} + +function cloneTemplateStorePayload(payload) { + try { + return JSON.parse(JSON.stringify(payload || {})); + } catch { + return { ...(payload || {}) }; + } +} + +function buildTemplateStoreInstallPayload(item) { + const payload = cloneTemplateStorePayload(item?.payload || {}); + payload.id = slugifyTemplateId(payload.id || payload.template_id || item?.id || item?.name || item?.fileName || 'store-template'); + payload.name = String(payload.name || payload.template_name || item?.name || payload.id).trim(); + payload.description = String(payload.description || item?.description || '').trim(); + if (!payload.templateImage && !payload.template_image && item?.image) { + payload.templateImage = item.image; + } + return payload; +} + +function isTemplateStoreItemInstalled(item) { + const normalizedId = normalizeTemplateIdClient(item?.id); + return !!normalizedId && templateStoreState.installedTemplateIds.has(normalizedId); +} + +async function refreshTemplateStoreInstalledTemplates() { + const installed = new Set(); + let page = 1; + let totalPages = 1; + try { + do { + const params = new URLSearchParams({ page: String(page), limit: '200' }); + const res = await fetch('/api/settings/templates?' + params.toString()); + const data = await res.json().catch(() => ({ templates: [] })); + if (!res.ok) throw new Error(data.error || 'Failed to load installed templates.'); + (Array.isArray(data.templates) ? data.templates : []).forEach(template => { + const normalizedId = normalizeTemplateIdClient(template?.id); + if (normalizedId) installed.add(normalizedId); + }); + totalPages = Math.max(1, Number(data.totalPages || 1)); + page += 1; + } while (page <= totalPages && page <= 10); + templateStoreState.installedTemplateIds = installed; + } catch (err) { + console.warn('[template-store] Failed to read installed templates:', err); + } +} + +function renderTemplateStoreCards(items) { + if (!templateStoreGrid) return; + templateStoreItemCache.clear(); + if (!Array.isArray(items) || items.length === 0) { + renderTemplateStoreEmpty(); + return; + } + + templateStoreGrid.innerHTML = ''; + const fragment = document.createDocumentFragment(); + + items.slice().sort(compareTemplateStoreItems).forEach(item => { + templateStoreItemCache.set(item.cacheKey, item); + const isInstalled = isTemplateStoreItemInstalled(item); + const card = document.createElement('article'); + card.className = 'template-store-card'; + + const media = document.createElement('div'); + media.className = 'template-store-card-media'; + if (item.image) { + const imageUrl = item.image.replace(/["\\\n\r]/g, ''); + media.style.backgroundImage = `url("${imageUrl}")`; + } else { + media.innerHTML = '
    '; + } + const chip = document.createElement('div'); + chip.className = 'template-store-category-chip'; + chip.textContent = item.categoryLabel; + media.appendChild(chip); + + const body = document.createElement('div'); + body.className = 'template-store-card-body'; + body.innerHTML = ` +
    ${escapeHtml(item.name || item.id)}
    +
    ${escapeHtml(item.description || 'No description')}
    +
    + + ${escapeHtml(item.dockerImage || 'Custom image')} +
    + `; + + const actions = document.createElement('div'); + actions.className = 'template-store-card-actions'; + actions.innerHTML = ` + + `; + + card.appendChild(media); + card.appendChild(body); + card.appendChild(actions); + fragment.appendChild(card); + }); + + templateStoreGrid.appendChild(fragment); +} + +async function loadTemplateStoreView() { + if (!templateStoreGrid) return; + const token = templateStoreState.renderToken + 1; + templateStoreState.renderToken = token; + const query = String(templateStoreState.query || '').trim().toLowerCase(); + setTemplateStoreFeedback(''); + + try { + if (query) { + renderTemplateStoreLoading('Searching store...'); + const allItems = await fetchAllTemplateStoreCategories(); + if (token !== templateStoreState.renderToken) return; + const terms = query.split(/\s+/).filter(Boolean); + const filtered = allItems + .filter(item => terms.every(term => item.searchText.includes(term))) + .sort(compareTemplateStoreItems); + renderTemplateStoreCards(filtered); + return; + } + + const category = getTemplateStoreCategory(templateStoreState.activeCategory); + renderTemplateStoreLoading(`Loading ${category.label}...`); + const items = await fetchTemplateStoreCategory(category.id); + if (token !== templateStoreState.renderToken) return; + renderTemplateStoreCards(items); + } catch (err) { + console.error(err); + if (token !== templateStoreState.renderToken) return; + setTemplateStoreFeedback('Unable to read the cached ADTemplates store.', 'error'); + renderTemplateStoreError('Unable to load store templates.'); + } +} + +function openTemplateStoreModal() { + if (!templateStoreOverlay || !templateStoreModal) return; + if (templateStoreState.closeTimer) { + clearTimeout(templateStoreState.closeTimer); + templateStoreState.closeTimer = null; + } + templateStoreOverlay.classList.remove('closing'); + templateStoreOverlay.removeAttribute('inert'); + templateStoreOverlay.setAttribute('aria-hidden', 'false'); + templateStoreOverlay.classList.add('show'); + templateStoreModal.classList.add('show'); + setTemplateStoreActiveCategory(templateStoreState.activeCategory); + refreshTemplateStoreInstalledTemplates().finally(loadTemplateStoreView); +} + +function closeTemplateStoreModal() { + if (!templateStoreOverlay || !templateStoreModal) return; + if (!templateStoreOverlay.classList.contains('show')) return; + templateStoreOverlay.classList.add('closing'); + if (templateStoreOverlay.contains(document.activeElement)) { + if (openTemplateStoreBtn) { + openTemplateStoreBtn.focus({ preventScroll: true }); + } else if (document.activeElement && typeof document.activeElement.blur === 'function') { + document.activeElement.blur(); + } + } + if (templateStoreState.closeTimer) clearTimeout(templateStoreState.closeTimer); + templateStoreState.closeTimer = setTimeout(() => { + templateStoreOverlay.classList.remove('show', 'closing'); + templateStoreModal.classList.remove('show'); + templateStoreOverlay.setAttribute('aria-hidden', 'true'); + templateStoreOverlay.setAttribute('inert', ''); + templateStoreState.closeTimer = null; + }, 220); + setTemplateStoreFeedback(''); +} + +async function installTemplateStoreItem(item, button) { + if (!item) return; + const originalHtml = button ? button.innerHTML : ''; + try { + if (button) { + button.disabled = true; + button.innerHTML = ' Installing'; + } + setTemplateStoreFeedback(''); + const payload = buildTemplateStoreInstallPayload(item); + const res = await fetch('/api/settings/templates', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload), + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + if (!res.ok) { + const alreadyExists = String(data.error || '').toLowerCase().includes('already exists'); + if (alreadyExists && button) { + button.classList.add('is-installed'); + button.disabled = true; + button.innerHTML = ' Installed'; + const normalizedId = normalizeTemplateIdClient(item?.id); + if (normalizedId) templateStoreState.installedTemplateIds.add(normalizedId); + setTemplateStoreFeedback(''); + } else if (button) { + button.disabled = false; + button.innerHTML = originalHtml; + setTemplateStoreFeedback(data.error || 'Failed to install template.', 'error'); + } + return; + } + + if (button) { + button.classList.add('is-installed'); + button.disabled = true; + button.innerHTML = ' Installed'; + } + const normalizedId = normalizeTemplateIdClient(data.template?.id || item?.id); + if (normalizedId) templateStoreState.installedTemplateIds.add(normalizedId); + setTemplateStoreFeedback(''); + _templatesPage = 1; + _templatesSearch = ''; + const localTemplatesSearchInput = document.getElementById('templatesSearchInput'); + if (localTemplatesSearchInput) localTemplatesSearchInput.value = ''; + loadTemplates(1, ''); + } catch (err) { + console.error(err); + if (button) { + button.disabled = false; + button.innerHTML = originalHtml; + } + setTemplateStoreFeedback('Network error while installing template.', 'error'); + } +} + +if (openTemplateStoreBtn) { + openTemplateStoreBtn.addEventListener('click', openTemplateStoreModal); +} + +if (templateStoreClose) { + templateStoreClose.addEventListener('click', closeTemplateStoreModal); +} + +// Click outside disabled — user must use close/cancel button +// if (templateStoreOverlay) { +// templateStoreOverlay.addEventListener('click', (e) => { +// if (e.target === templateStoreOverlay) closeTemplateStoreModal(); +// }); +// } + +document.querySelectorAll('.template-store-tab').forEach(tab => { + tab.addEventListener('click', () => { + setTemplateStoreActiveCategory(tab.dataset.storeCategory || 'games'); + templateStoreState.query = ''; + if (templateStoreSearch) templateStoreSearch.value = ''; + loadTemplateStoreView(); + }); +}); + +if (templateStoreSearch) { + templateStoreSearch.addEventListener('input', () => { + clearTimeout(templateStoreState.searchTimer); + templateStoreState.searchTimer = setTimeout(() => { + templateStoreState.query = templateStoreSearch.value.trim(); + loadTemplateStoreView(); + }, 220); + }); +} + +if (templateStoreGrid) { + templateStoreGrid.addEventListener('click', (e) => { + const button = e.target.closest('.template-store-install'); + if (!button) return; + const item = templateStoreItemCache.get(button.dataset.storeKey || ''); + installTemplateStoreItem(item, button); + }); +} + function openTemplateModal() { createTemplateOverlay.classList.add('show'); createTemplateModal.classList.add('show'); @@ -1188,8 +2081,11 @@ function closeTemplateModal() { function setTemplateModalMode(mode, template = null) { const nextMode = mode === 'edit' ? 'edit' : 'create'; + const modalStartup = getTemplateEditorStartup(template); templateEditorState.mode = nextMode; templateEditorState.editTemplateId = nextMode === 'edit' ? String(template?.id || '').trim() : ''; + templateEditorState.startupSource = modalStartup.source; + templateEditorState.startupValue = modalStartup.value; if (createTemplateModal) createTemplateModal.dataset.mode = nextMode; @@ -1213,6 +2109,40 @@ function setTemplateModalMode(mode, template = null) { } } +function getTemplateManagedStartup(template) { + return String( + template?.docker?.adpanelStartup || + template?.docker?.adpanel_startup || + template?.docker?.pterodactylStartup || + template?.docker?.pterodactyl_startup || + '' + ).trim(); +} + +function getTemplateEditorStartup(template) { + const managedStartup = getTemplateManagedStartup(template); + if (managedStartup) return { value: managedStartup, source: 'managed' }; + return { + value: String(template?.docker?.command || '').trim(), + source: '' + }; +} + +function startupCommandNeedsManagedRuntime(command) { + const value = String(command || '').trim(); + if (!value) return false; + if (value.includes('\n')) return true; + if (value.includes('`') || value.includes('$')) return true; + const args = parseRuntimeProcessArgsInput(value); + if (args.length && isRuntimeEnvAssignmentTokenInput(args[0])) return true; + const { execName: resolvedExecName, index: execIndex } = resolveRuntimeProcessExecutableArgsInput(args); + if (validateRuntimeContainerLauncherInput(args)) return false; + if (isBlockedRuntimeShellExecutableInput(resolvedExecName || args[0]) && isRuntimeShellWrapperArgsInput(args, execIndex)) { + return true; + } + return args.some(arg => RUNTIME_PROCESS_BLOCKED_TOKENS.has(String(arg || '').trim())); +} + function clearTemplateForm() { if (ct_name) ct_name.value = ''; if (ct_id) ct_id.value = ''; @@ -1224,7 +2154,9 @@ function clearTemplateForm() { if (ct_startup_command) ct_startup_command.value = ''; if (ct_workdir) ct_workdir.value = ''; if (ct_env_json) ct_env_json.value = ''; - if (ct_adpanel_startup) ct_adpanel_startup.value = ''; + templateEditorState.startupSource = ''; + templateEditorState.startupValue = ''; + if (ct_advanced_settings) ct_advanced_settings.open = false; populateTemplateInstallForm(null); if (ct_import_json) ct_import_json.value = ''; } @@ -1238,7 +2170,10 @@ function populateTemplateForm(template) { if (ct_default_port) ct_default_port.value = String(template.defaultPort || template.default_port || '').trim(); if (ct_image) ct_image.value = String(template?.docker?.image || '').trim(); if (ct_tag) ct_tag.value = String(template?.docker?.tag || 'latest').trim() || 'latest'; - if (ct_startup_command) ct_startup_command.value = String(template?.docker?.command || '').trim(); + const startup = getTemplateEditorStartup(template); + templateEditorState.startupSource = startup.source; + templateEditorState.startupValue = startup.value; + if (ct_startup_command) ct_startup_command.value = startup.value; if (ct_workdir) ct_workdir.value = String(template?.docker?.workdir || '').trim(); if (ct_env_json) { const env = template?.docker?.env && typeof template.docker.env === 'object' && !Array.isArray(template.docker.env) @@ -1246,15 +2181,6 @@ function populateTemplateForm(template) { : {}; ct_env_json.value = Object.keys(env).length ? JSON.stringify(env, null, 2) : ''; } - if (ct_adpanel_startup) { - ct_adpanel_startup.value = String( - template?.docker?.adpanelStartup || - template?.docker?.adpanel_startup || - template?.docker?.pterodactylStartup || - template?.docker?.pterodactyl_startup || - '' - ).trim(); - } populateTemplateInstallForm(template?.docker?.install || null); if (ct_import_json) ct_import_json.value = ''; } @@ -1346,19 +2272,11 @@ function buildTemplateInstallFromForm() { const script = String(ct_install_script?.value || '').trim(); if (!script) return null; - const timeoutRaw = String(ct_install_timeout?.value || '').trim(); - const timeout = timeoutRaw ? Number.parseInt(timeoutRaw, 10) : 1800; - if (!Number.isInteger(timeout) || timeout < 60 || timeout > 7200) { - throw new Error('Install timeout must be between 60 and 7200 seconds.'); - } - const install = { image: String(ct_install_image?.value || '').trim() || 'ghcr.io/pterodactyl/installers:debian', script, - entrypoint: String(ct_install_entrypoint?.value || '').trim() || 'bash', mountPath: sanitizeTemplateWorkdirInput(ct_install_mount?.value || '/mnt/server') || '/mnt/server', runtimePath: sanitizeTemplateWorkdirInput(ct_install_runtime?.value || '/home/container') || '/home/container', - timeoutSeconds: timeout, }; const mountError = validateTemplateWorkdirInput(install.mountPath); @@ -1372,10 +2290,8 @@ function buildTemplateInstallFromForm() { function populateTemplateInstallForm(install) { const cfg = install && typeof install === 'object' ? install : {}; if (ct_install_image) ct_install_image.value = String(cfg.image || cfg.container || '').trim(); - if (ct_install_entrypoint) ct_install_entrypoint.value = String(cfg.entrypoint || '').trim(); if (ct_install_mount) ct_install_mount.value = String(cfg.mountPath || cfg.containerPath || '/mnt/server').trim(); if (ct_install_runtime) ct_install_runtime.value = String(cfg.runtimePath || '/home/container').trim(); - if (ct_install_timeout) ct_install_timeout.value = String(cfg.timeoutSeconds || cfg.timeout || '').trim(); if (ct_install_script) ct_install_script.value = String(cfg.script || '').trim(); } @@ -1410,18 +2326,15 @@ function adpanelEggToTemplatePayload(payload) { description: String(payload.description || '').trim(), docker_image: image, docker_tag: tag, - startup: '', - adpanelStartup: startup, + startup, workdir: '/home/container', defaultPort, env, install: installation ? { image: String(installation.container || installation.image || '').trim() || 'ghcr.io/pterodactyl/installers:debian', script: String(installation.script || '').trim(), - entrypoint: String(installation.entrypoint || '').trim() || 'bash', mountPath: '/mnt/server', runtimePath: '/home/container', - timeoutSeconds: 1800, } : null, }; } @@ -1452,8 +2365,8 @@ function applyTemplateJsonImport(payload) { const description = String(payload.description || '').trim(); const dockerImage = String(payload.docker_image || '').trim(); const dockerTag = String(payload.docker_tag || 'latest').trim() || 'latest'; - const startup = String(payload.startup || '').trim(); - const adpanelStartup = String( + const startup = String( + payload.startup || payload.adpanelStartup || payload.adpanel_startup || payload.pterodactylStartup || @@ -1470,7 +2383,9 @@ function applyTemplateJsonImport(payload) { throw new Error('JSON must include non-empty template_name, template_id and docker_image.'); } - const startupCommandError = validateRuntimeProcessCommandInput(startup); + const startupCommandError = startupCommandNeedsManagedRuntime(startup) + ? null + : validateRuntimeProcessCommandInput(startup); if (startupCommandError) { throw new Error(startupCommandError); } @@ -1491,7 +2406,8 @@ function applyTemplateJsonImport(payload) { if (ct_image) ct_image.value = dockerImage; if (ct_tag) ct_tag.value = dockerTag; if (ct_startup_command) ct_startup_command.value = startup; - if (ct_adpanel_startup) ct_adpanel_startup.value = adpanelStartup; + templateEditorState.startupSource = startupCommandNeedsManagedRuntime(startup) ? 'managed' : ''; + templateEditorState.startupValue = startup; if (ct_template_image) ct_template_image.value = templateImage; if (ct_workdir) ct_workdir.value = workdir; if (ct_default_port) ct_default_port.value = defaultPort ? String(defaultPort) : ''; @@ -1499,7 +2415,7 @@ function applyTemplateJsonImport(payload) { populateTemplateInstallForm(install); } -[createTemplateCancel, createTemplateClose, createTemplateOverlay].forEach(el => { +[createTemplateCancel, createTemplateClose].forEach(el => { if (!el) return; el.addEventListener('click', (e) => { if (e.target === el || el === createTemplateCancel || el === createTemplateClose) { @@ -1507,6 +2423,12 @@ function applyTemplateJsonImport(payload) { } }); }); +// Click outside disabled — user must use close/cancel button +// if (createTemplateOverlay) { +// createTemplateOverlay.addEventListener('click', (e) => { +// if (e.target === createTemplateOverlay) closeTemplateModal(); +// }); +// } if (openCreateTemplateBtn) { openCreateTemplateBtn.addEventListener('click', () => { setTemplateModalMode('create'); @@ -1554,7 +2476,13 @@ if (createTemplateSave) { const startupCommand = (ct_startup_command?.value || '').trim(); const workdirInput = ct_workdir?.value || ''; const workdir = sanitizeTemplateWorkdirInput(workdirInput); - const adpanelStartup = String(ct_adpanel_startup?.value || '').trim(); + const preserveManagedStartup = templateEditorState.startupSource === 'managed' + && startupCommand + && startupCommand === templateEditorState.startupValue; + const storeStartupAsManaged = !!startupCommand && ( + preserveManagedStartup || + startupCommandNeedsManagedRuntime(startupCommand) + ); let defaultPort = null; let env = {}; let install = null; @@ -1569,7 +2497,9 @@ if (createTemplateSave) { return; } - const startupCommandError = validateRuntimeProcessCommandInput(startupCommand); + const startupCommandError = storeStartupAsManaged + ? null + : validateRuntimeProcessCommandInput(startupCommand); if (startupCommandError) { createTemplateFeedback.textContent = startupCommandError; return; @@ -1608,10 +2538,10 @@ if (createTemplateSave) { dockerTag: tag, templateImage, defaultPort, - command: startupCommand, + command: storeStartupAsManaged ? '' : startupCommand, dockerWorkdir: workdir, env, - adpanelStartup, + adpanelStartup: storeStartupAsManaged ? startupCommand : '', install, }) }); @@ -1882,9 +2812,12 @@ if (serverTemplateCancel) { if (serverTemplateClose) { serverTemplateClose.addEventListener('click', closeServerTemplateModal); } -if (serverTemplateOverlay) { - // Click outside disabled — user must use close/cancel button -} +// Click outside disabled — user must use close/cancel button +// if (serverTemplateOverlay) { +// serverTemplateOverlay.addEventListener('click', (e) => { +// if (e.target === serverTemplateOverlay) closeServerTemplateModal(); +// }); +// } if (serverTemplateDone) { serverTemplateDone.addEventListener('click', async () => { const server = serverTemplateModal?.dataset?.server || ''; @@ -1983,6 +2916,14 @@ createServerBtn.addEventListener('click', async () => { createServerBtn.innerHTML = ' Create'; } }); +serversListEl.addEventListener('mouseover', (e) => { + const resourceBtn = e.target.closest('.manage-resources'); + if (!resourceBtn) return; + const row = resourceBtn.closest('.server-row'); + const serverName = row?.dataset?.name || (resourceBtn.dataset.name ? decodeURIComponent(resourceBtn.dataset.name) : ''); + if (serverName) _prefetchResources(serverName); +}); + serversListEl.addEventListener('click', async (e) => { const resourceBtn = e.target.closest('.manage-resources'); if (resourceBtn) { @@ -2017,31 +2958,32 @@ serversListEl.addEventListener('click', async (e) => { if (serverName) openServerTemplateModal(serverName, currentTemplate); return; } + + const suspendBtn = e.target.closest('.server-suspension-action, .suspend-server'); + if (suspendBtn) { + if (suspendBtn.disabled) return; + const row = suspendBtn.closest('.server-row'); + const encName = suspendBtn.dataset.name; + const serverName = row?.dataset?.name || (encName ? decodeURIComponent(encName) : ''); + if (!serverName) return; + const nextSuspended = String(suspendBtn.dataset.nextSuspended || 'true').toLowerCase() !== 'false'; + if (typeof window.openServerSuspensionVerificationModal === 'function') { + window.openServerSuspensionVerificationModal(serverName, nextSuspended, suspendBtn); + } else { + alert('Security confirmation is still loading. Please try again.'); + } + return; + } + const btn = e.target.closest('.delete-server'); if (!btn) return; const encName = btn.dataset.name; if (!encName) return; const name = decodeURIComponent(encName); - const ok = confirm(`Delete server "${name}"? This will force-stop the container, permanently remove all server files/backups from the node, and erase related database records.`); - if (!ok) return; - try { - btn.disabled = true; - const res = await fetch(`/api/settings/servers/${encodeURIComponent(name)}`, { method: 'DELETE' }); - const data = await res.json().catch(() => ({ error: 'Invalid response' })); - if (!res.ok) { - alert(data.error || 'Failed to delete server'); - btn.disabled = false; - return; - } - const row = btn.closest('.server-row'); - if (row) row.remove(); - if (!serversListEl.children.length) { - loadServers(); - } - } catch (err) { - console.error(err); - alert('Network error while deleting server'); - btn.disabled = false; + if (typeof window.openServerDeleteVerificationModal === 'function') { + window.openServerDeleteVerificationModal(name, btn); + } else { + alert('Security confirmation is still loading. Please try again.'); } }); @@ -2219,9 +3161,12 @@ async function openTransferModal(serverName, currentNodeId = '') { if (transferModalClose) transferModalClose.addEventListener('click', () => showTransferModal(false)); if (transferCancel) transferCancel.addEventListener('click', () => showTransferModal(false)); -if (transferModalOverlay) { - // Click outside disabled — user must use close/cancel button -} +// Click outside disabled — user must use close/cancel button +// if (transferModalOverlay) { +// transferModalOverlay.addEventListener('click', (e) => { +// if (e.target === transferModalOverlay) showTransferModal(false); +// }); +// } const resourcesModalOverlay = document.getElementById('resourcesModalOverlay'); const resourcesModal = document.getElementById('resourcesModal'); @@ -2310,6 +3255,22 @@ let originalStartupCommand = ''; let originalStartupCommandSource = ''; let currentMinecraftJavaEnabled = false; let originalMinecraftJavaVersion = ''; + +const _resourcesCache = new Map(); +const _RESOURCES_CACHE_TTL = 60_000; +let _resourcesPrefetch = null; + +function _cacheResourcesData(serverName, data) { + _resourcesCache.set(serverName.toLowerCase(), { data, ts: Date.now() }); +} + +function _getCachedResourcesData(serverName) { + const entry = _resourcesCache.get(serverName.toLowerCase()); + if (entry && (Date.now() - entry.ts) < _RESOURCES_CACHE_TTL) return entry.data; + if (entry) _resourcesCache.delete(serverName.toLowerCase()); + return null; +} + registerModalCustomStateReader('resourcesModalOverlay', () => ({ server: currentResourcesServer || '', mainPort: currentServerMainPort ?? null, @@ -2346,7 +3307,8 @@ function renderStartupCommandPreview(command) { function renderStartupCommandEditorState(command) { renderStartupCommandPreview(command); - if (String(originalStartupCommandSource || '').trim().toLowerCase() === 'adpanel-startup') { + const source = String(originalStartupCommandSource || '').trim().toLowerCase(); + if (source === 'adpanel-startup' || source === 'image-default' || source === 'image-inspect') { if (resStartupCommand) { resStartupCommand.setAttribute('aria-invalid', 'false'); resStartupCommand.readOnly = true; @@ -2388,7 +3350,7 @@ function resetMinecraftJavaSelector() { resJavaVersion.disabled = true; } if (resJavaVersionField) resJavaVersionField.hidden = true; - if (resJavaVersionHint) resJavaVersionHint.textContent = 'Runs this Minecraft server with the selected Eclipse Temurin JRE image.'; + if (resJavaVersionHint) resJavaVersionHint.textContent = ''; } function renderMinecraftJavaSelector(data) { @@ -2432,9 +3394,7 @@ function renderMinecraftJavaSelector(data) { currentMinecraftJavaEnabled = true; if (resJavaVersionField) resJavaVersionField.hidden = false; if (resJavaVersionHint) { - const image = String(javaPayload?.image || 'eclipse-temurin').trim(); - const tag = String(javaPayload?.tag || `${selected}-jre`).trim(); - resJavaVersionHint.textContent = `Runtime image: ${image}:${tag}`; + resJavaVersionHint.textContent = ''; } } @@ -2805,6 +3765,89 @@ if (resPortsList) { }); } +function _applyResourcesFormData(data, serverName) { + currentResourcesServer = data.name || serverName; + currentResourcesRenameToken = data.renameActionToken || ''; + const r = data.resources || {}; + const stats = data.stats || {}; + currentServerTemplate = data.template || ''; + + resourcesModalTitle.textContent = `Resources: ${currentResourcesServer}`; + resServerNameInput.value = data.displayName || currentResourcesServer; + resRenameServerBtn.disabled = !currentResourcesRenameToken; + resRamMb.value = r.ramMb ?? ''; + resCpuCores.value = r.cpuCores ?? ''; + resStorageMb.value = r.storageMb ?? (r.storageGb != null ? Math.round(r.storageGb * 1024) : ''); + resSwapMb.value = r.swapMb != null ? String(r.swapMb) : '-1'; + resBackupsMax.value = r.backupsMax ?? ''; + resMaxSchedules.value = r.maxSchedules ?? ''; + resIoWeight.value = r.ioWeight ?? ''; + resCpuWeight.value = r.cpuWeight ?? ''; + resPidsLimit.value = r.pidsLimit ?? ''; + resFileLimit.value = r.fileLimit ?? ''; + resNetworkInboundLimitMb.value = r.networkInboundLimitMb ?? ''; + resNetworkOutboundLimitMb.value = r.networkOutboundLimitMb ?? ''; + resNetworkResetMinutes.value = r.networkResetMinutes ?? ''; + + if (data.hostPort) { + currentServerMainPort = Number(data.hostPort); + originalServerMainPort = currentServerMainPort; + } + if (Array.isArray(r.ports)) currentServerPorts = r.ports.slice(); + + const cmd = String(data.effectiveCommand || data.command || data.imageDefaultCommand || '').trim(); + originalStartupCommand = cmd; + originalStartupCommandSource = String(data.commandSource || '').trim(); + resStartupCommand.value = cmd; + const src = originalStartupCommandSource.toLowerCase(); + resStartupCommand.readOnly = src === 'adpanel-startup' || src === 'image-default' || src === 'image-inspect'; + + if (stats?.memory) { + const used = stats.memory.usedMb || 0; + const limit = stats.memory.limitMb || r.ramMb || 0; + const pct = limit > 0 ? Math.min(100, (used / limit) * 100) : 0; + resUsageBar.style.width = `${pct}%`; + resUsageBar.className = 'resource-usage-fill' + (pct > 80 ? ' warning' : ''); + resUsageText.textContent = limit > 0 ? `${Math.round(used)} MB / ${Math.round(limit)} MB (${pct.toFixed(1)}%)` : 'No limit set'; + } else { + resUsageBar.style.width = '0%'; + resUsageText.textContent = r.ramMb ? `0 MB / ${r.ramMb} MB (server stopped)` : 'No usage data'; + } + + renderStartupCommandEditorState(cmd); + renderMinecraftJavaSelector(data); + renderPortsList(); +} + +function _prefetchResources(serverName) { + if (!serverName) return; + if (_resourcesPrefetch && _resourcesPrefetch.key === serverName.toLowerCase()) return; + if (_getCachedResourcesData(serverName)) return; + const key = serverName.toLowerCase(); + const promise = fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/resources`) + .then(res => res.ok ? res.json() : null) + .then(data => { + if (data) _cacheResourcesData(serverName, data); + return data; + }) + .catch(() => null) + .finally(() => { + if (_resourcesPrefetch && _resourcesPrefetch.key === key) _resourcesPrefetch = null; + }); + _resourcesPrefetch = { key, promise }; +} + +async function _fetchResourcesData(serverName) { + const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/resources`); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw { status: res.status, error: data?.error || `HTTP ${res.status}` }; + } + const data = await res.json(); + _cacheResourcesData(serverName, data); + return data; +} + async function openResourcesModal(serverName) { currentResourcesServer = serverName; currentResourcesRenameToken = ''; @@ -2813,134 +3856,70 @@ async function openResourcesModal(serverName) { originalServerMainPort = null; currentServerTemplate = ''; clearResourcesFeedback(); - - if (resourcesModalTitle) resourcesModalTitle.textContent = `Resources: ${serverName}`; - if (resourcesModalSubtitle) resourcesModalSubtitle.textContent = 'Set limits for this server.'; - if (resServerNameInput) { - resServerNameInput.value = serverName; - resServerNameInput.disabled = false; - } - if (resRenameServerBtn) { - resRenameServerBtn.disabled = false; - resRenameServerBtn.innerHTML = ' Rename'; - } - if (resourcesSave) resourcesSave.disabled = false; - - if (resRamMb) resRamMb.value = ''; - if (resCpuCores) resCpuCores.value = ''; - if (resStorageMb) resStorageMb.value = ''; - if (resSwapMb) resSwapMb.value = '-1'; - if (resBackupsMax) resBackupsMax.value = ''; - if (resMaxSchedules) resMaxSchedules.value = ''; - if (resIoWeight) resIoWeight.value = ''; - if (resCpuWeight) resCpuWeight.value = ''; - if (resPidsLimit) resPidsLimit.value = ''; - if (resFileLimit) resFileLimit.value = ''; - if (resNetworkInboundLimitMb) resNetworkInboundLimitMb.value = ''; - if (resNetworkOutboundLimitMb) resNetworkOutboundLimitMb.value = ''; - if (resNetworkResetMinutes) resNetworkResetMinutes.value = ''; - if (resUsageBar) resUsageBar.style.width = '0%'; - if (resUsageText) resUsageText.textContent = 'Loading...'; - if (resNewPort) resNewPort.value = ''; - if (resStartupSection) resStartupSection.style.display = ''; - if (resStartupCommand) resStartupCommand.value = ''; - if (resStartupCommand) resStartupCommand.readOnly = false; - renderStartupCommandEditorState(''); resetMinecraftJavaSelector(); renderPortsList(); - if (resourcesModalOverlay) { - resourcesModalOverlay.setAttribute('aria-hidden', 'false'); - resourcesModalOverlay.classList.add('show'); + resourcesModalSubtitle.textContent = 'Set limits for this server.'; + resServerNameInput.value = serverName; + resServerNameInput.disabled = false; + resRenameServerBtn.disabled = false; + resRenameServerBtn.innerHTML = ' Rename'; + resourcesSave.disabled = false; + resNewPort.value = ''; + resStartupSection.style.display = ''; + resourcesModalOverlay.setAttribute('aria-hidden', 'false'); + resourcesModalOverlay.classList.add('show'); + + const cached = _getCachedResourcesData(serverName); + let populatedFromCache = false; + if (cached) { + _applyResourcesFormData(cached, serverName); + populatedFromCache = true; + } else { + resRamMb.value = ''; + resCpuCores.value = ''; + resStorageMb.value = ''; + resSwapMb.value = '-1'; + resBackupsMax.value = ''; + resMaxSchedules.value = ''; + resIoWeight.value = ''; + resCpuWeight.value = ''; + resPidsLimit.value = ''; + resFileLimit.value = ''; + resNetworkInboundLimitMb.value = ''; + resNetworkOutboundLimitMb.value = ''; + resNetworkResetMinutes.value = ''; + resUsageBar.style.width = '0%'; + resUsageText.textContent = 'Loading...'; + resStartupCommand.value = ''; + resStartupCommand.readOnly = false; } try { - const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/resources`); - if (res.ok) { - const data = await res.json(); - currentResourcesServer = data.name || serverName; - currentResourcesRenameToken = data.renameActionToken || ''; - const resources = data.resources || {}; - const stats = data.stats || {}; - currentServerTemplate = data.template || ''; - - if (resourcesModalTitle) resourcesModalTitle.textContent = `Resources: ${currentResourcesServer}`; - if (resourcesModalSubtitle) resourcesModalSubtitle.textContent = 'Set limits for this server.'; - if (resServerNameInput) resServerNameInput.value = data.displayName || currentResourcesServer; - if (resRenameServerBtn) resRenameServerBtn.disabled = !currentResourcesRenameToken; - - if (resources.ramMb != null && resRamMb) resRamMb.value = resources.ramMb; - if (resources.cpuCores != null && resCpuCores) resCpuCores.value = resources.cpuCores; - if (resources.storageMb != null && resStorageMb) { - resStorageMb.value = resources.storageMb; - } else if (resources.storageGb != null && resStorageMb) { - resStorageMb.value = Math.round(resources.storageGb * 1024); - } - if (resources.swapMb != null && resSwapMb) resSwapMb.value = String(resources.swapMb); - if (resources.backupsMax != null && resBackupsMax) resBackupsMax.value = resources.backupsMax; - if (resources.maxSchedules != null && resMaxSchedules) resMaxSchedules.value = resources.maxSchedules; - if (resources.ioWeight != null && resIoWeight) resIoWeight.value = resources.ioWeight; - if (resources.cpuWeight != null && resCpuWeight) resCpuWeight.value = resources.cpuWeight; - if (resources.pidsLimit != null && resPidsLimit) resPidsLimit.value = resources.pidsLimit; - if (resources.fileLimit != null && resFileLimit) resFileLimit.value = resources.fileLimit; - if (resources.networkInboundLimitMb != null && resNetworkInboundLimitMb) resNetworkInboundLimitMb.value = resources.networkInboundLimitMb; - if (resources.networkOutboundLimitMb != null && resNetworkOutboundLimitMb) resNetworkOutboundLimitMb.value = resources.networkOutboundLimitMb; - if (resources.networkResetMinutes != null && resNetworkResetMinutes) resNetworkResetMinutes.value = resources.networkResetMinutes; - - if (data.hostPort) { - currentServerMainPort = Number(data.hostPort); - originalServerMainPort = currentServerMainPort; - } - - if (Array.isArray(resources.ports)) { - currentServerPorts = resources.ports.slice(); - } - renderPortsList(); - - const startupCommandForEditor = String(data.effectiveCommand || data.command || data.imageDefaultCommand || '').trim(); - originalStartupCommand = startupCommandForEditor; - originalStartupCommandSource = String(data.commandSource || '').trim(); - if (resStartupCommand) { - resStartupCommand.value = originalStartupCommand; - resStartupCommand.readOnly = originalStartupCommandSource.toLowerCase() === 'adpanel-startup'; - } - renderStartupCommandEditorState(originalStartupCommand); - - renderMinecraftJavaSelector(data); - - if (resUsageText) { - if (stats && stats.memory) { - const usedMb = stats.memory.usedMb || 0; - const limitMb = stats.memory.limitMb || resources.ramMb || 0; - const percent = limitMb > 0 ? Math.min(100, (usedMb / limitMb) * 100) : 0; - - if (resUsageBar) { - resUsageBar.style.width = `${percent}%`; - resUsageBar.className = 'resource-usage-fill' + (percent > 80 ? ' warning' : ''); - } - resUsageText.textContent = limitMb > 0 - ? `${Math.round(usedMb)} MB / ${Math.round(limitMb)} MB (${percent.toFixed(1)}%)` - : 'No limit set'; - } else { - if (resUsageBar) resUsageBar.style.width = '0%'; - resUsageText.textContent = resources.ramMb - ? `0 MB / ${resources.ramMb} MB (server stopped)` - : 'No usage data'; - } - } + let data; + if (_resourcesPrefetch && _resourcesPrefetch.key === serverName.toLowerCase()) { + data = await _resourcesPrefetch.promise; + if (_resourcesPrefetch && _resourcesPrefetch.key === serverName.toLowerCase()) _resourcesPrefetch = null; } else { - if (resUsageBar) resUsageBar.style.width = '0%'; - if (resUsageText) resUsageText.textContent = 'Failed to load resources'; - if (resRenameServerBtn) resRenameServerBtn.disabled = true; - const data = await res.json().catch(() => ({})); - if (data?.error) showResourcesFeedback(data.error, true); + data = await _fetchResourcesData(serverName); + } + if (data) { + _applyResourcesFormData(data, serverName); + } else if (!populatedFromCache) { + resUsageBar.style.width = '0%'; + resUsageText.textContent = 'Failed to load resources'; + resRenameServerBtn.disabled = true; + showResourcesFeedback('Failed to load resources', true); } } catch (err) { - console.error('[resources] Failed to load:', err); - if (resUsageBar) resUsageBar.style.width = '0%'; - if (resUsageText) resUsageText.textContent = 'Failed to load'; - if (resRenameServerBtn) resRenameServerBtn.disabled = true; - showResourcesFeedback('Failed to load resources', true); + if (!populatedFromCache) { + console.error('[resources] Failed to load:', err); + resUsageBar.style.width = '0%'; + resUsageText.textContent = 'Failed to load'; + resRenameServerBtn.disabled = true; + if (err?.error) showResourcesFeedback(err.error, true); + else showResourcesFeedback('Failed to load resources', true); + } } } @@ -3034,7 +4013,8 @@ async function saveResources() { resStartupCommand?.focus(); return; } - if (String(originalStartupCommandSource || '').trim().toLowerCase() !== 'adpanel-startup' && startupCommand !== originalStartupCommand) { + const startupSource = String(originalStartupCommandSource || '').trim().toLowerCase(); + if (!['adpanel-startup', 'image-default', 'image-inspect'].includes(startupSource) && startupCommand !== originalStartupCommand) { requestBody.command = startupCommand; } @@ -3075,6 +4055,8 @@ async function saveResources() { showResourcesFeedback('Resources updated! Server is restarting...', false); + _resourcesCache.delete(currentResourcesServer.toLowerCase()); + setTimeout(() => { closeResourcesModal(); }, 2000); @@ -3096,10 +4078,7 @@ if (resourcesSave) resourcesSave.addEventListener('click', saveResources); if (resRenameServerBtn) resRenameServerBtn.addEventListener('click', submitResourcesRename); if (resJavaVersion) { resJavaVersion.addEventListener('change', () => { - const selected = normalizeMinecraftJavaVersionClient(resJavaVersion.value); - if (resJavaVersionHint && selected) { - resJavaVersionHint.textContent = `Runtime image: eclipse-temurin:${selected}-jre`; - } + // Removed dynamic hint update }); } if (resServerNameInput) { @@ -3110,9 +4089,12 @@ if (resServerNameInput) { } }); } -if (resourcesModalOverlay) { - // Click outside disabled — user must use close/cancel button -} +// Click outside disabled — user must use close/cancel button +// if (resourcesModalOverlay) { +// resourcesModalOverlay.addEventListener('click', (e) => { +// if (e.target === resourcesModalOverlay) closeResourcesModal(); +// }); +// } document.addEventListener('keydown', (e) => { if (e.key === 'Escape' && resourcesModalOverlay?.classList.contains('show')) { @@ -3137,7 +4119,7 @@ if (resCopyStartupCmd) { if (resStartupCommand) { resStartupCommand.addEventListener('input', () => { - if (String(originalStartupCommandSource || '').trim().toLowerCase() === 'adpanel-startup') return; + if (['adpanel-startup', 'image-default', 'image-inspect'].includes(String(originalStartupCommandSource || '').trim().toLowerCase())) return; renderStartupCommandEditorState(resStartupCommand.value); }); } @@ -3407,9 +4389,12 @@ if (portForwardModalClose) portForwardModalClose.addEventListener('click', close bindStrictPortInput(pfNewPublicPort); if (portForwardCancel) portForwardCancel.addEventListener('click', closePortForwardModal); if (portForwardSave) portForwardSave.addEventListener('click', savePortForwards); -if (portForwardModalOverlay) { - // Click outside disabled — user must use close/cancel button -} +// Click outside disabled — user must use close/cancel button +// if (portForwardModalOverlay) { +// portForwardModalOverlay.addEventListener('click', (e) => { +// if (e.target === portForwardModalOverlay) closePortForwardModal(); +// }); +// } if (pfAddRule) pfAddRule.addEventListener('click', addPFRule); if (pfNewPublicPort) { pfNewPublicPort.addEventListener('keypress', (e) => { @@ -3445,6 +4430,9 @@ async function loadAccounts() { accountsListEl._accounts = data.accounts || []; accountsListEl._bots = data.bots || []; accountsListEl._actionTokens = data.actionTokens || {}; + try { + window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); + } catch (_) { } renderAccounts(accountsListEl._accounts, accountsListEl._bots); } catch (e) { console.error(e); @@ -3453,6 +4441,8 @@ async function loadAccounts() { } function renderAccounts(accounts, bots, searchQuery = '') { accountsListEl.innerHTML = ''; + accountsListEl._deleteTokensByEmail = new Map(); + accountsListEl._suspensionTokensByEmail = new Map(); let filtered = Array.isArray(accounts) ? [...accounts] : []; if (searchQuery && searchQuery.trim()) { @@ -3478,40 +4468,106 @@ function renderAccounts(accounts, bots, searchQuery = '') { return; } filtered.forEach(acc => { - const div = document.createElement('div'); - div.className = 'account-row'; - const isAdminAccount = !!acc.admin; + const div = document.createElement('div'); + const isSuspendedAccount = !!acc.suspended; + div.className = `account-row${isSuspendedAccount ? ' account-row-suspended' : ''}`; + const isAdminAccount = !!acc.admin; + const twoFactorActionLabel = acc.has2FA ? 'Reset 2FA' : 'Setup 2FA'; + const email = String(acc.email || '').trim(); + const deleteToken = String(acc.deleteToken || '').trim(); + const suspensionToken = String(acc.suspensionToken || '').trim(); + if (email && deleteToken) { + accountsListEl._deleteTokensByEmail.set(email, deleteToken); + accountsListEl._deleteTokensByEmail.set(email.toLowerCase(), deleteToken); + } + if (email && suspensionToken) { + accountsListEl._suspensionTokensByEmail.set(email, suspensionToken); + accountsListEl._suspensionTokensByEmail.set(email.toLowerCase(), suspensionToken); + } const accessLabel = isAdminAccount ? 'admin account' - : ((Array.isArray(acc.servers) && acc.servers.length > 0) ? `${acc.servers.length} access` : 'no access'); + : (isSuspendedAccount ? 'suspended' : ((Array.isArray(acc.servers) && acc.servers.length > 0) ? `${acc.servers.length} access` : 'no access')); + const statusBadges = [ + isAdminAccount ? '' : '', + isSuspendedAccount ? '' : '' + ].filter(Boolean).join(''); const accessControls = isAdminAccount ? '' : `
    - - Agent -
    - + + Agent +
    + + `; + const suspensionButton = isAdminAccount ? '' : ` + `; div.innerHTML = `
    ${accessControls} - - - + ${suspensionButton} + + +
    `; + const deleteButton = div.querySelector('.delete-user-btn'); + if (deleteButton) deleteButton.dataset.deleteToken = deleteToken; + const suspensionButtonEl = div.querySelector('.account-suspension-btn'); + if (suspensionButtonEl) suspensionButtonEl.dataset.suspensionToken = suspensionToken; accountsListEl.appendChild(div); }); } +function getAccountDeleteToken(email, sourceButton = null) { + const directToken = String(sourceButton?.dataset?.deleteToken || '').trim(); + if (directToken) return directToken; + const normalizedEmail = String(email || '').trim(); + if (!normalizedEmail) return ''; + const tokens = accountsListEl?._deleteTokensByEmail; + if (tokens && typeof tokens.get === 'function') { + return String(tokens.get(normalizedEmail) || tokens.get(normalizedEmail.toLowerCase()) || '').trim(); + } + return ''; +} +async function refreshAccountDeleteToken(email) { + const normalizedEmail = String(email || '').trim(); + if (!normalizedEmail) return ''; + await loadAccounts(); + return getAccountDeleteToken(normalizedEmail); +} +function getAccountSuspensionToken(email, sourceButton = null) { + const directToken = String(sourceButton?.dataset?.suspensionToken || '').trim(); + if (directToken) return directToken; + const normalizedEmail = String(email || '').trim(); + if (!normalizedEmail) return ''; + const tokens = accountsListEl?._suspensionTokensByEmail; + if (tokens && typeof tokens.get === 'function') { + return String(tokens.get(normalizedEmail) || tokens.get(normalizedEmail.toLowerCase()) || '').trim(); + } + return ''; +} +async function refreshAccountSuspensionToken(email) { + const normalizedEmail = String(email || '').trim(); + if (!normalizedEmail) return ''; + await loadAccounts(); + return getAccountSuspensionToken(normalizedEmail); +} if (accountsSearchInput) { accountsSearchInput.addEventListener('input', (e) => { @@ -3541,48 +4597,29 @@ accountsListEl.addEventListener('click', async (e) => { return; } + const suspensionBtn = e.target.closest('.account-suspension-btn'); + if (suspensionBtn) { + const enc = suspensionBtn.dataset.email; + if (!enc) return; + const email = decodeURIComponent(enc); + const currentlySuspended = suspensionBtn.dataset.suspended === '1'; + if (typeof window.openAccountSuspensionVerificationModal === 'function') { + window.openAccountSuspensionVerificationModal(email, !currentlySuspended, suspensionBtn); + } else { + alert('Security confirmation is still loading. Please try again.'); + } + return; + } + const deleteBtn = e.target.closest('.delete-user-btn'); if (deleteBtn) { const enc = deleteBtn.dataset.email; if (!enc) return; const email = decodeURIComponent(enc); - - const confirmed = confirm(`Are you sure you want to permanently delete the user "${email}"?\n\nThis action cannot be undone. All access permissions will be removed.`); - if (!confirmed) return; - - deleteBtn.disabled = true; - deleteBtn.innerHTML = ''; - - try { - const res = await fetch(`/api/settings/accounts/${encodeURIComponent(email)}`, { - method: 'DELETE', - headers: { 'x-action-token': (accountsListEl._actionTokens || {}).deleteAccount || '' } - }); - const data = await res.json().catch(() => ({})); - - if (!res.ok) { - alert(data.error || 'Failed to delete user'); - deleteBtn.disabled = false; - deleteBtn.innerHTML = ''; - return; - } - - const toast = document.createElement('div'); - toast.className = 'perm-success-toast'; - toast.innerHTML = ' User deleted successfully'; - document.body.appendChild(toast); - setTimeout(() => { toast.classList.add('show'); }, 10); - setTimeout(() => { - toast.classList.remove('show'); - setTimeout(() => toast.remove(), 300); - }, 2000); - - loadAccounts(); - } catch (err) { - console.error('[delete-user]', err); - alert('Network error'); - deleteBtn.disabled = false; - deleteBtn.innerHTML = ''; + if (typeof window.openAccountDeleteVerificationModal === 'function') { + window.openAccountDeleteVerificationModal(email, deleteBtn); + } else { + alert('Security confirmation is still loading. Please try again.'); } return; } @@ -3723,12 +4760,13 @@ accountModalClose.addEventListener('click', () => { accountModalOverlay.classList.remove('show'); accountModal.classList.remove('show'); }); -accountModalOverlay.addEventListener('click', (e) => { - if (e.target === accountModalOverlay) { - accountModalOverlay.classList.remove('show'); - accountModal.classList.remove('show'); - } -}); +// Click outside disabled — user must use close/cancel button +// accountModalOverlay.addEventListener('click', (e) => { +// if (e.target === accountModalOverlay) { +// accountModalOverlay.classList.remove('show'); +// accountModal.classList.remove('show'); +// } +// }); async function openPermsModal(email, server, onSaved, existingPerms) { let serverPerms = null; try { @@ -3778,6 +4816,7 @@ function buildPermsFormHtml(existing, fromServer) { const currentSummary = existing ? summarizePerms(existing) : null; const permLabels = { files_read: { label: 'Read files', icon: 'fa-file' }, + files_write: { label: 'Edit existing files', icon: 'fa-file-pen' }, files_delete: { label: 'Delete files', icon: 'fa-trash' }, files_rename: { label: 'Rename files', icon: 'fa-pen' }, files_archive: { label: 'Create archives', icon: 'fa-file-zipper' }, @@ -3833,7 +4872,8 @@ function buildPermsFormHtml(existing, fromServer) { } permCancel.addEventListener('click', closePermsModal); if (permCancelBtn) permCancelBtn.addEventListener('click', closePermsModal); -permModalOverlay.addEventListener('click', (e) => { if (e.target === permModalOverlay) closePermsModal(); }); +// Click outside disabled — user must use close/cancel button +// permModalOverlay.addEventListener('click', (e) => { if (e.target === permModalOverlay) closePermsModal(); }); permSave.addEventListener('click', async () => { const email = permModal.dataset.email || ''; const server = permModal.dataset.server || ''; @@ -3888,11 +4928,18 @@ document.addEventListener('DOMContentLoaded', () => { { match: /^\/servers(?:\/|$)/i, panel: 'servers' }, { match: /^\/settings(?:\/|$)/i, panel: 'preferences' } ]; - function getRequestedPanel() { + function getExplicitRequestedPanel() { const params = new URLSearchParams(location.search); const p = params.get('panel'); if (p) return p; if (location.hash && location.hash.length > 1) return location.hash.slice(1); + return null; + } + function getRequestedPanel() { + const explicitPanel = getExplicitRequestedPanel(); + if (isValidSettingsPanel(explicitPanel)) return explicitPanel; + const savedPanel = getSavedSettingsPanel(); + if (savedPanel) return savedPanel; const path = location.pathname || '/'; for (const r of pathnameDefaults) { if (r.match.test(path)) return r.panel; @@ -3901,7 +4948,8 @@ document.addEventListener('DOMContentLoaded', () => { } function tryOpenPanel(panel) { if (!panel) return false; - const btn = document.querySelector(`${sidebarSelector} button[data-panel="${panel}"]`); + const safePanel = escapeSettingsPanelSelectorValue(panel); + const btn = document.querySelector(`${sidebarSelector} button[data-panel="${safePanel}"]`); if (btn) { try { btn.focus?.(); btn.click(); } catch { btn.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); } console.log(`[openPanel] opened panel: ${panel}`); @@ -3922,8 +4970,7 @@ document.addEventListener('DOMContentLoaded', () => { console.warn(`[openPanel] failed to open panel "${panel}"`); const directPanelEl = document.getElementById(panel); if (directPanelEl) { - document.querySelectorAll('.panel-section').forEach(s => s.classList.remove('active')); - directPanelEl.classList.add('active'); + activateSettingsPanel(panel); console.log(`[openPanel] opened panel by id: ${panel}`); } } @@ -3983,7 +5030,8 @@ function showCreateNodeModal(show) { openCreateNodeBtn.addEventListener('click', () => showCreateNodeModal(true)); createNodeClose.addEventListener('click', () => showCreateNodeModal(false)); createNodeCancel.addEventListener('click', () => showCreateNodeModal(false)); -createNodeOverlay.addEventListener('click', (e) => { if (e.target === createNodeOverlay) showCreateNodeModal(false); }); +// Click outside disabled — user must use close/cancel button +// createNodeOverlay.addEventListener('click', (e) => { if (e.target === createNodeOverlay) showCreateNodeModal(false); }); document.querySelectorAll('input[name="cn_ports_mode"]').forEach(r => { r.addEventListener('change', () => { const mode = document.querySelector('input[name="cn_ports_mode"]:checked').value; @@ -4195,7 +5243,7 @@ function renderNodes(nodes) {
    ${escapeHtml(n.name || 'unnamed')}
    -
    ${escapeHtml(n.address || '0.0.0.0')} • API ${Number(n.api_port || 8080)} • SFTP ${Number(n.sftp_port || 2022)} • RAM ${Number(n.ram_mb || 0) / 1024 | 0} GB • Disk ${Number(n.disk_gb || 0)} GB • Ports ${portCount}
    +
    ${escapeHtml(n.address || '0.0.0.0')} • API ${Number(n.api_port || 8080)} • RAM ${Number(n.ram_mb || 0) / 1024 | 0} GB • Disk ${Number(n.disk_gb || 0)} GB • Ports ${portCount}
    @@ -4341,7 +5389,6 @@ function captureCreateNodeDraft() { port_list: cn_port_list?.value || '', max_upload_mb: cn_max_upload_mb?.value || '', daemon_port: cn_daemon_port?.value || '', - sftp_port: cn_sftp_port?.value || '', ssl_enabled: !!(cn_ssl_enabled && cn_ssl_enabled.checked), under_cloudflare: !!(cn_under_cloudflare && cn_under_cloudflare.checked), connectionTouched: createNodeConnectionTouched, @@ -4361,7 +5408,6 @@ function restoreCreateNodeDraft() { if (cn_port_list) cn_port_list.value = createNodeDraft.port_list; if (cn_max_upload_mb) cn_max_upload_mb.value = createNodeDraft.max_upload_mb; if (cn_daemon_port) cn_daemon_port.value = createNodeDraft.daemon_port; - if (cn_sftp_port) cn_sftp_port.value = createNodeDraft.sftp_port; if (cn_ssl_enabled) cn_ssl_enabled.checked = !!createNodeDraft.ssl_enabled; if (cn_under_cloudflare) cn_under_cloudflare.checked = !!createNodeDraft.under_cloudflare; createNodeConnectionTouched = !!createNodeDraft.connectionTouched; @@ -4380,7 +5426,6 @@ function resetCreateNodeForm() { if (cn_port_list) cn_port_list.value = ''; if (cn_max_upload_mb) cn_max_upload_mb.value = '100'; if (cn_daemon_port) cn_daemon_port.value = '8080'; - if (cn_sftp_port) cn_sftp_port.value = '2022'; if (cn_ssl_enabled) cn_ssl_enabled.checked = false; if (cn_under_cloudflare) cn_under_cloudflare.checked = false; createNodeConnectionTouched = false; @@ -4454,8 +5499,6 @@ createNodeSave.addEventListener('click', async () => { if (!Number.isFinite(max_upload_mb) || max_upload_mb < 1 || max_upload_mb > 100000) throw new Error('Upload limit must be between 1 and 100000 MB'); const api_port = parseInt(cn_daemon_port?.value || '8080', 10); if (!Number.isFinite(api_port) || api_port < 1 || api_port > 65535) throw new Error('Daemon port must be between 1 and 65535'); - const sftp_port = parseInt(cn_sftp_port?.value || '2022', 10); - if (!Number.isFinite(sftp_port) || sftp_port < 1 || sftp_port > 65535) throw new Error('SFTP port must be between 1 and 65535'); const ssl_enabled = !!(cn_ssl_enabled && cn_ssl_enabled.checked && canUseHttpsForNodeAddress(address)); const under_cloudflare = !!(ssl_enabled && cn_under_cloudflare && cn_under_cloudflare.checked); if (under_cloudflare && !isCloudflareHttpsPort(api_port)) { @@ -4469,7 +5512,6 @@ createNodeSave.addEventListener('click', async () => { ports, max_upload_mb, api_port, - sftp_port, ssl_enabled, under_cloudflare }; @@ -4551,7 +5593,6 @@ function fillNodeModal(node, focusLinking = false) { nm_disk_gb.value = Number(node.disk_gb || 0); if (nm_max_upload_mb) nm_max_upload_mb.value = Number(node.max_upload_mb || 10240); if (nm_daemon_port) nm_daemon_port.value = Number(node.api_port || 8080); - if (nm_sftp_port) nm_sftp_port.value = Number(node.sftp_port || 2022); if (nm_ssl_row && nm_ssl_enabled) { nm_ssl_enabled.checked = !!node.ssl_enabled; if (nm_under_cloudflare) nm_under_cloudflare.checked = !!node.under_cloudflare; @@ -4575,6 +5616,10 @@ function fillNodeModal(node, focusLinking = false) { nm_cmd.value = ''; nm_cmd.style.display = 'none'; nm_cmdActions.style.display = 'none'; + configureStepUpCredentialField(nm_deleteCredential, nm_deleteCredentialLabel, nm_deleteCredentialHint); + bindStepUpCredentialInput(nm_deleteCredential); + if (nm_deleteCredential) nm_deleteCredential.value = ''; + if (nm_deleteFeedback) nm_deleteFeedback.textContent = ''; nm_tabs.forEach(b => b.classList.remove('active')); [tab_build, tab_linking, tab_deletion].forEach(p => p.classList.remove('active')); if (focusLinking) { @@ -4586,6 +5631,7 @@ function fillNodeModal(node, focusLinking = false) { tab_build.classList.add('active'); if (buildFooter) buildFooter.style.display = 'flex'; } + loadNodeDisks(); } function generateNodeConfigYml(node) { const panelUrl = location.origin; @@ -4599,6 +5645,9 @@ function generateNodeConfigYml(node) { `uuid: ${uuid}`, `token_id: ${token_id}`, `token: ${token}`, + `auth:`, + ` token_id: ${token_id}`, + ` token: ${token}`, `api:`, ` host: 0.0.0.0`, ` port: ${node.api_port || 8080}`, @@ -4609,8 +5658,6 @@ function generateNodeConfigYml(node) { ` upload_limit: ${node.max_upload_mb || 10240}`, `system:`, ` data: /var/lib/node`, - ` sftp:`, - ` bind_port: ${node.sftp_port || 2022}`, `allowed_mounts: []`, `panel:`, ` url: ${panelUrl}`, @@ -4618,26 +5665,19 @@ function generateNodeConfigYml(node) { ].join('\n'); return yml; } -function generateOneTimeCommand(node) { - const yml = generateNodeConfigYml(node); - return `set -e -mkdir -p /var/lib/node -cat > /var/lib/node/config.yml <<'ADPANEL_NODE_CONFIG' -${yml} -ADPANEL_NODE_CONFIG -restart_adaemon() { - if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then - systemctl restart ADaemon 2>/dev/null || systemctl restart adaemon 2>/dev/null || systemctl restart adpanel-daemon 2>/dev/null - elif command -v rc-service >/dev/null 2>&1; then - rc-service adaemon restart 2>/dev/null || rc-service ADaemon restart 2>/dev/null || rc-service adpanel-daemon restart 2>/dev/null - elif command -v service >/dev/null 2>&1; then - service adaemon restart 2>/dev/null || service ADaemon restart 2>/dev/null || service adpanel-daemon restart 2>/dev/null - else - echo "No supported service manager found; start ADaemon manually." >&2 - return 1 - fi -} -restart_adaemon`; +async function generateOneTimeCommand(node) { + const id = node?.id || node?.uuid || ''; + if (!id) throw new Error('Missing node id.'); + const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/one-time-command`, { cache: 'no-store' }); + let data = null; + try { data = await res.json(); } catch { data = null; } + if (!res.ok) { + throw new Error(data?.error || 'Failed to generate setup command.'); + } + if (!data || typeof data.command !== 'string' || !data.command.trim()) { + throw new Error('Setup command response was empty.'); + } + return data.command; } function legacyCopyToClipboard(text) { return new Promise((resolve, reject) => { @@ -4679,11 +5719,22 @@ nm_downloadConfig.addEventListener('click', () => { a.href = url; a.download = 'config.yml'; a.click(); URL.revokeObjectURL(url); }); -nm_showCmd.addEventListener('click', () => { +nm_showCmd.addEventListener('click', async () => { if (!CURRENT_NODE) return; - nm_cmd.value = generateOneTimeCommand(CURRENT_NODE); nm_cmd.style.display = 'block'; nm_cmdActions.style.display = 'flex'; + nm_cmd.value = 'Generating setup command...'; + const previousHtml = nm_showCmd.innerHTML; + nm_showCmd.disabled = true; + nm_showCmd.innerHTML = ' Generating'; + try { + nm_cmd.value = await generateOneTimeCommand(CURRENT_NODE); + } catch (err) { + nm_cmd.value = `Failed to generate setup command: ${err?.message || err}`; + } finally { + nm_showCmd.disabled = false; + nm_showCmd.innerHTML = previousHtml; + } }); nm_copyCmd.addEventListener('click', () => { copyToClipboard(nm_cmd.value || '').then(() => { nm_copyCmd.innerHTML = ' Copied'; setTimeout(() => nm_copyCmd.innerHTML = ' Copy Command', 1500); }); @@ -4703,6 +5754,122 @@ if (nm_under_cloudflare) { updateNodeConnectionCopy(nm_ssl_enabled, nm_connection_label, nm_connection_help, nm_under_cloudflare); }); } +function nodeApiId() { + return CURRENT_NODE ? (CURRENT_NODE.id || CURRENT_NODE.uuid) : ''; +} +function setDisksFeedback(msg, isError) { + if (!nm_disks_feedback) return; + nm_disks_feedback.textContent = msg || ''; + nm_disks_feedback.style.color = isError ? '#f87171' : '#4ade80'; +} +function formatDiskUsage(disk) { + const used = Number(disk?.usedGb || 0); + const limit = Number(disk?.limitGb || 0); + const usedStr = used >= 0 ? used.toFixed(used >= 10 ? 0 : 1).replace(/\.0$/, '') : '0'; + if (limit > 0) { + const pct = Math.min(100, Math.round((used / limit) * 100)); + return `${usedStr} / ${limit} GB (${pct}%)`; + } + return `${usedStr} GB used`; +} +function renderNodeDisks(disks) { + if (!nm_disks_list) return; + const list = Array.isArray(disks) ? disks.slice() : []; + list.sort((a, b) => (b.primary ? 1 : 0) - (a.primary ? 1 : 0)); + if (!list.length) { + nm_disks_list.innerHTML = '
    No disks reported.
    '; + return; + } + nm_disks_list.innerHTML = list.map((d) => { + const isPrimary = !!d.primary || String(d.id) === 'primary'; + const mount = escapeHtml(d.mountPath || (isPrimary ? '/var/lib/node' : '')); + const usage = escapeHtml(formatDiskUsage(d)); + const badge = isPrimary + ? 'Primary' + : ''; + const removeBtn = isPrimary + ? '' + : ``; + return ` +
    +
    +
    + + ${mount} + ${badge} +
    + ${usage} +
    + ${removeBtn} +
    `; + }).join(''); + nm_disks_list.querySelectorAll('.node-disk-remove').forEach((btn) => { + btn.addEventListener('click', () => removeNodeDisk(btn.getAttribute('data-disk-id'))); + }); +} +async function loadNodeDisks() { + if (!nm_disks_list) return; + const id = nodeApiId(); + if (!id) return; + nm_disks_list.innerHTML = '
    Loading disks…
    '; + setDisksFeedback(''); + try { + const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/disks`, { cache: 'no-store' }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Failed to load disks'); + renderNodeDisks(data.disks || []); + } catch (e) { + nm_disks_list.innerHTML = ''; + setDisksFeedback(e.message || 'Failed to load disks', true); + } +} +async function addNodeDisk() { + const id = nodeApiId(); + if (!id) return; + const mountPath = (nm_disk_mount?.value || '').trim(); + const limitGb = parseInt(nm_disk_limit?.value || '', 10); + if (!mountPath) { setDisksFeedback('Mount path required', true); return; } + if (!Number.isFinite(limitGb) || limitGb <= 0) { setDisksFeedback('Limit must be a positive number of GB', true); return; } + try { + nm_disk_add.disabled = true; + setDisksFeedback(''); + const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/disks`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mountPath, limitGb }) + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Failed to add disk'); + if (nm_disk_mount) nm_disk_mount.value = ''; + if (nm_disk_limit) nm_disk_limit.value = ''; + setDisksFeedback('Disk added'); + await loadNodeDisks(); + } catch (e) { + setDisksFeedback(e.message || 'Failed to add disk', true); + } finally { + nm_disk_add.disabled = false; + } +} +async function removeNodeDisk(diskId) { + const id = nodeApiId(); + if (!id || !diskId) return; + if (!confirm('Remove this disk? It must have no servers assigned.')) return; + try { + setDisksFeedback(''); + const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/disks/${encodeURIComponent(diskId)}`, { + method: 'DELETE', + headers: { 'Content-Type': 'application/json' } + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Failed to remove disk'); + setDisksFeedback('Disk removed'); + await loadNodeDisks(); + } catch (e) { + setDisksFeedback(e.message || 'Failed to remove disk', true); + } +} +if (nm_disk_add) nm_disk_add.addEventListener('click', addNodeDisk); + nm_save.addEventListener('click', async () => { if (!CURRENT_NODE) return; try { @@ -4722,14 +5889,12 @@ nm_save.addEventListener('click', async () => { if (!Number.isFinite(max_upload_mb) || max_upload_mb < 1 || max_upload_mb > 100000) throw new Error('Upload limit must be between 1 and 100000 MB'); const api_port = parseInt(nm_daemon_port?.value || '8080', 10); if (!Number.isFinite(api_port) || api_port < 1 || api_port > 65535) throw new Error('Daemon port must be between 1 and 65535'); - const sftp_port = parseInt(nm_sftp_port?.value || '2022', 10); - if (!Number.isFinite(sftp_port) || sftp_port < 1 || sftp_port > 65535) throw new Error('SFTP port must be between 1 and 65535'); const ssl_enabled = !!(nm_ssl_enabled && nm_ssl_enabled.checked && canUseHttpsForNodeAddress(address)); const under_cloudflare = !!(ssl_enabled && nm_under_cloudflare && nm_under_cloudflare.checked); if (under_cloudflare && !isCloudflareHttpsPort(api_port)) { throw new Error('Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443'); } - const payload = { name, address, cpu_cores, ram_mb: ram_gb * 1024, disk_gb, ports, max_upload_mb, api_port, sftp_port, ssl_enabled, under_cloudflare }; + const payload = { name, address, cpu_cores, ram_mb: ram_gb * 1024, disk_gb, ports, max_upload_mb, api_port, ssl_enabled, under_cloudflare }; const res = await fetch(`/api/nodes/${encodeURIComponent(CURRENT_NODE.id || CURRENT_NODE.uuid)}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); @@ -4750,13 +5915,25 @@ nm_delete.addEventListener('click', async () => { if (!CURRENT_NODE) return; const ok = confirm(`Delete node "${CURRENT_NODE.name}"? This action is permanent.`); if (!ok) return; + configureStepUpCredentialField(nm_deleteCredential, nm_deleteCredentialLabel, nm_deleteCredentialHint); + const credential = validateStepUpCredential(nm_deleteCredential, (message, isError) => { + nm_deleteFeedback.textContent = message || ''; + nm_deleteFeedback.style.color = isError ? '#f87171' : '#4ade80'; + }); + if (!credential) return; try { nm_delete.disabled = true; nm_deleteFeedback.textContent = ''; - const res = await fetch(`/api/nodes/${encodeURIComponent(CURRENT_NODE.id || CURRENT_NODE.uuid)}`, { method: 'DELETE' }); + const res = await fetch(`/api/nodes/${encodeURIComponent(CURRENT_NODE.id || CURRENT_NODE.uuid)}`, { + method: 'DELETE', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(appendStepUpCredentialPayload({}, credential)) + }); const data = await res.json().catch(() => ({})); + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); if (!res.ok) throw new Error(data.error || 'Failed to delete'); nm_deleteFeedback.textContent = 'Deleted'; + if (nm_deleteCredential) nm_deleteCredential.value = ''; showNodeModal(false, { force: true }); await loadNodes(); } catch (e) { @@ -5153,6 +6330,9 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { const maintenancePreAlertGroup = document.getElementById('maintenancePreAlertGroup'); const maintenancePreAlertMessage = document.getElementById('maintenancePreAlertMessage'); const maintenancePreAlertMinutes = document.getElementById('maintenancePreAlertMinutes'); + const maintenanceCredentialInput = document.getElementById('maintenanceCredentialInput'); + const maintenanceCredentialLabel = document.getElementById('maintenanceCredentialLabel'); + const maintenanceCredentialHint = document.getElementById('maintenanceCredentialHint'); const maintenanceSwitchLabel = maintenanceCard.querySelector('.switch'); if (maintenanceSwitchLabel) { @@ -5225,6 +6405,9 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { maintenancePreAlertGroup.style.display = 'none'; maintenancePreAlertMessage.value = ''; maintenancePreAlertMinutes.value = '30'; + configureStepUpCredentialField(maintenanceCredentialInput, maintenanceCredentialLabel, maintenanceCredentialHint); + bindStepUpCredentialInput(maintenanceCredentialInput); + if (maintenanceCredentialInput) maintenanceCredentialInput.value = ''; maintenanceModalSave.innerHTML = ' Enable Maintenance'; showFeedback(''); @@ -5249,6 +6432,7 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { if (revertToggle && pendingToggleState !== null) { maintenanceToggle.checked = !pendingToggleState; } + if (maintenanceCredentialInput) maintenanceCredentialInput.value = ''; pendingToggleState = null; } @@ -5259,6 +6443,7 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { const data = await res.json(); currentState = data; maintenanceActionTokens = data.actionTokens || {}; + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); updateUI(); } catch (e) { console.error('Failed to load maintenance state:', e); @@ -5371,6 +6556,10 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { } } + configureStepUpCredentialField(maintenanceCredentialInput, maintenanceCredentialLabel, maintenanceCredentialHint); + const credential = validateStepUpCredential(maintenanceCredentialInput, showFeedback); + if (!credential) return; + maintenanceModalSave.disabled = true; showFeedback('Enabling maintenance mode...'); @@ -5383,6 +6572,7 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { pre_alert_message: preAlertShow ? preAlertMessage : null, pre_alert_minutes_before: preAlertShow ? preAlertMinutes : null }; + appendStepUpCredentialPayload(body, credential); const res = await fetch('/api/settings/maintenance', { method: 'POST', @@ -5393,6 +6583,7 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { body: JSON.stringify(body) }); const data = await res.json(); + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); if (!res.ok) { showFeedback(data.error || 'Failed to enable maintenance mode', true); @@ -5435,32 +6626,43 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { const sessionRevokeModal = document.getElementById('sessionRevokeModal'); const sessionRevokeModalClose = document.getElementById('sessionRevokeModalClose'); const sessionRevokeModalCancel = document.getElementById('sessionRevokeModalCancel'); - const sessionRevokeModalConfirm = document.getElementById('sessionRevokeModalConfirm'); - const sessionRevokeTwoFactorInput = document.getElementById('sessionRevokeTwoFactorInput'); - const sessionRevokeTargetSession = document.getElementById('sessionRevokeTargetSession'); - const sessionRevokeTargetEmail = document.getElementById('sessionRevokeTargetEmail'); - const sessionRevokeModalFeedback = document.getElementById('sessionRevokeModalFeedback'); + const sessionRevokeModalConfirm = document.getElementById('sessionRevokeModalConfirm'); + const sessionRevokeTwoFactorInput = document.getElementById('sessionRevokeTwoFactorInput'); + const sessionRevokeCredentialLabel = document.getElementById('sessionRevokeCredentialLabel'); + const sessionRevokeCredentialHint = document.getElementById('sessionRevokeCredentialHint'); + const sessionRevokeTargetSession = document.getElementById('sessionRevokeTargetSession'); + const sessionRevokeTargetEmail = document.getElementById('sessionRevokeTargetEmail'); + const sessionRevokeModalFeedback = document.getElementById('sessionRevokeModalFeedback'); const PAGE_GROUP_SIZE = 6; const sessionsState = { actionTokens: {}, items: [], total: 0, + activeTotal: 0, + rememberedTotal: 0, page: 1, totalPages: 1, search: '', searchActive: false, from: 0, to: 0, - twoFactorEnabled: false, + twoFactorEnabled: currentUserHas2FA, graceExpiresAt: 0, loading: false, loadedOnce: false, abortController: null, - searchTimer: null, - selectedSession: null, - graceTicker: null, - }; + searchTimer: null, + selectedSession: null, + selectedServerDelete: null, + selectedServerSuspension: null, + selectedAccountDelete: null, + selectedAccountSuspension: null, + selectedDatabaseInstall: null, + securityModalMode: 'session', + graceTicker: null, + authMethod: currentUserHas2FA ? '2fa' : 'password', + }; function showSessionsFeedback(message, isError = false) { if (!sessionsFeedback) return; @@ -5578,25 +6780,26 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { function updateSessionsHeaderMeta() { if (sessionsCountBadge) { - sessionsCountBadge.textContent = `${sessionsState.total} active`; + const total = Number(sessionsState.total || 0); + const activeTotal = Number(sessionsState.activeTotal || 0); + const rememberedTotal = Number(sessionsState.rememberedTotal || 0); + sessionsCountBadge.textContent = `${total} login${total === 1 ? '' : 's'}`; + sessionsCountBadge.title = `${activeTotal} active, ${rememberedTotal} offline`; } - if (sessionsGraceBadge) { - sessionsGraceBadge.classList.remove('security-inline-chip-success', 'security-inline-chip-warning'); - if (!sessionsState.twoFactorEnabled) { - sessionsGraceBadge.textContent = '2FA disabled'; - sessionsGraceBadge.classList.add('security-inline-chip-warning'); - } else if (isGraceActive()) { - const remainingMs = Math.max(0, Number(sessionsState.graceExpiresAt || 0) - Date.now()); - const minutes = Math.floor(remainingMs / 60000); - const seconds = Math.floor((remainingMs % 60000) / 1000); - sessionsGraceBadge.textContent = `Trusted ${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`; - sessionsGraceBadge.classList.add('security-inline-chip-success'); - } else { - sessionsGraceBadge.textContent = '2FA required'; - sessionsGraceBadge.classList.add('security-inline-chip-warning'); - } - } + if (sessionsGraceBadge) { + sessionsGraceBadge.classList.remove('security-inline-chip-success', 'security-inline-chip-warning'); + if (isGraceActive()) { + const remainingMs = Math.max(0, Number(sessionsState.graceExpiresAt || 0) - Date.now()); + const minutes = Math.floor(remainingMs / 60000); + const seconds = Math.floor((remainingMs % 60000) / 1000); + sessionsGraceBadge.textContent = `Trusted ${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`; + sessionsGraceBadge.classList.add('security-inline-chip-success'); + } else { + sessionsGraceBadge.textContent = sessionsState.authMethod === 'password' ? 'Password required' : '2FA required'; + sessionsGraceBadge.classList.add('security-inline-chip-warning'); + } + } syncGraceTicker(); } @@ -5604,21 +6807,23 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { if (!sessionsSummary) return; if (sessionsState.loading && !sessionsState.loadedOnce) { - sessionsSummary.textContent = 'Loading active browser sessions...'; + sessionsSummary.textContent = 'Loading browser sessions...'; return; } if (sessionsState.searchActive) { - sessionsSummary.textContent = `${sessionsState.total} active session${sessionsState.total === 1 ? '' : 's'} matched "${sessionsState.search}"`; + sessionsSummary.textContent = `${sessionsState.total} browser login${sessionsState.total === 1 ? '' : 's'} matched "${sessionsState.search}"`; return; } if (!sessionsState.total) { - sessionsSummary.textContent = 'No active browser sessions found.'; + sessionsSummary.textContent = 'No browser sessions or saved logins found.'; return; } - sessionsSummary.textContent = `${sessionsState.from}-${sessionsState.to} of ${sessionsState.total} active sessions`; + const activeTotal = Number(sessionsState.activeTotal || 0); + const rememberedTotal = Number(sessionsState.rememberedTotal || 0); + sessionsSummary.textContent = `${sessionsState.from}-${sessionsState.to} of ${sessionsState.total} browser logins (${activeTotal} active, ${rememberedTotal} offline)`; } function renderEmptySessionsState(message, iconClass = 'fa-solid fa-circle-info') { @@ -5635,15 +6840,15 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { if (!sessionsList) return; if (sessionsState.loading && !sessionsState.loadedOnce) { - renderEmptySessionsState('Loading active sessions...', 'fa-solid fa-spinner fa-spin'); + renderEmptySessionsState('Loading browser sessions...', 'fa-solid fa-spinner fa-spin'); return; } if (!Array.isArray(sessionsState.items) || sessionsState.items.length === 0) { if (sessionsState.searchActive) { - renderEmptySessionsState(`No active sessions found for "${sessionsState.search}".`, 'fa-solid fa-search'); + renderEmptySessionsState(`No browser logins found for "${sessionsState.search}".`, 'fa-solid fa-search'); } else { - renderEmptySessionsState('There are no active browser sessions right now.', 'fa-solid fa-window-restore'); + renderEmptySessionsState('There are no browser sessions or saved logins right now.', 'fa-solid fa-window-restore'); } return; } @@ -5652,8 +6857,17 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { sessionsState.items.forEach((item) => { const displayId = item.displayId || item.sessionId || ''; const revokeToken = item.revokeToken || ''; + const isRemembered = item.status === 'remembered' || item.targetType === 'remembered'; + const statusPill = item.isCurrent + ? ' Current session' + : (isRemembered + ? ' Offline login' + : ' Active session'); + const browserLabel = item.userAgent + ? describeUserAgent(item.userAgent) + : (isRemembered ? 'Saved browser' : 'Browser not detected'); const row = document.createElement('div'); - row.className = 'session-row'; + row.className = `session-row${isRemembered ? ' session-row-remembered' : ''}`; row.innerHTML = `
    @@ -5661,15 +6875,15 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { ${escapeHtml(item.email || 'Unknown user')}
    - ${item.isCurrent ? ' Current session' : ''} + ${statusPill} Last seen ${escapeHtml(formatRelativeTime(item.lastSeenAt))} Expires ${escapeHtml(formatDateTime(item.expiresAt))} - ${escapeHtml(describeUserAgent(item.userAgent))} + ${escapeHtml(browserLabel)} ${item.ip ? ` ${escapeHtml(item.ip)}` : ''}
    -
    @@ -5696,7 +6910,7 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { return pages; } - function renderSessionsPagination() { + function renderSessionsPagination() { if (!sessionsPagination) return; if (sessionsState.searchActive || sessionsState.totalPages <= 1) { @@ -5723,9 +6937,43 @@ document.querySelectorAll('.toggle-pass').forEach(btn => {
    `; - } + } + + function applyRevokeSecurityFromPayload(security) { + if (!security || typeof security !== 'object') return; + const normalized = applyGlobalStepUpSecurityFromPayload(security); + sessionsState.twoFactorEnabled = !!normalized.twoFactorEnabled; + sessionsState.authMethod = normalized.authMethod === 'password' ? 'password' : '2fa'; + sessionsState.graceExpiresAt = Number(normalized.graceExpiresAt || 0); + configureSessionRevokeCredentialField(); + updateSessionsHeaderMeta(); + } + window.applyRevokeSecurityFromPayload = applyRevokeSecurityFromPayload; + + function configureSessionRevokeCredentialField() { + const passwordMode = sessionsState.authMethod === 'password'; + const trustedMode = isGraceActive(); + const credentialField = sessionRevokeTwoFactorInput?.closest('.password-field'); + if (credentialField) credentialField.style.display = trustedMode ? 'none' : ''; + if (sessionRevokeCredentialLabel) { + sessionRevokeCredentialLabel.textContent = passwordMode ? 'Current Password' : '2FA Code'; + } + if (sessionRevokeCredentialHint) { + sessionRevokeCredentialHint.textContent = passwordMode + ? 'Enter your current password to confirm this action.' + : 'Enter the code from your authenticator app.'; + } + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.type = passwordMode ? 'password' : 'text'; + sessionRevokeTwoFactorInput.placeholder = passwordMode ? 'Current password' : '000000'; + sessionRevokeTwoFactorInput.autocomplete = passwordMode ? 'current-password' : 'one-time-code'; + sessionRevokeTwoFactorInput.maxLength = passwordMode ? 1024 : 6; + sessionRevokeTwoFactorInput.inputMode = passwordMode ? '' : 'numeric'; + sessionRevokeTwoFactorInput.pattern = passwordMode ? '' : '[0-9]*'; + } + } - async function loadSessions(page = sessionsState.page, search = sessionsState.search) { + async function loadSessions(page = sessionsState.page, search = sessionsState.search) { if (sessionsState.abortController) { sessionsState.abortController.abort(); } @@ -5755,17 +7003,21 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { sessionsState.items = Array.isArray(data.items) ? data.items : []; sessionsState.total = Number(data.total || 0); + sessionsState.activeTotal = Number(data.activeTotal || 0); + sessionsState.rememberedTotal = Number(data.rememberedTotal || 0); sessionsState.page = Number(data.page || 1) || 1; sessionsState.totalPages = Number(data.totalPages || 1) || 1; sessionsState.search = String(data.search || '').trim(); sessionsState.searchActive = !!data.searchActive; sessionsState.from = Number(data.from || 0); sessionsState.to = Number(data.to || 0); - sessionsState.actionTokens = data.actionTokens || {}; - sessionsState.twoFactorEnabled = !!data.revokeSecurity?.twoFactorEnabled; - sessionsState.graceExpiresAt = Number(data.revokeSecurity?.graceExpiresAt || 0); - sessionsState.loadedOnce = true; - if (sessionsSearchInput && sessionsSearchInput.value !== sessionsState.search) { + sessionsState.actionTokens = data.actionTokens || {}; + sessionsState.twoFactorEnabled = !!data.revokeSecurity?.twoFactorEnabled; + sessionsState.authMethod = data.revokeSecurity?.authMethod === 'password' ? 'password' : '2fa'; + sessionsState.graceExpiresAt = Number(data.revokeSecurity?.graceExpiresAt || 0); + sessionsState.loadedOnce = true; + configureSessionRevokeCredentialField(); + if (sessionsSearchInput && sessionsSearchInput.value !== sessionsState.search) { sessionsSearchInput.value = sessionsState.search; } @@ -5776,30 +7028,88 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { } catch (err) { if (err?.name === 'AbortError') return; console.error('[sessions]', err); - renderEmptySessionsState(err.message || 'Failed to load active sessions.', 'fa-solid fa-circle-exclamation'); - showSessionsFeedback(err.message || 'Failed to load active sessions.', true); + renderEmptySessionsState(err.message || 'Failed to load browser sessions.', 'fa-solid fa-circle-exclamation'); + showSessionsFeedback(err.message || 'Failed to load browser sessions.', true); } finally { sessionsState.loading = false; renderSessionsSummary(); } } - function openSessionRevokeModal(revokeToken, displayId, email) { - sessionsState.selectedSession = { - revokeToken: String(revokeToken || '').trim(), - displayId: String(displayId || '').trim(), - email: String(email || '').trim().toLowerCase(), - }; + function setSecurityModalPresentation(config = {}) { + const title = sessionRevokeModal?.querySelector('.enterprise-modal-title'); + const targetLabel = sessionRevokeModal?.querySelector('.session-revoke-target-label'); + if (title) title.textContent = config.title || 'Security Verification'; + if (targetLabel) targetLabel.textContent = config.targetLabel || 'Target'; + if (sessionRevokeTargetSession) sessionRevokeTargetSession.textContent = config.targetValue || '—'; + if (sessionRevokeTargetEmail) sessionRevokeTargetEmail.textContent = config.targetSubvalue || ''; + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.innerHTML = config.confirmHtml || ' Confirm'; + sessionRevokeModalConfirm.style.background = config.danger ? '#ef4444' : ''; + } + configureSessionRevokeCredentialField(); + } - if (sessionRevokeTargetSession) { - sessionRevokeTargetSession.textContent = shortenSessionId(sessionsState.selectedSession.displayId); - } - if (sessionRevokeTargetEmail) { - sessionRevokeTargetEmail.textContent = sessionsState.selectedSession.email || 'Unknown user'; - } - if (sessionRevokeTwoFactorInput) { - sessionRevokeTwoFactorInput.value = ''; - } + function restoreSecurityModalConfirmButton() { + if (!sessionRevokeModalConfirm) return; + if (sessionsState.securityModalMode === 'delete-server') { + sessionRevokeModalConfirm.innerHTML = ' Delete Server'; + sessionRevokeModalConfirm.style.background = '#ef4444'; + } else if (sessionsState.securityModalMode === 'suspend-server') { + sessionRevokeModalConfirm.innerHTML = ' Suspend Server'; + sessionRevokeModalConfirm.style.background = '#ef4444'; + } else if (sessionsState.securityModalMode === 'restore-server') { + sessionRevokeModalConfirm.innerHTML = ' Restore Server'; + sessionRevokeModalConfirm.style.background = ''; + } else if (sessionsState.securityModalMode === 'delete-account') { + sessionRevokeModalConfirm.innerHTML = ' Delete User'; + sessionRevokeModalConfirm.style.background = '#ef4444'; + } else if (sessionsState.securityModalMode === 'suspend-account') { + sessionRevokeModalConfirm.innerHTML = ' Suspend Account'; + sessionRevokeModalConfirm.style.background = '#ef4444'; + } else if (sessionsState.securityModalMode === 'unsuspend-account') { + sessionRevokeModalConfirm.innerHTML = ' Unsuspend Account'; + sessionRevokeModalConfirm.style.background = ''; + } else if (sessionsState.securityModalMode === 'database-install') { + sessionRevokeModalConfirm.innerHTML = ' Continue'; + sessionRevokeModalConfirm.style.background = ''; + } else if (sessionsState.selectedSession?.targetType === 'remembered') { + sessionRevokeModalConfirm.innerHTML = ' Revoke Login'; + sessionRevokeModalConfirm.style.background = ''; + } else { + sessionRevokeModalConfirm.innerHTML = ' Revoke Session'; + sessionRevokeModalConfirm.style.background = ''; + } + } + + function openSessionRevokeModal(revokeToken, displayId, email, targetType = 'session') { + const isRemembered = targetType === 'remembered'; + sessionsState.securityModalMode = 'session'; + sessionsState.selectedServerDelete = null; + sessionsState.selectedServerSuspension = null; + sessionsState.selectedAccountDelete = null; + sessionsState.selectedAccountSuspension = null; + sessionsState.selectedDatabaseInstall = null; + sessionsState.selectedSession = { + revokeToken: String(revokeToken || '').trim(), + displayId: String(displayId || '').trim(), + email: String(email || '').trim().toLowerCase(), + targetType: isRemembered ? 'remembered' : 'session', + }; + setSecurityModalPresentation({ + title: isRemembered ? 'Revoke Saved Login' : 'Revoke Session', + targetLabel: isRemembered ? 'Saved Login' : 'Target Session', + targetValue: shortenSessionId(sessionsState.selectedSession.displayId), + targetSubvalue: isRemembered + ? `${sessionsState.selectedSession.email || 'Unknown user'} - offline browser login` + : (sessionsState.selectedSession.email || 'Unknown user'), + confirmHtml: isRemembered + ? ' Revoke Login' + : ' Revoke Session', + }); + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.value = ''; + } showSessionRevokeModalFeedback(''); if (sessionRevokeModalOverlay) { @@ -5810,13 +7120,356 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { sessionRevokeModal.classList.add('show'); } - window.setTimeout(() => { - sessionRevokeTwoFactorInput?.focus(); - }, 40); - } + window.setTimeout(() => { + if (isGraceActive()) sessionRevokeModalConfirm?.focus(); + else sessionRevokeTwoFactorInput?.focus(); + }, 40); + } - function closeSessionRevokeModal() { - sessionsState.selectedSession = null; + function openServerDeleteVerificationModal(serverName, sourceButton) { + sessionsState.securityModalMode = 'delete-server'; + sessionsState.selectedSession = null; + sessionsState.selectedServerSuspension = null; + sessionsState.selectedAccountDelete = null; + sessionsState.selectedAccountSuspension = null; + sessionsState.selectedServerDelete = { + name: String(serverName || '').trim(), + button: sourceButton || null, + actionToken: getServerDeleteToken(serverName, sourceButton), + }; + setSecurityModalPresentation({ + title: 'Delete Server', + targetLabel: 'Target Server', + targetValue: sessionsState.selectedServerDelete.name || '—', + targetSubvalue: 'This permanently removes server files, backups, schedules, and access records.', + confirmHtml: ' Delete Server', + danger: true, + }); + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.value = ''; + } + showSessionRevokeModalFeedback(''); + + if (sessionRevokeModalOverlay) { + sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false'); + sessionRevokeModalOverlay.classList.add('show'); + } + if (sessionRevokeModal) { + sessionRevokeModal.classList.add('show'); + } + + window.setTimeout(() => { + if (isGraceActive()) sessionRevokeModalConfirm?.focus(); + else sessionRevokeTwoFactorInput?.focus(); + }, 40); + } + window.openServerDeleteVerificationModal = openServerDeleteVerificationModal; + + function openServerSuspensionVerificationModal(serverName, nextSuspended, sourceButton) { + const suspend = nextSuspended !== false; + sessionsState.securityModalMode = suspend ? 'suspend-server' : 'restore-server'; + sessionsState.selectedSession = null; + sessionsState.selectedServerDelete = null; + sessionsState.selectedAccountDelete = null; + sessionsState.selectedAccountSuspension = null; + sessionsState.selectedDatabaseInstall = null; + sessionsState.selectedServerSuspension = { + name: String(serverName || '').trim(), + suspended: suspend, + button: sourceButton || null, + actionToken: getServerSuspensionToken(serverName, sourceButton), + }; + setSecurityModalPresentation({ + title: suspend ? 'Suspend Server' : 'Restore Server', + targetLabel: 'Target Server', + targetValue: sessionsState.selectedServerSuspension.name || '—', + targetSubvalue: suspend + ? 'The server will be force-stopped, locked, and the suspended page will be shown instead.' + : 'Suspension records will be cleared and the server panel will be unlocked.', + confirmHtml: suspend + ? ' Suspend Server' + : ' Restore Server', + danger: suspend, + }); + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.value = ''; + } + showSessionRevokeModalFeedback(''); + + if (sessionRevokeModalOverlay) { + sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false'); + sessionRevokeModalOverlay.classList.add('show'); + } + if (sessionRevokeModal) { + sessionRevokeModal.classList.add('show'); + } + + window.setTimeout(() => { + if (isGraceActive()) sessionRevokeModalConfirm?.focus(); + else sessionRevokeTwoFactorInput?.focus(); + }, 40); + } + window.openServerSuspensionVerificationModal = openServerSuspensionVerificationModal; + + function openAccountDeleteVerificationModal(email, sourceButton) { + sessionsState.securityModalMode = 'delete-account'; + sessionsState.selectedSession = null; + sessionsState.selectedServerDelete = null; + sessionsState.selectedServerSuspension = null; + sessionsState.selectedAccountSuspension = null; + sessionsState.selectedAccountDelete = { + email: String(email || '').trim(), + button: sourceButton || null, + actionToken: getAccountDeleteToken(email, sourceButton), + }; + setSecurityModalPresentation({ + title: 'Delete User', + targetLabel: 'Target Account', + targetValue: sessionsState.selectedAccountDelete.email || '—', + targetSubvalue: 'This permanently removes the user, server access records, and ACL entries.', + confirmHtml: ' Delete User', + danger: true, + }); + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.value = ''; + } + showSessionRevokeModalFeedback(''); + + if (sessionRevokeModalOverlay) { + sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false'); + sessionRevokeModalOverlay.classList.add('show'); + } + if (sessionRevokeModal) { + sessionRevokeModal.classList.add('show'); + } + + window.setTimeout(() => { + if (isGraceActive()) sessionRevokeModalConfirm?.focus(); + else sessionRevokeTwoFactorInput?.focus(); + }, 40); + } + window.openAccountDeleteVerificationModal = openAccountDeleteVerificationModal; + + function openAccountSuspensionVerificationModal(email, nextSuspended, sourceButton) { + const suspend = !!nextSuspended; + sessionsState.securityModalMode = suspend ? 'suspend-account' : 'unsuspend-account'; + sessionsState.selectedSession = null; + sessionsState.selectedServerDelete = null; + sessionsState.selectedServerSuspension = null; + sessionsState.selectedAccountDelete = null; + sessionsState.selectedAccountSuspension = { + email: String(email || '').trim(), + suspended: suspend, + button: sourceButton || null, + actionToken: getAccountSuspensionToken(email, sourceButton), + }; + setSecurityModalPresentation({ + title: suspend ? 'Suspend Account' : 'Unsuspend Account', + targetLabel: 'Target Account', + targetValue: sessionsState.selectedAccountSuspension.email || '—', + targetSubvalue: suspend + ? 'All active sessions and persistent logins will be revoked immediately.' + : 'The user will be allowed to sign in again after this change.', + confirmHtml: suspend + ? ' Suspend Account' + : ' Unsuspend Account', + danger: suspend, + }); + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.value = ''; + } + showSessionRevokeModalFeedback(''); + + if (sessionRevokeModalOverlay) { + sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false'); + sessionRevokeModalOverlay.classList.add('show'); + } + if (sessionRevokeModal) { + sessionRevokeModal.classList.add('show'); + } + + window.setTimeout(() => { + if (isGraceActive()) sessionRevokeModalConfirm?.focus(); + else sessionRevokeTwoFactorInput?.focus(); + }, 40); + } + window.openAccountSuspensionVerificationModal = openAccountSuspensionVerificationModal; + + function getDatabaseInstallServiceMeta(service) { + const raw = String(service || 'database').trim().toLowerCase(); + if (raw === 'phpmyadmin' || raw === 'phpmyadmin setup') return { key: 'phpmyadmin', label: 'phpMyAdmin' }; + if (raw === 'pgadmin' || raw === 'pgadmin4') return { key: 'pgadmin', label: 'pgAdmin4' }; + if (raw === 'mongodb' || raw === 'mongo') return { key: 'mongodb', label: 'MongoDB' }; + return { key: raw || 'database', label: String(service || 'Database') }; + } + + function resolveDatabaseInstallVerification(result) { + const pending = sessionsState.selectedDatabaseInstall; + sessionsState.selectedDatabaseInstall = null; + if (pending && typeof pending.resolve === 'function') { + pending.resolve(result || { ok: false }); + } + } + + function isDatabaseInstallVerificationError(data) { + return [ + '2fa-required', + 'invalid-2fa', + 'password-required', + 'invalid-password', + 'verification-rate-limit' + ].includes(String(data?.code || '')); + } + window.isDatabaseInstallVerificationError = isDatabaseInstallVerificationError; + + async function getDatabaseInstallVerifyToken(forceRefresh = false) { + let token = String((window._dbActionTokens || {}).verifyInstall || '').trim(); + if ((!token || forceRefresh) && typeof window.refreshDbActionTokens === 'function') { + await window.refreshDbActionTokens(); + token = String((window._dbActionTokens || {}).verifyInstall || '').trim(); + } + return token; + } + + async function verifyDatabaseInstallWithCredential(credentialValue = '') { + const pending = sessionsState.selectedDatabaseInstall; + if (!pending) return; + + const passwordMode = sessionsState.authMethod === 'password'; + const requiresVerification = !isGraceActive(); + const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\D/g, '').slice(0, 6); + + if (requiresVerification) { + if (passwordMode) { + if (!credential) { + showSessionRevokeModalFeedback('Enter your current password.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } else if (!/^\d{6}$/.test(credential)) { + showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } + + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = true; + sessionRevokeModalConfirm.innerHTML = ' Verifying...'; + } + + const sendVerification = async (token) => { + const res = await fetch('/api/settings/database/verify-install', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': token || '', + }, + body: JSON.stringify({ + service: pending.serviceKey, + twoFactorCode: requiresVerification && !passwordMode ? credential : undefined, + currentPassword: requiresVerification && passwordMode ? credential : undefined, + }), + }); + const data = await res.json().catch(() => ({ error: 'Invalid server response' })); + return { res, data }; + }; + + try { + let token = await getDatabaseInstallVerifyToken(false); + let result = await sendVerification(token); + if (!result.res.ok && result.data?.error === 'invalid or missing action token') { + token = await getDatabaseInstallVerifyToken(true); + if (token) result = await sendVerification(token); + } + + const { res, data } = result; + if (!res.ok) { + if (data.revokeSecurity) applyRevokeSecurityFromPayload(data.revokeSecurity); + showSessionRevokeModalFeedback(data.error || 'Verification failed.', true); + return; + } + + if (data.revokeSecurity) applyRevokeSecurityFromPayload(data.revokeSecurity); + else if (data.graceExpiresAt) { + applyRevokeSecurityFromPayload({ + twoFactorEnabled: sessionsState.twoFactorEnabled, + authMethod: sessionsState.authMethod, + graceExpiresAt: data.graceExpiresAt, + }); + } + + resolveDatabaseInstallVerification({ ok: true, graceExpiresAt: data.graceExpiresAt || sessionsState.graceExpiresAt || 0 }); + closeSessionRevokeModal(); + } catch (err) { + console.error('[database] install verification failed', err); + showSessionRevokeModalFeedback(err.message || 'Network error while verifying.', true); + } finally { + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = false; + restoreSecurityModalConfirmButton(); + } + } + } + + function openDatabaseInstallVerificationModal(service, options = {}) { + const meta = getDatabaseInstallServiceMeta(service); + if (isGraceActive() && !options.force) { + return Promise.resolve({ ok: true, trusted: true, graceExpiresAt: sessionsState.graceExpiresAt }); + } + if (!sessionRevokeModalOverlay || !sessionRevokeModal) { + return Promise.resolve({ ok: false, error: 'Security verification modal unavailable' }); + } + + if (sessionsState.selectedDatabaseInstall?.resolve) { + resolveDatabaseInstallVerification({ ok: false, cancelled: true }); + } + + return new Promise((resolve) => { + sessionsState.securityModalMode = 'database-install'; + sessionsState.selectedSession = null; + sessionsState.selectedServerDelete = null; + sessionsState.selectedServerSuspension = null; + sessionsState.selectedAccountDelete = null; + sessionsState.selectedAccountSuspension = null; + sessionsState.selectedDatabaseInstall = { + serviceKey: meta.key, + serviceLabel: meta.label, + resolve, + }; + setSecurityModalPresentation({ + title: 'Confirm Installation', + targetLabel: 'Database Tool', + targetValue: meta.label, + targetSubvalue: 'Confirm your identity before opening the install setup.', + confirmHtml: ' Continue', + }); + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.value = ''; + } + showSessionRevokeModalFeedback(''); + + sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false'); + sessionRevokeModalOverlay.classList.add('show'); + sessionRevokeModal.classList.add('show'); + + window.setTimeout(() => { + if (isGraceActive()) sessionRevokeModalConfirm?.focus(); + else sessionRevokeTwoFactorInput?.focus(); + }, 40); + }); + } + window.openDatabaseInstallVerificationModal = openDatabaseInstallVerificationModal; + + function closeSessionRevokeModal() { + if (sessionsState.selectedDatabaseInstall?.resolve) { + resolveDatabaseInstallVerification({ ok: false, cancelled: true }); + } + sessionsState.selectedSession = null; + sessionsState.selectedServerDelete = null; + sessionsState.selectedServerSuspension = null; + sessionsState.selectedAccountDelete = null; + sessionsState.selectedAccountSuspension = null; if (sessionRevokeModalOverlay) { sessionRevokeModalOverlay.setAttribute('aria-hidden', 'true'); sessionRevokeModalOverlay.classList.remove('show'); @@ -5827,21 +7480,28 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { showSessionRevokeModalFeedback(''); } - async function revokeSession(targetRevokeToken, targetEmail, twoFactorCode = '', targetDisplayId = '') { - const trimmedRevokeToken = String(targetRevokeToken || '').trim(); - const trimmedEmail = String(targetEmail || '').trim().toLowerCase(); - const trimmedDisplayId = String(targetDisplayId || sessionsState.selectedSession?.displayId || '').trim(); - if (!trimmedRevokeToken) return; - const modalVisible = !!sessionRevokeModalOverlay?.classList.contains('show'); - - const requiresTwoFactor = !isGraceActive(); - if (requiresTwoFactor) { - const code = String(twoFactorCode || '').replace(/\s+/g, ''); - if (!/^\d{6}$/.test(code)) { - showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true); - sessionRevokeTwoFactorInput?.focus(); - return; - } + async function revokeSession(targetRevokeToken, targetEmail, credentialValue = '', targetDisplayId = '', targetType = 'session') { + const trimmedRevokeToken = String(targetRevokeToken || '').trim(); + const trimmedEmail = String(targetEmail || '').trim().toLowerCase(); + const trimmedDisplayId = String(targetDisplayId || sessionsState.selectedSession?.displayId || '').trim(); + if (!trimmedRevokeToken) return; + const modalVisible = !!sessionRevokeModalOverlay?.classList.contains('show'); + + const requiresVerification = !isGraceActive(); + const passwordMode = sessionsState.authMethod === 'password'; + const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\s+/g, ''); + if (requiresVerification) { + if (passwordMode) { + if (!credential) { + showSessionRevokeModalFeedback('Enter your current password.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } else if (!/^\d{6}$/.test(credential)) { + showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } } if (sessionRevokeModalConfirm) { @@ -5856,38 +7516,31 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { 'Content-Type': 'application/json', 'x-action-token': sessionsState.actionTokens.revokeSession || '', }, - body: JSON.stringify({ - revokeToken: trimmedRevokeToken, - twoFactorCode: requiresTwoFactor ? String(twoFactorCode || '').replace(/\s+/g, '') : undefined, - }), - }); + body: JSON.stringify({ + revokeToken: trimmedRevokeToken, + twoFactorCode: requiresVerification && !passwordMode ? credential : undefined, + currentPassword: requiresVerification && passwordMode ? credential : undefined, + }), + }); const data = await res.json().catch(() => ({ error: 'Invalid server response' })); if (!res.ok) { - if (data.code === '2fa-required' || data.code === 'invalid-2fa') { - sessionsState.graceExpiresAt = 0; - updateSessionsHeaderMeta(); - if (!sessionRevokeModalOverlay?.classList.contains('show')) { - openSessionRevokeModal(trimmedRevokeToken, trimmedDisplayId, trimmedEmail); - } - showSessionRevokeModalFeedback(data.error || '2FA verification failed.', true); - return; - } - - if (data.code === '2fa-not-enabled') { - sessionsState.twoFactorEnabled = false; - sessionsState.graceExpiresAt = 0; - updateSessionsHeaderMeta(); - closeSessionRevokeModal(); - showSessionsFeedback(data.error || 'Enable 2FA before revoking sessions.', true); - await loadSessions(sessionsState.page, sessionsSearchInput?.value || ''); - return; - } + if (data.code === '2fa-required' || data.code === 'invalid-2fa' || data.code === 'password-required' || data.code === 'invalid-password') { + sessionsState.graceExpiresAt = 0; + sessionsState.authMethod = data.code === 'password-required' || data.code === 'invalid-password' ? 'password' : sessionsState.authMethod; + configureSessionRevokeCredentialField(); + updateSessionsHeaderMeta(); + if (!sessionRevokeModalOverlay?.classList.contains('show')) { + openSessionRevokeModal(trimmedRevokeToken, trimmedDisplayId, trimmedEmail, targetType); + } + showSessionRevokeModalFeedback(data.error || 'Verification failed.', true); + return; + } if (data.error === 'invalid or missing action token') { await loadSessions(sessionsState.page, sessionsSearchInput?.value || ''); } - if (data.code === 'session-action-expired') { + if (data.code === 'session-action-expired' || data.code === 'session-not-active' || data.code === 'saved-login-not-found') { await loadSessions(sessionsState.page, sessionsSearchInput?.value || ''); } @@ -5917,15 +7570,423 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { } else { showSessionsFeedback(err.message || 'Network error while revoking session.', true); } - } finally { - if (sessionRevokeModalConfirm) { - sessionRevokeModalConfirm.disabled = false; - sessionRevokeModalConfirm.innerHTML = ' Revoke Session'; - } - } - } + } finally { + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = false; + restoreSecurityModalConfirmButton(); + } + } + } - if (sessionsSearchInput) { + async function deleteServerWithVerification(serverName, credentialValue = '') { + const name = String(serverName || '').trim(); + if (!name) return; + const sourceButton = sessionsState.selectedServerDelete?.button || null; + let actionToken = String(sessionsState.selectedServerDelete?.actionToken || getServerDeleteToken(name, sourceButton) || '').trim(); + const requiresVerification = !isGraceActive(); + const passwordMode = sessionsState.authMethod === 'password'; + const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\s+/g, ''); + + if (requiresVerification) { + if (passwordMode) { + if (!credential) { + showSessionRevokeModalFeedback('Enter your current password.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } else if (!/^\d{6}$/.test(credential)) { + showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } + + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = true; + sessionRevokeModalConfirm.innerHTML = ' Destroying...'; + } + if (sourceButton) sourceButton.disabled = true; + + try { + if (!actionToken) { + actionToken = await refreshServerDeleteToken(name); + if (sessionsState.selectedServerDelete) sessionsState.selectedServerDelete.actionToken = actionToken; + } + + const sendDelete = async (token) => { + const res = await fetchWithTimeout(`/api/settings/servers/${encodeURIComponent(name)}`, { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': token, + }, + body: JSON.stringify({ + twoFactorCode: requiresVerification && !passwordMode ? credential : undefined, + currentPassword: requiresVerification && passwordMode ? credential : undefined, + }), + }, 30000); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + return { res, data }; + }; + + let result = await sendDelete(actionToken); + if (!result.res.ok && result.data?.error === 'invalid or missing action token') { + const freshToken = await refreshServerDeleteToken(name); + if (freshToken && freshToken !== actionToken) { + actionToken = freshToken; + if (sessionsState.selectedServerDelete) sessionsState.selectedServerDelete.actionToken = freshToken; + result = await sendDelete(freshToken); + } + } + + const { res, data } = result; + + if (!res.ok) { + if (data.code === '2fa-required' || data.code === 'invalid-2fa' || data.code === 'password-required' || data.code === 'invalid-password') { + sessionsState.graceExpiresAt = 0; + sessionsState.authMethod = data.code === 'password-required' || data.code === 'invalid-password' ? 'password' : sessionsState.authMethod; + configureSessionRevokeCredentialField(); + updateSessionsHeaderMeta(); + showSessionRevokeModalFeedback(data.error || 'Verification failed.', true); + return; + } + if (data.error === 'invalid or missing action token') { + showSessionRevokeModalFeedback('Security token expired. Please click Delete again.', true); + return; + } + showSessionRevokeModalFeedback(data.error || 'Failed to delete server.', true); + return; + } + + sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0); + updateSessionsHeaderMeta(); + const deleteQueued = res.status === 202 || data.deleting === true; + closeSessionRevokeModal(); + showSuccessToast(deleteQueued ? `Delete queued for ${name}` : `Deleted ${name}`); + const deletedRow = findServerRowByName(name); + if (deletedRow) deletedRow.remove(); + loadServers(_serversPage, _serversSearch).catch((refreshErr) => { + console.warn('[servers] refresh after delete failed', refreshErr); + }); + } catch (err) { + console.error('[servers] delete failed', err); + const isAbort = err && (err.name === 'AbortError' || /aborted/i.test(String(err.message || ''))); + showSessionRevokeModalFeedback(isAbort ? 'Delete request timed out. Refresh the server list and check whether the node completed it.' : (err.message || 'Network error while deleting server.'), true); + } finally { + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = false; + restoreSecurityModalConfirmButton(); + } + if (sourceButton) sourceButton.disabled = false; + } + } + + async function changeServerSuspensionWithVerification(serverName, nextSuspended = true, credentialValue = '') { + const name = String(serverName || '').trim(); + if (!name) return; + const suspend = nextSuspended !== false; + const sourceButton = sessionsState.selectedServerSuspension?.button || null; + let actionToken = String(sessionsState.selectedServerSuspension?.actionToken || getServerSuspensionToken(name, sourceButton) || '').trim(); + const requiresVerification = !isGraceActive(); + const passwordMode = sessionsState.authMethod === 'password'; + const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\s+/g, ''); + + if (requiresVerification) { + if (passwordMode) { + if (!credential) { + showSessionRevokeModalFeedback('Enter your current password.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } else if (!/^\d{6}$/.test(credential)) { + showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } + + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = true; + sessionRevokeModalConfirm.innerHTML = suspend + ? ' Suspending...' + : ' Restoring...'; + } + if (sourceButton) sourceButton.disabled = true; + + try { + if (!actionToken) { + actionToken = await refreshServerSuspensionToken(name); + if (sessionsState.selectedServerSuspension) sessionsState.selectedServerSuspension.actionToken = actionToken; + } + + const sendChange = async (token) => { + const res = await fetchWithTimeout(`/api/settings/servers/${encodeURIComponent(name)}/suspension`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': token, + }, + body: JSON.stringify({ + suspended: suspend, + twoFactorCode: requiresVerification && !passwordMode ? credential : undefined, + currentPassword: requiresVerification && passwordMode ? credential : undefined, + }), + }, suspend ? 70000 : 15000); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + return { res, data }; + }; + + let result = await sendChange(actionToken); + if (!result.res.ok && result.data?.error === 'invalid or missing action token') { + const freshToken = await refreshServerSuspensionToken(name); + if (freshToken && freshToken !== actionToken) { + actionToken = freshToken; + if (sessionsState.selectedServerSuspension) sessionsState.selectedServerSuspension.actionToken = freshToken; + result = await sendChange(freshToken); + } + } + + const { res, data } = result; + + if (!res.ok) { + if (data.code === '2fa-required' || data.code === 'invalid-2fa' || data.code === 'password-required' || data.code === 'invalid-password') { + sessionsState.graceExpiresAt = 0; + sessionsState.authMethod = data.code === 'password-required' || data.code === 'invalid-password' ? 'password' : sessionsState.authMethod; + configureSessionRevokeCredentialField(); + updateSessionsHeaderMeta(); + showSessionRevokeModalFeedback(data.error || 'Verification failed.', true); + return; + } + if (data.error === 'invalid or missing action token') { + showSessionRevokeModalFeedback(`Security token expired. Please click ${suspend ? 'Suspend' : 'Restore'} again.`, true); + return; + } + showSessionRevokeModalFeedback(data.error || `Failed to ${suspend ? 'suspend' : 'restore'} server.`, true); + return; + } + + if (data.revokeSecurity) applyRevokeSecurityFromPayload(data.revokeSecurity); + else { + sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0); + updateSessionsHeaderMeta(); + } + closeSessionRevokeModal(); + showSuccessToast(`${suspend ? 'Suspended' : 'Restored'} ${data.server || name}`); + await loadServers(_serversPage, _serversSearch); + } catch (err) { + console.error('[servers] suspension change failed', err); + showSessionRevokeModalFeedback(err.message || `Network error while ${suspend ? 'suspending' : 'restoring'} server.`, true); + } finally { + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = false; + restoreSecurityModalConfirmButton(); + } + if (sourceButton) sourceButton.disabled = false; + } + } + + async function deleteAccountWithVerification(email, credentialValue = '') { + const targetEmail = String(email || '').trim(); + if (!targetEmail) return; + const sourceButton = sessionsState.selectedAccountDelete?.button || null; + let actionToken = String(sessionsState.selectedAccountDelete?.actionToken || getAccountDeleteToken(targetEmail, sourceButton) || '').trim(); + const requiresVerification = !isGraceActive(); + const passwordMode = sessionsState.authMethod === 'password'; + const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\s+/g, ''); + + if (requiresVerification) { + if (passwordMode) { + if (!credential) { + showSessionRevokeModalFeedback('Enter your current password.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } else if (!/^\d{6}$/.test(credential)) { + showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } + + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = true; + sessionRevokeModalConfirm.innerHTML = ' Deleting...'; + } + if (sourceButton) sourceButton.disabled = true; + + try { + if (!actionToken) { + actionToken = await refreshAccountDeleteToken(targetEmail); + if (sessionsState.selectedAccountDelete) sessionsState.selectedAccountDelete.actionToken = actionToken; + } + + const sendDelete = async (token) => { + const res = await fetch(`/api/settings/accounts/${encodeURIComponent(targetEmail)}`, { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': token, + }, + body: JSON.stringify({ + twoFactorCode: requiresVerification && !passwordMode ? credential : undefined, + currentPassword: requiresVerification && passwordMode ? credential : undefined, + }), + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + return { res, data }; + }; + + let result = await sendDelete(actionToken); + if (!result.res.ok && result.data?.error === 'invalid or missing action token') { + const freshToken = await refreshAccountDeleteToken(targetEmail); + if (freshToken && freshToken !== actionToken) { + actionToken = freshToken; + if (sessionsState.selectedAccountDelete) sessionsState.selectedAccountDelete.actionToken = freshToken; + result = await sendDelete(freshToken); + } + } + + const { res, data } = result; + + if (!res.ok) { + if (data.code === '2fa-required' || data.code === 'invalid-2fa' || data.code === 'password-required' || data.code === 'invalid-password') { + sessionsState.graceExpiresAt = 0; + sessionsState.authMethod = data.code === 'password-required' || data.code === 'invalid-password' ? 'password' : sessionsState.authMethod; + configureSessionRevokeCredentialField(); + updateSessionsHeaderMeta(); + showSessionRevokeModalFeedback(data.error || 'Verification failed.', true); + return; + } + if (data.error === 'invalid or missing action token') { + showSessionRevokeModalFeedback('Security token expired. Please click Delete again.', true); + return; + } + showSessionRevokeModalFeedback(data.error || 'Failed to delete user.', true); + return; + } + + sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0); + updateSessionsHeaderMeta(); + closeSessionRevokeModal(); + showSuccessToast(`Deleted ${targetEmail}`); + await loadAccounts(); + } catch (err) { + console.error('[accounts] delete failed', err); + showSessionRevokeModalFeedback(err.message || 'Network error while deleting user.', true); + } finally { + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = false; + restoreSecurityModalConfirmButton(); + } + if (sourceButton) sourceButton.disabled = false; + } + } + + async function changeAccountSuspensionWithVerification(email, nextSuspended, credentialValue = '') { + const targetEmail = String(email || '').trim(); + if (!targetEmail) return; + const suspend = !!nextSuspended; + const sourceButton = sessionsState.selectedAccountSuspension?.button || null; + let actionToken = String(sessionsState.selectedAccountSuspension?.actionToken || getAccountSuspensionToken(targetEmail, sourceButton) || '').trim(); + const requiresVerification = !isGraceActive(); + const passwordMode = sessionsState.authMethod === 'password'; + const credential = passwordMode ? String(credentialValue || '') : String(credentialValue || '').replace(/\s+/g, ''); + + if (requiresVerification) { + if (passwordMode) { + if (!credential) { + showSessionRevokeModalFeedback('Enter your current password.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } else if (!/^\d{6}$/.test(credential)) { + showSessionRevokeModalFeedback('Enter a valid 6-digit code.', true); + sessionRevokeTwoFactorInput?.focus(); + return; + } + } + + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = true; + sessionRevokeModalConfirm.innerHTML = suspend + ? ' Suspending...' + : ' Unsuspending...'; + } + if (sourceButton) sourceButton.disabled = true; + + try { + if (!actionToken) { + actionToken = await refreshAccountSuspensionToken(targetEmail); + if (sessionsState.selectedAccountSuspension) sessionsState.selectedAccountSuspension.actionToken = actionToken; + } + + const sendChange = async (token) => { + const res = await fetch(`/api/settings/accounts/${encodeURIComponent(targetEmail)}/suspension`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': token, + }, + body: JSON.stringify({ + suspended: suspend, + twoFactorCode: requiresVerification && !passwordMode ? credential : undefined, + currentPassword: requiresVerification && passwordMode ? credential : undefined, + }), + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + return { res, data }; + }; + + let result = await sendChange(actionToken); + if (!result.res.ok && result.data?.error === 'invalid or missing action token') { + const freshToken = await refreshAccountSuspensionToken(targetEmail); + if (freshToken && freshToken !== actionToken) { + actionToken = freshToken; + if (sessionsState.selectedAccountSuspension) sessionsState.selectedAccountSuspension.actionToken = freshToken; + result = await sendChange(freshToken); + } + } + + const { res, data } = result; + + if (!res.ok) { + if (data.code === '2fa-required' || data.code === 'invalid-2fa' || data.code === 'password-required' || data.code === 'invalid-password') { + sessionsState.graceExpiresAt = 0; + sessionsState.authMethod = data.code === 'password-required' || data.code === 'invalid-password' ? 'password' : sessionsState.authMethod; + configureSessionRevokeCredentialField(); + updateSessionsHeaderMeta(); + showSessionRevokeModalFeedback(data.error || 'Verification failed.', true); + return; + } + if (data.error === 'invalid or missing action token') { + showSessionRevokeModalFeedback('Security token expired. Please click the account action again.', true); + return; + } + showSessionRevokeModalFeedback(data.error || `Failed to ${suspend ? 'suspend' : 'unsuspend'} account.`, true); + return; + } + + sessionsState.graceExpiresAt = Number(data.graceExpiresAt || sessionsState.graceExpiresAt || 0); + updateSessionsHeaderMeta(); + closeSessionRevokeModal(); + showSuccessToast(`${suspend ? 'Suspended' : 'Unsuspended'} ${targetEmail}`); + await loadAccounts(); + if (typeof loadSessions === 'function') { + loadSessions(sessionsState.page, sessionsSearchInput?.value || '').catch(() => {}); + } + } catch (err) { + console.error('[accounts] suspension change failed', err); + showSessionRevokeModalFeedback(err.message || `Network error while ${suspend ? 'suspending' : 'unsuspending'} account.`, true); + } finally { + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = false; + restoreSecurityModalConfirmButton(); + } + if (sourceButton) sourceButton.disabled = false; + } + } + + if (sessionsSearchInput) { sessionsSearchInput.addEventListener('input', (event) => { const nextValue = String(event.target.value || '').trim(); window.clearTimeout(sessionsState.searchTimer); @@ -5953,18 +8014,14 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { const revokeToken = decodeURIComponent(button.dataset.revokeToken || ''); const displayId = decodeURIComponent(button.dataset.sessionDisplay || ''); const email = decodeURIComponent(button.dataset.sessionEmail || ''); + const targetType = button.dataset.targetType === 'remembered' ? 'remembered' : 'session'; - if (!sessionsState.twoFactorEnabled) { - showSessionsFeedback('Enable 2FA before revoking sessions.', true); + if (isGraceActive()) { + revokeSession(revokeToken, email, '', displayId, targetType); return; } - if (isGraceActive()) { - revokeSession(revokeToken, email, '', displayId); - return; - } - - openSessionRevokeModal(revokeToken, displayId, email); + openSessionRevokeModal(revokeToken, displayId, email, targetType); }); } @@ -5977,27 +8034,101 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { } }); } - if (sessionRevokeTwoFactorInput) { - sessionRevokeTwoFactorInput.addEventListener('input', (e) => { - e.target.value = String(e.target.value || '').replace(/\D/g, '').slice(0, 6); - }); - sessionRevokeTwoFactorInput.addEventListener('keydown', (e) => { - if (e.key === 'Enter' && sessionsState.selectedSession) { - revokeSession( - sessionsState.selectedSession.revokeToken, - sessionsState.selectedSession.email, - sessionRevokeTwoFactorInput.value + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.addEventListener('input', (e) => { + if (sessionsState.authMethod !== 'password') { + e.target.value = String(e.target.value || '').replace(/\D/g, '').slice(0, 6); + } + }); + sessionRevokeTwoFactorInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter' && sessionsState.selectedDatabaseInstall) { + verifyDatabaseInstallWithCredential(sessionRevokeTwoFactorInput.value); + return; + } + if (e.key === 'Enter' && sessionsState.selectedAccountDelete) { + deleteAccountWithVerification( + sessionsState.selectedAccountDelete.email, + sessionRevokeTwoFactorInput.value + ); + return; + } + if (e.key === 'Enter' && sessionsState.selectedAccountSuspension) { + changeAccountSuspensionWithVerification( + sessionsState.selectedAccountSuspension.email, + sessionsState.selectedAccountSuspension.suspended, + sessionRevokeTwoFactorInput.value + ); + return; + } + if (e.key === 'Enter' && sessionsState.selectedServerSuspension) { + changeServerSuspensionWithVerification( + sessionsState.selectedServerSuspension.name, + sessionsState.selectedServerSuspension.suspended, + sessionRevokeTwoFactorInput.value + ); + return; + } + if (e.key === 'Enter' && sessionsState.selectedServerDelete) { + deleteServerWithVerification( + sessionsState.selectedServerDelete.name, + sessionRevokeTwoFactorInput.value + ); + return; + } + if (e.key === 'Enter' && sessionsState.selectedSession) { + revokeSession( + sessionsState.selectedSession.revokeToken, + sessionsState.selectedSession.email, + sessionRevokeTwoFactorInput.value, + sessionsState.selectedSession.displayId, + sessionsState.selectedSession.targetType ); } }); - } - if (sessionRevokeModalConfirm) { - sessionRevokeModalConfirm.addEventListener('click', () => { - if (!sessionsState.selectedSession) return; - revokeSession( + } + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.addEventListener('click', () => { + if (sessionsState.selectedDatabaseInstall) { + verifyDatabaseInstallWithCredential(sessionRevokeTwoFactorInput?.value || ''); + return; + } + if (sessionsState.selectedAccountDelete) { + deleteAccountWithVerification( + sessionsState.selectedAccountDelete.email, + sessionRevokeTwoFactorInput?.value || '' + ); + return; + } + if (sessionsState.selectedAccountSuspension) { + changeAccountSuspensionWithVerification( + sessionsState.selectedAccountSuspension.email, + sessionsState.selectedAccountSuspension.suspended, + sessionRevokeTwoFactorInput?.value || '' + ); + return; + } + if (sessionsState.selectedServerSuspension) { + changeServerSuspensionWithVerification( + sessionsState.selectedServerSuspension.name, + sessionsState.selectedServerSuspension.suspended, + sessionRevokeTwoFactorInput?.value || '' + ); + return; + } + if (sessionsState.selectedServerDelete) { + deleteServerWithVerification( + sessionsState.selectedServerDelete.name, + sessionRevokeTwoFactorInput?.value || '' + ); + return; + } + if (!sessionsState.selectedSession) return; + revokeSession( sessionsState.selectedSession.revokeToken, sessionsState.selectedSession.email, - sessionRevokeTwoFactorInput?.value || '' + sessionRevokeTwoFactorInput?.value || '', + sessionsState.selectedSession.displayId, + sessionsState.selectedSession.targetType ); }); } @@ -6106,6 +8237,14 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { qaTitle.addEventListener('input', updatePreview); } + if (qaLink) { + qaLink.addEventListener('input', updatePreview); + } + + if (qaNewTab) { + qaNewTab.addEventListener('change', updatePreview); + } + if (qaIcon) { qaIcon.addEventListener('input', () => { updateIconPreview(); @@ -6334,9 +8473,29 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { function updatePreview() { const title = qaTitle?.value || 'Action Title'; + const link = qaLink?.value || ''; + const newTab = qaNewTab?.checked || false; + if (previewTitle) { previewTitle.textContent = title || 'Action Title'; } + + if (quickActionPreview) { + if (link) { + quickActionPreview.setAttribute('data-href', link); + if (newTab) { + quickActionPreview.setAttribute('data-target', '_blank'); + } else { + quickActionPreview.removeAttribute('data-target'); + } + quickActionPreview.style.cursor = 'pointer'; + } else { + quickActionPreview.removeAttribute('data-href'); + quickActionPreview.removeAttribute('data-target'); + quickActionPreview.style.cursor = 'default'; + } + } + updateIconPreview(); } @@ -6636,22 +8795,29 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { async function loadDbConfig() { try { - const res = await fetch('/api/settings/database'); + const res = await fetchWithTimeout('/api/settings/database', {}, 8000); if (!res.ok) { console.warn('[database] Failed to load config'); return; } const data = await res.json(); dbConfig = data.config || null; - dbUsers = data.users || []; - phpmyadminEnabled = !!data.enabled; - dbActionTokens = data.actionTokens || {}; - window._dbActionTokens = dbActionTokens; - updateDbUI(); - } catch (err) { - console.error('[database] Load config error:', err); - } - } + dbUsers = data.users || []; + phpmyadminEnabled = !!data.enabled; + dbActionTokens = data.actionTokens || {}; + window._dbActionTokens = dbActionTokens; + try { + window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); + } catch (_) { } + updateDbUI(); + } catch (err) { + console.error('[database] Load config error:', err); + } + } + window.refreshDbActionTokens = async function () { + await loadDbConfig(); + return dbActionTokens || {}; + }; function updateDbUI() { if (!phpmyadminToggle) return; @@ -6703,8 +8869,8 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { `; } - function renderDbUsers() { - if (!dbUsersList) return; + function renderDbUsers() { + if (!dbUsersList) return; if (!dbUsers || dbUsers.length === 0) { dbUsersList.innerHTML = ` @@ -6738,31 +8904,59 @@ document.querySelectorAll('.toggle-pass').forEach(btn => { `; dbUsersList.appendChild(row); - }); - } + }); + } - function openSetupModal() { - if (!dbSetupModalOverlay || !dbSetupModal) return; + async function confirmDatabaseInstallBeforeSetup(serviceLabel, resetToggle) { + if (typeof window.openDatabaseInstallVerificationModal !== 'function') { + alert('Security verification is unavailable. Please reload the page and try again.'); + if (resetToggle) resetToggle(); + return false; + } + const result = await window.openDatabaseInstallVerificationModal(serviceLabel); + if (!result?.ok) { + if (resetToggle) resetToggle(); + return false; + } + if (typeof window.refreshDbActionTokens === 'function') { + await window.refreshDbActionTokens(); + } + return true; + } + window.confirmDatabaseInstallBeforeSetup = confirmDatabaseInstallBeforeSetup; - if (dbHost) dbHost.value = 'localhost'; - if (dbPort) dbPort.value = '3306'; + async function openSetupModal(options = {}) { + if (!dbSetupModalOverlay || !dbSetupModal) return; + + if (!options.skipVerification) { + const verified = await confirmDatabaseInstallBeforeSetup('phpmyadmin', () => { + if (phpmyadminToggle && !phpmyadminEnabled) phpmyadminToggle.checked = false; + }); + if (!verified) return; + } + + if (dbHost) dbHost.value = 'localhost'; + if (dbPort) dbPort.value = '3306'; if (dbUsername) dbUsername.value = ''; if (dbPassword) dbPassword.value = ''; const mysqlRadio = document.querySelector('input[name="db_type"][value="mysql"]'); if (mysqlRadio) mysqlRadio.checked = true; - clearDbFeedback(dbSetupFeedback); - openModal(dbSetupModalOverlay, dbSetupModal); - } + clearDbFeedback(dbSetupFeedback); + openModal(dbSetupModalOverlay, dbSetupModal); + } + window.openSetupModal = openSetupModal; function closeSetupModal() { closeModal(dbSetupModalOverlay, dbSetupModal); } - async function saveDbSetup() { - const dbType = document.querySelector('input[name="db_type"]:checked')?.value || 'mysql'; - const host = dbHost?.value?.trim() || 'localhost'; + async function saveDbSetup() { + if (!(await confirmDatabaseInstallBeforeSetup('phpmyadmin'))) return; + + const dbType = document.querySelector('input[name="db_type"]:checked')?.value || 'mysql'; + const host = dbHost?.value?.trim() || 'localhost'; const port = parseInt(dbPort?.value || getDefaultPort(dbType), 10); const username = dbUsername?.value?.trim(); const password = dbPassword?.value; @@ -7438,10 +9632,16 @@ function createDbDisableProgress(statusEl, steps, estimatedSecs, brandColor) { } } - function openPgAdminSetupModal() { - if (pgadminEmail) pgadminEmail.value = ''; - if (pgadminPassword) pgadminPassword.value = ''; - if (pgadminPasswordStrength) pgadminPasswordStrength.innerHTML = ''; + async function openPgAdminSetupModal(options = {}) { + if (!options.skipVerification && typeof window.confirmDatabaseInstallBeforeSetup === 'function') { + const verified = await window.confirmDatabaseInstallBeforeSetup('pgadmin', () => { + if (pgadminToggle && !pgadminToggle.dataset.wasEnabled) pgadminToggle.checked = false; + }); + if (!verified) return; + } + if (pgadminEmail) pgadminEmail.value = ''; + if (pgadminPassword) pgadminPassword.value = ''; + if (pgadminPasswordStrength) pgadminPasswordStrength.innerHTML = ''; showPgAdminFeedback(''); if (pgadminSetupModalOverlay) { pgadminSetupModalOverlay.classList.add('show'); @@ -7470,7 +9670,7 @@ function createDbDisableProgress(statusEl, steps, estimatedSecs, brandColor) { pgadminStatus.innerHTML = '
    Checking status...
    '; try { - const res = await fetch('/api/settings/database/pgadmin/status'); + const res = await fetchWithTimeout('/api/settings/database/pgadmin/status', {}, 6000); if (!res.ok) throw new Error('Failed to fetch status'); const data = await res.json(); @@ -7496,8 +9696,13 @@ function createDbDisableProgress(statusEl, steps, estimatedSecs, brandColor) { } }; - async function savePgAdminSetup() { - const email = pgadminEmail?.value?.trim() || ''; + async function savePgAdminSetup() { + if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') { + const verified = await window.confirmDatabaseInstallBeforeSetup('pgadmin'); + if (!verified) return; + } + + const email = pgadminEmail?.value?.trim() || ''; const password = pgadminPassword?.value || ''; const dbUser = document.getElementById('pgadmin_db_user')?.value?.trim() || 'admin'; const dbHost = document.getElementById('pgadmin_db_host')?.value?.trim() || '127.0.0.1'; @@ -7805,10 +10010,16 @@ function createDbDisableProgress(statusEl, steps, estimatedSecs, brandColor) { } } - function openMongoDBSetupModal() { - if (mongodbUsername) mongodbUsername.value = 'admin'; - if (mongodbPassword) mongodbPassword.value = ''; - if (mongodbPasswordStrength) mongodbPasswordStrength.innerHTML = ''; + async function openMongoDBSetupModal(options = {}) { + if (!options.skipVerification && typeof window.confirmDatabaseInstallBeforeSetup === 'function') { + const verified = await window.confirmDatabaseInstallBeforeSetup('mongodb', () => { + if (mongodbToggle && !mongodbToggle.dataset.wasEnabled) mongodbToggle.checked = false; + }); + if (!verified) return; + } + if (mongodbUsername) mongodbUsername.value = 'admin'; + if (mongodbPassword) mongodbPassword.value = ''; + if (mongodbPasswordStrength) mongodbPasswordStrength.innerHTML = ''; showMongoDBFeedback(''); if (mongodbSetupModalOverlay) { mongodbSetupModalOverlay.classList.add('show'); @@ -7837,7 +10048,7 @@ function createDbDisableProgress(statusEl, steps, estimatedSecs, brandColor) { mongodbStatus.innerHTML = '
    Checking status...
    '; try { - const res = await fetch('/api/settings/database/mongodb/status'); + const res = await fetchWithTimeout('/api/settings/database/mongodb/status', {}, 6000); if (!res.ok) throw new Error('Failed to fetch status'); const data = await res.json(); @@ -7891,8 +10102,13 @@ function createDbDisableProgress(statusEl, steps, estimatedSecs, brandColor) { } }; - async function saveMongoDBSetup() { - const username = mongodbUsername?.value?.trim() || 'admin'; + async function saveMongoDBSetup() { + if (typeof window.confirmDatabaseInstallBeforeSetup === 'function') { + const verified = await window.confirmDatabaseInstallBeforeSetup('mongodb'); + if (!verified) return; + } + + const username = mongodbUsername?.value?.trim() || 'admin'; const password = mongodbPassword?.value || ''; const host = document.getElementById('mongodb_host')?.value?.trim() || '127.0.0.1'; const port = document.getElementById('mongodb_port')?.value?.trim() || '27017'; @@ -8407,6 +10623,9 @@ const adminChangePasswordFeedback = document.getElementById('adminChangePassword const adminNewPassword = document.getElementById('adminNewPassword'); const adminConfirmPassword = document.getElementById('adminConfirmPassword'); const adminPasswordStrength = document.getElementById('adminPasswordStrength'); +const adminChangePasswordCredential = document.getElementById('adminChangePasswordCredential'); +const adminChangePasswordCredentialLabel = document.getElementById('adminChangePasswordCredentialLabel'); +const adminChangePasswordCredentialHint = document.getElementById('adminChangePasswordCredentialHint'); let currentAdminChangePasswordEmail = ''; @@ -8430,6 +10649,9 @@ function openAdminChangePasswordModal(email) { if (adminChangePasswordSubtitle) adminChangePasswordSubtitle.textContent = 'Set a new password for this user'; if (adminNewPassword) adminNewPassword.value = ''; if (adminConfirmPassword) adminConfirmPassword.value = ''; + configureStepUpCredentialField(adminChangePasswordCredential, adminChangePasswordCredentialLabel, adminChangePasswordCredentialHint); + bindStepUpCredentialInput(adminChangePasswordCredential); + if (adminChangePasswordCredential) adminChangePasswordCredential.value = ''; if (adminPasswordStrength) adminPasswordStrength.innerHTML = ''; clearAdminPasswordFeedback(); @@ -8445,6 +10667,7 @@ function closeAdminChangePasswordModal() { adminChangePasswordOverlay.classList.remove('show'); } currentAdminChangePasswordEmail = ''; + if (adminChangePasswordCredential) adminChangePasswordCredential.value = ''; clearAdminPasswordFeedback(); } @@ -8469,6 +10692,10 @@ async function saveAdminChangePassword() { return; } + configureStepUpCredentialField(adminChangePasswordCredential, adminChangePasswordCredentialLabel, adminChangePasswordCredentialHint); + const credential = validateStepUpCredential(adminChangePasswordCredential, showAdminPasswordFeedback); + if (!credential) return; + if (adminChangePasswordSave) { adminChangePasswordSave.disabled = true; adminChangePasswordSave.innerHTML = ' Updating...'; @@ -8481,10 +10708,11 @@ async function saveAdminChangePassword() { 'Content-Type': 'application/json', 'x-action-token': (accountsListEl._actionTokens || {}).changePassword || '' }, - body: JSON.stringify({ newPassword, confirm }) + body: JSON.stringify(appendStepUpCredentialPayload({ newPassword, confirm }, credential)) }); const data = await res.json().catch(() => ({})); + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); if (!res.ok) { showAdminPasswordFeedback(data.error || 'Failed to change password', true); @@ -8571,13 +10799,16 @@ const qrResetLoading = document.getElementById('qrResetLoading'); const qrResetContent = document.getElementById('qrResetContent'); const qrResetError = document.getElementById('qrResetError'); const qrResetErrorText = document.getElementById('qrResetErrorText'); -const qrResetImage = document.getElementById('qrResetImage'); -const qrResetSecretText = document.getElementById('qrResetSecretText'); const qrResetDoneBtn = document.getElementById('qrResetDoneBtn'); +const qrResetConfirm = document.getElementById('qrResetConfirm'); +const qrResetConfirmError = document.getElementById('qrResetConfirmError'); +const qrResetCredential = document.getElementById('qrResetCredential'); +const qrResetCredentialLabel = document.getElementById('qrResetCredentialLabel'); +const qrResetCredentialHint = document.getElementById('qrResetCredentialHint'); let currentQRResetEmail = ''; -let currentQRResetSecret = ''; let currentQRResetIsAdmin = false; +let qrResetCompleted = false; function openQROptionsModal(email, isAdmin = false) { if (!qrOptionsModalOverlay) return; @@ -8599,25 +10830,105 @@ function closeQROptionsModal() { function openQRResetModal() { if (!qrResetModalOverlay) return; - if (qrResetUserEmail) qrResetUserEmail.textContent = `New QR for ${currentQRResetEmail}`; - if (qrResetLoading) qrResetLoading.style.display = 'block'; + if (qrResetUserEmail) qrResetUserEmail.textContent = `Reset 2FA for ${currentQRResetEmail}`; + + // Configure the step-up credential field (password vs 2FA) based on the + // acting admin's own security mode, reusing the shared step-up helpers. + qrResetCompleted = false; + configureQRResetCredentialField(); + + if (qrResetConfirm) qrResetConfirm.style.display = 'block'; + if (qrResetLoading) qrResetLoading.style.display = 'none'; if (qrResetContent) qrResetContent.style.display = 'none'; if (qrResetError) qrResetError.style.display = 'none'; + if (qrResetConfirmError) { qrResetConfirmError.style.display = 'none'; qrResetConfirmError.textContent = ''; } + if (qrResetDoneBtn) { + qrResetDoneBtn.disabled = false; + qrResetDoneBtn.innerHTML = ' Reset 2FA'; + } qrResetModalOverlay.setAttribute('aria-hidden', 'false'); qrResetModalOverlay.classList.add('show'); + if (qrResetCredential) { try { qrResetCredential.focus(); } catch (_) {} } +} - generateNewQRCode(); +function configureQRResetCredentialField() { + if (!qrResetCredential) return; + const trustedMode = (typeof isStepUpGraceActive === 'function') ? isStepUpGraceActive() : false; + const passwordMode = (typeof getCurrentStepUpMode === 'function') ? getCurrentStepUpMode() === 'password' : true; + const container = qrResetCredential.closest('div'); + + if (trustedMode) { + // Recent verification still valid; no credential needed. + if (container) container.style.display = 'none'; + qrResetCredential.value = ''; + return; + } + if (container) container.style.display = ''; + + if (qrResetCredentialLabel) qrResetCredentialLabel.textContent = passwordMode ? 'Current Password' : '2FA Code'; + if (qrResetCredentialHint) { + qrResetCredentialHint.textContent = passwordMode + ? 'Enter your current password to confirm this action.' + : 'Enter the code from your authenticator app.'; + } + qrResetCredential.type = passwordMode ? 'password' : 'text'; + qrResetCredential.placeholder = passwordMode ? 'Current password' : '000000'; + qrResetCredential.autocomplete = passwordMode ? 'current-password' : 'one-time-code'; + qrResetCredential.maxLength = passwordMode ? 1024 : 6; + qrResetCredential.inputMode = passwordMode ? '' : 'numeric'; + qrResetCredential.value = ''; } function closeQRResetModal() { if (!qrResetModalOverlay) return; qrResetModalOverlay.setAttribute('aria-hidden', 'true'); qrResetModalOverlay.classList.remove('show'); - currentQRResetSecret = ''; + if (qrResetCredential) qrResetCredential.value = ''; } -async function generateNewQRCode() { +// Performs the admin 2FA reset. The backend clears the target user's 2FA after +// step-up verification; no TOTP secret is ever returned to the admin. +async function confirmQRReset() { + // After a successful reset the same button becomes "Done" and just closes. + if (qrResetCompleted) { + closeQRResetModal(); + return; + } + + const trustedMode = (typeof isStepUpGraceActive === 'function') ? isStepUpGraceActive() : false; + const passwordMode = (typeof getCurrentStepUpMode === 'function') ? getCurrentStepUpMode() === 'password' : true; + + const showConfirmError = (msg) => { + if (qrResetConfirmError) { + qrResetConfirmError.textContent = msg; + qrResetConfirmError.style.display = 'block'; + } + }; + + let credential = ''; + if (!trustedMode) { + credential = String((qrResetCredential && qrResetCredential.value) || ''); + if (passwordMode) { + if (!credential) { showConfirmError('Enter your current password.'); qrResetCredential?.focus(); return; } + } else { + credential = credential.replace(/\D/g, '').slice(0, 6); + if (!/^\d{6}$/.test(credential)) { showConfirmError('Enter a valid 6-digit code.'); qrResetCredential?.focus(); return; } + } + } + try { + if (qrResetDoneBtn) { + qrResetDoneBtn.disabled = true; + qrResetDoneBtn.innerHTML = ' Resetting...'; + } + if (qrResetConfirmError) qrResetConfirmError.style.display = 'none'; + + const body = { email: currentQRResetEmail }; + if (!trustedMode) { + if (passwordMode) body.currentPassword = credential; + else body.twoFactorCode = credential; + } + const res = await fetch('/api/admin/user/reset-2fa', { method: 'POST', headers: { @@ -8625,76 +10936,47 @@ async function generateNewQRCode() { 'x-action-token': (accountsListEl._actionTokens || {}).reset2fa || '' }, credentials: 'include', - body: JSON.stringify({ email: currentQRResetEmail }) + body: JSON.stringify(body) }); const data = await res.json(); if (!res.ok) { - throw new Error(data.error || 'Failed to generate QR code'); + // Keep the modal open so the admin can re-enter credentials on a + // verification failure rather than losing the dialog. + if (data && (data.code === '2fa-required' || data.code === 'password-required' || + data.code === 'invalid-2fa' || data.code === 'invalid-password')) { + if (data.revokeSecurity && typeof applyRevokeSecurityFromPayload === 'function') { + try { applyRevokeSecurityFromPayload(data.revokeSecurity); } catch (_) {} + } + configureQRResetCredentialField(); + showConfirmError(data.error || 'Verification required.'); + return; + } + throw new Error((data && data.error) || 'Failed to reset 2FA'); } - currentQRResetSecret = data.newSecret; - console.log('[admin] QR generated, secret stored:', currentQRResetSecret ? 'YES' : 'NO'); - if (qrResetImage) qrResetImage.src = data.qrCodeUrl; - if (qrResetSecretText) qrResetSecretText.textContent = data.newSecret; - + // Success: show the "user must re-enroll" message. + qrResetCompleted = true; + if (qrResetConfirm) qrResetConfirm.style.display = 'none'; if (qrResetLoading) qrResetLoading.style.display = 'none'; if (qrResetContent) qrResetContent.style.display = 'block'; if (qrResetError) qrResetError.style.display = 'none'; - - } catch (err) { - console.error('[admin] QR generation error:', err); - if (qrResetLoading) qrResetLoading.style.display = 'none'; - if (qrResetContent) qrResetContent.style.display = 'none'; - if (qrResetError) qrResetError.style.display = 'block'; - if (qrResetErrorText) qrResetErrorText.textContent = err.message || 'Failed to generate QR code'; - } -} - -async function confirmQRReset() { - if (!currentQRResetSecret) { - closeQRResetModal(); - return; - } - - try { if (qrResetDoneBtn) { - qrResetDoneBtn.disabled = true; - qrResetDoneBtn.innerHTML = ' Saving...'; + qrResetDoneBtn.innerHTML = ' Done'; } - - console.log('[admin] Confirming 2FA reset - email:', currentQRResetEmail, 'secret exists:', !!currentQRResetSecret); - const res = await fetch('/api/admin/user/confirm-2fa-reset', { - method: 'POST', - headers: { - 'Content-Type': 'application/json', - 'x-action-token': (accountsListEl._actionTokens || {}).confirmReset2fa || '' - }, - credentials: 'include', - body: JSON.stringify({ - email: currentQRResetEmail, - newSecret: currentQRResetSecret - }) - }); - - const data = await res.json(); - - if (!res.ok) { - throw new Error(data.error || 'Failed to save 2FA'); - } - - closeQRResetModal(); console.log('[admin] 2FA reset SUCCESS for', currentQRResetEmail); - alert(`2FA successfully reset for ${currentQRResetEmail}`); - } catch (err) { - console.error('[admin] QR confirm error:', err); - alert('Error: ' + (err.message || 'Failed to save 2FA')); + console.error('[admin] 2FA reset error:', err); + showConfirmError(err.message || 'Failed to reset 2FA'); } finally { if (qrResetDoneBtn) { qrResetDoneBtn.disabled = false; - qrResetDoneBtn.innerHTML = ' Done'; + if (qrResetCompleted) { + qrResetDoneBtn.innerHTML = ' Done'; + } else { + qrResetDoneBtn.innerHTML = ' Reset 2FA'; + } } } } @@ -8852,8 +11134,10 @@ const createUserRoleAdmin = document.getElementById('createUserRoleAdmin'); const createUserEmail = document.getElementById('createUserEmail'); const createUserPassword = document.getElementById('createUserPassword'); const createUserPasswordConfirm = document.getElementById('createUserPasswordConfirm'); +const createUserEnableTwoFactor = document.getElementById('createUserEnableTwoFactor'); const createUserAdminStepUp = document.getElementById('createUserAdminStepUp'); const createAdminPassword = document.getElementById('createAdminPassword'); +const createAdminTwoFactorField = document.getElementById('createAdminTwoFactorField'); const createAdminTwoFactor = document.getElementById('createAdminTwoFactor'); const createUserError = document.getElementById('createUserError'); @@ -8862,20 +11146,24 @@ const userCredentialsModal = document.getElementById('userCredentialsModal'); const credentialsModalClose = document.getElementById('credentialsModalClose'); const credentialsUserEmail = document.getElementById('credentialsUserEmail'); const credentialsUserRole = document.getElementById('credentialsUserRole'); +const credentialsOneTimeNoticeText = document.getElementById('credentialsOneTimeNoticeText'); +const credentialsQRCodeBlock = document.getElementById('credentialsQRCodeBlock'); const credentialsQRCode = document.getElementById('credentialsQRCode'); +const credentialsSecretBlock = document.getElementById('credentialsSecretBlock'); const credentialsSecret = document.getElementById('credentialsSecret'); +const credentialsRecoveryBlock = document.getElementById('credentialsRecoveryBlock'); const credentialsRecoveryCodes = document.getElementById('credentialsRecoveryCodes'); const downloadCredentialsBtn = document.getElementById('downloadCredentialsBtn'); const credentialsDoneBtn = document.getElementById('credentialsDoneBtn'); let lastCreatedUserCredentials = null; let createUserSelectedRole = 'user'; - function setCreateUserRole(role) { createUserSelectedRole = role === 'admin' ? 'admin' : 'user'; if (createUserRoleNormal) createUserRoleNormal.classList.toggle('active', createUserSelectedRole === 'user'); if (createUserRoleAdmin) createUserRoleAdmin.classList.toggle('active', createUserSelectedRole === 'admin'); if (createUserAdminStepUp) createUserAdminStepUp.style.display = createUserSelectedRole === 'admin' ? 'block' : 'none'; + if (createAdminTwoFactorField) createAdminTwoFactorField.style.display = createUserSelectedRole === 'admin' && currentUserHas2FA ? '' : 'none'; if (createUserSubmitBtn) { createUserSubmitBtn.innerHTML = createUserSelectedRole === 'admin' ? ' Create Admin' @@ -8889,6 +11177,7 @@ function openCreateUserModal() { if (createUserEmail) createUserEmail.value = ''; if (createUserPassword) createUserPassword.value = ''; if (createUserPasswordConfirm) createUserPasswordConfirm.value = ''; + if (createUserEnableTwoFactor) createUserEnableTwoFactor.checked = false; if (createAdminPassword) createAdminPassword.value = ''; if (createAdminTwoFactor) createAdminTwoFactor.value = ''; if (createUserError) { @@ -8923,8 +11212,8 @@ function getUtf8ByteLength(value) { } } -async function ensureCreateUserActionToken() { - if ((accountsListEl._actionTokens || {}).createUser) return true; +async function ensureCreateUserActionToken(forceRefresh = false) { + if (!forceRefresh && (accountsListEl._actionTokens || {}).createUser) return true; if (typeof loadAccounts === 'function') { await loadAccounts(); } @@ -8936,6 +11225,7 @@ async function submitCreateUser() { const password = createUserPassword?.value || ''; const confirmPassword = createUserPasswordConfirm?.value || ''; const role = createUserSelectedRole === 'admin' ? 'admin' : 'user'; + const enableTwoFactor = !!createUserEnableTwoFactor?.checked; const adminPassword = createAdminPassword?.value || ''; const adminTwoFactorCode = (createAdminTwoFactor?.value || '').replace(/\s+/g, ''); @@ -8947,8 +11237,8 @@ async function submitCreateUser() { showCreateUserError('Password is required'); return; } - if (password.length < 12) { - showCreateUserError('Password must be at least 12 characters'); + if (password.length < 8) { + showCreateUserError('Password must be at least 8 characters'); return; } if (getUtf8ByteLength(password) > 72) { @@ -8964,7 +11254,7 @@ async function submitCreateUser() { showCreateUserError('Your password is required'); return; } - if (!/^\d{6}$/.test(adminTwoFactorCode)) { + if (currentUserHas2FA && !/^\d{6}$/.test(adminTwoFactorCode)) { showCreateUserError('Enter a valid 6-digit 2FA code'); return; } @@ -8983,7 +11273,7 @@ async function submitCreateUser() { throw new Error('Admin action token missing'); } - const res = await fetch('/api/admin/user/create', { + const sendCreate = () => fetch('/api/admin/user/create', { method: 'POST', headers: { 'Content-Type': 'application/json', @@ -8993,14 +11283,27 @@ async function submitCreateUser() { body: JSON.stringify({ email, password, - confirmPassword, - role, - adminPassword, - adminTwoFactorCode - }) + confirmPassword, + role, + enableTwoFactor, + adminPassword, + adminTwoFactorCode: currentUserHas2FA ? adminTwoFactorCode : '' + }) }); - const data = await res.json().catch(() => ({})); + let res = await sendCreate(); + let data = await res.json().catch(() => ({})); + + // The settings page keeps a long-lived (10 min) action session, but if the + // token has expired after sitting in the modal, transparently refresh it + // once and retry so the admin never sees a spurious token error. + if (!res.ok && data.error === 'invalid or missing action token') { + const refreshed = await ensureCreateUserActionToken(true); + if (refreshed) { + res = await sendCreate(); + data = await res.json().catch(() => ({})); + } + } if (!res.ok) { if (typeof loadAccounts === 'function') loadAccounts(); @@ -9029,17 +11332,26 @@ async function submitCreateUser() { function openCredentialsModal(data) { if (!userCredentialsModalOverlay) return; - if (credentialsUserEmail) credentialsUserEmail.textContent = data.email; + const has2FA = !!data.has2FA || !!data.secret; + if (credentialsUserEmail) credentialsUserEmail.textContent = has2FA ? data.email : `${data.email} is ready.`; if (credentialsUserRole) { const isAdmin = data.role === 'admin' || data.admin === true; credentialsUserRole.textContent = isAdmin ? 'Admin User' : 'Normal User'; credentialsUserRole.classList.toggle('admin', isAdmin); } - if (credentialsQRCode) credentialsQRCode.src = data.qrCodeUrl; - if (credentialsSecret) credentialsSecret.textContent = data.secret; + if (credentialsOneTimeNoticeText) { + credentialsOneTimeNoticeText.textContent = has2FA + ? 'Give these credentials to the user. They can only be shown ONCE!' + : 'The account was created without 2FA. Share the password you set with the user securely.'; + } + if (credentialsQRCodeBlock) credentialsQRCodeBlock.style.display = has2FA ? 'inline-block' : 'none'; + if (credentialsSecretBlock) credentialsSecretBlock.style.display = has2FA ? 'block' : 'none'; + if (credentialsRecoveryBlock) credentialsRecoveryBlock.style.display = has2FA ? 'block' : 'none'; + if (credentialsQRCode) credentialsQRCode.src = has2FA ? (data.qrCodeUrl || '') : ''; + if (credentialsSecret) credentialsSecret.textContent = data.secret || ''; if (credentialsRecoveryCodes) { - credentialsRecoveryCodes.innerHTML = data.recoveryCodes.map((code, idx) => ` + credentialsRecoveryCodes.innerHTML = (Array.isArray(data.recoveryCodes) ? data.recoveryCodes : []).map((code, idx) => `
    ${idx + 1}. ${code}
    @@ -9062,16 +11374,20 @@ function downloadCredentials() { const data = lastCreatedUserCredentials; const role = data.role === 'admin' || data.admin === true ? 'Admin User' : 'Normal User'; + const has2FA = !!data.has2FA || !!data.secret; const content = `ADPanel User Credentials ======================== Email: ${data.email} Role: ${role} +2FA: ${has2FA ? 'Enabled' : 'Disabled'} +${has2FA ? ` 2FA Secret: ${data.secret} Recovery Codes (each can only be used once): -${data.recoveryCodes.map((code, i) => ` ${i + 1}. ${code}`).join('\n')} +${(Array.isArray(data.recoveryCodes) ? data.recoveryCodes : []).map((code, i) => ` ${i + 1}. ${code}`).join('\n')} +` : ''} IMPORTANT: Keep these credentials secure! `; @@ -10514,6 +12830,7 @@ document.addEventListener('DOMContentLoaded', () => { let webhooksConfig = { mode: 'single', single: null, multiple: {} }; let webhookCategories = []; let webhookEditCategory = null; + let webhookActionTokens = {}; const webhookModeSingle = document.getElementById('webhookModeSingle'); const webhookModeMultiple = document.getElementById('webhookModeMultiple'); @@ -10530,6 +12847,9 @@ document.addEventListener('DOMContentLoaded', () => { const webhookModalTitle = document.getElementById('webhookModalTitle'); const webhookModalSubtitle = document.getElementById('webhookModalSubtitle'); const webhookUrlInput = document.getElementById('webhookUrlInput'); + const webhookCredentialInput = document.getElementById('webhookCredentialInput'); + const webhookCredentialLabel = document.getElementById('webhookCredentialLabel'); + const webhookCredentialHint = document.getElementById('webhookCredentialHint'); const webhookModalError = document.getElementById('webhookModalError'); const webhookModeIndicator = document.getElementById('webhookModeIndicator'); const webhookCategoryLabel = document.getElementById('webhookCategoryLabel'); @@ -10538,6 +12858,10 @@ document.addEventListener('DOMContentLoaded', () => { const webhookDeleteCancelBtn = document.getElementById('webhookDeleteCancelBtn'); const webhookDeleteConfirmBtn = document.getElementById('webhookDeleteConfirmBtn'); const webhookDeleteText = document.getElementById('webhookDeleteText'); + const webhookDeleteCredentialInput = document.getElementById('webhookDeleteCredentialInput'); + const webhookDeleteCredentialLabel = document.getElementById('webhookDeleteCredentialLabel'); + const webhookDeleteCredentialHint = document.getElementById('webhookDeleteCredentialHint'); + const webhookDeleteError = document.getElementById('webhookDeleteError'); let pendingDeleteCategory = null; @@ -10559,6 +12883,9 @@ document.addEventListener('DOMContentLoaded', () => { webhookModalError.style.display = 'none'; } if (webhookUrlInput && resetInput) webhookUrlInput.value = ''; + configureStepUpCredentialField(webhookCredentialInput, webhookCredentialLabel, webhookCredentialHint); + bindStepUpCredentialInput(webhookCredentialInput); + if (webhookCredentialInput) webhookCredentialInput.value = ''; setTimeout(() => webhookUrlInput && webhookUrlInput.focus(), 100); } else { if (innerModal) innerModal.classList.remove('show'); @@ -10572,12 +12899,23 @@ document.addEventListener('DOMContentLoaded', () => { webhookDeleteOverlay.setAttribute('aria-hidden', show ? 'false' : 'true'); if (show) { webhookDeleteOverlay.classList.add('show'); + configureStepUpCredentialField(webhookDeleteCredentialInput, webhookDeleteCredentialLabel, webhookDeleteCredentialHint); + bindStepUpCredentialInput(webhookDeleteCredentialInput); + if (webhookDeleteCredentialInput) webhookDeleteCredentialInput.value = ''; + if (webhookDeleteError) { + webhookDeleteError.textContent = ''; + webhookDeleteError.style.display = 'none'; + } if (innerModal) { innerModal.style.animation = 'none'; innerModal.offsetHeight; innerModal.style.animation = ''; setTimeout(() => innerModal.classList.add('show'), 10); } + setTimeout(() => { + if (isStepUpGraceActive()) webhookDeleteConfirmBtn?.focus(); + else webhookDeleteCredentialInput?.focus(); + }, 100); } else { if (innerModal) innerModal.classList.remove('show'); setTimeout(() => webhookDeleteOverlay.classList.remove('show'), 200); @@ -10591,6 +12929,8 @@ document.addEventListener('DOMContentLoaded', () => { if (data.ok) { webhooksConfig = data.config || { mode: 'single', single: null, multiple: {} }; webhookCategories = data.categories || []; + webhookActionTokens = data.actionTokens || {}; + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); renderWebhooks(); } } catch (e) { @@ -10677,11 +13017,14 @@ document.addEventListener('DOMContentLoaded', () => { if (webhooksConfig.mode === 'single') return; try { const res = await fetch('/api/settings/webhooks', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': webhookActionTokens.saveWebhook || '' }, body: JSON.stringify({ mode: 'single' }) }); const data = await res.json(); + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); if (data.ok) { webhooksConfig.mode = 'single'; renderWebhooks(); } + else showWebhookToast(data.error || 'Failed to change mode', 'error'); } catch (e) { console.error(e); } }); } @@ -10691,11 +13034,14 @@ document.addEventListener('DOMContentLoaded', () => { if (webhooksConfig.mode === 'multiple') return; try { const res = await fetch('/api/settings/webhooks', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': webhookActionTokens.saveWebhook || '' }, body: JSON.stringify({ mode: 'multiple' }) }); const data = await res.json(); + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); if (data.ok) { webhooksConfig.mode = 'multiple'; renderWebhooks(); } + else showWebhookToast(data.error || 'Failed to change mode', 'error'); } catch (e) { console.error(e); } }); } @@ -10751,16 +13097,25 @@ document.addEventListener('DOMContentLoaded', () => { webhookModalError.style.display = 'block'; return; } + configureStepUpCredentialField(webhookCredentialInput, webhookCredentialLabel, webhookCredentialHint); + const credential = validateStepUpCredential(webhookCredentialInput, (message) => { + webhookModalError.textContent = message || ''; + webhookModalError.style.display = message ? 'block' : 'none'; + }); + if (!credential) return; webhookModalSave.disabled = true; webhookModalSave.innerHTML = ' Saving...'; try { const body = { url }; if (webhookEditCategory) body.category = webhookEditCategory; + appendStepUpCredentialPayload(body, credential); const res = await fetch('/api/settings/webhooks', { - method: 'POST', headers: { 'Content-Type': 'application/json' }, + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': webhookActionTokens.saveWebhook || '' }, body: JSON.stringify(body) }); const data = await res.json(); + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); if (data.ok) { toggleWebhookModal(false); loadWebhooks(); @@ -10784,22 +13139,46 @@ document.addEventListener('DOMContentLoaded', () => { if (webhookDeleteConfirmBtn) { webhookDeleteConfirmBtn.addEventListener('click', async () => { + configureStepUpCredentialField(webhookDeleteCredentialInput, webhookDeleteCredentialLabel, webhookDeleteCredentialHint); + const credential = validateStepUpCredential(webhookDeleteCredentialInput, (message) => { + if (!webhookDeleteError) return; + webhookDeleteError.textContent = message || ''; + webhookDeleteError.style.display = message ? 'block' : 'none'; + }); + if (!credential) return; webhookDeleteConfirmBtn.disabled = true; webhookDeleteConfirmBtn.innerHTML = ' Deleting...'; + let deleted = false; try { const body = {}; if (pendingDeleteCategory) body.category = pendingDeleteCategory; + appendStepUpCredentialPayload(body, credential); const res = await fetch('/api/settings/webhooks', { - method: 'DELETE', headers: { 'Content-Type': 'application/json' }, + method: 'DELETE', + headers: { 'Content-Type': 'application/json', 'x-action-token': webhookActionTokens.deleteWebhook || '' }, body: JSON.stringify(body) }); const data = await res.json(); - if (data.ok) { toggleWebhookDeleteModal(false); loadWebhooks(); } - } catch (e) { console.error(e); } + if (data.revokeSecurity) window.applyRevokeSecurityFromPayload?.(data.revokeSecurity); + if (data.ok) { + deleted = true; + toggleWebhookDeleteModal(false); + loadWebhooks(); + } else if (webhookDeleteError) { + webhookDeleteError.textContent = data.error || 'Failed to delete'; + webhookDeleteError.style.display = 'block'; + } + } catch (e) { + console.error(e); + if (webhookDeleteError) { + webhookDeleteError.textContent = 'Network error'; + webhookDeleteError.style.display = 'block'; + } + } finally { webhookDeleteConfirmBtn.disabled = false; webhookDeleteConfirmBtn.innerHTML = ' Delete'; - pendingDeleteCategory = null; + if (deleted) pendingDeleteCategory = null; } }); } @@ -11604,5 +13983,30 @@ document.addEventListener('DOMContentLoaded', () => { manualBtn.click(); } }); + } })(); + +(function () { + const tip = document.createElement('div'); + tip.className = 'resource-tooltip-floating'; + tip.style.cssText = 'position:fixed;z-index:10010;display:none;pointer-events:none;padding:10px 12px;border-radius:10px;border:1px solid rgba(255,255,255,0.1);background:rgba(18,18,24,0.96);box-shadow:0 14px 34px rgba(0,0,0,0.34);color:rgba(255,255,255,0.82);font-size:12px;font-weight:500;line-height:1.45;max-width:260px;white-space:normal;'; + document.body.appendChild(tip); + + document.addEventListener('mouseover', (e) => { + const trigger = e.target.closest('.resource-tooltip'); + if (!trigger) return; + const card = trigger.querySelector('.resource-tooltip-card'); + if (!card) return; + tip.textContent = card.textContent.trim(); + tip.style.display = 'block'; + const r = trigger.getBoundingClientRect(); + const tw = tip.offsetWidth; + tip.style.left = Math.max(4, r.left + r.width / 2 - tw / 2) + 'px'; + tip.style.top = (r.top - tip.offsetHeight - 8) + 'px'; + }); + + document.addEventListener('mouseout', (e) => { + if (e.target.closest('.resource-tooltip')) tip.style.display = 'none'; + }); +})(); diff --git a/public/js/ssh-terminal-window.js b/public/js/ssh-terminal-window.js new file mode 100644 index 0000000..45438c1 --- /dev/null +++ b/public/js/ssh-terminal-window.js @@ -0,0 +1,632 @@ +(function () { + "use strict"; + + const STORAGE_KEY = "adpanel:ssh-terminal-window:v1"; + const DEFAULT_WIDTH = 960; + const DEFAULT_HEIGHT = 640; + const MIN_WIDTH = 360; + const MIN_HEIGHT = 260; + const MINIMIZED_WIDTH = 380; + const MINIMIZED_HEIGHT = 38; + const MODAL_SELECTOR = [ + ".modal-overlay", + ".activity-modal", + ".info-modal", + ".scheduler-modal", + ".planner-modal", + ".ai-help-modal", + ".clear-console-modal", + ".notfound-modal", + ".activity-modal-overlay", + ].join(","); + const MOTION_QUERY = window.matchMedia + ? window.matchMedia("(prefers-reduced-motion: reduce), (update: slow)") + : { matches: false }; + + let win = null; + let frame = null; + let launcher = null; + let interaction = null; + let raf = 0; + let opening = null; + let motionId = 0; + let modalObserver = null; + let launcherVisibilityRaf = 0; + let geometry = { x: 24, y: 24, w: DEFAULT_WIDTH, h: DEFAULT_HEIGHT }; + + function readState() { + try { + const raw = localStorage.getItem(STORAGE_KEY); + if (!raw) return {}; + const data = JSON.parse(raw); + return data && typeof data === "object" ? data : {}; + } catch { + return {}; + } + } + + function writeState(patch) { + try { + const next = Object.assign({}, readState(), patch, { updatedAt: Date.now() }); + localStorage.setItem(STORAGE_KEY, JSON.stringify(next)); + } catch { } + } + + function viewport() { + return { + w: Math.max(320, window.innerWidth || document.documentElement.clientWidth || 1280), + h: Math.max(240, window.innerHeight || document.documentElement.clientHeight || 720), + }; + } + + function clampSize(w, h) { + const vp = viewport(); + return { + w: Math.max(Math.min(MIN_WIDTH, vp.w - 16), Math.min(Number.isFinite(w) ? w : DEFAULT_WIDTH, vp.w - 16)), + h: Math.max(Math.min(MIN_HEIGHT, vp.h - 16), Math.min(Number.isFinite(h) ? h : DEFAULT_HEIGHT, vp.h - 16)), + }; + } + + function clampGeometry(x, y, w, h, minimized) { + const vp = viewport(); + const size = clampSize(w, h); + const viewW = minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : size.w; + const viewH = minimized ? Math.min(MINIMIZED_HEIGHT, vp.h - 16) : size.h; + return { + x: Math.max(8, Math.min(Number.isFinite(x) ? x : 24, Math.max(8, vp.w - viewW - 8))), + y: Math.max(8, Math.min(Number.isFinite(y) ? y : 24, Math.max(8, vp.h - viewH - 8))), + w: size.w, + h: size.h, + }; + } + + function getGeometryForState(state) { + const minimized = !!state.minimized; + const size = clampSize(Number(state.w), Number(state.h)); + if (Number.isFinite(state.x) && Number.isFinite(state.y)) { + return clampGeometry(Number(state.x), Number(state.y), size.w, size.h, minimized); + } + const vp = viewport(); + const viewW = minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : size.w; + const viewH = minimized ? MINIMIZED_HEIGHT : size.h; + return clampGeometry(Math.round((vp.w - viewW) / 2), Math.round((vp.h - viewH) / 2), size.w, size.h, minimized); + } + + function applyGeometry(next) { + if (!win) return; + geometry = { + x: Math.round(next.x), + y: Math.round(next.y), + w: Math.round(next.w), + h: Math.round(next.h), + }; + win.style.setProperty("--adp-ssh-x", `${geometry.x}px`); + win.style.setProperty("--adp-ssh-y", `${geometry.y}px`); + win.style.setProperty("--adp-ssh-w", `${geometry.w}px`); + win.style.setProperty("--adp-ssh-h", `${geometry.h}px`); + } + + function writeWindowState(patch) { + writeState(Object.assign({ + x: geometry.x, + y: geometry.y, + w: geometry.w, + h: geometry.h, + }, patch)); + } + + function resizeCursor(handle) { + if (handle === "n" || handle === "s") return "ns-resize"; + if (handle === "e" || handle === "w") return "ew-resize"; + if (handle === "ne" || handle === "sw") return "nesw-resize"; + return "nwse-resize"; + } + + function setInteractionCursor(cursor) { + document.documentElement.style.cursor = cursor; + document.body.style.cursor = cursor; + if (win) win.style.cursor = cursor; + } + + function clearInteractionCursor() { + document.documentElement.style.cursor = ""; + document.body.style.cursor = ""; + if (win) win.style.cursor = ""; + } + + function clearMotionClasses(node) { + if (!node) return; + node.classList.remove("is-liquid-motion", "is-motion-open", "is-motion-minimize", "is-motion-restore", "is-motion-close", "is-motion-lite"); + } + + function cancelWindowMotion(node = win) { + motionId += 1; + if (node && node.getAnimations) { + node.getAnimations().forEach((animation) => { + try { animation.cancel(); } catch { } + }); + } + clearMotionClasses(node); + } + + function withoutWindowTransition(node, fn) { + if (!node) return; + const previous = node.style.transition; + node.style.transition = "none"; + fn(); + void node.offsetWidth; + node.style.transition = previous; + } + + function shouldUseLiteMotion() { + const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection; + return !!( + MOTION_QUERY.matches || + (navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 2) || + (navigator.deviceMemory && navigator.deviceMemory <= 2) || + (connection && connection.saveData) + ); + } + + function visualRectForGeometry(next, minimized) { + const vp = viewport(); + return { + left: next.x, + top: next.y, + width: minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : next.w, + height: minimized ? Math.min(MINIMIZED_HEIGHT, vp.h - 16) : next.h, + }; + } + + function rectTransform(rect, layoutRect) { + const sx = rect.width / Math.max(1, layoutRect.width); + const sy = rect.height / Math.max(1, layoutRect.height); + return `translate3d(${rect.left}px, ${rect.top}px, 0) scale(${sx}, ${sy})`; + } + + function morphRect(from, to, progress, sx, sy) { + return { + left: from.left + (to.left - from.left) * progress, + top: from.top + (to.top - from.top) * progress, + width: to.width * sx, + height: to.height * sy, + }; + } + + function motionKeyframes(kind, fromRect, toRect, layoutRect) { + const start = rectTransform(fromRect, layoutRect); + const end = rectTransform(toRect, layoutRect); + + if (kind === "minimize") { + return [ + { opacity: 1, transform: start, offset: 0 }, + { opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 0.72, 1.14, 0.68), layoutRect), offset: 0.58 }, + { opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 0.94, 0.96, 1.12), layoutRect), offset: 0.82 }, + { opacity: 1, transform: end, offset: 1 }, + ]; + } + + if (kind === "restore" || kind === "open") { + return [ + { opacity: kind === "open" ? 0 : 1, transform: start, offset: 0 }, + { opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 1, 1.028, 0.982), layoutRect), offset: 0.54 }, + { opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 1, 0.992, 1.006), layoutRect), offset: 0.78 }, + { opacity: 1, transform: end, offset: 1 }, + ]; + } + + return [ + { opacity: 1, transform: start, offset: 0 }, + { opacity: 0.86, transform: rectTransform(morphRect(fromRect, toRect, 1, 1.018, 0.9), layoutRect), offset: 0.45 }, + { opacity: 0, transform: end, offset: 1 }, + ]; + } + + function playWindowMotion(kind, fromRect, toRect, node = win) { + if (!node) return Promise.resolve(); + + cancelWindowMotion(node); + const currentMotion = motionId; + const lite = shouldUseLiteMotion(); + const layoutRect = node.getBoundingClientRect(); + const finalRect = toRect || layoutRect; + const initialRect = fromRect || { + left: finalRect.left + finalRect.width * 0.04, + top: finalRect.top + finalRect.height * 0.035, + width: finalRect.width * 0.92, + height: finalRect.height * 0.92, + }; + const duration = lite + ? 140 + : kind === "restore" || kind === "open" + ? 520 + : kind === "minimize" + ? 460 + : 260; + + node.classList.add("is-liquid-motion", `is-motion-${kind}`); + node.classList.toggle("is-motion-lite", lite); + + const cleanup = (animation) => { + if (currentMotion !== motionId) return; + if (animation) { + try { animation.cancel(); } catch { } + } + clearMotionClasses(node); + }; + + if (!node.animate) { + return new Promise((resolve) => { + setTimeout(() => { + cleanup(); + resolve(); + }, duration); + }); + } + + const easing = kind === "close" + ? "cubic-bezier(0.4, 0, 1, 1)" + : "cubic-bezier(0.16, 1, 0.3, 1)"; + const animation = node.animate(motionKeyframes(kind, initialRect, finalRect, layoutRect), { + duration, + easing, + fill: "both", + }); + + return animation.finished.catch(() => { }).then(() => cleanup(animation)); + } + + function ensureWindow() { + if (win) return win; + + win = document.createElement("section"); + win.id = "adpSshTerminalWindow"; + win.className = "adp-ssh-terminal-window"; + win.setAttribute("role", "dialog"); + win.setAttribute("aria-label", "SSH Terminal"); + win.innerHTML = ` +
    +
    + + SSH Terminal +
    + +
    + + +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    +
    +
    + `; + document.body.appendChild(win); + updateLauncherVisibility(); + frame = win.querySelector(".adp-ssh-terminal-frame"); + + const state = readState(); + const nextGeometry = getGeometryForState(state); + applyGeometry(nextGeometry); + win.classList.toggle("is-minimized", !!state.minimized); + + win.querySelector("[data-adp-ssh-close]")?.addEventListener("click", closeTerminal); + win.querySelector("[data-adp-ssh-minimize]")?.addEventListener("click", toggleMinimized); + win.querySelector("[data-adp-ssh-drag]")?.addEventListener("pointerdown", startDrag); + win.querySelectorAll("[data-adp-ssh-resize]").forEach((handle) => { + handle.addEventListener("pointerdown", startResize); + }); + win.querySelector("[data-adp-ssh-drag]")?.addEventListener("dblclick", (event) => { + if (event.target.closest("button")) return; + toggleMinimized(); + }); + + requestAnimationFrame(() => { + if (!win) return; + win.classList.add("is-ready"); + playWindowMotion("open"); + }); + return win; + } + + async function fetchLaunchUrl() { + const res = await fetch("/api/ssh-terminal/session", { credentials: "include" }); + const data = await res.json().catch(() => ({})); + if (!res.ok || !data || !data.launchUrl) { + throw new Error((data && data.error) || "Unable to open terminal"); + } + return data.launchUrl; + } + + async function openTerminal(options = {}) { + if (opening) return opening; + opening = (async () => { + const node = ensureWindow(); + const state = readState(); + const nextGeometry = getGeometryForState(state); + applyGeometry(nextGeometry); + node.classList.toggle("is-minimized", !!state.minimized); + writeWindowState({ open: true, minimized: !!state.minimized }); + updateLauncherVisibility(); + + if (frame && (!frame.getAttribute("src") || frame.getAttribute("src") === "about:blank")) { + frame.src = await fetchLaunchUrl(); + } + return node; + })(); + + try { + return await opening; + } catch (err) { + if (!options.silent) alert(err && err.message ? err.message : "Failed to open SSH terminal."); + throw err; + } finally { + opening = null; + } + } + + function toggleMinimized() { + if (!win) return; + if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win); + const node = win; + const from = node.getBoundingClientRect(); + const minimized = !win.classList.contains("is-minimized"); + const next = clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized); + + if (minimized) { + const to = visualRectForGeometry(next, true); + writeState({ open: true, minimized: true, x: next.x, y: next.y, w: next.w, h: next.h, updatedAt: Date.now() }); + playWindowMotion("minimize", from, to, node).then(() => { + if (win !== node) return; + withoutWindowTransition(node, () => { + node.classList.add("is-minimized"); + applyGeometry(next); + }); + }); + return; + } + + withoutWindowTransition(node, () => { + node.classList.remove("is-minimized"); + applyGeometry(next); + }); + const to = node.getBoundingClientRect(); + writeWindowState({ open: true, minimized: false }); + playWindowMotion("restore", from, to, node); + } + + function closeTerminal() { + if (win && win.classList.contains("is-liquid-motion")) cancelWindowMotion(win); + if (frame && frame.contentWindow) { + try { + frame.contentWindow.postMessage({ type: "adpanel-ssh-terminal-close" }, window.location.origin); + } catch { } + } + + try { + localStorage.setItem("adpanel:ssh-terminal-live:v1", "0"); + } catch { } + writeState({ open: false, minimized: false }); + + const old = win; + const from = old ? old.getBoundingClientRect() : null; + const to = from ? { + left: from.left + from.width * 0.04, + top: from.top + from.height * 0.08, + width: from.width * 0.9, + height: from.height * 0.76, + } : null; + win = null; + frame = null; + updateLauncherVisibility(); + if (old) { + playWindowMotion("close", from, to, old).then(() => { + old.classList.remove("is-ready"); + const iframe = old.querySelector("iframe"); + if (iframe) iframe.src = "about:blank"; + old.remove(); + }); + } + } + + function startDrag(event) { + if (!win || event.button !== 0 || event.target.closest("button")) return; + if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win); + interaction = { + type: "drag", + pointerId: event.pointerId, + offsetX: event.clientX - geometry.x, + offsetY: event.clientY - geometry.y, + x: geometry.x, + y: geometry.y, + w: geometry.w, + h: geometry.h, + }; + win.classList.add("is-interacting", "is-dragging"); + setInteractionCursor("grabbing"); + try { event.currentTarget.setPointerCapture(event.pointerId); } catch { } + event.preventDefault(); + } + + function startResize(event) { + if (!win || event.button !== 0 || win.classList.contains("is-minimized")) return; + if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win); + const handle = event.currentTarget.getAttribute("data-adp-ssh-resize") || ""; + interaction = { + type: "resize", + pointerId: event.pointerId, + handle, + startX: event.clientX, + startY: event.clientY, + x: geometry.x, + y: geometry.y, + w: geometry.w, + h: geometry.h, + next: Object.assign({}, geometry), + }; + win.classList.add("is-interacting", "is-resizing"); + setInteractionCursor(resizeCursor(handle)); + try { event.currentTarget.setPointerCapture(event.pointerId); } catch { } + event.preventDefault(); + event.stopPropagation(); + } + + function resizeGeometry(start, dx, dy, handle) { + const vp = viewport(); + let left = start.x; + let top = start.y; + let right = start.x + start.w; + let bottom = start.y + start.h; + if (handle.includes("e")) right += dx; + if (handle.includes("s")) bottom += dy; + if (handle.includes("w")) left += dx; + if (handle.includes("n")) top += dy; + + if (handle.includes("w")) { + left = Math.max(8, Math.min(left, right - Math.min(MIN_WIDTH, vp.w - 16))); + } else { + right = Math.min(vp.w - 8, Math.max(right, left + Math.min(MIN_WIDTH, vp.w - 16))); + } + + if (handle.includes("n")) { + top = Math.max(8, Math.min(top, bottom - Math.min(MIN_HEIGHT, vp.h - 16))); + } else { + bottom = Math.min(vp.h - 8, Math.max(bottom, top + Math.min(MIN_HEIGHT, vp.h - 16))); + } + + return clampGeometry(left, top, right - left, bottom - top, false); + } + + function moveInteraction(event) { + if (!interaction || !win || event.pointerId !== interaction.pointerId) return; + const minimized = win.classList.contains("is-minimized"); + const next = interaction.type === "resize" + ? resizeGeometry(interaction, event.clientX - interaction.startX, event.clientY - interaction.startY, interaction.handle) + : clampGeometry(event.clientX - interaction.offsetX, event.clientY - interaction.offsetY, interaction.w, interaction.h, minimized); + interaction.next = next; + if (!raf) { + raf = requestAnimationFrame(() => { + raf = 0; + if (interaction && interaction.next) applyGeometry(interaction.next); + }); + } + } + + function endInteraction(event) { + if (!interaction || !win || event.pointerId !== interaction.pointerId) return; + const minimized = win.classList.contains("is-minimized"); + const next = interaction.next || clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized); + applyGeometry(next); + writeWindowState({ open: true, minimized }); + win.classList.remove("is-interacting", "is-dragging", "is-resizing"); + clearInteractionCursor(); + interaction = null; + } + + function attachLaunchers() { + ensureLauncher(); + document.addEventListener("click", (event) => { + const trigger = event.target.closest("[data-open-ssh-terminal], #openSshTerminalBtn"); + if (!trigger) return; + event.preventDefault(); + if ("disabled" in trigger) trigger.disabled = true; + openTerminal().finally(() => { + if ("disabled" in trigger) trigger.disabled = false; + }); + }); + + const state = readState(); + if (state.open) { + openTerminal({ silent: true }).catch(() => { }); + } + } + + function ensureLauncher() { + if (launcher || document.querySelector("[data-open-ssh-terminal], #openSshTerminalBtn")) return; + launcher = document.createElement("button"); + launcher.type = "button"; + launcher.className = "adp-ssh-terminal-launcher"; + launcher.setAttribute("data-open-ssh-terminal", "true"); + launcher.setAttribute("title", "Open SSH Terminal"); + launcher.setAttribute("aria-label", "Open SSH Terminal"); + launcher.innerHTML = ''; + document.body.appendChild(launcher); + updateLauncherVisibility(); + } + + function updateLauncherVisibility() { + if (!launcher) return; + const open = !!win || !!readState().open; + launcher.classList.toggle("is-hidden", open || hasVisibleModal()); + } + + function isVisibleModal(node) { + if (!node || node === win || node === launcher) return false; + if (node.getAttribute("aria-hidden") === "true") return false; + if (node.classList.contains("show") || node.getAttribute("aria-hidden") === "false") return true; + const styles = window.getComputedStyle(node); + if (styles.display === "none" || styles.visibility === "hidden" || styles.opacity === "0") return false; + return node.offsetWidth > 0 && node.offsetHeight > 0; + } + + function hasVisibleModal() { + return Array.from(document.querySelectorAll(MODAL_SELECTOR)).some(isVisibleModal); + } + + function scheduleLauncherVisibility() { + if (launcherVisibilityRaf) return; + launcherVisibilityRaf = requestAnimationFrame(() => { + launcherVisibilityRaf = 0; + updateLauncherVisibility(); + }); + } + + function observeModalVisibility() { + if (modalObserver || !document.body) return; + modalObserver = new MutationObserver(scheduleLauncherVisibility); + modalObserver.observe(document.body, { + attributes: true, + attributeFilter: ["class", "style", "aria-hidden"], + childList: true, + subtree: true, + }); + } + + window.addEventListener("pointermove", moveInteraction, { passive: true }); + window.addEventListener("pointerup", endInteraction, { passive: true }); + window.addEventListener("pointercancel", endInteraction, { passive: true }); + window.addEventListener("resize", () => { + if (!win) return; + const minimized = win.classList.contains("is-minimized"); + const next = clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized); + applyGeometry(next); + writeWindowState({ open: true, minimized }); + }); + + window.ADPanelSshTerminal = { + open: openTerminal, + close: closeTerminal, + toggleMinimized, + }; + + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", () => { + attachLaunchers(); + observeModalVisibility(); + }, { once: true }); + } else { + attachLaunchers(); + observeModalVisibility(); + } +})(); diff --git a/public/js/status-monitor.js b/public/js/status-monitor.js new file mode 100644 index 0000000..e3be02f --- /dev/null +++ b/public/js/status-monitor.js @@ -0,0 +1,325 @@ +/* Admin /status monitoring client. + * + * - Opens the existing socket.io connection, joins the admin-only "monitor" + * room, and renders live bars (CPU/RAM/Storage/Network/RPS) once per second + * while the page is open. + * - Renders a fixed one-month calendar; clicking a day fetches that day's + * per-minute history via REST and draws it into the graph. Default view is + * today. + * - Everything here is read-only and admin-gated server-side. + */ +(function () { + "use strict"; + + var SOCKET = null; + var watching = false; + + // ---- helpers ----------------------------------------------------------- + function $(id) { return document.getElementById(id); } + + function clampPct(n) { + n = Number(n); + if (!isFinite(n) || n < 0) return 0; + if (n > 100) return 100; + return n; + } + + function fmtBytesPerSec(bps) { + bps = Number(bps) || 0; + var units = ["B/s", "KB/s", "MB/s", "GB/s"]; + var i = 0; + while (bps >= 1024 && i < units.length - 1) { bps /= 1024; i++; } + return (bps < 10 ? bps.toFixed(1) : Math.round(bps)) + " " + units[i]; + } + + function fmtUptime(ms) { + var s = Math.floor((Number(ms) || 0) / 1000); + var d = Math.floor(s / 86400); s -= d * 86400; + var h = Math.floor(s / 3600); s -= h * 3600; + var m = Math.floor(s / 60); s -= m * 60; + var parts = []; + if (d) parts.push(d + "d"); + if (h || d) parts.push(h + "h"); + parts.push(m + "m"); + parts.push(s + "s"); + return parts.join(" "); + } + + // ---- bar rendering ----------------------------------------------------- + function setBar(key, percent, valueText) { + var fill = document.querySelector('[data-bar-fill="' + key + '"]'); + var pctEl = document.querySelector('[data-bar-pct="' + key + '"]'); + var valEl = document.querySelector('[data-bar-value="' + key + '"]'); + var p = clampPct(percent); + + // Update circular ring progress + if (fill) { + var circumference = 2 * Math.PI * 15.9155; + var offset = circumference - (p / 100) * circumference; + fill.style.strokeDasharray = p + ', 100'; + } + + if (pctEl) pctEl.textContent = p.toFixed(1) + "%"; + if (valEl && valueText != null) valEl.textContent = valueText; + } + + // Network bars are scaled relative to a rolling observed peak so the bar is + // meaningful even without a hard cap. + var netPeak = { rx: 1024 * 256, tx: 1024 * 256 }; + function netPercent(dir, bps) { + bps = Number(bps) || 0; + if (bps > netPeak[dir]) netPeak[dir] = bps; + return (bps / netPeak[dir]) * 100; + } + + function applySample(s) { + if (!s) return; + setBar("cpu", s.cpu, (Number(s.cpu) || 0).toFixed(1) + "% of " + (s.cores || 1) + " cores"); + setBar("mem", s.memPercent, bytesPair(s.memUsed, s.memTotal)); + setBar("disk", s.diskPercent != null ? s.diskPercent : 0, + s.diskUsed != null ? bytesPair(s.diskUsed, s.diskTotal) : "n/a"); + if (s.netRx != null) setBar("netrx", netPercent("rx", s.netRx), fmtBytesPerSec(s.netRx)); + if (s.netTx != null) setBar("nettx", netPercent("tx", s.netTx), fmtBytesPerSec(s.netTx)); + + var rpsEl = $("metricRps"); + if (rpsEl) rpsEl.textContent = (Number(s.rps) || 0).toFixed(1); + var upEl = $("metricUptime"); + if (upEl && s.uptimeMs != null) upEl.textContent = fmtUptime(s.uptimeMs); + + if (s.services) applyServices(s.services); + pushLive(s); + } + + function bytesPair(used, total) { + return fmtBytes(used) + " / " + fmtBytes(total); + } + function fmtBytes(b) { + b = Number(b) || 0; + var units = ["B", "KB", "MB", "GB", "TB"]; + var i = 0; + while (b >= 1024 && i < units.length - 1) { b /= 1024; i++; } + return (b < 10 ? b.toFixed(1) : Math.round(b)) + " " + units[i]; + } + + // ---- services ---------------------------------------------------------- + function dot(ok) { return ok ? "ok" : "bad"; } + function applyServices(sv) { + var db = $("svcDatabase"); + if (db) { + db.dataset.state = dot(sv.database && sv.database.ok); + var lat = sv.database && sv.database.latencyMs != null ? sv.database.latencyMs + "ms" : "offline"; + var dbv = $("svcDatabaseVal"); if (dbv) dbv.textContent = lat; + } + setSvcText("svcNodes", sv.nodes ? (sv.nodes.online + "/" + sv.nodes.total + " online") : "n/a", + sv.nodes && sv.nodes.total > 0 && sv.nodes.online === sv.nodes.total); + setSvcText("svcContainers", sv.containers ? (sv.containers.running + " running, " + sv.containers.stopped + " stopped") : "n/a", true); + setSvcText("svcSsh", (sv.sshSessions || 0) + " active", true); + setSvcText("svcSockets", (sv.activeSockets || 0) + " connected", true); + var ver = $("svcVersion"); + if (ver && sv.panelVersion) ver.textContent = sv.panelVersion; + } + function setSvcText(id, text, ok) { + var el = $(id); + if (!el) return; + el.textContent = text; + var row = el.closest("[data-svc-row]"); + if (row) row.dataset.state = ok ? "ok" : "warn"; + } + + // ---- live sparkline buffer (current day, client-side) ------------------ + var liveBuffer = []; + function pushLive(s) { + liveBuffer.push({ ts: s.ts, cpu: s.cpu, mem: s.memPercent }); + if (liveBuffer.length > 600) liveBuffer.shift(); + } + + // ---- history graph ----------------------------------------------------- + var graphMode = "today"; // or a YYYY-MM-DD string + function drawGraph(points, label) { + var canvas = $("metricsGraph"); + if (!canvas) return; + var ctx = canvas.getContext("2d"); + var w = canvas.width = canvas.clientWidth * (window.devicePixelRatio || 1); + var h = canvas.height = canvas.clientHeight * (window.devicePixelRatio || 1); + ctx.clearRect(0, 0, w, h); + var lbl = $("graphLabel"); + if (lbl) lbl.textContent = label || ""; + + if (!points || !points.length) { + ctx.fillStyle = "rgba(255,255,255,0.35)"; + ctx.font = (14 * (window.devicePixelRatio || 1)) + "px system-ui"; + ctx.textAlign = "center"; + ctx.fillText("No data recorded for this day yet", w / 2, h / 2); + return; + } + + var pad = 8 * (window.devicePixelRatio || 1); + function line(series, color) { + ctx.beginPath(); + for (var i = 0; i < points.length; i++) { + var x = pad + (i / (points.length - 1 || 1)) * (w - pad * 2); + var v = clampPct(points[i][series]); + var y = h - pad - (v / 100) * (h - pad * 2); + if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y); + } + ctx.strokeStyle = color; + ctx.lineWidth = 2 * (window.devicePixelRatio || 1); + ctx.lineJoin = "round"; + ctx.stroke(); + } + // gridlines + ctx.strokeStyle = "rgba(255,255,255,0.06)"; + ctx.lineWidth = 1; + for (var g = 0; g <= 4; g++) { + var gy = pad + (g / 4) * (h - pad * 2); + ctx.beginPath(); ctx.moveTo(pad, gy); ctx.lineTo(w - pad, gy); ctx.stroke(); + } + line("cpu", "#0EA5E9"); + line("mem", "#8B5CF6"); + } + + function loadDay(dayStr) { + fetch("/api/status/metrics/day?day=" + encodeURIComponent(dayStr), { credentials: "include" }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (data) { + if (!data || !data.ok) { drawGraph([], dayStr); return; } + drawGraph(data.points, formatDayLabel(dayStr)); + }) + .catch(function () { drawGraph([], dayStr); }); + } + + function formatDayLabel(dayStr) { + try { + var d = new Date(dayStr + "T00:00:00Z"); + return d.toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" }); + } catch (_) { return dayStr; } + } + + // ---- calendar (fixed one month) ---------------------------------------- + function buildCalendar(summaryDays) { + var grid = $("calendarGrid"); + if (!grid) return; + grid.innerHTML = ""; + + var now = new Date(); + var year = now.getUTCFullYear(); + var month = now.getUTCMonth(); + var first = new Date(Date.UTC(year, month, 1)); + var daysInMonth = new Date(Date.UTC(year, month + 1, 0)).getUTCDate(); + var startWeekday = first.getUTCDay(); // 0=Sun + + var monthLabel = $("calendarMonth"); + if (monthLabel) { + monthLabel.textContent = first.toLocaleDateString(undefined, { month: "long", year: "numeric", timeZone: "UTC" }); + } + + var summaryByDay = {}; + (summaryDays || []).forEach(function (d) { + var key = new Date(d.ts).toISOString().slice(0, 10); + summaryByDay[key] = d; + }); + + var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; + weekdays.forEach(function (wd) { + var head = document.createElement("div"); + head.className = "cal-weekday"; + head.textContent = wd; + grid.appendChild(head); + }); + + for (var i = 0; i < startWeekday; i++) { + var blank = document.createElement("div"); + blank.className = "cal-cell cal-cell--blank"; + grid.appendChild(blank); + } + + var todayKey = now.toISOString().slice(0, 10); + for (var day = 1; day <= daysInMonth; day++) { + (function (day) { + var dateStr = year + "-" + String(month + 1).padStart(2, "0") + "-" + String(day).padStart(2, "0"); + var cell = document.createElement("button"); + cell.type = "button"; + cell.className = "cal-cell"; + cell.dataset.day = dateStr; + if (dateStr === todayKey) cell.classList.add("cal-cell--today"); + + var num = document.createElement("span"); + num.className = "cal-cell__num"; + num.textContent = day; + cell.appendChild(num); + + cell.addEventListener("click", function () { + document.querySelectorAll(".cal-cell--active").forEach(function (c) { c.classList.remove("cal-cell--active"); }); + cell.classList.add("cal-cell--active"); + graphMode = dateStr; + loadDay(dateStr); + }); + + grid.appendChild(cell); + })(day); + } + } + + function loadSummaryAndCalendar() { + fetch("/api/status/metrics/summary", { credentials: "include" }) + .then(function (r) { return r.ok ? r.json() : null; }) + .then(function (data) { + buildCalendar(data && data.ok ? data.days : []); + // default: today's graph + mark today active + var todayKey = new Date().toISOString().slice(0, 10); + var todayCell = document.querySelector('.cal-cell[data-day="' + todayKey + '"]'); + if (todayCell) todayCell.classList.add("cal-cell--active"); + loadDay(todayKey); + }) + .catch(function () { buildCalendar([]); }); + } + + // ---- socket wiring ----------------------------------------------------- + function connectSocket() { + if (typeof io !== "function") return; + SOCKET = window._monitorSocket || io({ withCredentials: true }); + window._monitorSocket = SOCKET; + + SOCKET.on("connect", subscribe); + SOCKET.on("monitor:snapshot", function (snap) { applySample(snap); }); + SOCKET.on("monitor:sample", function (s) { applySample(s); }); + SOCKET.on("monitor:error", function (e) { + console.warn("[monitor]", e && e.error); + }); + + if (SOCKET.connected) subscribe(); + } + + function subscribe() { + if (watching) return; + watching = true; + SOCKET.emit("monitor:subscribe"); + } + function unsubscribe() { + if (!watching || !SOCKET) return; + watching = false; + SOCKET.emit("monitor:unsubscribe"); + } + + // Pause intensive sampling when the tab is hidden (keeps cost near zero). + document.addEventListener("visibilitychange", function () { + if (document.hidden) unsubscribe(); + else if (SOCKET) { watching = false; subscribe(); } + }); + window.addEventListener("beforeunload", unsubscribe); + + function init() { + connectSocket(); + loadSummaryAndCalendar(); + window.addEventListener("resize", function () { + if (graphMode === "today") loadDay(new Date().toISOString().slice(0, 10)); + else loadDay(graphMode); + }); + } + + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", init); + } else { + init(); + } +})(); diff --git a/public/login.css b/public/login.css index da948a3..d9ca226 100644 --- a/public/login.css +++ b/public/login.css @@ -17,6 +17,20 @@ --menu-top: 100rem; --menu-left: -5rem; --watermark-offset-x: 3.5rem; + --login-card-width: min(450px, calc(100vw - 48px)); + --login-form-width: min(380px, calc(100vw - 48px)); + --login-card-height: 470px; + --login-card-height-2fa: 540px; + --login-form-top: calc(50% + 20px); + --login-form-top-2fa: calc(50% - 4px); + --login-icon-top: calc(50% - 190px); + --login-icon-top-2fa: calc(50% - 218px); + --login-title-top: calc(50% - 104px); + --login-title-top-2fa: calc(50% - 130px); + --login-desc-top: calc(50% - 66px); + --login-desc-top-2fa: calc(50% - 92px); + --login-subline-top: calc(50% - 46px); + --login-subline-top-2fa: calc(50% - 72px); } html, @@ -45,21 +59,23 @@ body { } } -form { +.login-form { position: absolute; + top: var(--login-form-top); + left: 50%; display: flex; flex-direction: column; user-select: none; - gap: 10px; - width: 300px; - margin-top: 300px; + gap: 12px; + width: var(--login-form-width); + margin: 0; + transform: translateX(-50%); z-index: 100; + transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1); } -@media (max-width: 768px) { - form { - margin-top: 270px; - } +body.login-has-2fa .login-form { + top: var(--login-form-top-2fa); } .input-icon { @@ -78,8 +94,30 @@ form { position: relative; display: flex; align-items: center; - width: 380px; - margin-left: -40px; + width: 100%; + margin-left: 0; +} + +.login-two-factor-field { + max-height: 48px; + opacity: 1; + overflow: hidden; + transform: translateY(0); + transition: + max-height 360ms cubic-bezier(0.2, 0.8, 0.2, 1), + opacity 220ms ease, + transform 360ms cubic-bezier(0.2, 0.8, 0.2, 1), + margin 360ms cubic-bezier(0.2, 0.8, 0.2, 1); + will-change: max-height, opacity, transform; +} + +.login-two-factor-field[aria-hidden="true"] { + max-height: 0; + opacity: 0; + margin-top: -6px; + margin-bottom: -6px; + pointer-events: none; + transform: translateY(-8px); } .input-holder:hover .input-icon { @@ -144,21 +182,15 @@ button { .get-started { position: relative; border-radius: 12px; - /* Smoother curve */ height: 48px; - /* Slightly taller for touch target size */ - width: 380px; + width: 100%; user-select: none; - margin-top: 50px; - margin-left: -40px; + margin-top: 4px; + margin-left: 0; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; - /* Apple font */ font-size: 16px; - /* slightly larger */ - letter-spacing: -0.01em; - /* Tighter tracking */ + letter-spacing: 0; font-weight: 600; - /* Bolder */ color: #ffffff; background: linear-gradient(to bottom, #363636, #1a1a1a, #000000); box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5); @@ -168,7 +200,7 @@ button { align-items: center; justify-content: center; gap: 0; - transition: transform 0.6s cubic-bezier(0.25, 1, 0.5, 1), background 0.6s ease, box-shadow 0.6s ease; + transition: transform 0.6s cubic-bezier(0.25, 1, 0.5, 1), background 0.6s ease, box-shadow 0.6s ease, margin-top 360ms cubic-bezier(0.2, 0.8, 0.2, 1); } .get-started__logo { @@ -182,7 +214,7 @@ button { @media (max-width: 768px) { .get-started { - margin-top: 30px; + margin-top: 4px; } } @@ -206,16 +238,25 @@ button { .menu { position: absolute; - width: 390px; - height: 480px; + top: 50%; + left: 50%; + box-sizing: border-box; + width: var(--login-card-width); + height: var(--login-card-height); border-radius: 30px; padding: 30px; - margin-top: 60px; + margin: 0; isolation: isolate; box-shadow: 0px 6px var(--outer-shadow-blur) rgba(0, 0, 0, 0.2); background-color: rgba(var(--tint-color), var(--tint-opacity)); border: 1px solid rgba(255, 255, 255, 0.25); pointer-events: none; + transform: translate(-50%, -50%); + transition: height 360ms cubic-bezier(0.2, 0.8, 0.2, 1); +} + +body.login-has-2fa .menu { + height: var(--login-card-height-2fa); } .menu::before { @@ -242,24 +283,17 @@ button { z-index: 1; } -@media (max-width: 768px) { - .menu { - font-size: 24px; - padding: 20px; - margin-top: 20px; - } -} - .forgot-password { - position: absolute; + position: relative; + align-self: flex-end; cursor: pointer; color: #f5f5f7; /* Matching pure white sub-tone */ user-select: none; - margin-top: 150px; - margin-left: 230px; + margin: -2px 0 0; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 14px; + line-height: 16px; font-weight: 500; white-space: nowrap; opacity: 0.65; @@ -285,62 +319,68 @@ button { } .sign-up { - position: relative; + position: absolute; + top: var(--login-title-top); + left: 50%; color: #f5f5f7 !important; user-select: none; - top: 140px; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 24px; font-weight: 600; - letter-spacing: -0.015em; + letter-spacing: 0; z-index: 1; text-shadow: 0 2px 8px rgba(0, 0, 0, 0.4); + transform: translateX(-50%); + white-space: nowrap; + transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1); } -@media (max-width: 768px) { - .sign-up { - top: 100px; - } +body.login-has-2fa .sign-up { + top: var(--login-title-top-2fa); } .sign-up-desc { - position: relative; + position: absolute; + top: var(--login-desc-top); + left: 50%; color: #a1a1a6; user-select: none; - top: 207px; text-align: center; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 15px; font-weight: 500; - letter-spacing: -0.012em; + letter-spacing: 0; opacity: 1; text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); + transform: translateX(-50%); + white-space: nowrap; + transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1); } -@media (max-width: 768px) { - .sign-up-desc { - top: 170px; - } +body.login-has-2fa .sign-up-desc { + top: var(--login-desc-top-2fa); } .sign-up-sublines { - position: relative; + position: absolute; + top: var(--login-subline-top); + left: 50%; color: #86868b; user-select: none; - top: 245px; text-align: center; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-size: 14px; font-weight: 500; - letter-spacing: -0.012em; + letter-spacing: 0; opacity: 1; text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); + transform: translateX(-50%); + white-space: nowrap; + transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1); } -@media (max-width: 758px) { - .sign-up-sublines { - top: 210px; - } +body.login-has-2fa .sign-up-sublines { + top: var(--login-subline-top-2fa); } @@ -371,27 +411,66 @@ button { .circle-icon { position: absolute; + top: calc(var(--login-icon-top) - var(--login-form-top)); + left: 50%; + display: flex; + align-items: center; + justify-content: center; background-color: white; - padding: 20px; + padding: 0; border-radius: 15px; - height: 12px; - width: 9px; + height: 54px; + width: 54px; box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5); - margin-top: -210px; - margin-left: 120px; + margin: 0; border: 1px solid #c4c4c4; + box-sizing: border-box; + z-index: 101; + transform: translateX(-50%); + transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1); +} + +body.login-has-2fa .circle-icon { + top: calc(var(--login-icon-top-2fa) - var(--login-form-top-2fa)); } .circle-icon__glyph { color: #000; font-size: 25px; - margin-top: -50px; - margin-left: -10px; + margin: 0; } @media (max-width: 768px) { - .circle-icon { - margin-top: -220px; + :root { + --login-card-width: min(420px, calc(100vw - 32px)); + --login-form-width: min(360px, calc(100vw - 56px)); + --login-card-height: 450px; + --login-card-height-2fa: 516px; + --login-form-top: calc(50% + 18px); + --login-form-top-2fa: calc(50% - 4px); + --login-icon-top: calc(50% - 182px); + --login-icon-top-2fa: calc(50% - 208px); + --login-title-top: calc(50% - 98px); + --login-title-top-2fa: calc(50% - 124px); + --login-desc-top: calc(50% - 60px); + --login-desc-top-2fa: calc(50% - 88px); + --login-subline-top: calc(50% - 40px); + --login-subline-top-2fa: calc(50% - 69px); + } + + .login-form { + width: var(--login-form-width); + } + + .menu { + font-size: 24px; + padding: 20px; + } + + .sign-up-desc, + .sign-up-sublines { + width: calc(100vw - 56px); + white-space: normal; } } @@ -567,7 +646,8 @@ button { } .captcha-modal__widget #recaptchaWidget[hidden], -.captcha-modal__widget #cf-turnstile[hidden] { +.captcha-modal__widget #cf-turnstile[hidden], +.captcha-modal__widget #hcaptchaWidget[hidden] { display: none; } diff --git a/public/settings.css b/public/settings.css index 855380e..3f5c586 100644 --- a/public/settings.css +++ b/public/settings.css @@ -523,42 +523,72 @@ .clickable-card:hover { transform: none; box-shadow: 0 18px 40px rgba(16, 24, 40, 0.12); - border: 1px solid var(--hover-border) + border: none } .server-row { + position: relative; display: flex; align-items: center; justify-content: space-between; - padding: 12px; - border-radius: 10px; - background: var(--card-contrast-bg); - border: 1px solid rgba(15, 23, 42, 0.04); - min-height: 64px + gap: 16px; + padding: 16px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.03); + border: none; + min-height: 64px; + transform: scale(1); + transform-origin: center; + transition: transform .2s ease, background .2s ease; + } + + .server-row:hover { + transform: scale(1.02); + background: rgba(255, 255, 255, 0.05); + } + + body.no-animations .server-row, + body.no-animations .server-row:hover { + transform: none; + } + + .server-row-suspended { + background: rgba(239, 68, 68, 0.06); + } + + .server-row-suspended:hover { + background: rgba(239, 68, 68, 0.09); } .server-row .left { display: flex; align-items: center; - gap: 12px + gap: 12px; + min-width: 0; + flex-wrap: wrap } .server-row .iconWrap { - width: 44px; - height: 44px; - border-radius: 8px; + flex-shrink: 0; + width: 42px; + height: 42px; + border-radius: 10px; display: flex; align-items: center; justify-content: center; - background: rgba(255, 255, 255, 0.06) + font-size: 17px; + color: var(--muted); + background: rgba(255, 255, 255, 0.05); } - [data-theme="dark"] .server-row .iconWrap { - background: rgba(255, 255, 255, 0.02) + .server-row-suspended .iconWrap { + color: #f87171; + background: rgba(239, 68, 68, 0.1); } .server-row .name { - font-weight: 700 + font-weight: 600; + font-size: 15px; } .server-name-wrap { @@ -576,8 +606,96 @@ .server-row .actions { display: flex; - gap: 8px; - align-items: center + gap: 6px; + align-items: center; + flex-wrap: nowrap; + justify-content: flex-end; + flex-shrink: 0; + } + + .server-row .actions .btn.ghost { + width: 36px; + height: 36px; + min-height: 36px; + padding: 0; + border: none !important; + border-radius: 9px; + display: inline-flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + background: rgba(255, 255, 255, 0.05); + color: var(--muted); + box-shadow: none; + transition: background .2s ease, color .2s ease; + } + + .server-row .actions .btn.ghost:hover { + background: rgba(255, 255, 255, 0.1); + color: var(--text); + } + + .server-row .actions .suspend-server:hover { + background: rgba(239, 68, 68, 0.12); + color: #f87171; + } + + .server-row .actions .restore-server:hover { + background: rgba(34, 197, 94, 0.12); + color: #4ade80; + } + + .server-row .actions .delete-server:hover { + background: rgba(239, 68, 68, 0.12); + color: #f87171; + } + + /* suspend / restore are icon-only buttons, sized like the rest */ + .server-row .actions .server-suspension-action { + width: 36px; + padding: 0; + gap: 0; + } + + .server-row .inline-badge { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 3px 10px; + border-radius: 999px; + font-size: 12px; + background: rgba(255, 255, 255, 0.06); + color: var(--muted); + } + + .server-row .template-chip { + padding: 3px 10px; + } + + .server-state-chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 10px; + border-radius: 999px; + font-size: 12px; + border: 1px solid rgba(239, 68, 68, 0.26); + background: rgba(239, 68, 68, 0.11); + color: #fca5a5; + white-space: nowrap + } + + .suspend-server { + color: #fca5a5 + } + + .restore-server { + color: #86efac + } + + .suspend-server:disabled { + opacity: .5; + cursor: not-allowed } .templates-grid { @@ -604,7 +722,8 @@ display: grid; grid-template-columns: 50px minmax(0, 1fr) auto; gap: 14px; - align-items: start; + align-items: center; + justify-items: center; padding: 14px 16px; width: 100%; height: 100% @@ -632,7 +751,9 @@ } .template-card__content { - display: grid; + display: flex; + flex-direction: column; + justify-content: center; gap: 7px; min-width: 0 } @@ -686,7 +807,7 @@ .template-card__actions { display: flex; flex-direction: column; - align-items: flex-end; + align-items: center; justify-content: center; gap: 7px } @@ -769,6 +890,517 @@ gap: 10px; } + .template-store-open-btn { + background: rgba(255, 255, 255, 0.065); + border-color: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.92); + box-shadow: none; + } + + .template-store-open-btn:hover { + transform: scale(1.02); + background: rgba(255, 255, 255, 0.09); + border-color: rgba(255, 255, 255, 0.18); + box-shadow: none; + } + + .enterprise-modal.template-store-modal { + width: 85%; + height: 85%; + max-width: 85%; + max-height: 85%; + display: flex; + flex-direction: column; + overflow: hidden; + } + + #templateStoreOverlay.show { + display: flex; + animation: templateStoreOverlayIn 0.24s cubic-bezier(0.32, 0.72, 0, 1) forwards; + } + + #templateStoreOverlay.closing { + display: flex; + animation: templateStoreOverlayOut 0.2s ease forwards; + } + + #templateStoreModal { + animation: templateStoreModalIn 0.28s cubic-bezier(0.32, 0.72, 0, 1) forwards; + transform-origin: center; + } + + #templateStoreOverlay.closing #templateStoreModal { + animation: templateStoreModalOut 0.2s ease forwards; + } + + @keyframes templateStoreOverlayIn { + from { opacity: 0; } + to { opacity: 1; } + } + + @keyframes templateStoreOverlayOut { + from { opacity: 1; } + to { opacity: 0; } + } + + @keyframes templateStoreModalIn { + from { + opacity: 0; + transform: scale(0.985); + filter: blur(5px); + } + to { + opacity: 1; + transform: scale(1); + filter: blur(0); + } + } + + @keyframes templateStoreModalOut { + from { + opacity: 1; + transform: scale(1); + filter: blur(0); + } + to { + opacity: 0; + transform: scale(0.985); + filter: blur(4px); + } + } + + .template-store-header { + display: grid; + grid-template-columns: auto minmax(0, 1fr) auto; + align-items: center; + gap: 22px; + padding: 16px 28px; + border-bottom: 1px solid rgba(255, 255, 255, 0.07); + background: rgba(255, 255, 255, 0.025); + overflow: visible; + } + + .template-store-brand { + display: flex; + align-items: center; + justify-content: flex-start; + min-width: 0; + } + + .template-store-brand img { + width: 72px; + height: 72px; + object-fit: contain; + flex: 0 0 auto; + filter: none; + } + + .template-store-body { + padding: 22px 28px 28px; + flex: 1 1 auto; + min-height: 0; + display: flex; + flex-direction: column; + overflow-y: auto; + scrollbar-width: none; + -ms-overflow-style: none; + } + + .template-store-body::-webkit-scrollbar { + display: none; + } + + .template-store-toolbar { + display: flex; + min-width: 0; + justify-content: space-between; + gap: 22px; + align-items: center; + overflow: visible; + } + + .template-store-tabs { + display: flex; + align-items: center; + gap: clamp(16px, 1.7vw, 30px); + flex: 1 1 auto; + min-width: 0; + overflow: visible; + padding: 8px 14px; + scrollbar-width: none; + -ms-overflow-style: none; + } + + .template-store-tabs::-webkit-scrollbar { + display: none; + } + + .template-store-tab { + position: relative; + isolation: isolate; + min-height: 34px; + padding: 0; + border: 0; + border-radius: 8px; + background: transparent; + color: rgba(255, 255, 255, 0.68); + font: inherit; + font-size: 13px; + font-weight: 500; + white-space: nowrap; + cursor: pointer; + overflow: visible; + transition: color 0.18s ease, transform 0.18s ease; + } + + .template-store-tab::before { + content: ""; + position: absolute; + inset: 3px -12px; + z-index: -1; + border-radius: 8px; + background: rgba(255, 255, 255, 0.075); + border: 1px solid rgba(255, 255, 255, 0.1); + opacity: 0; + transform: scale(0.94); + transition: opacity 0.18s ease, transform 0.18s ease; + } + + .template-store-tab.active { + color: #fff; + font-weight: 550; + } + + .template-store-tab:hover { + color: #fff; + transform: scale(1.02); + } + + .template-store-tab:hover::before { + opacity: 1; + transform: scale(1); + } + + .template-store-search { + position: relative; + display: flex; + align-items: center; + flex: 0 0 320px; + width: 320px; + min-width: 320px; + } + + .template-store-search i { + position: absolute; + left: 14px; + color: rgba(203, 213, 225, 0.58); + font-size: 13px; + pointer-events: none; + } + + .template-store-search input { + width: 100%; + min-height: 42px; + padding: 0 14px 0 40px; + border: 1px solid rgba(148, 163, 184, 0.18); + border-radius: 8px; + outline: none; + background: rgba(8, 12, 18, 0.42); + color: rgba(255, 255, 255, 0.94); + font-size: 13px; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04); + transition: border-color 0.18s ease, box-shadow 0.18s ease, background 0.18s ease; + } + + .template-store-search input:focus { + border-color: rgba(148, 163, 184, 0.18); + background: rgba(8, 12, 18, 0.42); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04); + } + + .template-store-search input::placeholder { + color: rgba(203, 213, 225, 0.48); + } + + .template-store-feedback { + flex: 0 0 18px; + margin-bottom: 12px; + color: rgba(203, 213, 225, 0.7); + font-size: 13px; + } + + .template-store-feedback.is-error { + color: #fca5a5; + } + + .template-store-feedback.is-success { + color: rgba(187, 247, 208, 0.86); + } + + .template-store-grid { + flex: 1 1 auto; + min-height: 0; + height: 100%; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + grid-auto-rows: minmax(248px, auto); + gap: clamp(12px, 1.1vw, 18px); + align-items: stretch; + align-content: start; + } + + .template-store-card { + position: relative; + display: grid; + grid-template-rows: 112px minmax(0, 1fr) auto; + min-height: 248px; + border: 1px solid rgba(97, 106, 132, 0.34); + border-radius: 8px; + background: rgba(20, 22, 36, 0.94); + overflow: hidden; + height: 100%; + box-shadow: 0 16px 32px rgba(0, 0, 0, 0.22); + transition: none; + } + + .template-store-card:hover { + transform: none; + border-color: rgba(97, 106, 132, 0.34); + background: rgba(20, 22, 36, 0.94); + box-shadow: 0 16px 32px rgba(0, 0, 0, 0.22); + } + + .template-store-card-media { + position: relative; + background: rgba(36, 40, 58, 0.86); + background-size: cover; + background-position: center; + } + + .template-store-card-media::after { + content: ""; + position: absolute; + inset: 0; + background: + linear-gradient(180deg, + rgba(20, 22, 36, 0) 0%, + rgba(20, 22, 36, 0.1) 42%, + rgba(20, 22, 36, 0.72) 78%, + rgba(20, 22, 36, 0.98) 100%); + pointer-events: none; + } + + .template-store-card-placeholder { + width: 100%; + height: 100%; + display: flex; + align-items: center; + justify-content: center; + color: rgba(226, 232, 240, 0.78); + font-size: 34px; + background: rgba(255, 255, 255, 0.045); + } + + .template-store-category-chip { + position: absolute; + left: 10px; + bottom: 10px; + z-index: 1; + max-width: calc(100% - 20px); + padding: 5px 8px; + border-radius: 8px; + background: rgba(2, 6, 23, 0.72); + border: 1px solid rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.82); + font-size: 11px; + font-weight: 700; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + backdrop-filter: blur(10px); + } + + .template-store-card-body { + display: flex; + flex-direction: column; + gap: 7px; + min-width: 0; + padding: 12px 14px 8px; + background: rgba(20, 22, 36, 0.98); + } + + .template-store-card-title { + color: rgba(255, 255, 255, 0.96); + font-size: 15px; + font-weight: 760; + line-height: 1.25; + overflow-wrap: anywhere; + } + + .template-store-card-desc { + color: rgba(203, 213, 225, 0.72); + font-size: 12.5px; + line-height: 1.45; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + } + + .template-store-card-meta { + margin-top: auto; + color: rgba(148, 163, 184, 0.82); + font-size: 11.5px; + display: flex; + align-items: center; + gap: 6px; + min-width: 0; + } + + .template-store-card-meta span { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .template-store-card-actions { + padding: 0 14px 14px; + background: rgba(20, 22, 36, 0.98); + } + + .template-store-install { + width: 100%; + min-height: 36px; + justify-content: center; + border-radius: 8px; + background: #4f46e5; + border: 1px solid rgba(199, 210, 254, 0.18); + color: #fff; + box-shadow: none; + transition: transform 0.18s ease, background 0.18s ease, opacity 0.18s ease; + } + + .template-store-install:hover:not(:disabled) { + transform: scale(1.02); + background: #4338ca; + box-shadow: none; + } + + .template-store-install:disabled { + opacity: 0.72; + cursor: not-allowed; + transform: none; + } + + .template-store-install.is-installed { + background: rgba(51, 65, 85, 0.92); + border-color: rgba(148, 163, 184, 0.22); + color: rgba(226, 232, 240, 0.86); + opacity: 1; + } + + .template-store-state { + grid-column: 1 / -1; + min-height: 100%; + height: 100%; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 10px; + border: 1px dashed rgba(148, 163, 184, 0.2); + border-radius: 8px; + background: rgba(255, 255, 255, 0.025); + color: rgba(203, 213, 225, 0.72); + text-align: center; + padding: 26px; + } + + .template-store-state i { + color: rgba(203, 213, 225, 0.7); + font-size: 24px; + } + + .template-store-empty-face { + color: rgba(226, 232, 240, 0.62); + font-size: 34px; + font-weight: 400; + line-height: 1; + } + + .template-store-empty-title { + color: rgba(226, 232, 240, 0.66); + font-size: 14px; + font-weight: 500; + } + + @media (max-width: 820px) { + .template-store-header { + grid-template-columns: auto minmax(0, 1fr) auto; + padding: 18px 18px 14px; + gap: 14px; + } + + .template-store-body { + padding: 14px 16px 18px; + } + + .template-store-toolbar { + flex-wrap: wrap; + gap: 10px; + } + + .template-store-tabs { + flex-basis: 100%; + order: 2; + overflow-x: auto; + overflow-y: visible; + } + + .template-store-search { + flex-basis: 320px; + } + + .template-store-grid { + grid-template-columns: repeat(auto-fill, minmax(210px, 1fr)); + } + } + + @media (max-width: 560px) { + .templates-header-actions { + width: 100%; + align-items: stretch; + flex-wrap: wrap; + } + + .templates-header-actions .nodes-search-wrap { + width: 100%; + } + + .templates-header-actions .nodes-search-wrap input { + width: 100%; + } + + .enterprise-modal.template-store-modal { + width: 94vw; + max-width: 94vw; + } + + .template-store-brand { + gap: 10px; + } + + .template-store-grid { + grid-template-columns: 1fr; + } + + .template-store-card { + min-height: 292px; + grid-template-rows: 126px minmax(0, 1fr) auto; + } + } + .create-inline { display: none; gap: 8px; @@ -792,11 +1424,15 @@ z-index: 10000 } - .modal-overlay.show { - display: flex - } + .modal-overlay.show { + display: flex + } - .modal { + #sessionRevokeModalOverlay.show { + z-index: 10002 + } + + .modal { width: 440px; background: var(--modal-bg); border-radius: 12px; @@ -834,14 +1470,59 @@ border: 1px solid rgba(15, 23, 42, 0.04) } + .account-row-suspended { + border-color: rgba(248, 113, 113, 0.24); + background: linear-gradient(135deg, rgba(248, 113, 113, 0.09), var(--card-contrast-bg)); + } + .account-left { display: flex; align-items: center; - gap: 12px + gap: 12px; + min-width: 0 } .account-email { - font-weight: 700 + font-weight: 700; + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + word-break: break-word + } + + .account-badge-row { + display: inline-flex; + align-items: center; + gap: 5px; + flex-wrap: wrap; + } + + .account-role-badge { + display: inline-flex; + align-items: center; + height: 18px; + padding: 0 7px; + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.05); + color: rgba(255, 255, 255, 0.66); + font-size: 10px; + font-weight: 700; + line-height: 1; + text-transform: uppercase; + } + + .account-role-badge-admin { + border-color: rgba(245, 158, 11, 0.32); + background: rgba(245, 158, 11, 0.14); + color: #fde68a; + } + + .account-role-badge-suspended { + border-color: rgba(248, 113, 113, 0.32); + background: rgba(248, 113, 113, 0.14); + color: #fecaca; } .access-pill { @@ -2162,6 +2843,16 @@ background: rgba(255, 255, 255, 0.05); } + .session-row-remembered { + border-color: rgba(245, 158, 11, 0.14); + background: rgba(245, 158, 11, 0.045); + } + + .session-row-remembered:hover { + border-color: rgba(245, 158, 11, 0.24); + background: rgba(245, 158, 11, 0.07); + } + .session-row-main { min-width: 0; display: flex; @@ -2221,6 +2912,18 @@ color: #4ade80; } + .session-meta-pill.session-meta-pill-active { + background: rgba(59, 130, 246, 0.1); + border-color: rgba(59, 130, 246, 0.18); + color: #93c5fd; + } + + .session-meta-pill.session-meta-pill-offline { + background: rgba(245, 158, 11, 0.12); + border-color: rgba(245, 158, 11, 0.22); + color: #fbbf24; + } + .session-meta-pill.session-meta-pill-ua { white-space: nowrap; overflow: hidden; @@ -2554,9 +3257,9 @@ } .servers-list { - margin-top: 12px; + margin-top: 14px; display: grid; - gap: 8px; + gap: 11px; } .modal-body { @@ -2683,25 +3386,11 @@ .startup-cmd-display-header { display: flex; - align-items: center; - justify-content: space-between; - padding: 10px 14px; - border-bottom: 1px solid rgba(255, 255, 255, 0.06); + align-items: flex-start; + gap: 8px; + padding: 12px 14px; background: rgba(255, 255, 255, 0.03); - } - - .startup-cmd-display-label { - font-size: 12px; - font-weight: 500; - color: rgba(255, 255, 255, 0.45); - display: flex; - align-items: center; - gap: 7px; - } - - .startup-cmd-display-label i { - color: rgba(56, 189, 248, 0.7); - font-size: 14px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); } .startup-cmd-copy-btn { @@ -2713,6 +3402,8 @@ cursor: pointer; font-size: 12px; transition: all 0.2s ease; + flex-shrink: 0; + align-self: flex-start; } .startup-cmd-copy-btn:hover { @@ -2722,14 +3413,16 @@ .startup-cmd-code { margin: 0; - padding: 14px 16px; + padding: 0; font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', 'Cascadia Code', 'Consolas', monospace; font-size: 12.5px; line-height: 1.6; color: rgba(167, 243, 208, 0.9); white-space: pre-wrap; - word-break: break-all; - overflow-x: auto; + word-break: break-word; + overflow-wrap: break-word; + flex: 1; + min-width: 0; } .startup-cmd-code code { @@ -3922,6 +4615,43 @@ font-size: 14px; } + .template-advanced-settings { + border-top: 1px solid rgba(255, 255, 255, 0.06); + padding-top: 14px; + } + + .template-advanced-summary { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + cursor: pointer; + list-style: none; + user-select: none; + } + + .template-advanced-summary::-webkit-details-marker { + display: none; + } + + .template-advanced-summary .node-form-section-title { + margin-bottom: 0; + } + + .template-advanced-chevron { + color: rgba(255, 255, 255, 0.48); + font-size: 12px; + transition: transform 0.18s ease; + } + + .template-advanced-settings[open] .template-advanced-chevron { + transform: rotate(180deg); + } + + .template-advanced-content { + margin-top: 14px; + } + .resources-section { margin-bottom: 24px; padding-bottom: 24px; @@ -4219,6 +4949,16 @@ color: rgba(255, 255, 255, 0.7); } + .node-delete-security-field { + width: min(100%, 340px); + margin: 18px auto 0; + text-align: left; + } + + .node-delete-security-field .node-form-input { + margin-top: 8px; + } + .node-danger-btn { display: inline-flex; align-items: center; @@ -4404,7 +5144,7 @@ } .resource-tooltip-card { - display: none; + display: none !important; position: absolute; z-index: 30; bottom: calc(100% + 8px); @@ -5057,6 +5797,92 @@ padding: 16px; } + .create-user-2fa-option { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + padding: 14px 16px; + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 14px; + background: rgba(255, 255, 255, 0.04); + cursor: pointer; + } + + .create-user-2fa-option-main { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; + } + + .create-user-2fa-option-icon { + width: 36px; + height: 36px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 10px; + background: rgba(99, 102, 241, 0.14); + color: #c7d2fe; + flex: 0 0 auto; + } + + .create-user-2fa-option-copy { + display: flex; + flex-direction: column; + gap: 3px; + min-width: 0; + } + + .create-user-2fa-option-copy strong { + color: #fff; + font-size: 14px; + font-weight: 650; + } + + .create-user-2fa-option-copy small { + color: var(--muted); + font-size: 12px; + line-height: 1.35; + } + + .create-user-2fa-option input { + position: absolute; + opacity: 0; + pointer-events: none; + } + + .create-user-2fa-switch { + position: relative; + width: 44px; + height: 24px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.16); + flex: 0 0 auto; + transition: background 0.18s ease; + } + + .create-user-2fa-switch::after { + content: ""; + position: absolute; + top: 3px; + left: 3px; + width: 18px; + height: 18px; + border-radius: 50%; + background: #fff; + transition: transform 0.18s ease; + } + + .create-user-2fa-option input:checked + .create-user-2fa-switch { + background: rgba(99, 102, 241, 0.78); + } + + .create-user-2fa-option input:checked + .create-user-2fa-switch::after { + transform: translateX(20px); + } + .create-user-password-wrap { position: relative; } @@ -5542,13 +6368,18 @@ gap: 10px; padding: 20px; background: rgba(255, 255, 255, 0.04); - border: 1px solid rgba(255, 255, 255, 0.08); + border: 1px solid rgba(255, 255, 255, 0.06); border-radius: 12px; max-width: 180px; margin: 0 auto; transition: all 0.3s ease; } + .quick-action-preview-card:hover { + background: rgba(124, 92, 255, 0.16); + transform: translateY(-4px); + } + .quick-action-preview-card i { font-size: 1.5rem; color: #a5b4fc; @@ -8499,3 +9330,64 @@ .alert-schedule-grid input[type="datetime-local"] { padding-right: 44px; } + + .enterprise-field-tooltip { + display: inline-flex; + align-items: center; + margin-left: 6px; + cursor: help; + position: relative; + } + + .enterprise-field-tooltip i { + font-size: 12px; + color: rgba(255, 255, 255, 0.4); + transition: color 0.2s ease; + } + + .enterprise-field-tooltip:hover i { + color: rgba(255, 255, 255, 0.7); + } + + .enterprise-field-tooltip-card { + display: none; + position: fixed; + bottom: auto; + left: auto; + transform: none; + background: rgba(30, 30, 40, 0.98); + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 12px; + padding: 12px 16px; + min-width: 220px; + max-width: 280px; + z-index: 100000; + backdrop-filter: blur(20px); + box-shadow: 0 12px 40px rgba(0, 0, 0, 0.5); + pointer-events: none; + white-space: normal; + word-wrap: break-word; + } + + .enterprise-field-tooltip-card::after { + content: ''; + position: absolute; + top: 100%; + left: 50%; + transform: translateX(-50%); + border: 7px solid transparent; + border-top-color: rgba(30, 30, 40, 0.98); + } + + .enterprise-field-tooltip:hover .enterprise-field-tooltip-card { + display: block; + } + + .enterprise-field-tooltip-card p { + margin: 0; + font-size: 13px; + color: rgba(255, 255, 255, 0.9); + line-height: 1.5; + } +5; + } diff --git a/public/style.css b/public/style.css index 9a85e06..3c9c78f 100644 --- a/public/style.css +++ b/public/style.css @@ -69,7 +69,8 @@ body { .top-actions { display: flex; gap: 8px; - align-items: center + align-items: center; + margin-left: auto } .icon-btn { diff --git a/quick-actions.json b/quick-actions.json index 21cda01..0b5e780 100644 --- a/quick-actions.json +++ b/quick-actions.json @@ -21,7 +21,7 @@ { "id": "default-3", "title": "ADPanel Github", - "link": "https://github.com/antonndev/ADPanel-Enterprise", + "link": "https://github.com/antonndev/ADPanel", "icon": "fa-duotone fa-regular fa-panel-ews", "animation": "scale", "newTab": true, @@ -41,12 +41,12 @@ { "id": "qa-1769251431563", "title": "ADPanel Site", - "link": "https://github.com/antonndev/ADPanel-Enterprise", + "link": "https://ad-panel.com", "icon": "fa-solid fa-globe", "animation": "scale", "newTab": true, "scaleValue": 1.01 } ], - "updatedAt": 1773427337191 + "updatedAt": 1780755825878 } \ No newline at end of file diff --git a/reinstall_multidisk_test.go b/reinstall_multidisk_test.go new file mode 100644 index 0000000..50906b2 --- /dev/null +++ b/reinstall_multidisk_test.go @@ -0,0 +1,95 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// TestReinstallPreservesDiskIdOnSecondDisk is a regression test for the bug where +// reinstalling a server that lives on a secondary disk dropped the __diskId from +// its rebuilt meta, causing the server to silently fall back to the primary disk +// on the next cold cache / restart and orphan its real files on the secondary +// disk. The reinstall handler rebuilds meta from scratch, so it must carry the +// disk assignment forward exactly like create persists it. +func TestReinstallPreservesDiskIdOnSecondDisk(t *testing.T) { + a, _ := newTestAgent(t) + mount := t.TempDir() + d := registerTestDisk(t, a, mount, 50) + a.setServerDiskMapping("beta", d.ID) + + serverDir := a.serverDir("beta") + if err := os.MkdirAll(serverDir, 0o750); err != nil { + t.Fatalf("mkdir srv: %v", err) + } + + // Pre-reinstall meta carries the secondary-disk assignment, as create writes it. + oldMeta := map[string]any{ + "type": "custom", + "template": "custom", + "__diskId": d.ID, + "createdAt": float64(123), + } + if err := a.saveMeta(serverDir, oldMeta); err != nil { + t.Fatalf("saveMeta old: %v", err) + } + + // Simulate the reinstall meta rebuild: a fresh meta map that must inherit + // __diskId from the old meta (mirrors handleReinstallServer). + rebuilt := map[string]any{ + "type": "custom", + "template": "custom", + "hostPort": 8080, + } + if diskID, ok := oldMeta["__diskId"].(string); ok && strings.TrimSpace(diskID) != "" { + rebuilt["__diskId"] = strings.TrimSpace(diskID) + } + if err := a.saveMeta(serverDir, rebuilt); err != nil { + t.Fatalf("saveMeta rebuilt: %v", err) + } + + // After a cold cache, the server must still resolve to the secondary disk. + a.invalidateServerDiskCache("beta") + if got := a.diskForServer("beta"); got.ID != d.ID { + t.Fatalf("server mis-routed after reinstall: got disk %q want %q", got.ID, d.ID) + } + if got := a.serverDir("beta"); got != serverDir { + t.Fatalf("serverDir after reinstall: got %q want %q", got, serverDir) + } + + // Confirm the persisted meta on disk still records the disk assignment. + persisted := a.loadMeta(serverDir) + if id, _ := persisted["__diskId"].(string); id != d.ID { + t.Fatalf("__diskId not persisted after reinstall: got %q want %q", id, d.ID) + } +} + +// TestReinstallPrimaryServerOmitsDiskId verifies the common single-disk case is +// unchanged: a primary-disk server with no __diskId stays on the primary disk +// after the reinstall meta rebuild, and we do not inject a spurious assignment. +func TestReinstallPrimaryServerOmitsDiskId(t *testing.T) { + a, vol := newTestAgent(t) + + serverDir := filepath.Join(vol, "alpha") + if err := os.MkdirAll(serverDir, 0o750); err != nil { + t.Fatalf("mkdir srv: %v", err) + } + oldMeta := map[string]any{"type": "custom", "template": "custom"} + + rebuilt := map[string]any{"type": "custom", "template": "custom", "hostPort": 8080} + if diskID, ok := oldMeta["__diskId"].(string); ok && strings.TrimSpace(diskID) != "" { + rebuilt["__diskId"] = strings.TrimSpace(diskID) + } + if _, ok := rebuilt["__diskId"]; ok { + t.Fatalf("primary-disk reinstall must not inject __diskId") + } + if err := a.saveMeta(serverDir, rebuilt); err != nil { + t.Fatalf("saveMeta: %v", err) + } + + a.invalidateServerDiskCache("alpha") + if got := a.diskForServer("alpha"); !(got.Primary || got.ID == primaryDiskID) { + t.Fatalf("primary-disk server mis-routed after reinstall to %q", got.ID) + } +} diff --git a/sshterm b/sshterm new file mode 100755 index 0000000..0576f64 Binary files /dev/null and b/sshterm differ diff --git a/templates.json b/templates.json index adeafc2..b333b5c 100644 --- a/templates.json +++ b/templates.json @@ -11,16 +11,30 @@ "ports": [ 25565 ], + "portProtocols": { + "25565": [ + "tcp" + ] + }, "volumes": [ "{BOT_DIR}:/data" ], "workdir": "/data", "env": {}, "command": "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui", + "adpanelStartup": "", + "startupDisplay": "", + "install": null, "restart": "unless-stopped", + "runAsRoot": false, "console": { - "type": "stdin" - } + "type": "stdin", + "targetProcesses": [ + "java", + "bedrock_server" + ] + }, + "javaVersion": "21" } }, { @@ -35,6 +49,7 @@ "ports": [ 3000 ], + "portProtocols": {}, "volumes": [ "{BOT_DIR}:/app" ], @@ -43,16 +58,20 @@ "NODE_ENV": "production" }, "command": "node /app/index.js", + "adpanelStartup": "", + "startupDisplay": "", + "install": null, "restart": "unless-stopped", + "runAsRoot": false, "console": { "type": "stdin" } } }, { - "id": "csgo", + "id": "cs2", "name": "Counter-Strike 2", - "description": "Counter-Strike 2 dedicated server installed with an ADPanel SteamCMD installer", + "description": "Counter-Strike 2 dedicated server template using the ADPanel SteamCMD installer. It installs app 730, persists the server in /home/container and starts the server with safe structured startup variables.", "defaultPort": 27015, "templateImage": "https://cdn.cloudflare.steamstatic.com/steam/apps/730/header.jpg", "docker": { @@ -63,6 +82,18 @@ 27020, 27005 ], + "portProtocols": { + "27005": [ + "udp" + ], + "27015": [ + "tcp", + "udp" + ], + "27020": [ + "udp" + ] + }, "volumes": [ "{BOT_DIR}:/home/container" ], @@ -86,26 +117,43 @@ "STEAM_AUTH": "", "EXTRA_FLAGS": "" }, - "adpanelStartup": "LD_LIBRARY_PATH=\"$HOME/game/bin/linuxsteamrt64:$LD_LIBRARY_PATH\" ./game/bin/linuxsteamrt64/cs2 -dedicated $( [ \"$VAC_ENABLED\" == \"1\" ] || printf %s ' -insecure' ) -ip 0.0.0.0 -port {{SERVER_PORT}} -tv_port {{TV_PORT}} -maxplayers {{MAX_PLAYERS}} $( [ \"$RCON_ENABLED\" == \"0\" ] || printf %s ' -usercon' ) +game_mode {{GAME_MODE}} +game_type {{GAME_TYPE}} +map {{SRCDS_MAP}} +hostname \"{{SERVER_NAME}}\" +sv_password \"{{SERVER_PASSWORD}}\" +rcon_password \"{{RCON_PASSWORD}}\" +sv_setsteamaccount {{STEAM_GSLT}}", + "command": "", + "adpanelStartup": "cd game && ./cs2.sh -dedicated $( [ \"$VAC_ENABLED\" = \"1\" ] || printf %s ' -insecure' ) -ip 0.0.0.0 -port {{SERVER_PORT}} -tv_port {{TV_PORT}} -maxplayers {{MAX_PLAYERS}} $( [ \"$RCON_ENABLED\" = \"0\" ] || printf %s ' -usercon' ) +game_mode {{GAME_MODE}} +game_type {{GAME_TYPE}} +map {{SRCDS_MAP}} +hostname \"{{SERVER_NAME}}\" +sv_password \"{{SERVER_PASSWORD}}\" +rcon_password \"{{RCON_PASSWORD}}\" $( [ -z \"{{STEAM_GSLT}}\" ] || printf %s ' +sv_setsteamaccount {{STEAM_GSLT}}' )", + "startupDisplay": "", "install": { "image": "ghcr.io/pterodactyl/installers:debian", - "entrypoint": "bash", + "script": "#!/bin/bash\nset -Eeuo pipefail\napp_id=\"${SRCDS_APPID:-730}\"\nsteam_user=\"${STEAM_USER:-anonymous}\"\nsteam_pass=\"${STEAM_PASS:-}\"\nsteam_auth=\"${STEAM_AUTH:-}\"\nmkdir -p /mnt/server/steamcmd /mnt/server/steamapps\ninstall_steamcmd() {\n rm -f /tmp/steamcmd.tar.gz\n curl --retry 5 --retry-delay 2 --connect-timeout 20 -fsSL -o /tmp/steamcmd.tar.gz https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz\n tar -xzf /tmp/steamcmd.tar.gz -C /mnt/server/steamcmd\n}\nif [ ! -x /mnt/server/steamcmd/steamcmd.sh ] || [ ! -x /mnt/server/steamcmd/linux32/steamcmd ]; then\n rm -rf /mnt/server/steamcmd\n mkdir -p /mnt/server/steamcmd\n install_steamcmd\nfi\ncd /mnt/server/steamcmd\nlogin_args=(+login \"$steam_user\")\nif [ \"$steam_user\" != \"anonymous\" ]; then\n login_args=(+login \"$steam_user\" \"$steam_pass\")\n [ -z \"$steam_auth\" ] || login_args+=(\"$steam_auth\")\nfi\nfor attempt in 1 2 3 4; do\n if HOME=/mnt/server ./steamcmd.sh +force_install_dir /mnt/server \"${login_args[@]}\" +app_update \"$app_id\" ${EXTRA_FLAGS:-} validate +quit; then\n break\n fi\n status=$?\n if [ \"$attempt\" -eq 4 ]; then\n exit \"$status\"\n fi\n rm -rf /mnt/server/steamcmd/package /mnt/server/steamcmd/linux32/steamcmd\n install_steamcmd\n sleep $((attempt * 15))\ndone\nmkdir -p /mnt/server/.steam/sdk32 /mnt/server/.steam/sdk64\ncp -f /mnt/server/steamcmd/linux32/steamclient.so /mnt/server/.steam/sdk32/steamclient.so || true\ncp -f /mnt/server/steamcmd/linux64/steamclient.so /mnt/server/.steam/sdk64/steamclient.so || true\nif [ ! -x /mnt/server/game/bin/linuxsteamrt64/cs2 ]; then\n echo \"CS2 executable missing after SteamCMD install.\"\n exit 30\nfi\nchmod -R a+rwX /mnt/server\necho \"Installation completed.\"", "mountPath": "/mnt/server", "runtimePath": "/home/container", - "timeoutSeconds": 7200, - "minimumStorageMb": 40000, - "script": "#!/bin/bash\nset -e\nif [[ -z \"${STEAM_USER}\" || -z \"${STEAM_PASS}\" ]]; then\n STEAM_USER=anonymous\n STEAM_PASS=\"\"\n STEAM_AUTH=\"\"\nfi\ncd /tmp\nmkdir -p /mnt/server/steamcmd /mnt/server/steamapps\ncurl -sSL -o steamcmd.tar.gz https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz\ntar -xzvf steamcmd.tar.gz -C /mnt/server/steamcmd\ncd /mnt/server/steamcmd\nchown -R root:root /mnt\nexport HOME=/mnt/server\n./steamcmd.sh +force_install_dir /mnt/server +login ${STEAM_USER} ${STEAM_PASS} ${STEAM_AUTH} +app_update ${SRCDS_APPID} ${EXTRA_FLAGS} validate +quit\nmkdir -p /mnt/server/.steam/sdk32 /mnt/server/.steam/sdk64\ncp -v linux32/steamclient.so /mnt/server/.steam/sdk32/steamclient.so || true\ncp -v linux64/steamclient.so /mnt/server/.steam/sdk64/steamclient.so || true\necho \"Installation completed.\"" + "timeoutSeconds": 3600, + "minimumStorageMb": 70000 }, "restart": "unless-stopped", + "runAsRoot": false, "console": { - "type": "stdin" + "type": "stdin", + "targetProcesses": [ + "cs2", + "srcds_linux" + ] } + }, + "documentation": [ + "https://hub.docker.com/r/joedwards32/cs2", + "https://developer.valvesoftware.com/wiki/Counter-Strike_2/Dedicated_Servers", + "https://steamcommunity.com/dev/managegameservers" + ], + "requirements": { + "minimumRamMb": 2048, + "recommendedRamMb": 4096, + "minimumStorageMb": 70000, + "requiresSteamGslt": true } }, { "id": "fivem", "name": "FiveM", - "description": "Run your FiveM servers with this template", + "description": "FiveM GTA V roleplay server template using ich777/fivemserver. The container downloads artifacts automatically, persists server files, and exposes the game, auxiliary and web console ports.", "defaultPort": 30120, "templateImage": "https://logos-world.net/wp-content/uploads/2021/03/FiveM-Symbol.png", "docker": { @@ -116,12 +164,25 @@ 30110, 8080 ], + "portProtocols": { + "8080": [ + "tcp" + ], + "30110": [ + "tcp", + "udp" + ], + "30120": [ + "tcp", + "udp" + ] + }, "volumes": [ "{BOT_DIR}:/serverdata/serverfiles" ], "workdir": "/serverdata/serverfiles", "env": { - "DATA_DIR": "/serverdata", + "DATA_DIR": "/serverdata/serverfiles", "SERVER_DIR": "/serverdata/serverfiles", "GAME_CONFIG": "server.cfg", "SERVER_KEY": "change-me", @@ -130,12 +191,41 @@ "ENABLE_WEBCONSOLE": "true", "UID": "99", "GID": "100", - "START_VARS": "" + "START_VARS": "", + "HOME": "/serverdata/serverfiles", + "DATA_PERM": "777" + }, + "command": "", + "adpanelStartup": "", + "startupDisplay": "", + "install": { + "image": "ghcr.io/pterodactyl/installers:debian", + "script": "#!/bin/sh\nset -eu\ncfg=/mnt/server/server.cfg\nserver_port=\"${SERVER_PORT:-${PORT:-30120}}\"\nmkdir -p /mnt/server/resources\nif [ ! -s \"$cfg\" ]; then\n cat > \"$cfg\" </dev/null || true\nchmod -R a+rwX /mnt/server", + "mountPath": "/mnt/server", + "runtimePath": "/serverdata/serverfiles", + "timeoutSeconds": 600, + "minimumStorageMb": 8192 }, "restart": "unless-stopped", + "runAsRoot": true, "console": { - "type": "stdin" + "type": "stdin", + "targetProcesses": [ + "FXServer", + "fxserver" + ] } + }, + "documentation": [ + "https://hub.docker.com/r/ich777/fivemserver", + "https://runtime.fivem.net/artifacts/fivem/build_proot_linux/master/", + "https://keymaster.fivem.net/" + ], + "requirements": { + "minimumRamMb": 2048, + "recommendedRamMb": 4096, + "minimumStorageMb": 8192, + "requiresServerKey": true } }, { @@ -150,6 +240,7 @@ "ports": [ 8000 ], + "portProtocols": {}, "volumes": [ "{BOT_DIR}:/app" ], @@ -158,10 +249,86 @@ "PYTHONUNBUFFERED": "1" }, "command": "python /app/main.py", + "adpanelStartup": "", + "startupDisplay": "", + "install": null, "restart": "unless-stopped", + "runAsRoot": false, "console": { "type": "stdin" } } + }, + { + "id": "ragemp", + "name": "RAGE:MP", + "description": "RAGE Multiplayer server template for GTA V multiplayer projects. It uses bambutz/ragemp, persists /ragemp, and exposes the UDP game port plus the TCP HTTP port.", + "defaultPort": 22005, + "templateImage": "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/ragemp-logo.avif", + "docker": { + "image": "bambutz/ragemp", + "tag": "latest", + "ports": [ + 22005, + 22006 + ], + "portProtocols": { + "22005": [ + "udp" + ], + "22006": [ + "tcp" + ] + }, + "volumes": [ + "{BOT_DIR}:/ragemp" + ], + "workdir": "/ragemp", + "env": { + "RAGEMP_ANNOUNCE": "false", + "RAGEMP_BIND": "0.0.0.0", + "RAGEMP_GAMEMODE": "freeroam", + "RAGEMP_MAXPLAYERS": "500", + "RAGEMP_NAME": "ADPanel RAGE:MP Server", + "RAGEMP_PORT": "22005", + "RAGEMP_LANGUAGE": "en", + "RAGEMP_VOICE_CHAT": "false", + "RAGEMP_CSHARP": "false", + "DOTNET_SYSTEM_GLOBALIZATION_INVARIANT": "1", + "COMPlus_GlobalizationInvariant": "1", + "PATH": "/ragemp/dotnet/runtime:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", + "LD_LIBRARY_PATH": "/ragemp/dotnet/runtime:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu", + "TZ": "Etc/UTC" + }, + "command": "", + "adpanelStartup": "", + "startupDisplay": "", + "install": { + "image": "ghcr.io/pterodactyl/installers:debian", + "script": "#!/bin/sh\nset -eu\nmkdir -p /mnt/server/resources /mnt/server/packages /mnt/server/plugins /mnt/server/maps /mnt/server/dotnet/resources /mnt/server/dotnet/runtime\nif [ ! -f /mnt/server/dotnet/runtime/dotnet ]; then\ncat > /mnt/server/dotnet/runtime/dotnet <<'EOF'\n#!/bin/sh\nexit 0\nEOF\nfi\nif [ ! -f /mnt/server/dotnet/runtime/libssl.so.1.1 ] || [ ! -f /mnt/server/dotnet/runtime/libcrypto.so.1.1 ]; then\n curl -fsSL -o /tmp/libssl1.1.deb http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.1_1.1.1w-0+deb11u5_amd64.deb\n rm -rf /tmp/libssl1.1\n mkdir -p /tmp/libssl1.1\n dpkg-deb -x /tmp/libssl1.1.deb /tmp/libssl1.1\n cp /tmp/libssl1.1/usr/lib/x86_64-linux-gnu/libssl.so.1.1 /mnt/server/dotnet/runtime/libssl.so.1.1\n cp /tmp/libssl1.1/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1 /mnt/server/dotnet/runtime/libcrypto.so.1.1\nfi\ncat > /tmp/adpanel-ragemp-acl.xml <<'EOF'\n\n\n \n \n \n \n \n \n\nEOF\nfor target in /mnt/server/acl.xml /mnt/server/dotnet/acl.xml /mnt/server/dotnet/runtime/acl.xml /mnt/server/resources/acl.xml; do\n if [ ! -f \"$target\" ]; then\n cp /tmp/adpanel-ragemp-acl.xml \"$target\"\n fi\ndone\nchmod +x /mnt/server/dotnet/runtime/dotnet\nchmod -R 777 /mnt/server", + "mountPath": "/mnt/server", + "runtimePath": "/ragemp", + "timeoutSeconds": 1800, + "minimumStorageMb": 2048 + }, + "restart": "unless-stopped", + "runAsRoot": false, + "console": { + "type": "stdin", + "targetProcesses": [ + "ragemp-server", + "ragemp" + ] + } + }, + "documentation": [ + "https://hub.docker.com/r/bambutz/ragemp", + "https://github.com/BamButz/docker-ragemp" + ], + "requirements": { + "minimumRamMb": 1024, + "recommendedRamMb": 2048, + "minimumStorageMb": 2048 + } } -] +] \ No newline at end of file diff --git a/transfer_import_multidisk_test.go b/transfer_import_multidisk_test.go new file mode 100644 index 0000000..1c55124 --- /dev/null +++ b/transfer_import_multidisk_test.go @@ -0,0 +1,233 @@ +package main + +import ( + "archive/tar" + "bytes" + "encoding/json" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "testing" +) + +// buildTransferTar produces a tarball in the exact shape handleExportServer +// emits: server files at the root, backups under ".adpanel_backups/", and the +// server meta under ".adpanel_meta/.json". The meta deliberately carries a +// SOURCE-node __diskId to simulate a server that lived on the source's secondary +// disk, which must be stripped by the destination on import. +func buildTransferTar(t *testing.T, name string, sourceMeta map[string]any) []byte { + t.Helper() + var buf bytes.Buffer + tw := tar.NewWriter(&buf) + + writeFile := func(tarName string, data []byte) { + hdr := &tar.Header{Name: tarName, Mode: 0o644, Size: int64(len(data)), Typeflag: tar.TypeReg} + if err := tw.WriteHeader(hdr); err != nil { + t.Fatalf("write header %s: %v", tarName, err) + } + if _, err := tw.Write(data); err != nil { + t.Fatalf("write body %s: %v", tarName, err) + } + } + + // Server payload file. + writeFile("server.properties", []byte("level-name=world\n")) + // A backup artifact. + writeFile(".adpanel_backups/backup-1.tar.gz", []byte("fake-backup-bytes")) + // Source meta with a stale disk identity. + metaBytes, err := json.Marshal(sourceMeta) + if err != nil { + t.Fatalf("marshal source meta: %v", err) + } + writeFile(".adpanel_meta/"+sanitizeName(name)+".json", metaBytes) + + if err := tw.Close(); err != nil { + t.Fatalf("close tar: %v", err) + } + return buf.Bytes() +} + +func doImportTar(t *testing.T, a *Agent, name, diskID string, body []byte) (*httptest.ResponseRecorder, map[string]any) { + t.Helper() + url := "/v1/servers/" + name + "/import-tar" + if diskID != "" { + url += "?diskId=" + diskID + } + req := httptest.NewRequest(http.MethodPost, url, bytes.NewReader(body)) + rr := httptest.NewRecorder() + a.handleImportTar(rr, req, name) + + var parsed map[string]any + _ = json.Unmarshal(rr.Body.Bytes(), &parsed) + return rr, parsed +} + +// TestImportTarToDestinationPrimaryStripsSourceDiskId covers the user's first +// scenario: a server is transferred to another node and lands on that node's +// PRIMARY disk. The source's __diskId must be discarded so the server resolves to +// the destination's default volumes/backups roots, not a phantom disk. +func TestImportTarToDestinationPrimaryStripsSourceDiskId(t *testing.T) { + a, vol := newTestAgent(t) + name := "alpha" + + // Source meta pretends the server lived on a secondary disk that does NOT + // exist on this destination node. + sourceMeta := map[string]any{ + "type": "custom", + "template": "custom", + "__diskId": "disk-source-secondary", + "resources": map[string]any{ + "ramMb": float64(2048), + }, + } + tarBytes := buildTransferTar(t, name, sourceMeta) + + rr, resp := doImportTar(t, a, name, "", tarBytes) + if rr.Code != 200 { + t.Fatalf("import-tar status: got %d body=%s", rr.Code, rr.Body.String()) + } + if ok, _ := resp["ok"].(bool); !ok { + t.Fatalf("import-tar not ok: %v", resp) + } + + // Files must live on the primary disk. + wantServerDir := filepath.Join(vol, name) + if _, err := os.Stat(filepath.Join(wantServerDir, "server.properties")); err != nil { + t.Fatalf("server file not on primary disk: %v", err) + } + if _, err := os.Stat(filepath.Join(a.backupsDir(), name, "backup-1.tar.gz")); err != nil { + t.Fatalf("backup file not on primary backups root: %v", err) + } + + // Meta must have the stale __diskId stripped and NOT re-added for primary. + a.invalidateServerDiskCache(name) + persisted := a.loadMeta(wantServerDir) + if _, present := persisted["__diskId"]; present { + t.Fatalf("__diskId must be absent for a primary-disk import, got %v", persisted["__diskId"]) + } + // Non-routing meta must be preserved. + if persisted["template"] != "custom" { + t.Fatalf("template meta not preserved: %v", persisted["template"]) + } + + // Routing must resolve to the primary disk across a cold cache. + if got := a.diskForServer(name); !(got.Primary || got.ID == primaryDiskID) { + t.Fatalf("server mis-routed after import: got disk %q", got.ID) + } + if got := a.serverDir(name); got != wantServerDir { + t.Fatalf("serverDir after import: got %q want %q", got, wantServerDir) + } +} + +// TestImportTarToDestinationSecondaryStampsCorrectDiskId covers the user's second +// scenario: a server (regardless of which disk it lived on at the source) is +// placed on a SECONDARY disk of the destination node. The destination must stamp +// ITS OWN disk id so the panel/node know the server is at +// "/adpanel/volumes/" with backups at +// "/adpanel/backups/". +func TestImportTarToDestinationSecondaryStampsCorrectDiskId(t *testing.T) { + a, _ := newTestAgent(t) + mount := t.TempDir() + dest := registerTestDisk(t, a, mount, 50) + name := "beta" + + sourceMeta := map[string]any{ + "type": "custom", + "template": "custom", + // A different, source-only disk id that must be replaced. + "__diskId": "disk-source-foreign", + } + tarBytes := buildTransferTar(t, name, sourceMeta) + + rr, resp := doImportTar(t, a, name, dest.ID, tarBytes) + if rr.Code != 200 { + t.Fatalf("import-tar status: got %d body=%s", rr.Code, rr.Body.String()) + } + if resp["diskId"] != dest.ID { + t.Fatalf("import-tar reported diskId %v want %q", resp["diskId"], dest.ID) + } + + // Files must live under the destination secondary disk's layout. + wantServerDir := filepath.Join(a.diskLayoutVolumes(mount), name) + if _, err := os.Stat(filepath.Join(wantServerDir, "server.properties")); err != nil { + t.Fatalf("server file not on secondary disk volumes root: %v", err) + } + wantBackupDir := filepath.Join(a.diskLayoutBackups(mount), name) + if _, err := os.Stat(filepath.Join(wantBackupDir, "backup-1.tar.gz")); err != nil { + t.Fatalf("backup file not on secondary disk backups root: %v", err) + } + + // Meta must record the DESTINATION disk id, never the source's. + persisted := a.loadMeta(wantServerDir) + if id, _ := persisted["__diskId"].(string); id != dest.ID { + t.Fatalf("__diskId after import: got %q want %q (must not keep source id)", id, dest.ID) + } + + // Routing must resolve to the destination secondary disk across a cold cache. + a.invalidateServerDiskCache(name) + if got := a.diskForServer(name); got.ID != dest.ID { + t.Fatalf("server mis-routed after import: got disk %q want %q", got.ID, dest.ID) + } + if got := a.serverDir(name); got != wantServerDir { + t.Fatalf("serverDir after import: got %q want %q", got, wantServerDir) + } + if got := a.serverBackupsDir(name); got != wantBackupDir { + t.Fatalf("serverBackupsDir after import: got %q want %q", got, wantBackupDir) + } +} + +// TestImportTarRejectsUnknownDiskId ensures a transfer that targets a disk this +// node does not own fails fast instead of silently extracting to the wrong place. +func TestImportTarRejectsUnknownDiskId(t *testing.T) { + a, _ := newTestAgent(t) + name := "gamma" + tarBytes := buildTransferTar(t, name, map[string]any{"type": "custom"}) + + rr, resp := doImportTar(t, a, name, "disk-does-not-exist", tarBytes) + if rr.Code != 400 { + t.Fatalf("expected 400 for unknown diskId, got %d body=%s", rr.Code, rr.Body.String()) + } + if ok, _ := resp["ok"].(bool); ok { + t.Fatalf("expected ok=false for unknown diskId, got %v", resp) + } +} + +// TestImportTarReimportClearsStaleSecondaryRouting guards a re-transfer: a server +// previously routed to a secondary disk that is then re-imported onto the primary +// disk must not retain the old secondary __diskId. +func TestImportTarReimportClearsStaleSecondaryRouting(t *testing.T) { + a, vol := newTestAgent(t) + mount := t.TempDir() + dest := registerTestDisk(t, a, mount, 50) + name := "delta" + + // First import onto the secondary disk. + first := buildTransferTar(t, name, map[string]any{"type": "custom", "__diskId": "disk-source"}) + if rr, _ := doImportTar(t, a, name, dest.ID, first); rr.Code != 200 { + t.Fatalf("first import failed: %d %s", rr.Code, rr.Body.String()) + } + if got := a.diskForServer(name); got.ID != dest.ID { + t.Fatalf("after first import expected secondary disk, got %q", got.ID) + } + + // Re-import onto the primary disk; routing/meta must follow the new target. + second := buildTransferTar(t, name, map[string]any{"type": "custom", "__diskId": dest.ID}) + if rr, _ := doImportTar(t, a, name, "", second); rr.Code != 200 { + t.Fatalf("second import failed: %d %s", rr.Code, rr.Body.String()) + } + + wantServerDir := filepath.Join(vol, name) + a.invalidateServerDiskCache(name) + if got := a.serverDir(name); got != wantServerDir { + t.Fatalf("serverDir after re-import to primary: got %q want %q", got, wantServerDir) + } + persisted := a.loadMeta(wantServerDir) + if _, present := persisted["__diskId"]; present { + t.Fatalf("__diskId must be cleared on re-import to primary, got %v", persisted["__diskId"]) + } + // The secondary-disk copy must no longer be the routing target. + if got := a.diskForServer(name); !(got.Primary || got.ID == primaryDiskID) { + t.Fatalf("re-import did not re-route to primary, got %q", got.ID) + } +} diff --git a/utils/dashboard-assistant-tools.js b/utils/dashboard-assistant-tools.js index f2bc446..5b6e2c1 100644 --- a/utils/dashboard-assistant-tools.js +++ b/utils/dashboard-assistant-tools.js @@ -1654,9 +1654,6 @@ function createDashboardAssistantToolRunner(deps) { } let sanitizedDocker = sanitizeDockerTemplatePayload(template.docker); - if (sanitizedDocker && Array.isArray(sanitizedDocker.ports) && sanitizedDocker.ports.length > 1) { - sanitizedDocker.ports = [sanitizedDocker.ports[0]]; - } const payload = { name, @@ -1717,6 +1714,7 @@ function createDashboardAssistantToolRunner(deps) { volumes: sanitizedDocker.volumes, env: sanitizedDocker.env, ports: sanitizedDocker.ports, + portProtocols: sanitizedDocker.portProtocols, }; } diff --git a/utils/panel-metrics.js b/utils/panel-metrics.js new file mode 100644 index 0000000..13f8eae --- /dev/null +++ b/utils/panel-metrics.js @@ -0,0 +1,501 @@ +"use strict"; + +/** + * Panel metrics collector for the admin-only /status monitoring page. + * + * Design goals (best-practice, ultra-low overhead): + * - Collect host + panel-process resource usage (CPU, RAM, storage) cheaply + * using only Node core modules (os, fs) plus a single `pm2 jlist` poll for + * aggregate Node/PM2 network counters. No heavy native deps. + * - Live data lives in RAM. We only run the intensive 1s sampling loop while at + * least one admin is actually watching the page (driven by socket room size). + * When nobody watches, the loop stops -> zero ongoing cost. + * - Persistence is RRD-like: one row per minute in `panel_metrics`. A monthly + * cleanup keeps the table at a fixed, small size (~31 days). Writes happen + * once per minute (averaged), never per second. + * - All reads are wrapped so a transient failure never throws into the loop. + * + * This module is intentionally framework-agnostic: index.js wires it to the + * existing socket.io server, admin auth, and MySQL pool. + */ + +const os = require("os"); +const fsp = require("fs/promises"); +const { execFile } = require("child_process"); + +// --------------------------------------------------------------------------- +// Tunables (overridable via env, sane defaults for cheap VPS). +// --------------------------------------------------------------------------- +const LIVE_SAMPLE_MS = clampInt(process.env.PANEL_METRICS_LIVE_MS, 1000, 250, 10000); +const PERSIST_INTERVAL_MS = clampInt(process.env.PANEL_METRICS_PERSIST_MS, 60_000, 10_000, 600_000); +const RETENTION_DAYS = clampInt(process.env.PANEL_METRICS_RETENTION_DAYS, 31, 7, 366); +const PM2_POLL_MS = clampInt(process.env.PANEL_METRICS_PM2_MS, 5000, 2000, 60_000); +const CLEANUP_INTERVAL_MS = 6 * 60 * 60 * 1000; // run retention sweep 4x/day + +function clampInt(value, def, min, max) { + const n = parseInt(value, 10); + if (!Number.isFinite(n)) return def; + return Math.min(Math.max(n, min), max); +} + +function nowMs() { + return Date.now(); +} + +// --------------------------------------------------------------------------- +// CPU sampling: delta of os.cpus() times between two reads -> busy percentage. +// Cheap: a single os.cpus() call (reads /proc/stat once on Linux). +// --------------------------------------------------------------------------- +function cpuTotals() { + const cpus = os.cpus() || []; + let idle = 0; + let total = 0; + for (const c of cpus) { + const t = c.times; + idle += t.idle; + total += t.user + t.nice + t.sys + t.idle + t.irq; + } + return { idle, total, cores: cpus.length || 1 }; +} + +// --------------------------------------------------------------------------- +// Storage: usage of the filesystem holding the panel working directory. +// Uses statfs when available (Node >= 18.15), else falls back to null. +// --------------------------------------------------------------------------- +async function readStorage() { + try { + if (typeof fsp.statfs === "function") { + const s = await fsp.statfs(process.cwd()); + const total = s.blocks * s.bsize; + const free = s.bfree * s.bsize; + const used = total - free; + if (total > 0) { + return { usedBytes: used, totalBytes: total, percent: round1((used / total) * 100) }; + } + } + } catch (_) { /* ignore */ } + return { usedBytes: null, totalBytes: null, percent: null }; +} + +function round1(n) { + return Math.round(n * 10) / 10; +} + +// --------------------------------------------------------------------------- +// PM2 network counters. `pm2 jlist` exposes per-process monit + env; PM2 does +// not natively expose net bytes, so we read aggregate NIC counters from +// /proc/net/dev (sum of all non-loopback interfaces) and derive a per-second +// rate from deltas. This reflects the whole Node/PM2 host traffic, which is the +// closest reliable "panel network" signal without per-socket accounting. +// --------------------------------------------------------------------------- +async function readNetCounters() { + try { + const raw = await fsp.readFile("/proc/net/dev", "utf8"); + let rx = 0; + let tx = 0; + const lines = raw.split("\n"); + for (const line of lines) { + const idx = line.indexOf(":"); + if (idx === -1) continue; + const iface = line.slice(0, idx).trim(); + if (!iface || iface === "lo") continue; + const parts = line.slice(idx + 1).trim().split(/\s+/); + if (parts.length < 9) continue; + rx += Number(parts[0]) || 0; // bytes received + tx += Number(parts[8]) || 0; // bytes transmitted + } + return { rxBytes: rx, txBytes: tx }; + } catch (_) { + return { rxBytes: null, txBytes: null }; + } +} + +function pm2List() { + return new Promise((resolve) => { + try { + execFile("pm2", ["jlist"], { timeout: 4000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => { + if (err || !stdout) return resolve(null); + try { + resolve(JSON.parse(stdout)); + } catch (_) { + resolve(null); + } + }); + } catch (_) { + resolve(null); + } + }); +} + +// --------------------------------------------------------------------------- +// Collector +// --------------------------------------------------------------------------- +class PanelMetricsCollector { + constructor(options = {}) { + this.db = options.db || null; // { query } + this.io = options.io || null; // socket.io server + this.room = options.room || "monitor"; + this.startTime = options.startTime || nowMs(); + this.panelVersion = options.panelVersion || null; + this.getServiceStatus = typeof options.getServiceStatus === "function" + ? options.getServiceStatus + : async () => ({}); + + // Live state + this._prevCpu = cpuTotals(); + this._prevNet = null; + this._prevNetAt = 0; + this._reqCounter = 0; // incremented by middleware + this._prevReqCount = 0; + this._prevReqAt = nowMs(); + this._pm2Cache = { at: 0, data: null }; + this._svcCache = { at: 0, data: null }; + this._svcTtlMs = clampInt(process.env.PANEL_METRICS_SVC_MS, 5000, 2000, 60_000); + + // Minute-accumulator for persistence (average over the window) + this._acc = this._freshAcc(); + + // Timers + this._liveTimer = null; + this._persistTimer = null; + this._cleanupTimer = null; + + this._lastSample = null; + } + + _freshAcc() { + return { + count: 0, + cpu: 0, + memUsed: 0, + memTotal: 0, + diskUsed: 0, + diskTotal: 0, + netRx: 0, + netTx: 0, + rps: 0, + }; + } + + /** + * The request counter (`_reqCounter`) is incremented directly by a tiny + * Express middleware in index.js (one integer add per request, no allocation). + * The collector only reads/diffs it; it never touches the hot request path + * beyond that single increment. + */ + + start() { + // Persistence + cleanup always run (cheap, once per minute / few hours). + if (!this._persistTimer) { + this._persistTimer = setInterval(() => this._persist().catch(() => {}), PERSIST_INTERVAL_MS); + this._persistTimer.unref?.(); + } + if (!this._cleanupTimer) { + // Run once shortly after boot, then on interval. + setTimeout(() => this._cleanup().catch(() => {}), 30_000).unref?.(); + this._cleanupTimer = setInterval(() => this._cleanup().catch(() => {}), CLEANUP_INTERVAL_MS); + this._cleanupTimer.unref?.(); + } + // Drive the live loop from room occupancy. + this._refreshLiveLoop(); + } + + stop() { + for (const t of [this._liveTimer, this._persistTimer, this._cleanupTimer]) { + if (t) clearInterval(t); + } + this._liveTimer = this._persistTimer = this._cleanupTimer = null; + } + + /** Called by index.js whenever a client joins/leaves the monitor room. */ + onRoomChange() { + this._refreshLiveLoop(); + } + + _watcherCount() { + try { + const room = this.io?.sockets?.adapter?.rooms?.get(this.room); + return room ? room.size : 0; + } catch (_) { + return 0; + } + } + + _refreshLiveLoop() { + const watching = this._watcherCount() > 0; + if (watching && !this._liveTimer) { + // Prime baselines so the first emitted sample is sane. + this._prevCpu = cpuTotals(); + this._liveTimer = setInterval(() => this._tick().catch(() => {}), LIVE_SAMPLE_MS); + this._liveTimer.unref?.(); + // Emit one immediately. + this._tick().catch(() => {}); + } else if (!watching && this._liveTimer) { + clearInterval(this._liveTimer); + this._liveTimer = null; + } + } + + async _readPm2() { + const now = nowMs(); + if (this._pm2Cache.data && (now - this._pm2Cache.at) < PM2_POLL_MS) { + return this._pm2Cache.data; + } + const list = await pm2List(); + let memBytes = 0; + let cpuPercent = 0; + let found = false; + if (Array.isArray(list)) { + for (const proc of list) { + const monit = proc?.monit || {}; + if (typeof monit.memory === "number") memBytes += monit.memory; + if (typeof monit.cpu === "number") cpuPercent += monit.cpu; + found = true; + } + } + const data = found ? { memBytes, cpuPercent: round1(cpuPercent) } : null; + this._pm2Cache = { at: now, data }; + return data; + } + + /** Build one live sample (cheap). */ + async _collect() { + const now = nowMs(); + + // CPU (host) via delta + const cur = cpuTotals(); + let cpuPercent = 0; + const idleDiff = cur.idle - this._prevCpu.idle; + const totalDiff = cur.total - this._prevCpu.total; + if (totalDiff > 0) { + cpuPercent = round1((1 - idleDiff / totalDiff) * 100); + if (cpuPercent < 0) cpuPercent = 0; + if (cpuPercent > 100) cpuPercent = 100; + } + this._prevCpu = cur; + + // Memory (host) + const memTotal = os.totalmem(); + const memFree = os.freemem(); + const memUsed = memTotal - memFree; + + // Storage + const storage = await readStorage(); + + // Network rate (bytes/sec) from /proc/net/dev deltas + const net = await readNetCounters(); + let rxRate = null; + let txRate = null; + if (net.rxBytes != null && this._prevNet && this._prevNetAt) { + const dt = (now - this._prevNetAt) / 1000; + if (dt > 0) { + rxRate = Math.max(0, Math.round((net.rxBytes - this._prevNet.rxBytes) / dt)); + txRate = Math.max(0, Math.round((net.txBytes - this._prevNet.txBytes) / dt)); + } + } + if (net.rxBytes != null) { + this._prevNet = net; + this._prevNetAt = now; + } + + // RPS from request counter delta + const dtReq = (now - this._prevReqAt) / 1000; + let rps = 0; + if (dtReq > 0) { + rps = round1((this._reqCounter - this._prevReqCount) / dtReq); + if (rps < 0) rps = 0; + } + this._prevReqCount = this._reqCounter; + this._prevReqAt = now; + + // PM2 process aggregate (cached) + const pm2 = await this._readPm2(); + + const sample = { + ts: now, + cpu: cpuPercent, + cores: cur.cores, + memUsed, + memTotal, + memPercent: memTotal > 0 ? round1((memUsed / memTotal) * 100) : 0, + diskUsed: storage.usedBytes, + diskTotal: storage.totalBytes, + diskPercent: storage.percent, + netRx: rxRate, + netTx: txRate, + rps, + pm2MemBytes: pm2 ? pm2.memBytes : null, + pm2Cpu: pm2 ? pm2.cpuPercent : null, + uptimeMs: now - this.startTime, + }; + + // Feed the minute accumulator (averages). + const a = this._acc; + a.count++; + a.cpu += sample.cpu; + a.memUsed += sample.memUsed; + a.memTotal += sample.memTotal; + if (sample.diskUsed != null) a.diskUsed += sample.diskUsed; + if (sample.diskTotal != null) a.diskTotal += sample.diskTotal; + if (sample.netRx != null) a.netRx += sample.netRx; + if (sample.netTx != null) a.netTx += sample.netTx; + a.rps += sample.rps; + + this._lastSample = sample; + return sample; + } + + async _services() { + const now = nowMs(); + if (this._svcCache.data && (now - this._svcCache.at) < this._svcTtlMs) { + return this._svcCache.data; + } + let data = {}; + try { + data = await this.getServiceStatus(); + } catch (_) { + data = {}; + } + this._svcCache = { at: now, data }; + return data; + } + + async _tick() { + const sample = await this._collect(); + if (!this.io) return; + const services = await this._services(); + this.io.to(this.room).emit("monitor:sample", { ...sample, services }); + } + + /** Persist one averaged row per minute. */ + async _persist() { + if (!this.db || typeof this.db.query !== "function") return; + const a = this._acc; + this._acc = this._freshAcc(); + + let row; + if (a.count > 0) { + row = { + cpu: round1(a.cpu / a.count), + memPercent: a.memTotal > 0 ? round1((a.memUsed / a.memTotal) * 100) : 0, + diskPercent: a.diskTotal > 0 ? round1((a.diskUsed / a.diskTotal) * 100) : 0, + netRx: Math.round(a.netRx / a.count), + netTx: Math.round(a.netTx / a.count), + rps: round1(a.rps / a.count), + }; + } else { + // No live watchers this window: take one cheap point-in-time read so the + // history graph stays continuous without running the 1s loop. + const s = await this._collect(); + // Reset accumulator again (the collect above pushed into it). + this._acc = this._freshAcc(); + row = { + cpu: s.cpu, + memPercent: s.memPercent, + diskPercent: s.diskPercent ?? 0, + netRx: s.netRx ?? 0, + netTx: s.netTx ?? 0, + rps: s.rps, + }; + } + + try { + const d = new Date(); + // Bucket to the minute (UTC) for a stable RRD-style key. + const bucket = Math.floor(d.getTime() / 60000) * 60000; + await this.db.query( + `INSERT INTO panel_metrics + (bucket_ts, cpu_percent, mem_percent, disk_percent, net_rx_bps, net_tx_bps, rps) + VALUES (?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + cpu_percent = VALUES(cpu_percent), + mem_percent = VALUES(mem_percent), + disk_percent = VALUES(disk_percent), + net_rx_bps = VALUES(net_rx_bps), + net_tx_bps = VALUES(net_tx_bps), + rps = VALUES(rps)`, + [bucket, row.cpu, row.memPercent, row.diskPercent, row.netRx, row.netTx, row.rps] + ); + } catch (err) { + // Never let persistence crash the loop. + if (!String(err && err.message).includes("panel_metrics")) { + // table missing or transient; stay silent in prod, log once otherwise. + } + } + } + + /** Retention sweep: drop anything older than RETENTION_DAYS. */ + async _cleanup() { + if (!this.db || typeof this.db.query !== "function") return; + try { + const cutoff = nowMs() - RETENTION_DAYS * 24 * 60 * 60 * 1000; + await this.db.query("DELETE FROM panel_metrics WHERE bucket_ts < ?", [cutoff]); + } catch (_) { /* ignore */ } + } + + /** Admin REST: fetch history rows for a given UTC day (YYYY-MM-DD). */ + async getHistoryForDay(dayStr) { + if (!this.db || typeof this.db.query !== "function") return []; + const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dayStr || "")); + if (!m) return []; + const start = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 0, 0, 0); + const end = start + 24 * 60 * 60 * 1000; + const rows = await this.db.query( + `SELECT bucket_ts, cpu_percent, mem_percent, disk_percent, net_rx_bps, net_tx_bps, rps + FROM panel_metrics + WHERE bucket_ts >= ? AND bucket_ts < ? + ORDER BY bucket_ts ASC`, + [start, end] + ); + return (rows || []).map((r) => ({ + ts: Number(r.bucket_ts), + cpu: Number(r.cpu_percent), + mem: Number(r.mem_percent), + disk: Number(r.disk_percent), + netRx: Number(r.net_rx_bps), + netTx: Number(r.net_tx_bps), + rps: Number(r.rps), + })); + } + + /** Admin REST: daily averages across the retained window (for the calendar). */ + async getDailySummary() { + if (!this.db || typeof this.db.query !== "function") return []; + const cutoff = nowMs() - RETENTION_DAYS * 24 * 60 * 60 * 1000; + const rows = await this.db.query( + `SELECT + FLOOR(bucket_ts / 86400000) AS day_idx, + AVG(cpu_percent) AS cpu, + AVG(mem_percent) AS mem, + AVG(disk_percent) AS disk, + AVG(net_rx_bps) AS net_rx, + AVG(net_tx_bps) AS net_tx, + AVG(rps) AS rps, + COUNT(*) AS samples + FROM panel_metrics + WHERE bucket_ts >= ? + GROUP BY day_idx + ORDER BY day_idx ASC`, + [cutoff] + ); + return (rows || []).map((r) => ({ + ts: Number(r.day_idx) * 86400000, + cpu: round1(Number(r.cpu)), + mem: round1(Number(r.mem)), + disk: round1(Number(r.disk)), + netRx: Math.round(Number(r.net_rx)), + netTx: Math.round(Number(r.net_tx)), + rps: round1(Number(r.rps)), + samples: Number(r.samples), + })); + } + + /** Current snapshot for the initial REST hydrate when a watcher opens. */ + async getSnapshot() { + const sample = this._lastSample || (await this._collect()); + const services = await this._services(); + return { ...sample, services, panelVersion: this.panelVersion, startTime: this.startTime }; + } +} + +module.exports = { PanelMetricsCollector }; diff --git a/utils/server-delete.js b/utils/server-delete.js index 85f2814..362e797 100644 --- a/utils/server-delete.js +++ b/utils/server-delete.js @@ -2,6 +2,152 @@ const { getTechnicalServerName } = require("./server-name"); +function isRemoteMissingResponse(response) { + const status = Number(response?.status || 0); + if (status === 404 || status === 410) return true; + const raw = String(response?.json?.error || response?.json?.detail || response?.json?.message || "").toLowerCase(); + return raw.includes("not found") || raw.includes("not exist") || raw.includes("no such server") || raw.includes("no such container"); +} + +async function remoteServerExists(deps, baseUrl, headers, technicalName, timeoutMs = 8000) { + const response = await deps.httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}`, + "GET", + headers, + null, + timeoutMs + ); + if (response.status === 200 && response.json && (response.json.ok === true || response.json.name || response.json.status)) { + return true; + } + if (isRemoteMissingResponse(response)) return false; + return null; +} + +function deleteStatusShowsActiveGone(response) { + const body = response?.json || {}; + return response?.status === 200 && + body.deleteStatus === true && + (body.deleted === true || ( + body.containerExists === false && + body.serverDirExists === false && + body.metaExists === false && + body.backupsDirExists === false + )); +} + +async function waitForRemoteDeleteConfirmation(deps, baseUrl, headers, technicalName, timeoutMs = 3_000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const timeout = Math.min(1200, Math.max(500, deadline - Date.now())); + const status = await deps.httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/delete-status`, + "GET", + headers, + null, + timeout + ).catch(() => null); + if (deleteStatusShowsActiveGone(status)) return true; + + const exists = await remoteServerExists(deps, baseUrl, headers, technicalName, timeout).catch(() => null); + if (exists === false) return true; + await new Promise((resolve) => setTimeout(resolve, 250)); + } + return false; +} + +async function requestRemoteDeleteAndConfirm(deps, { name, technicalName, baseUrl, headers, timeoutMs = 3_000 }) { + try { + await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 3_000); + } catch { + } + + const response = await deps.httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}?async=true&force=true&brutal=true`, + "DELETE", + headers, + null, + 6_000 + ); + if (isRemoteMissingResponse(response)) return { accepted: true, confirmed: true }; + if (!((response.status === 200 || response.status === 202) && response.json && response.json.ok) && response.status !== 0) { + const message = response.json && (response.json.error || response.json.detail || response.json.message) + ? (response.json.error || response.json.detail || response.json.message) + : `remote delete failed (${response.status})`; + console.warn(`[delete] Remote delete request for ${name} did not complete cleanly: ${message}`); + return { accepted: false, confirmed: false }; + } + const confirmed = await waitForRemoteDeleteConfirmation(deps, baseUrl, headers, technicalName, timeoutMs); + return { accepted: true, confirmed }; +} + +function withTimeout(promise, ms, label = "timeout") { + let timer; + return Promise.race([ + Promise.resolve(promise), + new Promise((_, reject) => { + timer = setTimeout(() => reject(new Error(label)), ms); + }), + ]).finally(() => clearTimeout(timer)); +} + +function queueRemoteDelete(deps, { name, technicalName, baseUrl, headers }) { + setImmediate(async () => { + try { + try { + await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 3_000); + console.log(`[delete] Force-stopped server ${name}`); + } catch (error) { + console.log(`[delete] Could not force-stop server ${name} (may already be stopped): ${error.message}`); + } + + const response = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}?async=true&force=true&brutal=true`, "DELETE", headers, null, 8_000); + if ((response.status === 200 || response.status === 202) && response.json && response.json.ok) { + console.log(`[delete] Remote delete queued for ${name} on node.`); + return; + } + if (isRemoteMissingResponse(response)) { + console.log(`[delete] Remote server ${name} is already gone.`); + return; + } + if (response.status === 0) { + const exists = await remoteServerExists(deps, baseUrl, headers, technicalName, 8_000); + if (exists === false) { + console.log(`[delete] Remote delete for ${name} timed out, but follow-up check confirms it is gone.`); + return; + } + } + const message = response.json && (response.json.error || response.json.detail) + ? (response.json.error || response.json.detail) + : `remote delete failed (${response.status})`; + console.warn(`[delete] Background remote delete for ${name} did not complete cleanly: ${message}`); + } catch (error) { + console.warn(`[delete] Background remote delete failed for ${name}: ${error?.message || error}`); + } + }); +} + +function deleteNameCandidates(entry, requestedName, technicalName) { + const values = [ + technicalName, + entry?.bot, + entry?.legacyId, + entry?.legacy_id, + entry?.name, + entry?.id, + requestedName, + ]; + const out = []; + const seen = new Set(); + for (const value of values) { + const clean = String(value || "").trim(); + if (!clean || seen.has(clean)) continue; + seen.add(clean); + out.push(clean); + } + return out; +} + async function deleteServerByName(deps, rawName) { if (!deps || typeof deps !== "object") { throw new Error("Server delete dependencies are required."); @@ -45,49 +191,74 @@ async function deleteServerByName(deps, rawName) { const headers = deps.nodeAuthHeadersFor(node, true); - try { - await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 30_000); - console.log(`[delete] Force-stopped server ${name}`); - } catch (error) { - console.log(`[delete] Could not force-stop server ${name} (may already be stopped): ${error.message}`); + if (typeof deps.markServerDeletingStatus === "function") { + await withTimeout(deps.markServerDeletingStatus(name), 5000, "mark-delete-status-timeout").catch((error) => { + console.warn(`[delete] Could not mark ${name} as deleting: ${error?.message || error}`); + }); } - try { - const backupsRes = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/backups`, "GET", headers, null, 10_000); - if (backupsRes.status === 200 && backupsRes.json?.backups) { - for (const backup of backupsRes.json.backups) { - if (!backup?.id) continue; - await deps.httpRequestJson( - `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/backups/${encodeURIComponent(backup.id)}`, - "DELETE", - headers, - null, - 30_000 - ); - console.log(`[delete] Deleted backup ${backup.id} for server ${name}`); - } + let deleteAccepted = false; + let confirmedDeleted = false; + let attemptedName = technicalName; + for (const candidate of deleteNameCandidates(entry, name, technicalName)) { + attemptedName = candidate; + const outcome = await requestRemoteDeleteAndConfirm(deps, { + name, + technicalName: candidate, + baseUrl, + headers, + timeoutMs: 3_000, + }).catch((error) => { + console.warn(`[delete] Could not confirm remote delete for ${name} using ${candidate}: ${error?.message || error}`); + return { accepted: false, confirmed: false }; + }); + deleteAccepted = !!outcome.accepted; + confirmedDeleted = !!outcome.confirmed; + if (confirmedDeleted) break; + if (deleteAccepted) break; + } + + if (confirmedDeleted) { + await withTimeout(deps.deleteServerSchedules(name), 5000, "delete-schedules-timeout").catch((error) => { + console.warn(`[delete] Could not clean schedules for ${name}: ${error?.message || error}`); + }); + try { + await withTimeout(deps.removeAccessForServerName(name), 5000, "delete-access-timeout"); + } catch (error) { + console.warn(`[delete] Could not remove access rows for ${name}: ${error?.message || error}`); } - } catch (error) { - console.log(`[delete] Could not delete backups for ${name}: ${error.message}`); + await withTimeout(deps.removeServerIndexEntry(name), 8000, "delete-index-timeout"); + return { + ok: true, + remote: true, + deleted: true, + queued: false, + }; } - await deps.deleteServerSchedules(name); - - const response = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}`, "DELETE", headers, null, 60_000); - if (response.status !== 200 || !(response.json && response.json.ok)) { - const message = response.json && (response.json.error || response.json.detail) - ? (response.json.error || response.json.detail) - : `remote delete failed (${response.status})`; - return { ok: false, statusCode: 502, error: message }; + if (typeof deps.enqueueServerDeleteJob === "function") { + await deps.enqueueServerDeleteJob({ name, technicalName: attemptedName, node }); + if (typeof deps.kickServerDeleteWorker === "function") deps.kickServerDeleteWorker(); + } else { + queueRemoteDelete(deps, { name, technicalName: attemptedName, baseUrl, headers }); } - try { - await deps.removeAccessForServerName(name); - } catch { + withTimeout(deps.deleteServerSchedules(name), 5000, "delete-schedules-timeout").catch((error) => { + console.warn(`[delete] Could not clean schedules for ${name}: ${error?.message || error}`); + }); + if (typeof deps.removeAccessForServerName === "function") { + withTimeout(deps.removeAccessForServerName(name), 5000, "delete-access-timeout").catch((error) => { + console.warn(`[delete] Could not remove access rows for ${name}: ${error?.message || error}`); + }); } - await deps.removeServerIndexEntry(name); - return { ok: true, remote: true }; + return { + ok: true, + remote: true, + deleting: true, + queued: true, + accepted: deleteAccepted, + }; } module.exports = { diff --git a/utils/server-startup-command.js b/utils/server-startup-command.js index 6d6d1d8..4285d7b 100644 --- a/utils/server-startup-command.js +++ b/utils/server-startup-command.js @@ -406,7 +406,7 @@ function buildDefaultStartupCommand({ name, templateId, docker, hostPort, resour const serverName = cleanString(name) || "{SERVER_NAME}"; const externalPort = toPositiveNumber(hostPort); const containerPort = getContainerPort(normalizedTemplateId, docker, hostPort); - const parts = ["docker run -d -t", "--name", serverName, "--restart", cleanString(docker?.restart) || "unless-stopped"]; + const parts = ["docker run -d -i -t", "--name", serverName, "--restart", cleanString(docker?.restart) || "unless-stopped"]; parts.push(...buildResourceArgs(resources)); diff --git a/utils/server-template-payload.js b/utils/server-template-payload.js index e78e65a..da039e4 100644 --- a/utils/server-template-payload.js +++ b/utils/server-template-payload.js @@ -1,5 +1,7 @@ "use strict"; +const POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]); + function cleanString(value) { return String(value ?? "").trim(); } @@ -17,6 +19,41 @@ function toFiniteNumber(value) { return Number.isFinite(numeric) ? numeric : null; } +function normalizePortProtocol(value) { + const protocol = cleanString(value).toLowerCase(); + return protocol === "tcp" || protocol === "udp" || protocol === "sctp" ? protocol : ""; +} + +function sanitizePortProtocolPayload(portProtocols, ports = []) { + if (!portProtocols || typeof portProtocols !== "object" || Array.isArray(portProtocols)) return null; + + const allowedPorts = new Set( + (Array.isArray(ports) ? ports : []) + .map((entry) => toFiniteNumber(entry)) + .filter((entry) => Number.isInteger(entry) && entry > 0) + .map((entry) => String(entry)) + ); + const out = {}; + for (const [rawPort, rawProtocols] of Object.entries(portProtocols)) { + const port = toFiniteNumber(rawPort); + if (!Number.isInteger(port) || port < 1 || port > 65535) continue; + const portKey = String(port); + if (allowedPorts.size && !allowedPorts.has(portKey)) continue; + + const source = Array.isArray(rawProtocols) ? rawProtocols : [rawProtocols]; + const protocols = []; + const seen = new Set(); + for (const entry of source) { + const protocol = normalizePortProtocol(entry); + if (!protocol || seen.has(protocol)) continue; + seen.add(protocol); + protocols.push(protocol); + } + if (protocols.length) out[portKey] = protocols; + } + return Object.keys(out).length ? out : null; +} + function cleanAbsoluteContainerPath(value, fallback = "") { let raw = cleanString(value).replace(/\0/g, "").replace(/\\/g, "/"); if (!raw) return fallback; @@ -31,6 +68,7 @@ function sanitizeEnvPayload(env) { const out = {}; for (const [key, value] of Object.entries(env)) { const envKey = cleanString(key); + if (POLLUTION_KEYS.has(envKey)) continue; if (!envKey) continue; out[envKey] = String(value ?? ""); } @@ -44,7 +82,6 @@ function sanitizeDockerInstallPayload(install) { if (!script) return null; const image = cleanString(install.image || install.container) || "ghcr.io/pterodactyl/installers:debian"; - const entrypoint = cleanString(install.entrypoint) || "bash"; const mountPath = cleanAbsoluteContainerPath( install.mountPath || install.containerPath || install.container_path || install.serverPath, "/mnt/server" @@ -54,24 +91,26 @@ function sanitizeDockerInstallPayload(install) { "/home/container" ); - const timeoutRaw = toFiniteNumber(install.timeoutSeconds || install.timeout_seconds || install.timeout); - const timeoutSeconds = timeoutRaw && timeoutRaw > 0 - ? Math.max(60, Math.min(Math.trunc(timeoutRaw), 7200)) - : 1800; const minimumStorageRaw = toFiniteNumber(install.minimumStorageMb || install.minimum_storage_mb); const minimumStorageMb = minimumStorageRaw && minimumStorageRaw > 0 ? Math.max(1, Math.min(Math.trunc(minimumStorageRaw), 1024 * 1024)) : 0; + const timeoutRaw = toFiniteNumber(install.timeoutSeconds || install.timeout_seconds); + const timeoutSeconds = timeoutRaw && timeoutRaw > 0 + ? Math.max(60, Math.min(Math.trunc(timeoutRaw), 7200)) + : 1800; const payload = { image, script, - entrypoint, mountPath, runtimePath, timeoutSeconds, }; if (minimumStorageMb > 0) payload.minimumStorageMb = minimumStorageMb; + if (install.allowEmpty === true || install.allowEmptyResult === true) { + payload.allowEmpty = true; + } const env = sanitizeEnvPayload(install.env); if (env) payload.env = env; @@ -104,6 +143,10 @@ function sanitizeDockerTemplatePayload(docker) { const restartPolicy = cleanString(docker.restartPolicy); if (restartPolicy) payload.restartPolicy = restartPolicy; + if (docker.runAsRoot === true || docker.run_as_root === true) { + payload.runAsRoot = true; + } + const ports = Array.isArray(docker.ports) ? docker.ports .map((entry) => { @@ -114,6 +157,12 @@ function sanitizeDockerTemplatePayload(docker) { : []; if (ports.length) payload.ports = ports; + const portProtocols = sanitizePortProtocolPayload( + docker.portProtocols || docker.port_protocols || docker.protocols, + ports + ); + if (portProtocols) payload.portProtocols = portProtocols; + const volumes = Array.isArray(docker.volumes) ? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean) : []; @@ -132,6 +181,17 @@ function sanitizeDockerTemplatePayload(docker) { ); if (adpanelStartup) payload.adpanelStartup = adpanelStartup; + const startupDisplay = cleanScript( + docker.startupDisplay || + docker.startup_display || + docker.startupPreview || + docker.startup_preview || + docker.imageDefaultStartup || + docker.image_default_startup, + 32768 + ); + if (startupDisplay) payload.startupDisplay = startupDisplay; + const install = sanitizeDockerInstallPayload(docker.install || docker.installation); if (install) payload.install = install; @@ -146,4 +206,5 @@ module.exports = { sanitizeDockerTemplatePayload, sanitizeDockerInstallPayload, sanitizeEnvPayload, + sanitizePortProtocolPayload, }; diff --git a/views/bot.ejs b/views/bot.ejs index 12d4ee2..84d2471 100644 --- a/views/bot.ejs +++ b/views/bot.ejs @@ -9,54 +9,57 @@ <% const assetVersion = typeof themeVersion !== 'undefined' ? themeVersion : '1'; %> + + - + + src="https://cdn.jsdelivr.net/npm/ansi_up@5.1.0/ansi_up.min.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/ace.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/theme-one_dark.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-javascript.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-json.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-yaml.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-python.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-sh.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-ini.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-html.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-css.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-java.js" defer> + src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-text.js" defer> - + + + src="https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs/loader.min.js" defer> + + +
    + diff --git a/views/forgot-password.ejs b/views/forgot-password.ejs index 7c7614e..4f78cf5 100644 --- a/views/forgot-password.ejs +++ b/views/forgot-password.ejs @@ -66,9 +66,8 @@

    [Dashboard] Due to security reasons you can only reset your password directly from the terminal using the command - bash initialize.sh from the ADPanel directory or switching to an admin account and resetting it for the specific user from Accounts settings category. + bash initialize.sh from the ADPanel directory or asking an admin to reset it for the specific user from Accounts settings category.

    -

    This panel version doesn't support change password feature directly from normal user UI.

    diff --git a/views/index.ejs b/views/index.ejs index b0e3d00..3f52b4f 100644 --- a/views/index.ejs +++ b/views/index.ejs @@ -8,6 +8,7 @@ <%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> + + + - + + +
    @@ -1974,6 +1622,166 @@
    © 2026-<%= new Date().getFullYear() %> ADPanel Dashboard
    + + + + diff --git a/views/login.ejs b/views/login.ejs index c9d711d..b26bb8a 100644 --- a/views/login.ejs +++ b/views/login.ejs @@ -1,13 +1,17 @@ <% const loginBackgroundType=(branding && branding.loginBackgroundType) ? branding.loginBackgroundType : 'video' ; const loginBackgroundUrl='/auth-assets/background' ; const protectedLoginWatermarkUrl='/auth-assets/watermark' ; const loginBackgroundMimeType=(branding && branding.loginBackgroundMimeType) ? branding.loginBackgroundMimeType - : 'video/webm' ; %> + : 'video/webm' ; const loginRequiresTwoFactor=typeof requiresTwoFactor !== 'undefined' && !!requiresTwoFactor; const + loginEmailValue=typeof loginEmail !== 'undefined' ? String(loginEmail || '') : ''; const + loginExternalCaptchaAvailable=typeof externalCaptchaAvailable !== 'undefined' ? !!externalCaptchaAvailable : !!useExternalCaptcha; const + loginCaptchaChallengeActive=!!useExternalCaptcha || !!showLocalCaptcha; %> Login - <%= (branding && branding.appName) ? branding.appName : 'Panel' %> + @@ -75,7 +79,7 @@ - +
    - <% if (useExternalCaptcha) { %> - <% if (["cloudflare","turnstile","cf"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %> - - <% } else { %> - + + <% if (loginExternalCaptchaAvailable) { %> + <% if (["cloudflare","turnstile","cf"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %> + + <% } else if (["hcaptcha","h"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %> + + <% } else { %> + <% } %> <% } %> @@ -444,19 +633,23 @@ }) .then(function (resp) { return resp.json(); }) .then(function (data) { - if (data.ok && data.done) { - setLocalStatus("Verified!", "success"); - if (typeof window.__adCaptchaResolved === "function") window.__adCaptchaResolved(); - return; - } - if (data.ok && !data.done && data.question) { - selected.clear(); - rebuildGrid(data.question); - setLocalStatus("", ""); - submitBtn.disabled = false; - return; - } - setLocalStatus(data.error === "expired" ? "Expired. Reloading..." : "Incorrect selection. Reloading...", "error"); + if (data.ok && data.done) { + setLocalStatus("Verified!", "success"); + if (typeof window.__adCaptchaResolved === "function") window.__adCaptchaResolved(data); + return; + } + if (data.ok && !data.done && data.question) { + selected.clear(); + rebuildGrid(data.question); + setLocalStatus("", ""); + submitBtn.disabled = false; + return; + } + if (!data.ok && data.redirect) { + window.location.href = data.redirect; + return; + } + setLocalStatus(data.error === "expired" ? "Expired. Reloading..." : "Incorrect selection. Reloading...", "error"); setTimeout(function () { window.location.reload(); }, 1800); }) .catch(function () { @@ -533,7 +726,7 @@ - + + <%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> Settings @@ -61,8 +60,14 @@ })(); - - + + + + + + + + + + + + + + + + + + + + + +
    +
    +
    +
    +

    System Status

    +

    Real-time metrics and performance insights

    +
    +
    + <%= bots.length %> + <%= (typeof panelVersion !== 'undefined' && panelVersion) ? panelVersion : '—' %> +
    +
    + + +
    +
    +
    + + + + + + + + + + +
    +
    +
    Processor
    +
    0%
    +
    —
    +
    + +
    +
    + + + + + + + + + + +
    +
    +
    Memory
    +
    0%
    +
    —
    +
    + +
    +
    + + + + + + + + + + +
    +
    +
    Storage
    +
    0%
    +
    —
    +
    + +
    +
    + + + + + + + + + + +
    +
    +
    Network
    +
    0%
    +
    + — + ↓ + — + ↑ +
    +
    +
    + + +
    +
    +
    +
    +
    Requests
    +
    0/s
    +
    +
    +
    +
    +
    +
    Uptime
    +
    0s
    +
    +
    +
    + + +
    +
    Services
    +
    +
    + +
    +
    Database
    +
    checking…
    +
    +
    +
    + +
    +
    Nodes
    +
    checking…
    +
    +
    +
    + +
    +
    Containers
    +
    checking…
    +
    +
    +
    + +
    +
    Terminal
    +
    checking…
    +
    +
    +
    + +
    +
    Connections
    +
    checking…
    +
    +
    +
    +
    + + +
    +
    Performance History
    +
    +
    +
    + Processor + Memory +
    +
    +
    + +
    + +
    +
    +
    + +
    —
    + +
    +
    Select a day to view details
    +
    +
    +
    +
    +
    +
    + + <% if (isAdmin) { %> +
    + +
    + <% } %> + + <% if (isAdmin) { %> + + + + + + + + + + + <% } %> + + + + + + +
    + © 2026-<%= new Date().getFullYear() %> ADPanel Dashboard +
    + + + + + + + diff --git a/views/suspended.ejs b/views/suspended.ejs new file mode 100644 index 0000000..9a37da8 --- /dev/null +++ b/views/suspended.ejs @@ -0,0 +1,16 @@ + + + + + +ADPanel | Suspended server + + + + +