commit b0bf3b71674606fbc84bb76f4bf1073630b38fd3 Author: antonn Date: Fri May 8 19:09:25 2026 +0000 Fix: apply .gitignore and remove untracked files diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..e69de29 diff --git a/README.md b/README.md new file mode 100644 index 0000000..c1a4b22 --- /dev/null +++ b/README.md @@ -0,0 +1,76 @@ +
+ + ADPanel Banner + + +
+ + **"A change of thought and perfection found its way."** + + [![License](https://img.shields.io/badge/license-MIT-black?style=flat-square)](./LICENSE) + [![Docs](https://img.shields.io/badge/docs-ADPanel-blue?style=flat-square)](https://ad-panel.com/adocs) + [![Discord](https://img.shields.io/badge/Discord-Join%20Community-5865F2?style=flat-square&logo=discord&logoColor=white)](https://ad-panel.com/discord) +
+
+ + ### ⚡ Quick Deployment + +
+ +### ADPanel + +```bash +sudo mkdir -p /var/www && sudo git clone https://github.com/antonndev/ADPanel.git /var/www/adpanel && cd /var/www/adpanel && sudo bash ./initialize.sh --choice 1 +``` + +### ADaemon + +```bash +curl -fsSL https://raw.githubusercontent.com/antonndev/ADPanel-Daemon/main/install-daemon.sh | tr -d '\r' | sudo bash -s -- --yes +``` + +--- + +### Overview +**ADPanel™** | The open-source Docker Panel engineered for speed. Host containers with ease. While others charge for features, we deliver free. + +### Architecture +* **Security Rule #1** We bring an Apple-like experience to the developer's workflow. +* **Needing a change** Developers shouldn't have to settle for outdated interfaces. We're ending the era of boring, complex UIs. + +### Documentation & Resources +* **Official Website:** [ad-panel.com](https://ad-panel.com) +* **Documentation:** [ad-panel.com/adocs](https://ad-panel.com/adocs) +* **API Reference:** [ad-panel.com/adocs/api](https://ad-panel.com/adocs/api) + +### Infrastructure Support +**ADPanel™** isn’t just a game hosting panel, it’s a modern UI capable of running any Docker image on the planet. Start your journey today; our developers are constantly improving the platform to bring an enterprise-grade experience directly on your servers. + +--- + +### Manual Setup + +If you prefer to set up ADPanel manually instead of using the one-liner installer: + +```bash +# Clone the repository +git clone https://github.com/antonndev/ADPanel.git +cd ADPanel + +# Copy the example environment file and fill in your values +cp .env.example .env + +# Install dependencies +npm install + +# Start the panel +npm start +``` + +> **Redis is optional.** ADPanel works out of the box with file-based sessions. +> For production, we recommend enabling Redis — just uncomment `SESSION_STORE=redis` +> and set `REDIS_URL` in your `.env` file. If Redis becomes unavailable at runtime, +> the client automatically reconnects with exponential backoff. + +### License +Released under the MIT License. Copyright © 2026 - present ADPanel Workers. diff --git a/adpanel-sudoers b/adpanel-sudoers new file mode 100644 index 0000000..40c3abf --- /dev/null +++ b/adpanel-sudoers @@ -0,0 +1,10 @@ +# /etc/sudoers.d/adpanel-panel +# ADPanel runs as the unprivileged 'adpanel' user, but installer/database +# workflows require unattended root-level package/service operations. +# +# This policy intentionally allows non-interactive sudo for adpanel so +# panel-managed setup jobs (phpMyAdmin, pgAdmin, MongoDB, etc.) do not fail +# with "sudo: a password is required". + +Defaults:adpanel !requiretty +adpanel ALL=(ALL) NOPASSWD: ALL diff --git a/audit-fix.sh b/audit-fix.sh new file mode 100644 index 0000000..42e98fa --- /dev/null +++ b/audit-fix.sh @@ -0,0 +1,2 @@ +#!/bin/bash +nice -n 19 ionice -c 3 npm audit fix --package-lock-only \ No newline at end of file diff --git a/data/branding.json b/data/branding.json new file mode 100644 index 0000000..5d8774a --- /dev/null +++ b/data/branding.json @@ -0,0 +1,12 @@ +{ + "appName": "ADPanel", + "logoUrl": "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/adpanel-dark.webp", + "localLogoPath": null, + "loginWatermarkUrl": "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/watermark.webp", + "localLoginWatermarkPath": null, + "loginBackgroundType": "image", + "loginBackgroundExternalUrl": "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/waves.png", + "localLoginBackgroundPath": "login-background-remote-80a53467cc608e86.png", + "loginBackgroundMimeType": "image/png", + "updatedAt": "2026-03-22T15:19:17.938Z" +} \ No newline at end of file diff --git a/data/global-alert.json b/data/global-alert.json new file mode 100644 index 0000000..0637a08 --- /dev/null +++ b/data/global-alert.json @@ -0,0 +1 @@ +[] \ No newline at end of file diff --git a/data/maintenance.json b/data/maintenance.json new file mode 100644 index 0000000..440aa0e --- /dev/null +++ b/data/maintenance.json @@ -0,0 +1,13 @@ +{ + "enabled": false, + "scheduled_at": null, + "enabled_by": null, + "enabled_at": null, + "reason": null, + "pre_alert": { + "show": false, + "message": null, + "minutes_before": null + }, + "previous_alert_backup": null +} \ No newline at end of file diff --git a/data/runtime-scaling.env b/data/runtime-scaling.env new file mode 100644 index 0000000..05c3c29 --- /dev/null +++ b/data/runtime-scaling.env @@ -0,0 +1,6 @@ +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/db.js b/db.js new file mode 100644 index 0000000..9fad1fb --- /dev/null +++ b/db.js @@ -0,0 +1,91 @@ +"use strict"; + +const fs = require("fs"); +const mysql = require("mysql2/promise"); +const path = require("path"); +const { URL } = require("url"); + +const MYSQL_URL = String(process.env.MYSQL_URL || "").trim(); +const MYSQL_HOST = String(process.env.MYSQL_HOST || "127.0.0.1").trim(); +const MYSQL_PORT = parseInt(process.env.MYSQL_PORT || "3306", 10); +const MYSQL_USER = String(process.env.MYSQL_USER || "root").trim(); +const MYSQL_PASSWORD = String(process.env.MYSQL_PASSWORD || "").trim(); +const MYSQL_DATABASE = String(process.env.MYSQL_DATABASE || process.env.MYSQL_DB || "").trim(); +const MYSQL_POOL_SIZE = parseInt(process.env.MYSQL_POOL_SIZE || "10", 10); + +function configFromUrl(raw) { + if (!raw) return null; + try { + const url = new URL(raw); + if (url.protocol !== "mysql:") return null; + return { + host: url.hostname, + port: url.port ? Number(url.port) : 3306, + user: decodeURIComponent(url.username || ""), + password: decodeURIComponent(url.password || ""), + database: url.pathname ? url.pathname.replace(/^\//, "") : "", + }; + } catch { + return null; + } +} + +const urlConfig = configFromUrl(MYSQL_URL); +const dbName = (urlConfig && urlConfig.database) || MYSQL_DATABASE; +if (!dbName) { + console.warn("[db] MYSQL_DATABASE is not set; database selection may fail."); +} + +const pool = mysql.createPool({ + host: (urlConfig && urlConfig.host) || MYSQL_HOST, + port: (urlConfig && urlConfig.port) || MYSQL_PORT || 3306, + user: (urlConfig && urlConfig.user) || MYSQL_USER, + password: (urlConfig && urlConfig.password) || MYSQL_PASSWORD, + ...(dbName ? { database: dbName } : {}), + waitForConnections: true, + connectionLimit: Number.isFinite(MYSQL_POOL_SIZE) ? MYSQL_POOL_SIZE : 50, + queueLimit: 5000, + connectTimeout: 10000, + decimalNumbers: true, +}); + +async function query(sql, params = []) { + const [rows] = await pool.execute(sql, params); + return rows; +} + +function parseSchemaStatements(sql) { + return String(sql) + .split(";") + .map((stmt) => stmt.trim()) + .filter(Boolean); +} + +async function ensureSchema() { + const schemaPath = path.join(__dirname, "mysql-schema.sql"); + if (!fs.existsSync(schemaPath)) { + throw new Error("mysql-schema.sql not found"); + } + const sql = fs.readFileSync(schemaPath, "utf8"); + const statements = parseSchemaStatements(sql); + if (!statements.length) { + throw new Error("mysql-schema.sql is empty"); + } + const conn = await pool.getConnection(); + try { + for (const stmt of statements) { + await conn.query(stmt); + } + } finally { + conn.release(); + } +} + +module.exports = { + pool, + query, + ensureSchema, + async close() { + await pool.end(); + }, +}; diff --git a/docker_engine.go b/docker_engine.go new file mode 100644 index 0000000..6e42bbe --- /dev/null +++ b/docker_engine.go @@ -0,0 +1,375 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/url" + "sort" + "strings" + "sync" + "time" +) + +const ( + dockerEngineSocketPath = "/var/run/docker.sock" + dockerEngineAPIVersion = "v1.41" +) + +var ( + dockerEngineHTTPClient *http.Client + dockerEngineHTTPClientOnce sync.Once +) + +type dockerEngineError struct { + Message string `json:"message"` +} + +type dockerPortBinding struct { + HostIP string `json:"HostIp,omitempty"` + HostPort string `json:"HostPort,omitempty"` +} + +type dockerRestartPolicy struct { + Name string `json:"Name,omitempty"` + MaximumRetryCount int `json:"MaximumRetryCount,omitempty"` +} + +type dockerUlimit struct { + Name string `json:"Name"` + Soft int64 `json:"Soft"` + Hard int64 `json:"Hard"` +} + +type dockerHostConfig struct { + Binds []string `json:"Binds,omitempty"` + PortBindings map[string][]dockerPortBinding `json:"PortBindings,omitempty"` + RestartPolicy dockerRestartPolicy `json:"RestartPolicy,omitempty"` + CapAdd []string `json:"CapAdd,omitempty"` + CapDrop []string `json:"CapDrop,omitempty"` + SecurityOpt []string `json:"SecurityOpt,omitempty"` + PidsLimit int64 `json:"PidsLimit,omitempty"` + ReadonlyRootfs bool `json:"ReadonlyRootfs,omitempty"` + Tmpfs map[string]string `json:"Tmpfs,omitempty"` + Memory int64 `json:"Memory,omitempty"` + MemoryReservation int64 `json:"MemoryReservation,omitempty"` + MemorySwap int64 `json:"MemorySwap,omitempty"` + CpuShares int64 `json:"CpuShares,omitempty"` + CpuPeriod int64 `json:"CpuPeriod,omitempty"` + CpuQuota int64 `json:"CpuQuota,omitempty"` + BlkioWeight int64 `json:"BlkioWeight,omitempty"` + Ulimits []dockerUlimit `json:"Ulimits,omitempty"` +} + +type dockerContainerCreateRequest struct { + Image string `json:"Image"` + Env []string `json:"Env,omitempty"` + Cmd []string `json:"Cmd,omitempty"` + Entrypoint []string `json:"Entrypoint,omitempty"` + WorkingDir string `json:"WorkingDir,omitempty"` + User string `json:"User,omitempty"` + Tty bool `json:"Tty,omitempty"` + OpenStdin bool `json:"OpenStdin,omitempty"` + AttachStdin bool `json:"AttachStdin,omitempty"` + AttachStdout bool `json:"AttachStdout,omitempty"` + AttachStderr bool `json:"AttachStderr,omitempty"` + StdinOnce bool `json:"StdinOnce,omitempty"` + ExposedPorts map[string]struct{} `json:"ExposedPorts,omitempty"` + HostConfig dockerHostConfig `json:"HostConfig,omitempty"` +} + +type dockerContainerCreateResponse struct { + ID string `json:"Id"` +} + +type dockerContainerInspectResponse struct { + HostConfig dockerHostConfig `json:"HostConfig"` +} + +type dockerPullProgress struct { + Status string `json:"status"` + Error string `json:"error"` +} + +type dockerImageInspectConfig struct { + Entrypoint []string `json:"Entrypoint"` + Cmd []string `json:"Cmd"` + WorkingDir string `json:"WorkingDir"` + Env []string `json:"Env"` + User string `json:"User"` + Volumes map[string]any `json:"Volumes"` +} + +type dockerImageInspectResponse struct { + Config dockerImageInspectConfig `json:"Config"` +} + +func sanitizeStringList(values []string) []string { + out := make([]string, 0, len(values)) + for _, value := range values { + clean := strings.TrimSpace(value) + if clean != "" { + out = append(out, clean) + } + } + return out +} + +func (d Docker) inspectImageConfigAPI(ctx context.Context, ref string) (imageConfig, error) { + imageRef := strings.TrimSpace(ref) + if imageRef == "" { + return imageConfig{}, fmt.Errorf("missing image reference") + } + + body, status, err := d.engineRequest(ctx, http.MethodGet, "/images/"+url.PathEscape(imageRef)+"/json", nil, nil) + if err != nil { + return imageConfig{}, err + } + if status < 200 || status >= 300 { + return imageConfig{}, fmt.Errorf("failed to inspect image %s: %s", imageRef, decodeDockerAPIError(body)) + } + + var payload dockerImageInspectResponse + if err := json.Unmarshal(body, &payload); err != nil { + return imageConfig{}, err + } + + cfg := imageConfig{Env: map[string]string{}} + cfg.Entrypoint = sanitizeStringList(payload.Config.Entrypoint) + cfg.Cmd = sanitizeStringList(payload.Config.Cmd) + cfg.Workdir = strings.TrimSpace(payload.Config.WorkingDir) + cfg.User = strings.TrimSpace(payload.Config.User) + + if len(payload.Config.Volumes) > 0 { + cfg.Volumes = make([]string, 0, len(payload.Config.Volumes)) + for volumePath := range payload.Config.Volumes { + clean := strings.TrimSpace(volumePath) + if clean != "" && clean != "/" { + cfg.Volumes = append(cfg.Volumes, clean) + } + } + sort.Strings(cfg.Volumes) + } + + for _, kv := range sanitizeStringList(payload.Config.Env) { + if k, v, ok := strings.Cut(kv, "="); ok { + cfg.Env[strings.TrimSpace(k)] = v + } + } + + return cfg, nil +} + +func dockerEngineClient() *http.Client { + dockerEngineHTTPClientOnce.Do(func() { + transport := &http.Transport{ + DialContext: func(ctx context.Context, _, _ string) (net.Conn, error) { + var dialer net.Dialer + return dialer.DialContext(ctx, "unix", dockerEngineSocketPath) + }, + DisableCompression: true, + } + dockerEngineHTTPClient = &http.Client{ + Transport: transport, + Timeout: 0, + } + }) + return dockerEngineHTTPClient +} + +func dockerAPIPath(rawPath string, query url.Values) string { + path := "/" + dockerEngineAPIVersion + rawPath + if query == nil || len(query) == 0 { + return path + } + return path + "?" + query.Encode() +} + +func decodeDockerAPIError(body []byte) string { + trimmed := strings.TrimSpace(string(body)) + if trimmed == "" { + return "docker engine request failed" + } + var payload dockerEngineError + if err := json.Unmarshal(body, &payload); err == nil && strings.TrimSpace(payload.Message) != "" { + return strings.TrimSpace(payload.Message) + } + return trimmed +} + +func (d Docker) engineRequest(ctx context.Context, method, rawPath string, query url.Values, body any) ([]byte, int, error) { + var reader io.Reader + if body != nil { + payload, err := json.Marshal(body) + if err != nil { + return nil, 0, err + } + reader = bytes.NewReader(payload) + } + + req, err := http.NewRequestWithContext(ctx, method, "http://docker"+dockerAPIPath(rawPath, query), reader) + if err != nil { + return nil, 0, err + } + if body != nil { + req.Header.Set("Content-Type", "application/json") + } + + resp, err := dockerEngineClient().Do(req) + if err != nil { + return nil, 0, err + } + defer resp.Body.Close() + + respBody, readErr := io.ReadAll(resp.Body) + if readErr != nil { + return nil, resp.StatusCode, readErr + } + return respBody, resp.StatusCode, nil +} + +func splitDockerImageRef(ref string) (string, string) { + clean := strings.TrimSpace(ref) + if clean == "" { + return "", "" + } + if at := strings.Index(clean, "@"); at > 0 { + return clean, "" + } + lastSlash := strings.LastIndex(clean, "/") + lastColon := strings.LastIndex(clean, ":") + if lastColon > lastSlash { + return clean[:lastColon], clean[lastColon+1:] + } + return clean, "latest" +} + +func (d Docker) pullImageAPI(ctx context.Context, ref string) error { + image, tag := splitDockerImageRef(ref) + if image == "" { + return fmt.Errorf("missing image reference") + } + query := url.Values{} + query.Set("fromImage", image) + if tag != "" { + query.Set("tag", tag) + } + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://docker"+dockerAPIPath("/images/create", query), nil) + if err != nil { + return err + } + resp, err := dockerEngineClient().Do(req) + if err != nil { + return err + } + defer resp.Body.Close() + + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + body, _ := io.ReadAll(resp.Body) + return fmt.Errorf("failed to pull image %s: %s", ref, decodeDockerAPIError(body)) + } + + dec := json.NewDecoder(resp.Body) + for { + var item dockerPullProgress + if err := dec.Decode(&item); err != nil { + if err == io.EOF { + break + } + return err + } + if strings.TrimSpace(item.Error) != "" { + return fmt.Errorf("failed to pull image %s: %s", ref, strings.TrimSpace(item.Error)) + } + } + return nil +} + +func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool) error { + query := url.Values{} + if force { + query.Set("force", "1") + } + body, status, err := d.engineRequest(ctx, http.MethodDelete, "/containers/"+url.PathEscape(name), query, nil) + if err != nil { + return err + } + if status == http.StatusNotFound { + return nil + } + if status < 200 || status >= 300 { + return fmt.Errorf("failed to remove container %s: %s", name, decodeDockerAPIError(body)) + } + return nil +} + +func (d Docker) createContainerAPI(ctx context.Context, name string, req dockerContainerCreateRequest) (string, error) { + query := url.Values{} + query.Set("name", name) + body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/create", query, req) + if err != nil { + return "", err + } + if status < 200 || status >= 300 { + return "", fmt.Errorf("failed to create container %s: %s", name, decodeDockerAPIError(body)) + } + + var created dockerContainerCreateResponse + if err := json.Unmarshal(body, &created); err != nil { + return "", err + } + if strings.TrimSpace(created.ID) == "" { + return "", fmt.Errorf("docker engine did not return a container id") + } + return created.ID, nil +} + +func (d Docker) inspectContainerAPI(ctx context.Context, name string) (dockerContainerInspectResponse, error) { + body, status, err := d.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(name)+"/json", nil, nil) + if err != nil { + return dockerContainerInspectResponse{}, err + } + if status < 200 || status >= 300 { + return dockerContainerInspectResponse{}, fmt.Errorf("failed to inspect container %s: %s", name, decodeDockerAPIError(body)) + } + + var payload dockerContainerInspectResponse + if err := json.Unmarshal(body, &payload); err != nil { + return dockerContainerInspectResponse{}, err + } + return payload, nil +} + +func (d Docker) startContainerAPI(ctx context.Context, name string) error { + body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(name)+"/start", nil, nil) + if err != nil { + return err + } + if status < 200 || status >= 300 { + return fmt.Errorf("failed to start container %s: %s", name, decodeDockerAPIError(body)) + } + return nil +} + +func (d Docker) runContainerAPI(ctx context.Context, name string, req dockerContainerCreateRequest) error { + removeCtx, removeCancel := context.WithTimeout(ctx, 15*time.Second) + _ = d.removeContainerAPI(removeCtx, name, true) + removeCancel() + + pullCtx, pullCancel := context.WithTimeout(ctx, 10*time.Minute) + if err := d.pullImageAPI(pullCtx, req.Image); err != nil { + pullCancel() + return err + } + pullCancel() + + if _, err := d.createContainerAPI(ctx, name, req); err != nil { + return err + } + return d.startContainerAPI(ctx, name) +} diff --git a/ecosystem.config.js b/ecosystem.config.js new file mode 100644 index 0000000..f724b29 --- /dev/null +++ b/ecosystem.config.js @@ -0,0 +1,20 @@ +module.exports = { + apps: [ + { + name: "adpanel", + script: "/ADPanel/ADPanel-Enterprise/index.js", + cwd: "/ADPanel/ADPanel-Enterprise", + exec_mode: "cluster", + instances: 1, + node_args: "--max-old-space-size=5399", + max_memory_restart: "6352M", + restart_delay: 5000, + exp_backoff_restart_delay: 250, + kill_timeout: 5000, + listen_timeout: 10000, + env: { + NODE_ENV: "production" + } + } + ] +}; diff --git a/ecosystem.config.template.js b/ecosystem.config.template.js new file mode 100644 index 0000000..234454a --- /dev/null +++ b/ecosystem.config.template.js @@ -0,0 +1,20 @@ +module.exports = { + apps: [ + { + name: "adpanel", + script: "__SCRIPT_PATH__", + cwd: "__PANEL_DIR__", + exec_mode: "cluster", + instances: __INSTANCES__, + node_args: "--max-old-space-size=__MAX_OLD_SPACE_MB__", + max_memory_restart: "__WORKER_RAM_MB__M", + restart_delay: 5000, + exp_backoff_restart_delay: 250, + kill_timeout: 5000, + listen_timeout: 10000, + env: { + NODE_ENV: "production" + } + } + ] +}; diff --git a/index.js b/index.js new file mode 100644 index 0000000..7a92b89 --- /dev/null +++ b/index.js @@ -0,0 +1,28491 @@ + +"use strict"; + +require("dotenv").config({ override: true }); + +const express = require("express"); +const path = require("path"); +const fs = require("fs"); +const fsp = require("fs/promises"); +const net = require("net"); +const dns = require("dns").promises; +const os = require("os"); +const { spawn } = require("child_process"); +const helmet = require("helmet"); +const rateLimit = require("express-rate-limit"); +const { RedisStore: RateLimitRedisStore } = require("rate-limit-redis"); +const cookieParser = require("cookie-parser"); +const session = require("express-session"); +const zlib = require("zlib"); +let _multer; function getLazyMulter() { if (!_multer) _multer = require("multer"); return _multer; } +let _Busboy; function getLazyBusboy() { if (!_Busboy) _Busboy = require("busboy"); return _Busboy; } +const hpp = require("hpp"); +const crypto = require("crypto"); +const https = require("https"); +const httpMod = require("http"); +const { URL } = require("url"); +const { Server: SocketIOServer } = require("socket.io"); +let _FileStore; function getLazyFileStore() { if (!_FileStore) _FileStore = require("session-file-store")(session); return _FileStore; } +let _FormData; function getLazyFormData() { if (!_FormData) _FormData = require("form-data"); return _FormData; } +const db = require("./db"); +const mysql = require("mysql2/promise"); +const DASHBOARD_CSS = path.join(process.cwd(), "public", "css", "dashboard.css"); +const BOT_CSS = path.join(process.cwd(), "public", "css", "bot.css"); +const { makeCssBackground } = require("./utils/background"); +const { + brandingMiddleware, + loadBrandingConfig, + saveBrandingConfig, + sanitizeAppName, + sanitizeLogoUrl, + generateSafeLogoFilename, + validateBase64Image, + validateBase64Video, + getValidatedExtension, + getValidatedVideoExtension, + getMimeTypeForExtension, + getMediaTypeFromFilename, + getMediaTypeFromUrl, + getExtensionFromUrl, + resolveLoginWatermarkAssetUrl, + resolveLoginBackgroundAssetUrl, + invalidateBrandingCache +} = require("./utils/branding"); +const { scaleForMemory } = require("./utils/memory-scaling"); +const dbProxy = require("./utils/db-proxy"); +const { + sanitizeDockerTemplatePayload, + sanitizeDockerInstallPayload, + sanitizeEnvPayload, +} = require("./utils/server-template-payload"); +const { deleteServerByName } = require("./utils/server-delete"); +const { applyRemoteAssetToServer } = require("./utils/server-asset-apply"); +const { ensureStealthConfig } = require("./utils/stealth"); +const { + BOT_GOOGLE_FUNCTION_DECLARATIONS, + BOT_OPENAI_TOOL_DEFINITIONS, + BOT_TOOL_DEFINITIONS, + MAX_BOT_TOOL_LOOPS, + buildBotAssistantSystemPrompt, + buildBotReplyFromToolResult, + parseBotAssistantToolPlan, + resolveBackupFromList, + resolveServerFromAccessibleList, +} = require("./utils/bot-ai-tools"); + +const nodesRouter = require("./nodes.js"); +const subdomainsRouter = require("./routes/subdomains.js"); +const createDashboardAssistantRouter = require("./routes/dashboard-assistant.js"); +const { recordActivity } = nodesRouter; + + +const app = express(); +app.locals.themeVersion = Date.now(); +const GUEST_AVATAR_URL = "https://icon-library.com/images/guest-account-icon/guest-account-icon-1.jpg"; +const ADMIN_AVATAR_URL = "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/admin-avatar.webp"; +const DEFAULT_USER_AVATAR_URLS = [ + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-1.webp", + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-2.webp", + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-3.webp", +]; + +function getDefaultUserAvatar(seed) { + const hash = crypto.createHash("sha256").update(String(seed || "adpanel-user")).digest(); + return DEFAULT_USER_AVATAR_URLS[hash[0] % DEFAULT_USER_AVATAR_URLS.length]; +} + +function resolveUserAvatarUrl(user) { + if (user?.avatar_url && String(user.avatar_url).trim()) { + return String(user.avatar_url).trim(); + } + if (!user) { + return GUEST_AVATAR_URL; + } + if (user.admin) { + return ADMIN_AVATAR_URL; + } + return getDefaultUserAvatar(user.email || user.id || "adpanel-user"); +} +app.disable("x-powered-by"); + +function isDisallowedResponseHeader(name) { + const normalized = String(name || "").trim().toLowerCase(); + return normalized === "x-powered-by" || normalized === "server"; +} + +function hardenResponseHeaderWrites(res) { + if (!res || res.__adpanelResponseHeadersHardened) return; + res.__adpanelResponseHeadersHardened = true; + + const originalSetHeader = res.setHeader; + res.setHeader = function patchedSetHeader(name, value) { + if (isDisallowedResponseHeader(name)) return this; + return originalSetHeader.call(this, name, value); + }; + + const originalWriteHead = res.writeHead; + res.writeHead = function patchedWriteHead(statusCode, reasonPhrase, headers) { + let finalReasonPhrase = reasonPhrase; + let finalHeaders = headers; + + if (finalHeaders === undefined && finalReasonPhrase && typeof finalReasonPhrase === "object") { + finalHeaders = finalReasonPhrase; + finalReasonPhrase = undefined; + } + + if (finalHeaders && typeof finalHeaders === "object") { + for (const headerName of Object.keys(finalHeaders)) { + if (isDisallowedResponseHeader(headerName)) delete finalHeaders[headerName]; + } + } + + try { + this.removeHeader("Server"); + this.removeHeader("X-Powered-By"); + } catch { } + + if (finalReasonPhrase === undefined && finalHeaders === undefined) { + return originalWriteHead.call(this, statusCode); + } + if (finalReasonPhrase === undefined) { + return originalWriteHead.call(this, statusCode, finalHeaders); + } + return originalWriteHead.call(this, statusCode, finalReasonPhrase, finalHeaders); + }; +} + +app.use((req, res, next) => { + hardenResponseHeaderWrites(res); + try { + res.removeHeader("Server"); + res.removeHeader("X-Powered-By"); + } catch { } + next(); +}); +const ALLOWED_HTTP_METHODS = "GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS"; +app.use((req, res, next) => { + const method = String(req.method || "").toUpperCase(); + if (method === "TRACE" || method === "TRACK") { + res.setHeader("Allow", ALLOWED_HTTP_METHODS); + return res.status(405).type("text/plain").send("Method Not Allowed"); + } + if (method === "OPTIONS") { + res.setHeader("Allow", ALLOWED_HTTP_METHODS); + return res.status(204).end(); + } + return 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()); +const SCHEDULER_ENABLED_EARLY = ["1", "true", "yes", "on"].includes(String(process.env.SCHEDULER_ENABLED ?? "1").trim().toLowerCase()); +if (FREEZE_PROTOTYPES && !SCHEDULER_ENABLED_EARLY) { + Object.freeze(Object.prototype); + Object.freeze(Array.prototype); +} else if (FREEZE_PROTOTYPES && SCHEDULER_ENABLED_EARLY) { + console.log("[security] FREEZE_PROTOTYPES skipped - BullMQ scheduler requires unfrozen prototypes"); +} +const CSP_NONCE_BYTES = parseInt(process.env.CSP_NONCE_BYTES || "", 10) || 16; + + +const BCRYPT_ROUNDS = parseInt(process.env.BCRYPT_ROUNDS || "12", 10) || 12; + +function parseBoolean(value, defaultValue = false) { + if (value === undefined || value === null || value === "") return defaultValue; + if (typeof value === "boolean") return value; + const normalized = String(value).trim().toLowerCase(); + if (["1", "true", "yes", "on"].includes(normalized)) return true; + if (["0", "false", "no", "off"].includes(normalized)) return false; + return defaultValue; +} + + +function validatePort(port) { + if (port === undefined || port === null) return null; + const str = String(port).trim(); + if (!/^[1-9]\d{0,4}$/.test(str) && str !== '0') return null; + const num = parseInt(str, 10); + if (isNaN(num) || num < 1 || num > 65535) return null; + return num; +} + +function validatePortListInput(value) { + if (value === undefined || value === null || value === "") return []; + const rawEntries = Array.isArray(value) ? value : String(value).split(","); + const parsed = []; + const seen = new Set(); + for (const entry of rawEntries) { + const port = validatePort(entry); + if (!port) return null; + if (seen.has(port)) continue; + seen.add(port); + parsed.push(port); + } + return parsed; +} + +function validateIPv4(ip) { + if (!ip || typeof ip !== 'string') return null; + const trimmed = ip.trim(); + const ipv4Regex = /^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/; + return ipv4Regex.test(trimmed) ? trimmed : null; +} + +function validateIPv6(ip) { + if (!ip || typeof ip !== 'string') return null; + const trimmed = ip.trim(); + if (/['"\\$`\s;|&<>(){}[\]!#]/.test(trimmed)) return null; + const ipv6Regex = /^(?:[a-fA-F0-9]{1,4}:){0,7}[a-fA-F0-9]{0,4}$/; + if (trimmed === '::' || trimmed === '::1' || trimmed === '::0') return trimmed; + const parts = trimmed.split(':'); + if (parts.length < 2 || parts.length > 8) return null; + for (const part of parts) { + if (part !== '' && !/^[a-fA-F0-9]{1,4}$/.test(part)) return null; + } + return trimmed; +} + +function validateHostname(host) { + if (!host || typeof host !== 'string') return null; + const trimmed = host.trim().toLowerCase(); + if (trimmed.length === 0 || trimmed.length > 253) return null; + if (!/^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/.test(trimmed)) return null; + const labels = trimmed.split('.'); + for (const label of labels) { + if (label.length === 0 || label.length > 63) return null; + if (!/^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/.test(label)) return null; + if (label.startsWith('-') || label.endsWith('-')) return null; + } + return trimmed; +} + +function validateDbHost(host) { + if (!host || typeof host !== 'string') return null; + const trimmed = host.trim(); + + if (trimmed === 'localhost') return 'localhost'; + + if (trimmed === '0.0.0.0') return '0.0.0.0'; + + const ipv4 = validateIPv4(trimmed); + if (ipv4) return ipv4; + + const ipv6 = validateIPv6(trimmed); + if (ipv6) return ipv6; + + const hostname = validateHostname(trimmed); + if (hostname) return hostname; + + return null; +} + +const AUTO_MANAGE_FIREWALL = parseBoolean(process.env.ADPANEL_AUTO_MANAGE_FIREWALL, false); + +function isLocalOnlyDbHost(host) { + const normalized = String(host || "").trim().toLowerCase(); + return normalized === "localhost" || normalized === "127.0.0.1" || normalized === "::1" || normalized === "[::1]"; +} + +async function maybeOpenFirewallPort(runCmd, listenPort, listenHost, serviceTag) { + if (isLocalOnlyDbHost(listenHost)) { + console.log(`[${serviceTag}] Service is configured for local-only access; skipping firewall changes`); + return; + } + if (!AUTO_MANAGE_FIREWALL) { + console.log(`[${serviceTag}] Skipping automatic firewall changes for port ${listenPort}. Set ADPANEL_AUTO_MANAGE_FIREWALL=1 to re-enable this behavior.`); + return; + } + await runCmd(`ufw allow ${listenPort}/tcp 2>/dev/null || true`, 30000); + await runCmd(`iptables -C INPUT -p tcp --dport ${listenPort} -j ACCEPT 2>/dev/null || iptables -A INPUT -p tcp --dport ${listenPort} -j ACCEPT 2>/dev/null || true`, 10000); +} + +async function maybeRemoveFirewallPort(runCmd, listenPort, serviceTag) { + if (!AUTO_MANAGE_FIREWALL) { + console.log(`[${serviceTag}] Skipping automatic firewall cleanup for port ${listenPort}.`); + return; + } + await runCmd(`ufw delete allow ${listenPort}/tcp 2>/dev/null || true`, 10000); + await runCmd(`iptables -D INPUT -p tcp --dport ${listenPort} -j ACCEPT 2>/dev/null || true`, 10000); +} + +function escapePhpSingleQuote(str) { + if (!str || typeof str !== 'string') return ''; + return str.replace(/\\/g, '\\\\').replace(/'/g, "\\'"); +} + +function escapeHtml(input) { + const s = String(input ?? ""); + return s + .replace(/&/g, "&") + .replace(//g, ">") + .replace(/\"/g, """) + .replace(/'/g, "'"); +} + +const POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]); + +const FILE_SIGNATURES = { + 'image/jpeg': [Buffer.from([0xFF, 0xD8, 0xFF])], + 'image/png': [Buffer.from([0x89, 0x50, 0x4E, 0x47])], + 'image/gif': [Buffer.from([0x47, 0x49, 0x46, 0x38])], + 'image/webp': [Buffer.from([0x52, 0x49, 0x46, 0x46])], +}; + +function validateFileMagicBytes(buffer, declaredMimeType) { + if (!buffer || buffer.length < 4) return false; + + const signatures = FILE_SIGNATURES[declaredMimeType]; + if (!signatures) return false; + + for (const sig of signatures) { + if (buffer.slice(0, sig.length).equals(sig)) { + if (declaredMimeType === 'image/webp') { + if (buffer.length < 12) return false; + const webpSig = buffer.slice(8, 12).toString('ascii'); + return webpSig === 'WEBP'; + } + return true; + } + } + return false; +} + +function checkFileForDangerousContent(buffer) { + if (!buffer || buffer.length === 0) return false; + + const checkSize = Math.min(buffer.length, 8192); + const content = buffer.slice(0, checkSize).toString('utf8', 0, checkSize); + + const dangerousPatterns = [ + /<%.*%>/i, + /<\?php/i, + /<\?=/i, + /]/i, + /eval\s*\(/i, + /exec\s*\(/i, + /system\s*\(/i, + /passthru\s*\(/i, + /shell_exec\s*\(/i, + /\bimport\s+os\b/i, + /\bsubprocess\b/i, + /#!\/.*\/(bash|sh|python|perl|ruby)/i, + ]; + + for (const pattern of dangerousPatterns) { + if (pattern.test(content)) { + return false; + } + } + + return true; +} + +// Unified TTL cache with auto-sweep and max-size eviction +class TTLCache { + constructor({ name = "cache", ttlMs = 60000, maxSize = Infinity, sweepMs = 0 } = {}) { + this._name = name; + this._ttlMs = ttlMs; + this._maxSize = maxSize; + this._map = new Map(); + this._sweepTimer = null; + if (sweepMs > 0) { + this._sweepTimer = setInterval(() => this.sweep(), sweepMs); + this._sweepTimer.unref(); + } + } + + get size() { + return this._map.size; + } + + get(key) { + const entry = this._map.get(key); + if (!entry) return undefined; + if (entry.expiresAt > 0 && Date.now() >= entry.expiresAt) { + this._map.delete(key); + return undefined; + } + return entry.value; + } + + has(key) { + return this.get(key) !== undefined; + } + + set(key, value, ttlMs) { + const ttl = ttlMs !== undefined ? ttlMs : this._ttlMs; + if (this._map.size >= this._maxSize && !this._map.has(key)) { + // Evict oldest entry + const oldestKey = this._map.keys().next().value; + if (oldestKey !== undefined) this._map.delete(oldestKey); + } + this._map.set(key, { + value, + expiresAt: ttl > 0 ? Date.now() + ttl : 0, + updatedAt: Date.now() + }); + } + + delete(key) { + return this._map.delete(key); + } + + clear(predicate) { + if (!predicate) { + this._map.clear(); + return; + } + for (const [key, entry] of this._map.entries()) { + if (predicate(key, entry.value)) this._map.delete(key); + } + } + + // Iterate over non-expired entries + *entries() { + const now = Date.now(); + for (const [key, entry] of this._map.entries()) { + if (entry.expiresAt > 0 && now >= entry.expiresAt) continue; + yield [key, entry.value]; + } + } + + *keys() { + for (const [key] of this.entries()) yield key; + } + + *values() { + for (const [, value] of this.entries()) yield value; + } + + sweep() { + const now = Date.now(); + for (const [key, entry] of this._map.entries()) { + if (entry.expiresAt > 0 && now >= entry.expiresAt) { + this._map.delete(key); + } + } + } + + // Get raw entry metadata (updatedAt) for consumers that need it + getMeta(key) { + const entry = this._map.get(key); + if (!entry) return null; + if (entry.expiresAt > 0 && Date.now() >= entry.expiresAt) { + this._map.delete(key); + return null; + } + return { value: entry.value, updatedAt: entry.updatedAt, expiresAt: entry.expiresAt }; + } + + destroy() { + if (this._sweepTimer) { + clearInterval(this._sweepTimer); + this._sweepTimer = null; + } + this._map.clear(); + } +} + +const serverCreateLocks = new Set(); +setInterval(() => { serverCreateLocks.clear(); }, 600_000).unref(); + +let mongodbOperationLock = false; + +const transferJobs = new Map(); + +const TRANSFER_JOB_TTL_SEC = parseInt(process.env.TRANSFER_JOB_TTL_SEC || "", 10) || 3600; + +function transferJobRedisKey(name) { + const key = String(name || "").trim(); + return `transferJob:${key}`; +} + +async function getTransferJobFromRedis(name) { + if (!redisClient) return null; + const key = String(name || "").trim(); + if (!key) return null; + try { + const raw = await redisClient.get(transferJobRedisKey(key)); + if (!raw) return null; + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === "object") { + transferJobs.set(key, parsed); + return parsed; + } + } catch { } + return null; +} + +function getTransferJob(name) { + const key = String(name || "").trim(); + if (!key) return null; + return transferJobs.get(key) || null; +} + +function setTransferJob(name, patch) { + const key = String(name || "").trim(); + if (!key) return; + const existing = transferJobs.get(key) || { name: key }; + const updated = { ...existing, ...patch, updatedAt: Date.now() }; + transferJobs.set(key, updated); + + if (redisClient) { + redisClient.set(transferJobRedisKey(key), JSON.stringify(updated), "EX", TRANSFER_JOB_TTL_SEC).catch(() => { }); + } +} + +setInterval(() => { + try { + const now = Date.now(); + for (const [key, job] of transferJobs.entries()) { + if (job.finishedAt && (now - job.finishedAt > TRANSFER_JOB_TTL_SEC * 1000)) { + transferJobs.delete(key); + } else if (job.updatedAt && (now - job.updatedAt > TRANSFER_JOB_TTL_SEC * 1000 * 2)) { + transferJobs.delete(key); + } + } + } catch (err) { console.debug("[transferJobs] sweep error:", err.message); } +}, 300_000).unref(); + + +function cleanupTransferJobLater(name, ms = 10 * 60 * 1000) { + const key = String(name || "").trim(); + if (!key) return; + setTimeout(() => { + const j = transferJobs.get(key); + if (!j) return; + if (j.finishedAt) { + transferJobs.delete(key); + if (redisClient) { + try { redisClient.del(transferJobRedisKey(key)).catch(() => { }); } catch { } + } + } + }, ms); +} + +function httpStreamRequest(fullUrl, { method = "GET", headers = {}, bodyStream = null, timeoutMs = 120000 } = {}) { + return new Promise((resolve, reject) => { + try { + const isHttps = fullUrl.startsWith("https:"); + const lib = isHttps ? https : httpMod; + const requestOptions = { method, headers }; + if (isHttps && nodeMtlsAgent) requestOptions.agent = nodeMtlsAgent; + + const cleanup = () => { + if (req) { + req.removeListener("timeout", onTimeout); + req.removeListener("error", onError); + } + }; + + const onTimeout = () => { + cleanup(); + try { req.destroy(new Error("timeout")); } catch { } + }; + + const onError = (e) => { + cleanup(); + reject(e); + }; + + const req = lib.request(fullUrl, requestOptions, (res) => { + cleanup(); + resolve({ req, res }); + }); + + req.on("timeout", onTimeout); + req.on("error", onError); + req.setTimeout(timeoutMs); + + if (bodyStream) bodyStream.pipe(req); + else req.end(); + } catch (e) { + reject(e); + } + }); +} + +async function stopServerOnNode(node, name) { + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return; + const headers = nodeAuthHeadersFor(node, true); + try { + await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(name)}/stop`, "POST", headers, null, 30_000); + } catch { } +} + +async function waitForServerStopped(node, name, { timeoutMs = 30_000, intervalMs = 1500 } = {}) { + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return true; + const headers = nodeAuthHeadersFor(node, true); + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const r = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(name)}`, + "GET", headers, null, 10_000 + ); + if (r.status === 200 && r.json) { + const st = String(r.json.status || "").toLowerCase(); + if (st === "stopped" || st === "exited" || st === "not running") return true; + } + if (r.status === 404) return true; + } catch { } + await new Promise(r => setTimeout(r, intervalMs)); + } + return false; +} + +async function waitForServerReady(node, name, { timeoutMs = 30_000, intervalMs = 2000 } = {}) { + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return false; + const headers = nodeAuthHeadersFor(node, true); + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + try { + const r = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(name)}`, + "GET", headers, null, 10_000 + ); + if (r.status === 200 && r.json && r.json.ok) { + return true; + } + } catch { } + await new Promise(r => setTimeout(r, intervalMs)); + } + return false; +} + +function isRecoverableNodeCreateStatus(status) { + return status === 0 || status === 520 || status === 522 || status === 523 || status === 524; +} + +async function deleteServerOnNode(node, name, { filesOnly = false } = {}) { + 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 qs = filesOnly ? "?files_only=true" : ""; + const r = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(name)}${qs}`, "DELETE", headers, null, 120_000); + 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) : `remote delete failed (${r.status})`; + throw new Error(msg); + } +} + +function computeTransferEffectiveResources(serverResources, sourceNode, destNode) { + const inRes = (serverResources && typeof serverResources === "object") ? serverResources : {}; + const out = { ...inRes }; + + const srcRam = Number(sourceNode?.ram_mb || 0); + const dstRam = Number(destNode?.ram_mb || 0); + const srcDisk = Number(sourceNode?.disk_gb || 0); + const dstDisk = Number(destNode?.disk_gb || 0); + + const srcCores = Number(sourceNode?.buildConfig?.cpu_cores || sourceNode?.buildConfig?.cpuCores || 0); + const dstCores = Number(destNode?.buildConfig?.cpu_cores || destNode?.buildConfig?.cpuCores || 0); + + const coerceInt = (v) => { + const n = Number(v); + return Number.isFinite(n) ? Math.trunc(n) : null; + }; + const coerceFloat = (v) => { + const n = Number(v); + return Number.isFinite(n) ? n : null; + }; + + const isUnlimitedOrNodeMaxInt = (val, srcMax) => { + if (val == null) return true; + const n = coerceInt(val); + if (n == null) return true; + if (n <= 0) return true; + if (srcMax > 0 && n === Math.trunc(srcMax)) return true; + return false; + }; + + const isUnlimitedOrNodeMaxFloat = (val, srcMax) => { + if (val == null) return true; + const n = coerceFloat(val); + if (n == null) return true; + if (n <= 0) return true; + if (srcMax > 0 && Math.abs(n - srcMax) < 0.0001) return true; + return false; + }; + + if (dstRam > 0) { + const cur = coerceInt(inRes.ramMb); + if (isUnlimitedOrNodeMaxInt(inRes.ramMb, srcRam)) out.ramMb = Math.trunc(dstRam); + else if (cur != null && cur > Math.trunc(dstRam)) out.ramMb = Math.trunc(dstRam); + } + + const srcDiskMb = srcDisk > 0 ? srcDisk * 1024 : 0; + const dstDiskMb = dstDisk > 0 ? dstDisk * 1024 : 0; + const storageField = inRes.storageMb != null ? 'storageMb' : 'storageGb'; + const storageSrcMax = storageField === 'storageMb' ? srcDiskMb : srcDisk; + const storageDstMax = storageField === 'storageMb' ? dstDiskMb : dstDisk; + if ((storageField === 'storageMb' ? dstDiskMb : dstDisk) > 0) { + const cur = coerceInt(inRes[storageField]); + if (isUnlimitedOrNodeMaxInt(inRes[storageField], storageSrcMax)) out[storageField] = Math.trunc(storageDstMax); + else if (cur != null && cur > Math.trunc(storageDstMax)) out[storageField] = Math.trunc(storageDstMax); + } + + if (dstCores > 0) { + const cur = coerceFloat(inRes.cpuCores); + if (isUnlimitedOrNodeMaxFloat(inRes.cpuCores, srcCores)) out.cpuCores = dstCores; + else if (cur != null && cur > dstCores) out.cpuCores = dstCores; + } + + return out; +} + +function parseOptionalIntegerResource(value, label, min, max) { + if (value === null || value === undefined || String(value).trim() === "") return null; + const text = String(value).trim(); + if (!/^\d+$/.test(text)) { + throw new Error(`${label} must be a whole number.`); + } + const parsed = Number(text); + if (!Number.isSafeInteger(parsed) || parsed < min || parsed > max) { + throw new Error(`${label} must be between ${min} and ${max}.`); + } + return parsed; +} + +function collectResourcePerformanceOptions(input) { + const source = (input && typeof input === "object") ? input : {}; + const options = {}; + const ioWeight = parseOptionalIntegerResource(source.ioWeight, "I/O Priority", 10, 1000); + const cpuWeight = parseOptionalIntegerResource(source.cpuWeight, "CPU Priority", 1, 1000); + const pidsLimit = parseOptionalIntegerResource(source.pidsLimit, "Process Limit", 64, 4096); + const fileLimit = parseOptionalIntegerResource(source.fileLimit, "File Limit", 1024, 1048576); + if (ioWeight != null) options.ioWeight = ioWeight; + if (cpuWeight != null) options.cpuWeight = cpuWeight; + if (pidsLimit != null) options.pidsLimit = pidsLimit; + if (fileLimit != null) options.fileLimit = fileLimit; + return options; +} + +const RESOURCE_NETWORK_LIMIT_MAX_MB = 1073741824; +const RESOURCE_NETWORK_RESET_MAX_MINUTES = 43200; + +function collectResourceAntiAbuseOptions(input) { + const source = (input && typeof input === "object") ? input : {}; + const options = {}; + const inboundLimitMb = parseOptionalIntegerResource(source.networkInboundLimitMb, "Inbound Limit", 0, RESOURCE_NETWORK_LIMIT_MAX_MB); + const outboundLimitMb = parseOptionalIntegerResource(source.networkOutboundLimitMb, "Outbound Limit", 0, RESOURCE_NETWORK_LIMIT_MAX_MB); + const resetMinutes = parseOptionalIntegerResource(source.networkResetMinutes, "Reset Time", 0, RESOURCE_NETWORK_RESET_MAX_MINUTES); + if (inboundLimitMb != null) options.networkInboundLimitMb = inboundLimitMb; + if (outboundLimitMb != null) options.networkOutboundLimitMb = outboundLimitMb; + if (resetMinutes != null) options.networkResetMinutes = resetMinutes; + return options; +} + +async function startServerOnNode(node, name, hostPort) { + 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 payload = (hostPort != null && Number.isFinite(Number(hostPort))) ? { hostPort: Number(hostPort) } : {}; + const r = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(name)}/start`, "POST", headers, payload, 240_000); + if (r.status !== 200 || !(r.json && (r.json.ok === true || r.json.ok === undefined))) { + const msg = (r.json && (r.json.error || r.json.detail)) ? (r.json.error || r.json.detail) : `remote start failed (${r.status})`; + throw new Error(msg); + } +} + +async function streamExportToImport({ sourceNode, destNode, serverName, 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`; + + const srcHeaders = { + Authorization: `Bearer ${sourceNode.token}`, + "X-Node-Token": sourceNode.token || "", + "X-Node-Token-Id": sourceNode.token_id || "" + }; + const dstHeaders = { + Authorization: `Bearer ${destNode.token}`, + "X-Node-Token": destNode.token || "", + "X-Node-Token-Id": destNode.token_id || "", + "Content-Type": "application/x-tar" + }; + + const { res: srcRes } = await httpStreamRequest(srcUrl, { method: "GET", headers: srcHeaders, timeoutMs: 10 * 60 * 1000 }); + if (srcRes.statusCode !== 200) { + const MAX_ERR_BYTES = 64 * 1024; + const chunks = []; + let srcTotal = 0; + srcRes.on("data", (d) => { + if (srcTotal < MAX_ERR_BYTES) { chunks.push(d); srcTotal += d.length; } + }); + await new Promise((r) => srcRes.on("end", r)); + const msg = Buffer.concat(chunks).toString("utf8").slice(0, 500); + throw new Error(`export failed (${srcRes.statusCode}): ${msg || "no body"}`); + } + + const totalBytesHeader = srcRes.headers["x-adpanel-server-bytes"] || srcRes.headers["content-length"]; + const totalBytes = totalBytesHeader ? Number(totalBytesHeader) : 0; + let transferred = 0; + + srcRes.on("data", (chunk) => { + transferred += chunk.length; + if (typeof onProgress === "function") { + const pct = totalBytes > 0 ? Math.min(100, Math.floor((transferred / totalBytes) * 100)) : null; + onProgress({ transferred, totalBytes, percent: pct }); + } + }); + + srcRes.once("end", () => { + try { + if (typeof onProgress === "function") onProgress({ transferred, totalBytes, percent: 100 }); + } catch { } + }); + + const { req: dstReq, res: dstRes } = await httpStreamRequest(dstUrl, { method: "POST", headers: dstHeaders, bodyStream: srcRes, timeoutMs: 30 * 60 * 1000 }); + const dstBody = await new Promise((resolve, reject) => { + const MAX_ERR_BYTES = 64 * 1024; + const chunks = []; + let dstTotal = 0; + dstRes.on("data", (d) => { + if (dstTotal < MAX_ERR_BYTES) { chunks.push(d); dstTotal += d.length; } + }); + dstRes.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + dstRes.on("error", reject); + dstReq.on("error", reject); + }); + + if (dstRes.statusCode !== 200) { + throw new Error(`import failed (${dstRes.statusCode}): ${String(dstBody || "").slice(0, 500) || "no body"}`); + } + + if (dstBody) { + try { + const parsed = JSON.parse(dstBody); + if (parsed && parsed.ok === false) { + throw new Error(parsed.error || "import failed"); + } + } catch { } + } +} + +function isPlainObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +function safeMerge(target, source) { + const safeTarget = isPlainObject(target) ? target : Object.create(null); + if (!isPlainObject(source)) return safeTarget; + + for (const key of Object.keys(source)) { + if (key === "__proto__" || key === "constructor" || key === "prototype") continue; + + if (POLLUTION_KEYS.has(key)) continue; + + const val = source[key]; + + if (isPlainObject(val)) { + if (!safeTarget[key] || !isPlainObject(safeTarget[key])) { + safeTarget[key] = Object.create(null); + } + safeTarget[key] = safeMerge(safeTarget[key], val); + } else { + safeTarget[key] = val; + } + } + return safeTarget; +} + +const ENABLE_WEEKLY_AUDIT_FIX = parseBoolean(process.env.ENABLE_WEEKLY_AUDIT_FIX, false); + +function scheduleWeeklySecurityAudit() { + if (!ENABLE_WEEKLY_AUDIT_FIX) { + console.log("[ADSecurity] Weekly npm audit fix disabled (set ENABLE_WEEKLY_AUDIT_FIX=true to enable)"); + return; + } + const timestampFile = path.join(__dirname, ".last_audit_ts"); + const now = Date.now(); + const ONE_WEEK = 7 * 24 * 60 * 60 * 1000; + + if (fs.existsSync(timestampFile)) { + const lastRun = parseInt(fs.readFileSync(timestampFile, "utf8"), 10); + if (now - lastRun < ONE_WEEK) return; + } + + console.log("[ADSecurity] Initialized the npm audit fix weekly"); + + const child = spawn("bash", [path.join(__dirname, "audit-fix.sh")], { + detached: true, + stdio: "ignore", + cwd: __dirname, + }); + + child.unref(); + + fs.writeFileSync(timestampFile, now.toString()); +} + +scheduleWeeklySecurityAudit(); + +function safeCompare(a, b) { + if (typeof a !== "string" || typeof b !== "string") return false; + + const bufA = Buffer.from(a); + const bufB = Buffer.from(b); + + if (bufA.length !== bufB.length) { + crypto.timingSafeEqual(bufA, bufA); + return false; + } + + return crypto.timingSafeEqual(bufA, bufB); +} + +const ACTION_TOKEN_SECRET = + process.env.ACTION_TOKEN_SECRET || + crypto.createHmac("sha256", process.env.SESSION_SECRET).update("adpanel-action-token-key-v1").digest("hex"); + +const SSH_TERM_TOKEN_SECRET = + process.env.SSH_TERM_TOKEN_SECRET || + crypto.createHmac("sha256", process.env.SESSION_SECRET).update("adpanel-ssh-term-token-key-v1").digest("hex"); +const SSH_TERM_TOKEN_TTL_MS = parseInt(process.env.SSH_TERM_TOKEN_TTL_MS || "", 10) || 20 * 60 * 1000; + +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(str) { + const s = String(str).replace(/-/g, "+").replace(/_/g, "/"); + const pad = s.length % 4 ? "=".repeat(4 - (s.length % 4)) : ""; + return Buffer.from(s + pad, "base64"); +} + +function stableStringify(obj) { + if (obj === null || obj === undefined) return "null"; + if (typeof obj !== "object") return JSON.stringify(obj); + if (Array.isArray(obj)) return `[${obj.map(stableStringify).join(",")}]`; + const keys = Object.keys(obj).sort(); + return `{${keys.map(k => `${JSON.stringify(k)}:${stableStringify(obj[k])}`).join(",")}}`; +} + +function signActionPayload(payloadB64) { + const sig = crypto.createHmac("sha256", ACTION_TOKEN_SECRET).update(payloadB64).digest(); + return b64urlEncode(sig); +} + +function signSshTerminalPayload(payloadB64) { + const sig = crypto.createHmac("sha256", SSH_TERM_TOKEN_SECRET).update(payloadB64).digest(); + return b64urlEncode(sig); +} + +function issueSshTerminalToken(req) { + const payload = { + v: 1, + uid: String(req?.session?.user || ""), + ip: String(getRequestIp(req) || ""), + exp: Date.now() + SSH_TERM_TOKEN_TTL_MS, + }; + const payloadB64 = b64urlEncode(JSON.stringify(payload)); + const sig = signSshTerminalPayload(payloadB64); + return `${payloadB64}.${sig}`; +} + +function issueActionToken(req, action, resource = {}, opts = {}) { + const ttlSeconds = Number(opts.ttlSeconds ?? 300); + const oneTime = !!opts.oneTime; + + const now = Date.now(); + const payload = { + v: 1, + uid: String(req.session?.user || ""), + sid: String(req.sessionID || ""), + act: String(action), + res: stableStringify(resource || {}), + exp: now + ttlSeconds * 1000, + n: oneTime ? crypto.randomBytes(16).toString("hex") : undefined + }; + + const payloadB64 = b64urlEncode(JSON.stringify(payload)); + const sig = signActionPayload(payloadB64); + return `${payloadB64}.${sig}`; +} + +function getActionTokenFromRequest(req) { + return ( + req.get("x-action-token") || + req.body?.actionToken || + null + ); +} + +function markNonceUsed(req, nonce, expMs) { + if (!req.session) return false; + if (!req.session.usedActionNonces) req.session.usedActionNonces = {}; + const used = req.session.usedActionNonces; + + const now = Date.now(); + for (const [k, v] of Object.entries(used)) { + if (Number(v) < now) delete used[k]; + } + + if (used[nonce]) return false; + used[nonce] = expMs; + req.session.usedActionNonces = used; + return true; +} + +function verifyActionToken(req, token, expectedAction, expectedResource = {}) { + try { + if (!token || typeof token !== "string") return false; + const parts = token.split("."); + if (parts.length !== 2) return false; + + const [payloadB64, sig] = parts; + const expectedSig = signActionPayload(payloadB64); + if (!safeCompare(sig, expectedSig)) return false; + + const payload = JSON.parse(b64urlDecode(payloadB64).toString("utf8")); + if (!payload || payload.v !== 1) return false; + + if (!req.session || !req.session.user) return false; + if (String(payload.uid).toLowerCase() !== String(req.session.user).toLowerCase()) return false; + if (String(payload.sid) !== String(req.sessionID)) return false; + + if (String(payload.act) !== String(expectedAction)) return false; + + const now = Date.now(); + if (!payload.exp || Number(payload.exp) < now) return false; + + const expectedRes = stableStringify(expectedResource || {}); + if (String(payload.res) !== expectedRes) return false; + + if (payload.n) { + const ok = markNonceUsed(req, String(payload.n), Number(payload.exp)); + if (!ok) return false; + } + + return true; + } catch { + return false; + } +} + +function requireActionTokenOr403(req, res, action, resource = {}) { + const token = getActionTokenFromRequest(req); + const ok = verifyActionToken(req, token, action, resource); + if (!ok) { + res.status(403).json({ error: "invalid or missing action token" }); + return false; + } + return true; +} + +function readJson(file, fallback) { + try { + if (!fs.existsSync(file)) return fallback; + const raw = fs.readFileSync(file, "utf8").trim(); + if (!raw) return fallback; + return JSON.parse(raw); + } catch { + return fallback; + } +} + +function safeWriteJson(file, obj) { + try { + fs.writeFileSync(file, JSON.stringify(obj, null, 2), "utf8"); + return true; + } catch { + return false; + } +} + +function parseDbJson(value, fallback = null) { + if (value === null || value === undefined || value === "") return fallback; + if (typeof value === "object") return value; + try { + return JSON.parse(String(value)); + } catch { + return fallback; + } +} + +function toDbJson(value) { + if (value === undefined || value === null) return null; + if (typeof value === "string") { + try { + JSON.parse(value); + return value; + } catch { + return JSON.stringify(value); + } + } + return JSON.stringify(value); +} + +const GLOBAL_ALERT_FILE = path.join(process.cwd(), "data", "global-alert.json"); +let cachedAlerts = null; + +const MAINTENANCE_FILE = path.join(process.cwd(), "data", "maintenance.json"); +let maintenanceState = null; +const DASHBOARD_ASSISTANT_CONFIG_FILE = path.join(process.cwd(), "data", "dashboard-assistant-config.json"); +let dashboardAssistantConfigCache = null; + +function loadMaintenanceState() { + try { + if (fs.existsSync(MAINTENANCE_FILE)) { + const data = JSON.parse(fs.readFileSync(MAINTENANCE_FILE, "utf-8")); + if (data && typeof data === "object") { + maintenanceState = data; + return data; + } + } + } catch (e) { + console.error("[maintenance] Failed to read maintenance.json:", e); + } + maintenanceState = { + enabled: false, + scheduled_at: null, + enabled_by: null, + enabled_at: null, + reason: null, + pre_alert: { show: false, message: null, minutes_before: null }, + previous_alert_backup: null + }; + return maintenanceState; +} + +function getMaintenanceState() { + if (maintenanceState === null) loadMaintenanceState(); + return maintenanceState; +} + +function saveMaintenanceState(state) { + try { + maintenanceState = state; + fs.writeFileSync(MAINTENANCE_FILE, JSON.stringify(state, null, 2), "utf-8"); + return true; + } catch (e) { + console.error("[maintenance] Failed to save maintenance.json:", e); + return false; + } +} + +function isMaintenanceActive() { + const state = getMaintenanceState(); + if (!state) return false; + if (state.enabled) return true; + if (state.scheduled_at) { + const scheduledTime = new Date(state.scheduled_at).getTime(); + if (!isNaN(scheduledTime) && Date.now() >= scheduledTime) { + state.enabled = true; + state.enabled_at = new Date().toISOString(); + saveMaintenanceState(state); + console.log("[maintenance] Scheduled maintenance activated automatically"); + return true; + } + } + return false; +} + +function normalizeDashboardAssistantConfig(value) { + const source = value && typeof value === "object" ? value : {}; + return { + allowNormalUsers: !!source.allowNormalUsers, + updatedAt: source.updatedAt ? String(source.updatedAt) : null, + updatedBy: source.updatedBy ? String(source.updatedBy) : null, + }; +} + +function loadDashboardAssistantConfig() { + dashboardAssistantConfigCache = normalizeDashboardAssistantConfig( + readJson(DASHBOARD_ASSISTANT_CONFIG_FILE, null) + ); + return dashboardAssistantConfigCache; +} + +function getDashboardAssistantConfig() { + if (!dashboardAssistantConfigCache) { + return loadDashboardAssistantConfig(); + } + return dashboardAssistantConfigCache; +} + +function saveDashboardAssistantConfig(config) { + const normalized = normalizeDashboardAssistantConfig(config); + if (!safeWriteJson(DASHBOARD_ASSISTANT_CONFIG_FILE, normalized)) { + return false; + } + dashboardAssistantConfigCache = normalized; + return true; +} + +function isDashboardAssistantEnabledForNormalUsers() { + return !!getDashboardAssistantConfig().allowNormalUsers; +} + +function canUserAccessDashboardAssistant(user) { + return !!(user && (user.admin || isDashboardAssistantEnabledForNormalUsers())); +} + +let maintenanceCheckerInterval = null; + +function startMaintenanceChecker() { + if (maintenanceCheckerInterval) return; + maintenanceCheckerInterval = setInterval(() => { + try { + const state = getMaintenanceState(); + if (!state) return; + + if (!state.enabled && state.scheduled_at) { + const scheduledTime = new Date(state.scheduled_at).getTime(); + if (!isNaN(scheduledTime) && Date.now() >= scheduledTime) { + state.enabled = true; + state.enabled_at = new Date().toISOString(); + saveMaintenanceState(state); + console.log("[maintenance] Scheduled maintenance activated"); + } + + if (!state.enabled && state.pre_alert && state.pre_alert.show && state.pre_alert.message && state.pre_alert.minutes_before) { + const alertTime = scheduledTime - (state.pre_alert.minutes_before * 60 * 1000); + if (Date.now() >= alertTime && !state.pre_alert._alert_injected) { + const currentAlert = getActiveGlobalAlert(); + if (currentAlert) { + state.previous_alert_backup = currentAlert; + } + addGlobalAlert(state.pre_alert.message, new Date().toISOString()); + state.pre_alert._alert_injected = true; + state.pre_alert._injected_alert_message = state.pre_alert.message; + saveMaintenanceState(state); + console.log("[maintenance] Pre-maintenance alert injected"); + } + } + } + } catch (e) { + console.error("[maintenance] Checker error:", e); + } + }, 30000); +} + +function stopMaintenanceChecker() { + if (maintenanceCheckerInterval) { + clearInterval(maintenanceCheckerInterval); + maintenanceCheckerInterval = null; + } +} + +function restoreAlertAfterMaintenance(state) { + try { + if (state.pre_alert && state.pre_alert._injected_alert_message) { + const alerts = getGlobalAlerts(); + const maintenanceAlertIdx = alerts.findIndex(a => a.message === state.pre_alert._injected_alert_message); + if (maintenanceAlertIdx !== -1) { + alerts.splice(maintenanceAlertIdx, 1); + saveGlobalAlerts(alerts); + } + } + } catch (e) { + console.error("[maintenance] Failed to restore alert:", e); + } +} + +loadMaintenanceState(); + +function loadGlobalAlerts() { + try { + if (fs.existsSync(GLOBAL_ALERT_FILE)) { + const data = JSON.parse(fs.readFileSync(GLOBAL_ALERT_FILE, "utf-8")); + if (Array.isArray(data)) return data.map(normalizeGlobalAlert).filter(Boolean); + if (data && data.message) { + return [normalizeGlobalAlert({ + id: 'legacy', + message: data.message, + date: new Date(0).toISOString(), + createdAt: new Date(0).toISOString(), + neverEnds: true, + endDate: null + })].filter(Boolean); + } + return []; + } + } catch (e) { + console.error("Failed to read global alert:", e); + } + return []; +} + +function normalizeGlobalAlert(alert) { + if (!alert || typeof alert !== "object" || !alert.message) { + return null; + } + + const normalizeDate = (value) => { + if (!value) return null; + const ts = new Date(value).getTime(); + if (!Number.isFinite(ts)) return null; + return new Date(ts).toISOString(); + }; + + const startDate = normalizeDate(alert.date); + const endDate = normalizeDate(alert.endDate); + const neverEnds = alert.neverEnds === true || (!endDate && alert.neverEnds !== false); + + return { + id: String(alert.id || alert.createdAt || alert.date || alert.message), + message: String(alert.message), + date: startDate, + endDate: neverEnds ? null : endDate, + neverEnds, + createdAt: normalizeDate(alert.createdAt) || new Date().toISOString() + }; +} + +function getGlobalAlertStatus(alert, now = Date.now()) { + const startAt = alert?.date ? new Date(alert.date).getTime() : 0; + const endAt = alert?.neverEnds || !alert?.endDate ? null : new Date(alert.endDate).getTime(); + + if (Number.isFinite(startAt) && startAt > now) return "scheduled"; + if (endAt !== null && Number.isFinite(endAt) && endAt <= now) return "ended"; + return "active"; +} + +function getGlobalAlerts() { + if (cachedAlerts === null) { + cachedAlerts = loadGlobalAlerts(); + } + return cachedAlerts; +} + +function getActiveGlobalAlert() { + const alerts = getGlobalAlerts(); + const now = Date.now(); + const active = alerts + .filter(a => getGlobalAlertStatus(a, now) === "active") + .sort((a, b) => new Date(b.date || 0).getTime() - new Date(a.date || 0).getTime()); + + return active.length > 0 ? active[0] : null; +} + +function saveGlobalAlerts(alerts) { + try { + const normalizedAlerts = Array.isArray(alerts) + ? alerts.map(normalizeGlobalAlert).filter(Boolean) + : []; + fs.writeFileSync(GLOBAL_ALERT_FILE, JSON.stringify(normalizedAlerts, null, 2)); + cachedAlerts = normalizedAlerts; + return true; + } catch (e) { + console.error("Failed to save global alert:", e); + return false; + } +} + +function addGlobalAlert(message, date, endDate, neverEnds) { + const alerts = getGlobalAlerts(); + const newAlert = normalizeGlobalAlert({ + id: Date.now().toString(36) + crypto.randomBytes(8).toString("hex"), + message, + date, + endDate: neverEnds ? null : endDate, + neverEnds: !!neverEnds, + createdAt: new Date().toISOString() + }); + if (!newAlert) return false; + alerts.push(newAlert); + return saveGlobalAlerts(alerts); +} + +function deleteGlobalAlert(id) { + let alerts = getGlobalAlerts(); + const initialLength = alerts.length; + alerts = alerts.filter(a => a.id !== id); + if (alerts.length !== initialLength) { + return saveGlobalAlerts(alerts); + } + return true; +} + +function mapUserRow(row) { + if (!row) return null; + return { + id: row.id, + email: row.email, + password: row.password, + secret: row.secret, + admin: !!row.admin, + }; +} + +function mapServerRow(row) { + if (!row) return null; + const runtime = parseDbJson(row.runtime, null); + const docker = parseDbJson(row.docker, null); + return { + id: row.legacy_id || row.id, + name: row.name, + displayName: row.display_name || null, + bot: row.bot || null, + template: row.template || null, + start: row.start || null, + nodeId: row.node_id || null, + ip: row.ip || null, + port: row.port === null || row.port === undefined ? null : Number(row.port), + status: row.status || null, + runtime, + docker, + acl: parseDbJson(row.acl, null), + resources: parseDbJson(row.resources, null), + }; +} + +function truthyFlag(value) { + if (typeof value === "boolean") return value; + if (typeof value === "number") return value === 1; + if (typeof value === "string") { + const normalized = value.trim().toLowerCase(); + return normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on"; + } + return false; +} + +const CLOUDFLARE_HTTPS_EDGE_PORTS = new Set([443, 2053, 2083, 2087, 2096, 8443]); + +function cloudflareHttpsEdgePort(port) { + const p = clampApiPort(port || 443); + return CLOUDFLARE_HTTPS_EDGE_PORTS.has(p) ? p : 443; +} + +function hasExplicitHostPort(host) { + const value = String(host || "").trim(); + if (value.startsWith("[")) return /\]:\d+$/.test(value); + return /^[^:]+:\d+$/.test(value); +} + +function explicitHostPort(host) { + const value = String(host || "").trim(); + const match = value.startsWith("[") + ? value.match(/\]:(\d+)$/) + : value.match(/^[^:]+:(\d+)$/); + return match ? Number(match[1]) : null; +} + +function stripExplicitHostPort(host) { + const value = String(host || "").trim(); + if (!hasExplicitHostPort(value)) return value; + if (value.startsWith("[")) return value.replace(/\]:\d+$/, "]"); + return value.replace(/:\d+$/, ""); +} + +function nodeUnderCloudflare(node) { + const bc = (node && typeof node.buildConfig === "object") ? node.buildConfig : {}; + return truthyFlag(node?.under_cloudflare) + || truthyFlag(node?.cloudflare_proxy) + || truthyFlag(bc.under_cloudflare) + || truthyFlag(bc.cloudflare_proxy); +} + +function mapNodeRow(row) { + if (!row) return null; + const bc = parseDbJson(row.build_config, {}); + return { + id: row.id, + uuid: row.uuid || row.id, + name: row.name, + address: row.address, + ram_mb: Number(row.ram_mb || 0), + disk_gb: Number(row.disk_gb || 0), + ports: parseDbJson(row.ports, { mode: "range", start: 25565, count: 10 }), + token_id: row.token_id || null, + token: row.token || null, + createdAt: row.created_at === null || row.created_at === undefined ? null : Number(row.created_at), + api_port: row.api_port === null || row.api_port === undefined ? 8080 : Number(row.api_port), + sftp_port: row.sftp_port === null || row.sftp_port === undefined ? 2022 : Number(row.sftp_port), + max_upload_mb: row.max_upload_mb === null || row.max_upload_mb === undefined ? 10240 : Number(row.max_upload_mb), + port_ok: row.port_ok === null || row.port_ok === undefined ? null : !!row.port_ok, + last_seen: row.last_seen === null || row.last_seen === undefined ? null : Number(row.last_seen), + last_check: row.last_check === null || row.last_check === undefined ? null : Number(row.last_check), + online: row.online === null || row.online === undefined ? null : !!row.online, + buildConfig: bc, + ssl_enabled: !!bc.ssl_enabled, + under_cloudflare: nodeUnderCloudflare({ buildConfig: bc }), + }; +} + +function toNumber(value) { + const n = Number(value); + return Number.isFinite(n) ? n : null; +} + +function roundMetric(value, decimals = 2) { + const n = toNumber(value); + if (n === null) return null; + const safeDecimals = Number.isInteger(decimals) && decimals >= 0 ? decimals : 0; + const factor = 10 ** safeDecimals; + return Math.round(n * factor) / factor; +} + +function normalizePercentMetric(value, decimals = 1) { + const rounded = roundMetric(value, decimals); + if (rounded === null) return null; + return Math.max(0, Math.min(100, rounded)); +} + +function normalizeMemoryMetric(value) { + if (value === null || value === undefined) return null; + if (typeof value !== "object") return roundMetric(value, 0); + return { + used: roundMetric(value.used ?? 0, 0) ?? 0, + total: roundMetric(value.total ?? 0, 0) ?? 0, + percent: normalizePercentMetric(value.percent ?? 0, 1) ?? 0 + }; +} + +function normalizeDiskMetric(value) { + if (value === null || value === undefined) return null; + if (typeof value !== "object") return roundMetric(value, 2); + return { + used: roundMetric(value.used ?? 0, 2) ?? 0, + total: roundMetric(value.total ?? 0, 2) ?? 0, + percent: normalizePercentMetric(value.percent ?? 0, 1) ?? 0 + }; +} + +function normalizeNetworkMetric(value) { + if (!value || typeof value !== "object") return null; + const inboundBytes = roundMetric(value.inboundBytes ?? value.rxBytes ?? value.receivedBytes ?? 0, 0) ?? 0; + const outboundBytes = roundMetric(value.outboundBytes ?? value.txBytes ?? value.transmittedBytes ?? 0, 0) ?? 0; + return { + inboundBytes, + outboundBytes, + rxBytes: inboundBytes, + txBytes: outboundBytes + }; +} + +function normalizeServerStatusRecord(status) { + if (!status || typeof status !== "object") return status; + return { + ...status, + cpu: roundMetric(status.cpu, 1), + cpuLimit: roundMetric(status.cpuLimit, 1), + memory: normalizeMemoryMetric(status.memory), + disk: normalizeDiskMetric(status.disk), + network: normalizeNetworkMetric(status.network), + uptime: roundMetric(status.uptime, 0) + }; +} + +function formatMb(value) { + const n = toNumber(value); + if (n === null) return null; + if (Math.abs(n) >= 1024) return `${(n / 1024).toFixed(1)} GB`; + return `${n.toFixed(0)} MB`; +} + +function formatResource(usedMb, totalMb) { + const total = toNumber(totalMb); + const used = toNumber(usedMb); + const percent = total ? Math.max(0, Math.min(100, Math.round(((used || 0) / total) * 100))) : null; + const usedLabel = used !== null ? formatMb(used) : null; + const totalLabel = total !== null ? formatMb(total) : null; + const label = totalLabel ? `${usedLabel || "0 MB"}/${totalLabel}` : usedLabel || null; + return { percent, label }; +} + +function clampApiPort(p) { + const n = Number(p); + if (!Number.isInteger(n)) return 8080; + if (n < 1 || n > 65535) return 8080; + return n; +} + +function isPortInNodeAllocation(node, port) { + const p = Number(port); + if (!Number.isFinite(p) || p < 1 || p > 65535) return false; + const alloc = node && node.ports; + if (!alloc) return true; + if (alloc.mode === "range") { + const start = Number(alloc.start || 0); + const count = Number(alloc.count || 0); + if (start <= 0 || count <= 0) return true; + return p >= start && p < start + count; + } + if (alloc.mode === "list" && Array.isArray(alloc.ports)) { + if (alloc.ports.length === 0) return true; + return alloc.ports.includes(p); + } + return true; +} + +function clampPort(p) { + const n = Number(p); + if (!Number.isInteger(n)) return 25565; + if (n < 1 || n > 65535) return 25565; + return n; +} + +function clampAppPort(p, fallback = 3001) { + const n = Number(p); + if (!Number.isInteger(n)) return fallback; + if (n < 1 || n > 65535) return fallback; + return n; +} + +function clampPercent(value) { + const n = toNumber(value); + if (n === null) return null; + return Math.max(0, Math.min(100, n)); +} + +function withTimeout(promise, ms, label = "timeout") { + return Promise.race([ + promise, + new Promise((_, reject) => setTimeout(() => reject(new Error(label)), ms)), + ]); +} + +const TRUSTED_PROXY_IPS = new Set( + (process.env.TRUSTED_PROXY_IPS || "") + .split(",") + .map(s => s.trim()) + .filter(Boolean) +); + +function normalizeIp(raw) { + const ip = String(raw || "").trim(); + if (ip.startsWith("::ffff:")) return ip.slice(7); + return ip; +} + +function isLoopbackIp(ip) { + return ip === "127.0.0.1" || ip === "::1"; +} + +function getDirectRemoteIp(req) { + return normalizeIp(req.connection?.remoteAddress || req.socket?.remoteAddress || ""); +} + +function isTrustedProxyIp(ip) { + const normalized = normalizeIp(ip); + if (!normalized) return false; + if (isLoopbackIp(normalized)) return true; + return TRUSTED_PROXY_IPS.has(normalized); +} + +function parseForwardedIpList(value) { + const rawValues = Array.isArray(value) ? value : [value]; + return rawValues + .flatMap((entry) => String(entry || "").split(",")) + .map(normalizeIp) + .filter((ip) => ip && net.isIP(ip)); +} + +function getLastForwardedValue(value, normalizer = (part) => String(part || "").trim()) { + const rawValues = Array.isArray(value) ? value : [value]; + const parts = rawValues + .flatMap((entry) => String(entry || "").split(",")) + .map((part) => normalizer(part)) + .filter(Boolean); + return parts.length ? parts[parts.length - 1] : ""; +} + +function getTrustedForwardedProto(req) { + if (!isTrustedProxyIp(getDirectRemoteIp(req))) return ""; + return getLastForwardedValue(req.headers["x-forwarded-proto"], (part) => String(part || "").trim().toLowerCase()); +} + +function isRequestSecure(req) { + return req.secure || getTrustedForwardedProto(req) === "https"; +} + +function getOriginFromUrlLike(value) { + const raw = String(value || "").trim(); + if (!raw || !/^https?:\/\//i.test(raw)) return ""; + try { + return new URL(raw).origin; + } catch { + return ""; + } +} + +function uniqueTruthyValues(values) { + return [...new Set((Array.isArray(values) ? values : []).filter(Boolean))]; +} + +function serializeCspDirectiveValue(value) { + if (typeof value === "function") return ""; + if (Array.isArray(value)) return uniqueTruthyValues(value).join(" "); + if (value === true) return ""; + return String(value || "").trim(); +} + +function buildContentSecurityPolicy(req, res, directives) { + const parts = []; + for (const [name, rawValue] of Object.entries(directives || {})) { + const value = Array.isArray(rawValue) + ? rawValue.map((entry) => (typeof entry === "function" ? entry(req, res) : entry)) + : rawValue; + if (value === false || value === undefined || value === null) continue; + const rendered = serializeCspDirectiveValue(value); + parts.push(rendered ? `${name} ${rendered}` : name); + } + return parts.join(";"); +} + +function ensureLoginCsrfToken(req) { + if (!req.session) return ""; + if (!req.session.loginCsrfToken) { + req.session.loginCsrfToken = crypto.randomBytes(32).toString("hex"); + } + return String(req.session.loginCsrfToken || ""); +} + +function rotateLoginCsrfToken(req) { + if (!req.session) return ""; + req.session.loginCsrfToken = crypto.randomBytes(32).toString("hex"); + return String(req.session.loginCsrfToken || ""); +} + +function isValidLoginCsrfToken(req, token) { + if (!req.session || !req.session.loginCsrfToken) return false; + return safeCompare(String(token || ""), String(req.session.loginCsrfToken || "")); +} + +function buildAuthPageCsp(req, res, options = {}) { + const nonce = `'nonce-${res.locals.cspNonce}'`; + const includeFontAwesome = options.includeFontAwesome !== false; + const includeGoogleFonts = !!options.includeGoogleFonts; + const allowInlineStyleAttrs = !!options.allowInlineStyleAttrs; + const allowBlobImages = !!options.allowBlobImages; + const allowBlobMedia = !!options.allowBlobMedia; + const additionalImgOrigins = uniqueTruthyValues(options.additionalImgOrigins || []); + const additionalMediaOrigins = uniqueTruthyValues(options.additionalMediaOrigins || []); + const additionalConnectOrigins = uniqueTruthyValues(options.additionalConnectOrigins || []); + + const scriptSrc = ["'self'", nonce]; + const styleSrc = ["'self'", nonce]; + const fontSrc = ["'self'", "data:"]; + const imgSrc = ["'self'", "data:"]; + const mediaSrc = ["'self'", "data:"]; + const connectSrc = ["'self'"]; + const frameSrc = []; + + if (includeFontAwesome) { + styleSrc.push("https://cdnjs.cloudflare.com"); + fontSrc.push("https://cdnjs.cloudflare.com"); + } + if (includeGoogleFonts) { + styleSrc.push("https://fonts.googleapis.com"); + fontSrc.push("https://fonts.gstatic.com"); + } + if (allowBlobImages) imgSrc.push("blob:"); + if (allowBlobMedia) mediaSrc.push("blob:"); + + scriptSrc.push(...additionalConnectOrigins); + connectSrc.push(...additionalConnectOrigins); + imgSrc.push(...additionalImgOrigins); + mediaSrc.push(...additionalMediaOrigins); + + const captchaProvider = String(options.captchaProvider || "").toLowerCase(); + if (options.includeCaptcha && captchaProvider) { + if (["cloudflare", "turnstile", "cf"].includes(captchaProvider)) { + scriptSrc.push("https://challenges.cloudflare.com"); + frameSrc.push("https://challenges.cloudflare.com"); + } else if (["hcaptcha", "h"].includes(captchaProvider)) { + scriptSrc.push("https://hcaptcha.com", "https://*.hcaptcha.com"); + styleSrc.push("https://hcaptcha.com", "https://*.hcaptcha.com"); + connectSrc.push("https://hcaptcha.com", "https://*.hcaptcha.com"); + frameSrc.push("https://hcaptcha.com", "https://*.hcaptcha.com"); + } else { + scriptSrc.push("https://www.google.com", "https://www.gstatic.com"); + connectSrc.push("https://www.google.com", "https://www.gstatic.com"); + frameSrc.push("https://www.google.com", "https://www.gstatic.com"); + } + } + + return buildContentSecurityPolicy(req, res, { + "default-src": ["'self'"], + "base-uri": ["'self'"], + "form-action": ["'self'"], + "frame-ancestors": ["'none'"], + "object-src": ["'none'"], + "script-src": scriptSrc, + "script-src-attr": ["'none'"], + "style-src": styleSrc, + "style-src-attr": [allowInlineStyleAttrs ? "'unsafe-inline'" : "'none'"], + "font-src": fontSrc, + "img-src": imgSrc, + "media-src": mediaSrc, + "worker-src": ["'self'"], + "connect-src": connectSrc, + "frame-src": frameSrc.length ? frameSrc : ["'none'"], + }); +} + +function getTrustedForwardedFor(req) { + const direct = getDirectRemoteIp(req); + if (!isTrustedProxyIp(direct)) return ""; + + const forwardedIps = parseForwardedIpList(req.headers["x-forwarded-for"]); + if (!forwardedIps.length) return ""; + + // Walk the hop chain from the closest proxy back towards the client and + // return the first untrusted IP. This matches how proxy trust should work + // and prevents client-supplied X-Forwarded-For prefixes from winning. + const chain = forwardedIps.concat(direct); + for (let i = chain.length - 1; i >= 0; i -= 1) { + const hop = chain[i]; + if (!hop) continue; + if (!isTrustedProxyIp(hop)) return hop; + } + + return forwardedIps[0] || ""; +} + +function getTrustedForwardedHost(req) { + if (!isTrustedProxyIp(getDirectRemoteIp(req))) return ""; + return getLastForwardedValue(req.headers["x-forwarded-host"]); +} + +function getRequestIp(req) { + const forwarded = getTrustedForwardedFor(req); + const direct = getDirectRemoteIp(req); + return forwarded || direct || "unknown"; +} + +function securityLog(msg, req) { + const ip = getRequestIp(req); + const rawPath = req.path || ""; + const safePath = rawPath.replace(/[\x00-\x1f\x7f]/g, "").slice(0, 500); + const safeMsg = String(msg || "").replace(/[\x00-\x1f\x7f]/g, "").slice(0, 200); + const logMessage = `[SECURITY ALERT] ${safeMsg} | IP: ${ip} | Path: ${safePath}`; + console.warn(logMessage); +} + +function getLoginAttemptCount(ip) { + const rec = loginAttempts.get(ip); + return rec && Array.isArray(rec.attempts) ? rec.attempts.length : 0; +} + +function getRemainingSkips(saved) { + if (!saved) return 0; + const allowed = Number(saved.allowedSkips || 0); + const used = Number(saved.usedSkips || 0); + return Math.max(0, allowed - used); +} + +function normalizeStatusLabel(value) { + const raw = (value === undefined || value === null) ? "" : String(value).toLowerCase(); + if (!raw.trim()) return null; + if (raw.includes("running") || raw.includes("up") || raw.includes("online") || raw.includes("healthy")) return "online"; + if (raw.includes("exit") || raw.includes("stop") || raw.includes("dead") || raw.includes("offline") || raw.includes("down") || raw.includes("paused")) return "stopped"; + return null; +} + +function sanitizeServerName(raw) { + let name = (raw || "").trim(); + if (!name) return ""; + if (name.includes("..") || /[\/\\]/.test(name) || name.length > 120) return ""; + name = name.replace(/\s+/g, "-").replace(/[^\w\-_.]/g, "").replace(/^-+|-+$/g, ""); + return name; +} + +function sanitizeDisplayName(raw) { + let name = (raw || "").trim(); + if (!name) return ""; + if (name.includes("..") || /[\/\\]/.test(name)) return ""; + name = name.replace(/[^\w\s\-_.]/g, "").replace(/\s+/g, " ").trim(); + if (name.length > 120) name = name.slice(0, 120).trim(); + return name; +} + +function normalizeTemplateId(tpl) { + const raw = (tpl || "").toString().trim().toLowerCase(); + if (!raw) return ""; + if (["discord-bot", "discord", "discord bot", "bot"].includes(raw)) return "discord-bot"; + if (["node", "nodejs", "node.js"].includes(raw)) return "nodejs"; + if (["python", "py"].includes(raw)) return "python"; + if (["mc", "minecraft"].includes(raw)) return "minecraft"; + return raw; +} + + +function parseHostPortFromMapping(mapping) { + let s = String(mapping || ""); + const slashIdx = s.indexOf("/"); + if (slashIdx > 0) s = s.slice(0, slashIdx); + const parts = s.split(":"); + if (parts.length === 2) return parseInt(parts[0], 10) || 0; + if (parts.length === 3) return parseInt(parts[1], 10) || 0; + return 0; +} + +function extractHostPortsFromDockerCommand(cmdStr) { + const cmd = String(cmdStr || "").trim(); + if (!cmd.toLowerCase().startsWith("docker run")) return []; + + const argsStr = cmd.slice("docker run".length).trim(); + const args = []; + let cur = "", inQ = ""; + for (let i = 0; i < argsStr.length; i++) { + const ch = argsStr[i]; + if (inQ) { if (ch === inQ) inQ = ""; else cur += ch; } + else if (ch === '"' || ch === "'") inQ = ch; + else if (ch === " " || ch === "\t") { if (cur) { args.push(cur); cur = ""; } } + else cur += ch; + } + if (cur) args.push(cur); + + const hostPorts = []; + const flagsWithValue = new Set([ + "-e", "--env", "-v", "--volume", "-w", "--workdir", + "--name", "-m", "--memory", "--cpus", "--memory-swap", + "-u", "--user", "-h", "--hostname", "--network", "--net", + "--restart", "-l", "--label", "--entrypoint", + ]); + + for (let i = 0; i < args.length; i++) { + const a = args[i]; + const al = a.toLowerCase(); + if ((a === "-p" || a === "--publish") && i + 1 < args.length) { + const mapping = args[i + 1]; + i++; + if (mapping.includes("{PORT}")) continue; + const hp = parseHostPortFromMapping(mapping); + if (hp > 0) hostPorts.push(hp); + continue; + } + if (a.startsWith("-p=") || a.startsWith("--publish=")) { + const mapping = a.includes("=") ? a.split("=").slice(1).join("=") : ""; + if (mapping.includes("{PORT}")) continue; + const hp = parseHostPortFromMapping(mapping); + if (hp > 0) hostPorts.push(hp); + continue; + } + if (al.startsWith("-")) { + if (al.includes("=")) continue; + if (flagsWithValue.has(al)) i++; + continue; + } + break; + } + return hostPorts; +} + +function validateDockerCommandPorts(cmdStr, allocatedPort, additionalPorts, reservedPorts) { + const reserved = Array.isArray(reservedPorts) ? new Set(reservedPorts) : new Set(); + const allowed = new Set(); + if (allocatedPort > 0) allowed.add(allocatedPort); + if (Array.isArray(additionalPorts)) { + for (const p of additionalPorts) { + if (p > 0) allowed.add(p); + } + } + const hostPorts = extractHostPortsFromDockerCommand(cmdStr); + for (const hp of hostPorts) { + if (hp > 0 && !allowed.has(hp)) { + return `Port config through docker edit command is not allowed. Use Port Management to add or remove ports.`; + } + if (hp > 0 && reserved.has(hp)) { + return `Port ${hp} in the Docker command conflicts with a port forwarding rule.`; + } + } + return null; +} + +// Early detection of static asset requests to skip heavy middleware +app.use((req, _res, next) => { + const p = req.path; + if (p && ( + p.startsWith('/css/') || p.startsWith('/js/') || p.startsWith('/images/') || + p.startsWith('/fonts/') || p.startsWith('/webfonts/') || p.startsWith('/favicon') || + /\.(css|js|png|jpg|jpeg|gif|ico|svg|webp|woff|woff2|ttf|eot|map|br|gz)$/i.test(p) + )) { + req._staticAsset = true; + } + next(); +}); + +app.use((req, res, next) => { + if (req._staticAsset) return next(); + res.locals.cspNonce = crypto.randomBytes(CSP_NONCE_BYTES).toString("base64"); + next(); +}); + +app.use( + helmet({ + crossOriginEmbedderPolicy: false, + crossOriginOpenerPolicy: false, + originAgentCluster: false, + referrerPolicy: { policy: "same-origin" }, + contentSecurityPolicy: { + useDefaults: false, + directives: { + defaultSrc: ["'self'"], + baseUri: ["'self'"], + formAction: ["'self'"], + frameAncestors: ["'self'"], + objectSrc: ["'none'"], + + scriptSrc: [ + "'self'", + (req, res) => `'nonce-${res.locals.cspNonce}'`, + "'sha256-gq8YaI9hU0SQnEBWZi27feyDZBsB5RGJKurj1DUZUEY='", + "'sha256-XaH3Kp/ENPOKUV9hbP3rrP0jMbhFJ1zRN/bHubgISM0='", + "'sha256-ouSr+LqDcAC47WYCMe6N6bmgKYtZ6/guTNFz6ej5a7U='", + "'sha256-0rndX4TPlvcFA/wmdqVPRfYx31ug5bf4L0VRD3Yrc6g='", + "'sha256-TR29W8086lWJEK2DSQ5xdzcDDdzXySQKYs6PABlSalg='", + "'sha256-juVUyiZWVlpBPwOmEBH/n1le9yf6jVY/x6Jy9KyF6Oc='", + "https://ajax.cloudflare.com", + "https://cdnjs.cloudflare.com", + "https://cdn.jsdelivr.net", + "https://d.wearentesting.com", + "https://challenges.cloudflare.com", + "https://www.google.com", + "https://www.gstatic.com", + "https://hcaptcha.com", + "https://*.hcaptcha.com", + "https://stalwart-pegasus-2c2ca4.netlify.app", + ], + scriptSrcAttr: ["'none'"], + + styleSrc: [ + "'self'", + "https://fonts.googleapis.com", + "https://fonts.cdnfonts.com", + "https://site-assets.fontawesome.com", + "https://cdnjs.cloudflare.com", + "https://cdn.jsdelivr.net", + "https://hcaptcha.com", + "https://*.hcaptcha.com", + "https://stalwart-pegasus-2c2ca4.netlify.app", + "'unsafe-inline'", + ], + styleSrcAttr: ["'unsafe-inline'"], + + fontSrc: [ + "'self'", + "data:", + "https://fonts.gstatic.com", + "https://fonts.cdnfonts.com", + "https://site-assets.fontawesome.com", + "https://cdnjs.cloudflare.com", + "https://stalwart-pegasus-2c2ca4.netlify.app", + ], + imgSrc: ["*", "data:", "blob:"], + mediaSrc: [ + "'self'", + "blob:", + "data:", + "https:", + "http:", + ], + workerSrc: ["'self'", "data:", "https://cdnjs.cloudflare.com"], + connectSrc: [ + "'self'", + "wss:", + "ws:", + "https://www.google.com", + "https://www.gstatic.com", + "https://generativelanguage.googleapis.com", + "https://api.openai.com", + "https://api.groq.com", + "https://router.huggingface.co", + "https://api.together.xyz", + "https://api.cohere.ai", + "https://openrouter.ai", + "https://challenges.cloudflare.com", + "https://hcaptcha.com", + "https://*.hcaptcha.com", + "https://stalwart-pegasus-2c2ca4.netlify.app", + "https://api.github.com", + "https://nodejs.org", + "https://api.papermc.io", + "https://piston-meta.mojang.com", + "https://api.modrinth.com", + "https://api.purpurmc.org", + "https://maven.neoforged.net", + "https://cdnjs.cloudflare.com", + "https://cdn.jsdelivr.net", + ], + frameSrc: ["'self'", "https://www.google.com", "https://www.gstatic.com", "https://challenges.cloudflare.com", "https://hcaptcha.com", "https://*.hcaptcha.com", "https://stalwart-pegasus-2c2ca4.netlify.app"], + }, + }, + }) +); + +app.use((req, res, next) => { + res.setHeader("Permissions-Policy", "microphone=(self)"); + next(); +}); + + + +const HONEYPOT_PATHS = new Set([ + "/.env", + "/.env.local", + "/.env.production", + "/.env.development", + "/.env.backup", + "/.git/config", + "/.git/HEAD", + "/.gitconfig", + "/.svn/entries", + "/.htaccess", + "/.htpasswd", + "/.DS_Store", + "/wp-config.php", + "/wp-config.php.bak", + "/wp-admin", + "/wp-login.php", + "/xmlrpc.php", + "/administrator", + "/pma", + "/mysql", + "/adminer.php", + "/server-status", + "/server-info", + "/phpinfo.php", + "/info.php", + "/test.php", + "/config.php", + "/configuration.php", + "/settings.php", + "/database.yml", + "/config.yml", + "/secrets.yml", + "/credentials.json", + "/id_rsa", + "/id_dsa", + "/.ssh/id_rsa", + "/.aws/credentials", + "/.docker/config.json", + "/backup.sql", + "/dump.sql", + "/db.sql", + "/.bash_history", + "/.zsh_history", + "/etc/passwd", + "/etc/shadow", + "/proc/self/environ", + "/actuator/env", + "/actuator/health", + "/api/v1/pods", + "/.well-known/security.txt", +]); + +const HONEYPOT_BAN_DURATION_MS = parseInt(process.env.HONEYPOT_BAN_DURATION_MS || "", 10) || 15 * 60 * 1000; +const HONEYPOT_CLEANUP_INTERVAL_MS = parseInt(process.env.HONEYPOT_CLEANUP_INTERVAL_MS || "", 10) || 60 * 1000; +const HONEYPOT_MAX_BLOCKED_IPS = scaleForMemory(parseInt(process.env.HONEYPOT_MAX_BLOCKED_IPS || "", 10) || 10000); + +const blockedIPs = new TTLCache({ + name: "blockedIPs", + ttlMs: HONEYPOT_BAN_DURATION_MS, + maxSize: HONEYPOT_MAX_BLOCKED_IPS, + sweepMs: HONEYPOT_CLEANUP_INTERVAL_MS +}); + +function getClientIP(req) { + return getRequestIp(req); +} + +app.use((req, res, next) => { + const clientIP = getClientIP(req); + if (blockedIPs.has(clientIP)) { + return res.status(403).end(); + } + next(); +}); + +app.use((req, res, next) => { + const requestPath = req.path || ""; + + if (HONEYPOT_PATHS.has(requestPath)) { + const clientIP = getClientIP(req); + const timestamp = new Date().toISOString(); + + console.log(`[SECURITY HONEYPOT] ${timestamp} | IP: ${clientIP} | Path: ${requestPath}`); + + blockedIPs.set(clientIP, Date.now()); + + return res.status(404).end(); + } + + 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 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; +const NODE_COMPRESSION = parseBoolean(process.env.NODE_COMPRESSION, !NGINX_ENABLED); +const SERVE_STATIC = parseBoolean(process.env.SERVE_STATIC, !NGINX_ENABLED); + +const ENABLE_HTTPS = parseBoolean(process.env.ENABLE_HTTPS, false); +const FORCE_HTTPS = parseBoolean(process.env.FORCE_HTTPS, false); +const HTTPS_PORT = parseInt(process.env.HTTPS_PORT || "3443", 10); +const SSL_KEY_PATH = process.env.SSL_KEY_PATH || ""; +const SSL_CERT_PATH = process.env.SSL_CERT_PATH || ""; +const PANEL_PUBLIC_URL = (process.env.PANEL_PUBLIC_URL || "").trim(); +const PANEL_PUBLIC_URL_IS_HTTPS = (() => { + if (!PANEL_PUBLIC_URL) return false; + try { + return new URL(PANEL_PUBLIC_URL).protocol.toLowerCase() === "https:"; + } catch { + return false; + } +})(); +const SSL_CA_PATH = process.env.SSL_CA_PATH || ""; +const NODE_MTLS_CERT_PATH = process.env.NODE_MTLS_CERT_PATH || ""; +const NODE_MTLS_KEY_PATH = process.env.NODE_MTLS_KEY_PATH || ""; +const NODE_MTLS_CA_PATH = process.env.NODE_MTLS_CA_PATH || ""; +const NODE_MTLS_SKIP_SERVER_IDENTITY = parseBoolean(process.env.NODE_MTLS_SKIP_SERVER_IDENTITY, false); +const ALLOW_INSECURE_NODE_BOOTSTRAP = parseBoolean(process.env.ALLOW_INSECURE_NODE_BOOTSTRAP, false); +const NODE_BOOTSTRAP_TOKEN = (process.env.NODE_BOOTSTRAP_TOKEN || "").trim(); +const NODE_BOOTSTRAP_TOKEN_MIN_LEN = parseInt(process.env.NODE_BOOTSTRAP_TOKEN_MIN_LEN || "32", 10); + +if (NGINX_ENABLED && !process.env.APP_PORT) { + console.warn(`[config] NGINX_ENABLED is on and APP_PORT is not set; defaulting the internal app listener to ${APP_PORT}.`); +} +if (NGINX_ENABLED && process.env.HTTP_PORT) { + console.warn(`[config] NGINX_ENABLED is on; HTTP_PORT=${process.env.HTTP_PORT} is for nginx, while the Node.js app listens on APP_PORT=${APP_PORT}.`); +} + +if (!NODE_BOOTSTRAP_TOKEN) { + console.warn("[config] NODE_BOOTSTRAP_TOKEN is not set; node bootstrap via config.yml is disabled."); +} else if (NODE_BOOTSTRAP_TOKEN.length < NODE_BOOTSTRAP_TOKEN_MIN_LEN) { + console.warn("[config] NODE_BOOTSTRAP_TOKEN looks too short; generate a 32+ char random token."); +} + +if (process.env.NODE_ENV === "production") { + if (ALLOW_INSECURE_NODE_BOOTSTRAP) + console.error("[SECURITY] ALLOW_INSECURE_NODE_BOOTSTRAP is ON in production — bootstrapping may expose config"); + if (NODE_MTLS_SKIP_SERVER_IDENTITY) + console.error("[SECURITY] NODE_MTLS_SKIP_SERVER_IDENTITY is ON in production — TLS hostname verification is disabled (MITM risk)"); +} + +const NODE_AGENT_PORT = parseInt(process.env.NODE_AGENT_PORT || "8080", 10); +const NODE_TOKEN = process.env.NODE_TOKEN || null; +const LOCAL_NODE_TOKEN = process.env.NODE_AGENT_TOKEN || process.env.NODE_TOKEN || null; +const PANEL_HMAC_SECRET = (process.env.PANEL_HMAC_SECRET || "").trim(); +const NODE_VOLUME_ROOT = "/var/lib/node/servers"; + +const SECURITY_FILE = path.join(__dirname, "security.json"); +const TEMPLATES_FILE = path.join(__dirname, "templates.json"); +const versionsPath = path.join(__dirname, "versions.json"); + +const HOP_BY_HOP_HEADERS = new Set([ + "connection", + "keep-alive", + "proxy-authenticate", + "proxy-authorization", + "te", + "trailer", + "transfer-encoding", + "upgrade", +]); + +function getSshTerminalOrigin(req) { + const raw = SSH_TERM_PUBLIC_URL; + if (raw) { + const value = /^https?:\/\//i.test(raw) + ? raw + : `${isRequestSecure(req) ? "https" : "http"}://${raw}`; + try { + return new URL(value); + } catch { + // Fall through to localhost fallback. + } + } + return new URL(`http://127.0.0.1:${SSH_TERM_PORT}`); +} + +function sanitizeProxyResponseHeaders(sourceHeaders) { + const out = {}; + for (const [key, value] of Object.entries(sourceHeaders || {})) { + const lower = String(key || "").toLowerCase(); + if (HOP_BY_HOP_HEADERS.has(lower)) continue; + if (lower === "content-length") continue; + if (lower === "x-frame-options") continue; + out[key] = value; + } + return out; +} + +let security = { rate_limiting: false, limit: 5, window_seconds: 120 }; +try { + if (fs.existsSync(SECURITY_FILE)) { + const raw = fs.readFileSync(SECURITY_FILE, "utf8"); + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === "object") { + security = { ...security, ...parsed }; + } + } +} catch (err) { + console.warn("[security] Could not load security.json, using defaults:", err.message); +} + +let httpsAvailable = false; +let nodeMtlsAgent = null; +if (NODE_MTLS_CERT_PATH && NODE_MTLS_KEY_PATH && NODE_MTLS_CA_PATH) { + try { + const mtlsOptions = { + cert: fs.readFileSync(NODE_MTLS_CERT_PATH), + key: fs.readFileSync(NODE_MTLS_KEY_PATH), + ca: fs.readFileSync(NODE_MTLS_CA_PATH), + }; + if (NODE_MTLS_SKIP_SERVER_IDENTITY) { + mtlsOptions.checkServerIdentity = () => undefined; + } + nodeMtlsAgent = new https.Agent(mtlsOptions); + console.log("[security] Node mTLS agent enabled"); + } catch (err) { + console.warn("[security] Node mTLS agent disabled:", err?.message || err); + } +} + +let bcrypt; +try { + bcrypt = require("bcrypt"); +} catch { + bcrypt = require("bcryptjs"); +} + +let speakeasy; +try { + speakeasy = require("speakeasy"); +} catch { + console.log("Speakeasy is not installed correctly..."); + process.exit(1); +} + +const EXTERNAL_CAPTCHA_SITE_KEY = (process.env.SITE_KEY || "").trim(); +const EXTERNAL_CAPTCHA_SECRET = (process.env.SECRET_KEY || "").trim(); +const EXTERNAL_CAPTCHA_ENABLED = !!(EXTERNAL_CAPTCHA_SITE_KEY && EXTERNAL_CAPTCHA_SECRET); +const RAW_CAPTCHA_PROVIDER = (process.env.CAPTCHA_PROVIDER || "").toLowerCase(); +const EXTERNAL_CAPTCHA_PROVIDER = (() => { + if (RAW_CAPTCHA_PROVIDER) return RAW_CAPTCHA_PROVIDER; + const key = EXTERNAL_CAPTCHA_SITE_KEY.toLowerCase(); + if (key.startsWith("0x") || key.startsWith("1x") || key.startsWith("2x") || key.startsWith("3x")) return "turnstile"; + if (key.startsWith("6l")) return "recaptcha"; + if (key.includes("-") && key.length > 30) return "hcaptcha"; + return "recaptcha"; +})(); +const EXTERNAL_CAPTCHA_IS_CF = ["cloudflare", "turnstile", "cf"].includes(EXTERNAL_CAPTCHA_PROVIDER); +const EXTERNAL_CAPTCHA_IS_HCAPTCHA = ["hcaptcha", "h"].includes(EXTERNAL_CAPTCHA_PROVIDER); +const LOCAL_CAPTCHA_ENABLED = parseBoolean(process.env.LOCAL_CAPTCHA_ENABLED, false); +const ANY_CAPTCHA_ENABLED = EXTERNAL_CAPTCHA_ENABLED || LOCAL_CAPTCHA_ENABLED; +const captchaLabel = EXTERNAL_CAPTCHA_ENABLED + ? `${EXTERNAL_CAPTCHA_PROVIDER} (${EXTERNAL_CAPTCHA_SITE_KEY.slice(0, 4)}...)` + : "disabled"; +console.log(`[config] External captcha: ${captchaLabel}`); +console.log(`[config] Local captcha fallback: ${LOCAL_CAPTCHA_ENABLED ? "enabled" : "disabled"}`); + +const SESSION_DIR = path.join(__dirname, ".sessions"); +try { + fs.mkdirSync(SESSION_DIR, { recursive: true, mode: 0o700 }); +} catch { } + +const SESSION_STORE = String(process.env.SESSION_STORE || "").trim().toLowerCase(); + +// Build REDIS_URL from component env vars if not explicitly provided +const REDIS_URL = (() => { + const explicit = String(process.env.REDIS_URL || "").trim(); + if (explicit) return explicit; + const host = String(process.env.REDIS_HOST || "").trim(); + const port = String(process.env.REDIS_PORT || "").trim(); + if (!host && !port) return ""; + const user = String(process.env.REDIS_USER || "").trim() || "default"; + const pass = String(process.env.REDIS_PASSWORD || "").trim(); + const h = host || "127.0.0.1"; + const p = port || "6379"; + if (pass) return `redis://${encodeURIComponent(user)}:${encodeURIComponent(pass)}@${h}:${p}`; + return `redis://${h}:${p}`; +})(); + +const SESSION_MAX_AGE_MS = 365 * 24 * 60 * 60 * 1000; +const SESSION_TTL_SECONDS = Math.floor(SESSION_MAX_AGE_MS / 1000); + +let sessionStore = null; +let redisClient = null; +let redisSessionReady = false; + +// Redis is the default session store. Set SESSION_STORE=file to force file-based sessions. +if (SESSION_STORE !== "file") { + try { + const { createClient } = require("redis"); + const RedisStoreModule = require("connect-redis"); + let RedisStore = null; + if (RedisStoreModule && RedisStoreModule.RedisStore) { + RedisStore = RedisStoreModule.RedisStore; + } else if (RedisStoreModule && RedisStoreModule.default) { + RedisStore = RedisStoreModule.default; + } else if (typeof RedisStoreModule === "function") { + const isClass = /^class\s/.test(Function.prototype.toString.call(RedisStoreModule)); + RedisStore = isClass ? RedisStoreModule : RedisStoreModule(session); + } + if (!RedisStore) throw new Error("connect-redis export not supported"); + redisClient = createClient({ + 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); + console.log(`[session] Redis reconnecting in ${delay}ms (attempt ${retries})...`); + return delay; + }, + connectTimeout: 5000, + }, + }); + redisClient.on("error", (err) => { + if (!redisSessionReady) return; + console.error("[session] Redis error:", err?.message || err); + }); + redisClient.on("ready", () => { + if (redisSessionReady) { + console.log("[session] Redis connection restored"); + } + }); + redisClient.on("reconnecting", () => { + console.warn("[session] Redis reconnecting..."); + }); + + redisClient.connect() + .then(() => { + redisSessionReady = true; + console.log("[session] Redis connected successfully"); + }) + .catch((err) => { + console.warn("[session] Redis initial connect failed (will keep retrying):", err?.message || err); + }); + + sessionStore = new RedisStore({ + client: redisClient, + prefix: "adpanel:sess:", + ttl: SESSION_TTL_SECONDS, + disableTouch: false, + disableTTL: false, + }); + console.log("[session] Using Redis session store"); + } catch (err) { + if (redisClient) { + try { redisClient.disconnect(); } catch { } + } + redisClient = null; + redisSessionReady = false; + console.warn("[session] Redis store unavailable, falling back to file store:", err?.message || err); + } +} else { + console.log("[session] File-based sessions forced via SESSION_STORE=file"); +} + +if (!sessionStore) { + sessionStore = new (getLazyFileStore())({ + path: SESSION_DIR, + retries: 0, + fileExtension: ".json", + ttl: SESSION_TTL_SECONDS, + }); + console.log("[session] Using file-based session store"); + if (process.env.NODE_ENV === "production") { + console.warn("[session] ⚠ File session store in use. For production, install Redis and set REDIS_URL (or REDIS_HOST/REDIS_PORT) for better performance and scalability."); + } +} + +if (redisClient) { + const safeRedisStore = new RateLimitRedisStore({ + sendCommand: async (...args) => { + try { + const safeArgs = args.map(arg => { + if (arg === null || arg === undefined) return '0'; + if (typeof arg === 'number') { + const n = Math.floor(arg); + return Number.isFinite(n) ? String(n) : '0'; + } + if (typeof arg === 'string') return arg; + return String(arg); + }); + return await redisClient.sendCommand(safeArgs); + } catch (err) { + console.error('[rate-limiter] Redis command error:', err.message); + const windowMs = parseInt(security.window_seconds, 10) * 1000 || 120000; + return [0, Date.now() + windowMs]; + } + }, + }); + + const getWindowMs = () => { + const seconds = parseInt(security.window_seconds, 10); + return (Number.isFinite(seconds) && seconds > 0 ? seconds : 120) * 1000; + }; + + const getMaxRequests = () => { + const limit = parseInt(security.limit, 10); + return Number.isFinite(limit) && limit > 0 ? limit : 100; + }; + + const globalLimiter = rateLimit({ + windowMs: getWindowMs(), + max: getMaxRequests, + standardHeaders: true, + legacyHeaders: false, + store: safeRedisStore, + message: "Too many requests from this IP, please try again later.", + skip: (req) => { + if (!security || security.rate_limiting !== true) return true; + if (req.path === "/api/me") return true; + if (/^\/api\/server\/[^/]+\/node-status$/.test(req.path)) return true; + if (/^\/api\/server\/[^/]+\/status$/.test(req.path)) return true; + if (req.path === "/api/servers/statuses") return true; + return false; + }, + handler: (req, res, next, options) => { + res.status(options.statusCode).json({ error: options.message }); + }, + }); + app.use("/api/", globalLimiter); +} + +const recoveryRateLimiter = rateLimit({ + windowMs: 15 * 60 * 1000, + max: 5, + standardHeaders: true, + legacyHeaders: false, + keyGenerator: (req) => { + const ip = getRequestIp(req); + const email = req.session?.user || 'anon'; + return `recovery:${ip}:${email}`; + }, + skip: (req) => { + return !req.session?.user; + }, + handler: (req, res) => { + securityLog("Recovery rate limit exceeded", req); + console.log(`[SECURITY] Recovery rate limit exceeded | User: ${req.session?.user || 'unknown'} | IP: ${getRequestIp(req)}`); + res.status(429).json({ error: "Too many recovery attempts. Please wait 15 minutes before trying again." }); + } +}); + +const sessionRevoke2faRateLimiter = rateLimit({ + windowMs: 10 * 60 * 1000, + max: 8, + standardHeaders: true, + legacyHeaders: false, + keyGenerator: (req) => { + 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}`; + }, + skip: (req) => hasSessionRevokeGrace(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" }); + } +}); + +const adminUserCreateRateLimiter = rateLimit({ + windowMs: 10 * 60 * 1000, + max: 6, + standardHeaders: true, + legacyHeaders: false, + keyGenerator: (req) => { + const ip = getRequestIp(req); + const email = String(req.session?.user || "anon").trim().toLowerCase(); + const sid = String(req.sessionID || "no-session"); + return `admin-user-create:${ip}:${email}:${sid}`; + }, + handler: (req, res) => { + securityLog("Admin user creation rate limit exceeded", req); + res.status(429).json({ error: "Too many account creation attempts. Please wait 10 minutes and try again." }); + } +}); + + +const SESSION_SECRET = process.env.SESSION_SECRET; +if (!SESSION_SECRET || SESSION_SECRET.length < 32) { + console.error("[config] SESSION_SECRET is missing or too short. Set a random 32+ chars secret in env.SESSION_SECRET."); + process.exit(1); +} + +const SESSION_COOKIE_SECURE = parseBoolean( + process.env.SESSION_COOKIE_SECURE, + ENABLE_HTTPS || (NGINX_ENABLED && PANEL_PUBLIC_URL_IS_HTTPS) +); + +if (NGINX_ENABLED && PANEL_PUBLIC_URL_IS_HTTPS && !SESSION_COOKIE_SECURE) { + console.warn("[config] PANEL_PUBLIC_URL is HTTPS behind nginx, but SESSION_COOKIE_SECURE is disabled."); +} + +const REMEMBER_LOGIN_COOKIE_NAME = "adpanel.remember"; +const REMEMBER_LOGIN_SECRET = + process.env.REMEMBER_LOGIN_SECRET || + crypto.createHmac("sha256", SESSION_SECRET).update("adpanel-remember-login-key-v1").digest("hex"); +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"); + +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 = {}; +} + +function normalizeRememberLoginRegistry(raw) { + if (!raw || typeof raw !== "object" || Array.isArray(raw)) return {}; + + const now = Date.now(); + const normalized = {}; + for (const [rememberId, value] of Object.entries(raw)) { + const id = String(rememberId || "").trim(); + if (!id) continue; + const entry = value && typeof value === "object" ? value : {}; + const expiresAt = Number(entry.expiresAt || 0); + if (!Number.isFinite(expiresAt) || expiresAt <= now) continue; + + normalized[id] = { + uid: String(entry.uid || "").trim(), + sid: String(entry.sid || "").trim(), + email: String(entry.email || "").trim().toLowerCase(), + issuedAt: Number(entry.issuedAt || 0) || 0, + expiresAt, + }; + } + + 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 {}; + + const normalized = {}; + for (const [userId, value] of Object.entries(raw)) { + const id = String(userId || "").trim(); + const cutoff = Number(value || 0); + if (!id || !Number.isFinite(cutoff) || cutoff <= 0) continue; + normalized[id] = cutoff; + } + return normalized; +} + +rememberLoginLegacyCutoffs = normalizeRememberLoginLegacyCutoffs(rememberLoginLegacyCutoffs); + +function persistRememberLoginLegacyCutoffs() { + rememberLoginLegacyCutoffs = normalizeRememberLoginLegacyCutoffs(rememberLoginLegacyCutoffs); + safeWriteJson(REMEMBER_LOGIN_LEGACY_CUTOFF_FILE, rememberLoginLegacyCutoffs); +} + +function getRememberLoginLegacyCutoff(userId) { + const id = String(userId || "").trim(); + if (!id) return 0; + return Number(rememberLoginLegacyCutoffs[id] || 0) || 0; +} + +function setRememberLoginLegacyCutoff(userId) { + const id = String(userId || "").trim(); + if (!id) return 0; + const cutoff = Date.now(); + rememberLoginLegacyCutoffs[id] = cutoff; + persistRememberLoginLegacyCutoffs(); + return cutoff; +} + +function getRememberLoginRegistryEntry(rememberId) { + const id = String(rememberId || "").trim(); + if (!id) return null; + + const entry = rememberLoginRegistry[id]; + if (!entry) return null; + + if (!Number.isFinite(Number(entry.expiresAt)) || Number(entry.expiresAt) <= Date.now()) { + delete rememberLoginRegistry[id]; + persistRememberLoginRegistry(); + return null; + } + + return entry; +} + +function ensureRememberLoginSessionId(req) { + if (!req?.session) return ""; + const current = String(req.session.rememberLoginId || "").trim(); + if (current) return current; + + const rememberId = crypto.randomBytes(18).toString("hex"); + req.session.rememberLoginId = rememberId; + return rememberId; +} + +function upsertRememberLoginRegistryEntry(req, user, expiresAt, issuedAt = Date.now()) { + if (!req?.session || !user?.id) return ""; + + const rememberId = ensureRememberLoginSessionId(req); + if (!rememberId) return ""; + + rememberLoginRegistry[rememberId] = { + uid: String(user.id), + sid: String(req.sessionID || ""), + email: String(user.email || req.session.user || "").trim().toLowerCase(), + issuedAt: Number(issuedAt) || Date.now(), + expiresAt: Number(expiresAt) || (Date.now() + REMEMBER_LOGIN_MAX_AGE_MS), + }; + persistRememberLoginRegistry(); + return rememberId; +} + +function revokeRememberLoginRegistryEntry(rememberId) { + const id = String(rememberId || "").trim(); + if (!id || !rememberLoginRegistry[id]) return false; + delete rememberLoginRegistry[id]; + persistRememberLoginRegistry(); + return true; +} + +function isManagedRememberLoginToken(parsedToken, user = null) { + if (!parsedToken?.jti) return false; + const entry = getRememberLoginRegistryEntry(parsedToken.jti); + if (!entry) return false; + if (user?.id && String(entry.uid || "") !== String(user.id)) return false; + if (user?.email && String(entry.email || "").toLowerCase() !== String(user.email || "").toLowerCase()) return false; + return true; +} + +function getRememberLoginCookieOptions() { + return { + maxAge: REMEMBER_LOGIN_MAX_AGE_MS, + sameSite: "lax", + secure: SESSION_COOKIE_SECURE, + httpOnly: true, + path: "/", + }; +} + +function clearRememberLoginCookie(res) { + if (!res) return; + res.clearCookie(REMEMBER_LOGIN_COOKIE_NAME, { + httpOnly: true, + sameSite: "lax", + secure: SESSION_COOKIE_SECURE, + path: "/", + }); +} + +function clearRememberLoginSessionState(req) { + if (!req?.session) return; + delete req.session.rememberLoginCheckedAt; + delete req.session.rememberLoginExpiresAt; +} + +function markRememberLoginSessionFresh(req, expiresAt) { + if (!req?.session) return; + req.session.rememberLoginCheckedAt = Date.now(); + req.session.rememberLoginExpiresAt = Number(expiresAt) || 0; +} + +function canSkipRememberLoginValidation(req) { + if (!req?.session?.user) return false; + + const checkedAt = Number(req.session.rememberLoginCheckedAt || 0); + const expiresAt = Number(req.session.rememberLoginExpiresAt || 0); + if (!checkedAt || !expiresAt) return false; + + if (Date.now() - checkedAt >= REMEMBER_LOGIN_VALIDATE_INTERVAL_MS) return false; + if (expiresAt - Date.now() <= REMEMBER_LOGIN_REFRESH_WINDOW_MS) return false; + + return true; +} + +function getRememberLoginFingerprint(user) { + if (!user || !user.password) return ""; + return crypto + .createHash("sha256") + .update(String(user.password || "")) + .update("\n") + .update(String(user.secret || "")) + .digest("hex"); +} + +function signRememberLoginPayload(encodedPayload) { + return crypto.createHmac("sha256", REMEMBER_LOGIN_SECRET).update(String(encodedPayload || "")).digest("base64url"); +} + +function readRememberLoginToken(token) { + const raw = String(token || "").trim(); + if (!raw) return null; + + const parts = raw.split("."); + if (parts.length !== 2) return null; + + const [encodedPayload, signature] = parts; + if (!encodedPayload || !signature) return null; + + const expectedSignature = signRememberLoginPayload(encodedPayload); + if (!safeCompare(signature, expectedSignature)) return null; + + try { + const payload = JSON.parse(Buffer.from(encodedPayload, "base64url").toString("utf8")); + if (!payload || ![1, 2].includes(Number(payload.v))) return null; + + const uid = String(payload.uid || "").trim(); + const iat = Number(payload.iat); + const exp = Number(payload.exp); + const fp = String(payload.fp || "").trim(); + const jti = String(payload.jti || "").trim(); + + if (!uid || !Number.isFinite(iat) || !Number.isFinite(exp) || !fp) return null; + if (iat > Date.now() + 5 * 60 * 1000) return null; + if (exp <= Date.now()) return null; + + return { v: Number(payload.v), uid, iat, exp, fp, jti }; + } catch { + return null; + } +} + +function issueRememberLoginToken(req, user, now = Date.now()) { + if (!req?.session || !user || !user.id || !user.password) return ""; + + const expiresAt = now + REMEMBER_LOGIN_MAX_AGE_MS; + const rememberId = upsertRememberLoginRegistryEntry(req, user, expiresAt, now); + if (!rememberId) return ""; + + const payload = { + v: 2, + uid: String(user.id), + iat: now, + exp: expiresAt, + fp: getRememberLoginFingerprint(user), + jti: rememberId, + }; + const encodedPayload = Buffer.from(JSON.stringify(payload), "utf8").toString("base64url"); + const signature = signRememberLoginPayload(encodedPayload); + return `${encodedPayload}.${signature}`; +} + +function setRememberLoginCookie(req, res, user) { + if (!req?.session || !res) return; + const now = Date.now(); + const token = issueRememberLoginToken(req, user, now); + if (!token) return; + res.cookie(REMEMBER_LOGIN_COOKIE_NAME, token, getRememberLoginCookieOptions()); + return now + REMEMBER_LOGIN_MAX_AGE_MS; +} + +function rememberLoginNeedsRefresh(tokenPayload) { + if (!tokenPayload) return true; + return tokenPayload.exp - Date.now() <= REMEMBER_LOGIN_REFRESH_WINDOW_MS; +} + +async function ensureRememberLoginCookie(req, res, user = null) { + const parsed = readRememberLoginToken(req.cookies?.[REMEMBER_LOGIN_COOKIE_NAME]); + const sessionRememberId = ensureRememberLoginSessionId(req); + + if ( + parsed && + parsed.jti && + parsed.jti === sessionRememberId && + isManagedRememberLoginToken(parsed) && + !rememberLoginNeedsRefresh(parsed) && + canSkipRememberLoginValidation(req) + ) { + markRememberLoginSessionFresh(req, parsed.exp); + return; + } + + const resolvedUser = user || (req.session?.user ? await findUserByEmail(req.session.user) : null); + if (!resolvedUser || !resolvedUser.id || !resolvedUser.password) { + clearRememberLoginSessionState(req); + clearRememberLoginCookie(res); + return; + } + + const expiresAt = setRememberLoginCookie(req, res, resolvedUser); + markRememberLoginSessionFresh(req, expiresAt); +} + +async function restoreRememberedLogin(req, res) { + const rawToken = String(req.cookies?.[REMEMBER_LOGIN_COOKIE_NAME] || "").trim(); + if (!rawToken) return false; + + const parsed = readRememberLoginToken(rawToken); + if (!parsed) { + clearRememberLoginSessionState(req); + clearRememberLoginCookie(res); + return false; + } + + const user = await findUserById(parsed.uid); + if (!user || !user.password) { + clearRememberLoginSessionState(req); + clearRememberLoginCookie(res); + return false; + } + + if (!safeCompare(parsed.fp, getRememberLoginFingerprint(user))) { + clearRememberLoginSessionState(req); + clearRememberLoginCookie(res); + return false; + } + + if (parsed.v === 1) { + const legacyCutoff = getRememberLoginLegacyCutoff(user.id); + if (legacyCutoff && Number(parsed.iat || 0) <= legacyCutoff) { + clearRememberLoginSessionState(req); + clearRememberLoginCookie(res); + return false; + } + } + + if (parsed.jti && !isManagedRememberLoginToken(parsed, user)) { + clearRememberLoginSessionState(req); + clearRememberLoginCookie(res); + return false; + } + + await new Promise((resolve, reject) => req.session.regenerate((err) => (err ? reject(err) : resolve()))); + req.session.user = user.email; + req.session.rememberLoginId = parsed.jti || crypto.randomBytes(18).toString("hex"); + 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); + return true; +} + +const sessionMiddleware = session({ + store: sessionStore, + secret: SESSION_SECRET, + name: "adpanel.sid", + resave: false, + saveUninitialized: false, + rolling: true, + cookie: { + maxAge: SESSION_MAX_AGE_MS, + sameSite: "lax", + secure: SESSION_COOKIE_SECURE, + httpOnly: true, + }, +}); + +app.use(cookieParser()); +app.use(sessionMiddleware); + +app.use(async (req, res, next) => { + try { + if (req._staticAsset) return next(); + + if (req.session?.user) { + await ensureRememberLoginCookie(req, res); + return next(); + } + + await restoreRememberedLogin(req, res); + return next(); + } catch (err) { + clearRememberLoginSessionState(req); + clearRememberLoginCookie(res); + console.warn("[auth] Persistent login restore failed:", err?.message || err); + return next(); + } +}); + +// 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) { + // Force session touch to refresh Redis TTL + req.session.touch(); + } + 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 ACTIVE_BROWSER_SESSION_PAGE_SIZE = 25; +const SESSION_REVOKE_TARGET_TOKEN_TTL_MS = 10 * 60 * 1000; +const SESSION_REVOKE_TARGET_TOKEN_MAX = 250; + +const activeBrowserSessionCache = { + scannedAt: 0, + sessions: new Map(), + promise: null, +}; + +function normalizeBrowserSessionAudit(raw, fallback = {}) { + const audit = raw && typeof raw === "object" ? raw : {}; + + const createdAt = Number(audit.createdAt || fallback.createdAt || 0) || 0; + const lastSeenAt = Number(audit.lastSeenAt || audit.updatedAt || fallback.lastSeenAt || 0) || 0; + + return { + email: String(audit.email || fallback.email || "").trim().toLowerCase(), + createdAt: createdAt || lastSeenAt || 0, + lastSeenAt: lastSeenAt || createdAt || 0, + userAgent: String(audit.userAgent || fallback.userAgent || "").trim().slice(0, 255), + firstIp: String(audit.firstIp || fallback.firstIp || "").trim().slice(0, 64), + lastIp: String(audit.lastIp || fallback.lastIp || "").trim().slice(0, 64), + rememberLoginId: String(audit.rememberLoginId || fallback.rememberLoginId || "").trim(), + }; +} + +function buildBrowserSessionAuditFromRequest(req, email, rememberLoginId = "", existing = null) { + const now = Date.now(); + const currentIp = String(getRequestIp(req) || "").trim().slice(0, 64); + const currentUserAgent = String(req?.get?.("user-agent") || "").trim().slice(0, 255); + const currentAudit = normalizeBrowserSessionAudit(existing, { + email: String(email || req?.session?.user || "").trim().toLowerCase(), + createdAt: now, + lastSeenAt: now, + userAgent: currentUserAgent, + firstIp: currentIp, + lastIp: currentIp, + rememberLoginId, + }); + + currentAudit.email = String(email || currentAudit.email || "").trim().toLowerCase(); + currentAudit.createdAt = currentAudit.createdAt || now; + currentAudit.lastSeenAt = now; + if (currentUserAgent) currentAudit.userAgent = currentUserAgent; + if (currentIp && !currentAudit.firstIp) currentAudit.firstIp = currentIp; + if (currentIp) currentAudit.lastIp = currentIp; + if (rememberLoginId) currentAudit.rememberLoginId = String(rememberLoginId).trim(); + return currentAudit; +} + +function buildActiveBrowserSessionRecord(sessionId, sess) { + const sid = String(sessionId || sess?.id || "").trim(); + if (!sid || !sess || typeof sess !== "object") return null; + + const email = String(sess.user || "").trim().toLowerCase(); + if (!email) return null; + + const cookieExpiresAt = sess?.cookie?.expires ? new Date(sess.cookie.expires).getTime() : 0; + if (Number.isFinite(cookieExpiresAt) && cookieExpiresAt > 0 && cookieExpiresAt <= Date.now()) { + return null; + } + + const audit = normalizeBrowserSessionAudit(sess.browserSessionAudit, { + email, + lastSeenAt: Number(sess.__lastAccess || 0) || 0, + rememberLoginId: String(sess.rememberLoginId || "").trim(), + }); + + return { + sessionId: sid, + email, + createdAt: audit.createdAt, + lastSeenAt: audit.lastSeenAt, + expiresAt: Number.isFinite(cookieExpiresAt) && cookieExpiresAt > 0 ? cookieExpiresAt : 0, + userAgent: audit.userAgent, + ip: audit.lastIp || audit.firstIp || "", + rememberLoginId: audit.rememberLoginId, + }; +} + +function upsertActiveBrowserSessionCacheEntry(sessionId, sess) { + const record = buildActiveBrowserSessionRecord(sessionId, sess); + const sid = String(sessionId || sess?.id || "").trim(); + if (!sid) return; + if (!record) { + activeBrowserSessionCache.sessions.delete(sid); + return; + } + activeBrowserSessionCache.sessions.set(record.sessionId, record); +} + +function removeActiveBrowserSessionCacheEntry(sessionId) { + const sid = String(sessionId || "").trim(); + if (!sid) return; + activeBrowserSessionCache.sessions.delete(sid); +} + +function invalidateActiveBrowserSessionCache() { + activeBrowserSessionCache.scannedAt = 0; +} + +function touchBrowserSessionAudit(req) { + if (req?._staticAsset || !req?.session?.user) return; + + const now = Date.now(); + const currentIp = String(getRequestIp(req) || "").trim().slice(0, 64); + const currentUserAgent = String(req.get("user-agent") || "").trim().slice(0, 255); + const rememberLoginId = String(req.session.rememberLoginId || "").trim(); + + const currentAudit = normalizeBrowserSessionAudit(req.session.browserSessionAudit, { + email: String(req.session.user || "").trim().toLowerCase(), + rememberLoginId, + }); + + let changed = false; + if (!currentAudit.createdAt) { + currentAudit.createdAt = now; + changed = true; + } + if (!currentAudit.lastSeenAt || now - currentAudit.lastSeenAt >= BROWSER_SESSION_AUDIT_TOUCH_INTERVAL_MS) { + currentAudit.lastSeenAt = now; + changed = true; + } + if (String(currentAudit.email || "").toLowerCase() !== String(req.session.user || "").toLowerCase()) { + currentAudit.email = String(req.session.user || "").trim().toLowerCase(); + changed = true; + } + if (currentUserAgent && currentAudit.userAgent !== currentUserAgent) { + currentAudit.userAgent = currentUserAgent; + changed = true; + } + if (currentIp && !currentAudit.firstIp) { + currentAudit.firstIp = currentIp; + changed = true; + } + if (currentIp && currentAudit.lastIp !== currentIp) { + currentAudit.lastIp = currentIp; + changed = true; + } + if (rememberLoginId && currentAudit.rememberLoginId !== rememberLoginId) { + currentAudit.rememberLoginId = rememberLoginId; + changed = true; + } + + if (changed) { + req.session.browserSessionAudit = currentAudit; + } + + upsertActiveBrowserSessionCacheEntry(req.sessionID, { + ...req.session, + browserSessionAudit: currentAudit, + }); +} + +app.use((req, _res, next) => { + try { + touchBrowserSessionAudit(req); + } catch (err) { + console.warn("[session] Failed to refresh browser session audit:", err?.message || err); + } + next(); +}); + +function callSessionStore(methodName, ...args) { + return new Promise((resolve, reject) => { + if (!sessionStore || typeof sessionStore[methodName] !== "function") { + return reject(new Error(`session store method "${methodName}" is not available`)); + } + let settled = false; + const done = (err, result) => { + if (settled) return; + settled = true; + if (err) return reject(err); + resolve(result); + }; + try { + const maybePromise = sessionStore[methodName](...args, done); + if (maybePromise && typeof maybePromise.then === "function") { + maybePromise.then((result) => done(null, result)).catch((err) => done(err)); + } + } catch (err) { + done(err); + } + }); +} + +async function mapWithConcurrency(items, limit, worker) { + const allItems = Array.isArray(items) ? items : []; + const concurrency = Math.max(1, Number(limit || 1)); + const results = new Array(allItems.length); + let cursor = 0; + + async function consume() { + while (cursor < allItems.length) { + const index = cursor++; + results[index] = await worker(allItems[index], index); + } + } + + await Promise.all(Array.from({ length: Math.min(concurrency, allItems.length || 1) }, () => consume())); + return results; +} + +function getFileStoreSessionIdFromFilename(fileName) { + const raw = String(fileName || "").trim(); + if (!raw) return ""; + const extension = String(sessionStore?.options?.fileExtension || ".json"); + if (!extension) return raw; + return raw.endsWith(extension) ? raw.slice(0, -extension.length) : raw; +} + +function normalizeSessionStoreSession(rawSession) { + if (!rawSession) return null; + if (typeof rawSession === "string") { + try { + return JSON.parse(rawSession); + } catch { + return null; + } + } + return rawSession && typeof rawSession === "object" ? rawSession : null; +} + +function normalizeSessionStoreEntries(rawSessions) { + const entries = []; + const pushEntry = (maybeId, rawSession) => { + const sess = normalizeSessionStoreSession(rawSession); + if (!sess) return; + const sid = String(maybeId || sess.id || sess.sid || "").trim(); + entries.push({ sessionId: sid, session: sess }); + }; + + if (Array.isArray(rawSessions)) { + rawSessions.forEach((entry) => { + if (Array.isArray(entry) && entry.length >= 2) { + pushEntry(entry[0], entry[1]); + } else { + pushEntry("", entry); + } + }); + return entries; + } + + if (rawSessions instanceof Map) { + for (const [sid, sess] of rawSessions.entries()) { + pushEntry(sid, sess); + } + return entries; + } + + if (rawSessions && typeof rawSessions === "object") { + for (const [sid, sess] of Object.entries(rawSessions)) { + pushEntry(sid, sess); + } + } + + return entries; +} + +async function scanActiveBrowserSessionsByIds(sessionIds) { + const ids = (Array.isArray(sessionIds) ? sessionIds : []) + .map((sid) => String(sid || "").trim()) + .filter(Boolean); + + const sessions = await mapWithConcurrency(ids, ACTIVE_BROWSER_SESSION_SCAN_CONCURRENCY, async (sid) => { + try { + const sess = await callSessionStore("get", sid); + return buildActiveBrowserSessionRecord(sid, sess); + } catch { + return null; + } + }); + + return sessions.filter(Boolean); +} + +async function scanActiveBrowserSessionsFromStore() { + let allError = null; + if (typeof sessionStore?.all === "function") { + try { + const sessions = await callSessionStore("all"); + const records = normalizeSessionStoreEntries(sessions) + .map(({ sessionId, session }) => buildActiveBrowserSessionRecord(sessionId || session?.id, session)) + .filter(Boolean); + if (records.length > 0 || (typeof sessionStore?.ids !== "function" && typeof sessionStore?.list !== "function")) { + return records; + } + } catch (err) { + allError = err; + } + } + + if (typeof sessionStore?.ids === "function") { + try { + return await scanActiveBrowserSessionsByIds(await callSessionStore("ids")); + } catch (err) { + if (!allError) allError = err; + } + } + + if (typeof sessionStore?.list === "function") { + const files = await callSessionStore("list"); + const sessionIds = (Array.isArray(files) ? files : []) + .map(getFileStoreSessionIdFromFilename) + .filter(Boolean); + + return scanActiveBrowserSessionsByIds(sessionIds); + } + + if (allError) throw allError; + throw new Error("session store does not support browser session inventory"); +} + +async function getCachedActiveBrowserSessions({ force = false } = {}) { + const now = Date.now(); + if (!force && activeBrowserSessionCache.scannedAt && now - activeBrowserSessionCache.scannedAt < ACTIVE_BROWSER_SESSION_SCAN_TTL_MS) { + return Array.from(activeBrowserSessionCache.sessions.values()); + } + + if (activeBrowserSessionCache.promise) { + return activeBrowserSessionCache.promise; + } + + activeBrowserSessionCache.promise = (async () => { + const scannedSessions = await scanActiveBrowserSessionsFromStore(); + activeBrowserSessionCache.sessions = new Map(scannedSessions.map((record) => [record.sessionId, record])); + activeBrowserSessionCache.scannedAt = Date.now(); + return scannedSessions; + })() + .catch((err) => { + if (activeBrowserSessionCache.sessions.size > 0) { + return Array.from(activeBrowserSessionCache.sessions.values()); + } + throw err; + }) + .finally(() => { + activeBrowserSessionCache.promise = null; + }); + + return activeBrowserSessionCache.promise; +} + +function getSessionRevokeGraceState(req) { + if (!req?.session) return null; + + const state = req.session.sessionRevoke2fa; + if (!state || typeof state !== "object") return null; + + const email = String(state.email || "").trim().toLowerCase(); + const verifiedAt = Number(state.verifiedAt || 0); + if (!email || !Number.isFinite(verifiedAt) || verifiedAt <= 0) { + delete req.session.sessionRevoke2fa; + return null; + } + + 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; + return null; + } + + return { + email, + verifiedAt, + expiresAt: verifiedAt + SESSION_REVOKE_2FA_GRACE_MS, + }; +} + +function hasSessionRevokeGrace(req) { + return !!getSessionRevokeGraceState(req); +} + +function getSessionRevokeGraceUaHash(req) { + return crypto + .createHash("sha256") + .update(String(req?.get?.("user-agent") || "").trim().slice(0, 255)) + .digest("hex"); +} + +function setSessionRevokeGrace(req) { + if (!req?.session?.user) return 0; + const verifiedAt = Date.now(); + req.session.sessionRevoke2fa = { + email: String(req.session.user || "").trim().toLowerCase(), + verifiedAt, + ip: String(getRequestIp(req) || "").trim().slice(0, 64), + uaHash: getSessionRevokeGraceUaHash(req), + }; + return verifiedAt + SESSION_REVOKE_2FA_GRACE_MS; +} + +function getSessionDisplayId(sessionId) { + const raw = String(sessionId || "").trim(); + if (!raw) return ""; + if (raw.length <= 18) return raw; + return `${raw.slice(0, 8)}...${raw.slice(-6)}`; +} + +function pruneSessionRevokeTargetTokens(req) { + if (!req?.session) return {}; + + const now = Date.now(); + const rawTargets = req.session.sessionRevokeTargets; + const targets = rawTargets && typeof rawTargets === "object" && !Array.isArray(rawTargets) + ? rawTargets + : {}; + const normalized = {}; + + for (const [token, value] of Object.entries(targets)) { + const entry = value && typeof value === "object" ? value : {}; + const sessionId = String(entry.sessionId || "").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 }; + } + + const entries = Object.entries(normalized) + .sort((a, b) => Number(a[1].issuedAt || 0) - Number(b[1].issuedAt || 0)); + while (entries.length > SESSION_REVOKE_TARGET_TOKEN_MAX) { + const [oldToken] = entries.shift(); + delete normalized[oldToken]; + } + + req.session.sessionRevokeTargets = normalized; + return normalized; +} + +function issueSessionRevokeTargetToken(req, sessionId) { + const sid = String(sessionId || "").trim(); + if (!req?.session || !sid) return ""; + + const targets = pruneSessionRevokeTargetTokens(req); + const token = crypto.randomBytes(24).toString("base64url"); + const now = Date.now(); + targets[token] = { + sessionId: sid, + issuedAt: now, + expiresAt: now + SESSION_REVOKE_TARGET_TOKEN_TTL_MS, + }; + req.session.sessionRevokeTargets = targets; + return token; +} + +function resolveSessionRevokeTargetToken(req, token) { + const raw = String(token || "").trim(); + if (!raw || raw.length > 128 || !/^[A-Za-z0-9_-]+$/.test(raw)) return ""; + + const targets = pruneSessionRevokeTargetTokens(req); + const entry = targets[raw]; + if (!entry) return ""; + return String(entry.sessionId || "").trim(); +} + +function clearSessionRevokeTargetToken(req, token) { + const raw = String(token || "").trim(); + if (!raw || !req?.session?.sessionRevokeTargets) return; + delete req.session.sessionRevokeTargets[raw]; +} + +const STEALTH_MODE = parseBoolean(process.env.STEALTH_MODE, true); +const STEALTH_ALLOW_HEALTHCHECK = parseBoolean(process.env.STEALTH_ALLOW_HEALTHCHECK, false); +const STEALTH_RESPONSE_FLOOR_MS = Math.max(0, parseInt(process.env.STEALTH_RESPONSE_FLOOR_MS || "90", 10) || 90); +const STEALTH_BOOTSTRAP_TTL_MS = Math.max(1000, parseInt(process.env.STEALTH_BOOTSTRAP_TTL_MS || "120000", 10) || 120000); +const STEALTH_COOKIE_TTL_DAYS = Math.max(1, parseInt(process.env.STEALTH_COOKIE_TTL_DAYS || "30", 10) || 30); +const STEALTH_CONFIG = ensureStealthConfig({ + enabled: STEALTH_MODE, + cookieTtlDays: STEALTH_COOKIE_TTL_DAYS, +}); +const STEALTH_ACTIVE = STEALTH_MODE && STEALTH_CONFIG.enabled !== false; +const STEALTH_COOKIE_NAME = String(STEALTH_CONFIG.cookieName || "adpanel_gate"); +const STEALTH_LOGIN_PATHS = new Set(["/login", "/forgot-password", "/register"]); +const STEALTH_ASSET_PATHS = new Set([ + "/favicon.ico", + "/login.css", + "/images/adpanel-dark.webp", + "/images/ADPanel-christmas.png", + "/images/ADPanel-christmas.webp", + "/images/bgvid.webm", + "/branding-media/login-watermark", + "/branding-media/login-background", +]); + +function isStealthProtectedAssetPath(pathname) { + const p = String(pathname || "").trim(); + return p.startsWith("/auth-assets/") || STEALTH_ASSET_PATHS.has(p); +} + +function isStealthProtectedLoginPath(pathname) { + return STEALTH_LOGIN_PATHS.has(String(pathname || "").trim()); +} + +function sanitizeStealthReturnTo(value) { + const raw = String(value || "").trim(); + if (!raw.startsWith("/")) return "/login"; + if (raw.startsWith("//") || raw.startsWith("/_stealth/")) return "/login"; + return raw; +} + +function getStealthGateCookieMaxAgeMs() { + return (STEALTH_CONFIG.cookieTtlDays || STEALTH_COOKIE_TTL_DAYS || 30) * 24 * 60 * 60 * 1000; +} + +function signStealthGatePayload(payload) { + return crypto + .createHmac("sha256", String(STEALTH_CONFIG.cookieSecret || "")) + .update(String(payload || "")) + .digest("base64url"); +} + +function createStealthGateToken() { + const expiresAt = Date.now() + getStealthGateCookieMaxAgeMs(); + const nonce = crypto.randomBytes(18).toString("base64url"); + const payload = `${expiresAt}.${nonce}`; + return `${payload}.${signStealthGatePayload(payload)}`; +} + +function hasValidStealthGateToken(token) { + const raw = String(token || "").trim(); + if (!raw) return false; + const parts = raw.split("."); + if (parts.length !== 3) return false; + const [expiresAtRaw, nonce, signature] = parts; + const expiresAt = parseInt(expiresAtRaw, 10); + if (!Number.isFinite(expiresAt) || expiresAt <= Date.now()) return false; + if (!nonce || !signature) return false; + const payload = `${expiresAt}.${nonce}`; + return safeCompare(signature, signStealthGatePayload(payload)); +} + +function getStealthCookieOptions() { + return { + httpOnly: true, + sameSite: "lax", + secure: SESSION_COOKIE_SECURE, + path: "/", + maxAge: getStealthGateCookieMaxAgeMs(), + }; +} + +function delay(ms) { + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +async function applyStealthResponseFloor(startedAt) { + const elapsed = Date.now() - Number(startedAt || 0); + const remaining = STEALTH_RESPONSE_FLOOR_MS - elapsed; + if (remaining > 0) { + await delay(remaining); + } +} + +function getStealthBootstrapState(req) { + if (!req.session || !req.session.stealthBootstrap || typeof req.session.stealthBootstrap !== "object") { + return null; + } + return req.session.stealthBootstrap; +} + +function setStealthBootstrapState(req, returnTo) { + if (!req.session) return null; + const state = { + id: crypto.randomBytes(18).toString("base64url"), + returnTo: sanitizeStealthReturnTo(returnTo), + issuedAt: Date.now(), + }; + req.session.stealthBootstrap = state; + return state; +} + +function clearStealthBootstrapState(req) { + if (!req.session) return; + delete req.session.stealthBootstrap; +} + +function buildStealthBootstrapHtml(res, authorizeUrl, stateId) { + const nonce = res.locals.cspNonce || crypto.randomBytes(16).toString("base64"); + const variant = crypto + .createHash("sha256") + .update(`${STEALTH_CONFIG.htmlVariantSalt || "stealth"}:${stateId || ""}`) + .digest("hex") + .slice(0, 16); + const rawAuthorizeUrl = String(authorizeUrl || "/login"); + const metaAuthorizeUrl = rawAuthorizeUrl + .replace(/&/g, "&") + .replace(/"/g, """); + const safeAuthorizeUrl = JSON.stringify(rawAuthorizeUrl); + + return ` + + + + + + + Please wait + + + + +
+ +
Preparing secure access...
+
+ +`; +} + +function applyStealthPageHeaders(res, nonce) { + const currentNonce = nonce || res.locals.cspNonce || crypto.randomBytes(16).toString("base64"); + res.setHeader("Cache-Control", "no-store, private"); + res.setHeader("Pragma", "no-cache"); + res.setHeader("Vary", "Accept, Cookie"); + res.setHeader( + "Content-Security-Policy", + `default-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'; object-src 'none'; img-src 'self' data:; style-src 'nonce-${currentNonce}'; script-src 'nonce-${currentNonce}'; connect-src 'self';` + ); + return currentNonce; +} + +async function sendStealthBootstrap(req, res, returnTo) { + const startedAt = Date.now(); + const state = setStealthBootstrapState(req, returnTo); + const finalize = async () => { + const nonce = applyStealthPageHeaders(res, res.locals.cspNonce); + const target = sanitizeStealthReturnTo(returnTo); + const authorizeUrl = `/_stealth/authorize?id=${encodeURIComponent(state?.id || "")}&r=${encodeURIComponent(target)}`; + await applyStealthResponseFloor(startedAt); + res.status(200).type("html").send(buildStealthBootstrapHtml({ ...res, locals: { ...res.locals, cspNonce: nonce } }, authorizeUrl, state?.id || "")); + }; + + if (req.session?.save) { + return req.session.save((err) => { + if (err) return res.status(500).type("text/plain").send("Service unavailable"); + finalize().catch(() => { + if (!res.headersSent) res.status(500).type("text/plain").send("Service unavailable"); + }); + }); + } + return finalize(); +} + +async function sendStealthNotFound(res) { + const startedAt = Date.now(); + res.setHeader("Cache-Control", "no-store, private"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Content-Security-Policy", "default-src 'none'; base-uri 'none'; frame-ancestors 'none'; object-src 'none';"); + await applyStealthResponseFloor(startedAt); + return res.status(404).type("text/plain").send(""); +} + +async function sendStealthEmptyFavicon(res) { + const startedAt = Date.now(); + res.setHeader("Cache-Control", "no-store, private"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.setHeader("Content-Security-Policy", "default-src 'none'; base-uri 'none'; frame-ancestors 'none'; object-src 'none';"); + await applyStealthResponseFloor(startedAt); + return res.status(204).end(); +} + +async function hasStealthAccess(req) { + if (!STEALTH_ACTIVE) return true; + if (hasValidStealthGateToken(req.cookies?.[STEALTH_COOKIE_NAME])) return true; + try { + return await isAuthenticated(req); + } catch { + return false; + } +} + +app.get("/_stealth/authorize", (req, res) => { + const startedAt = Date.now(); + const returnTo = sanitizeStealthReturnTo(req.query?.r || "/login"); + if (!STEALTH_ACTIVE) { + return res.redirect(303, returnTo); + } + + const stateId = String(req.query?.id || "").trim(); + const currentState = getStealthBootstrapState(req); + const validState = !!( + currentState && + stateId && + safeCompare(stateId, String(currentState.id || "")) && + sanitizeStealthReturnTo(currentState.returnTo) === returnTo && + (Date.now() - Number(currentState.issuedAt || 0)) <= STEALTH_BOOTSTRAP_TTL_MS + ); + + clearStealthBootstrapState(req); + + const finalize = async () => { + if (validState) { + res.cookie(STEALTH_COOKIE_NAME, createStealthGateToken(), getStealthCookieOptions()); + } else { + res.clearCookie(STEALTH_COOKIE_NAME, { path: "/" }); + } + await applyStealthResponseFloor(startedAt); + return res.redirect(303, validState ? returnTo : "/login"); + }; + + if (req.session?.save) { + return req.session.save((err) => { + if (err) return res.status(500).type("text/plain").send("Service unavailable"); + finalize().catch(() => { + if (!res.headersSent) res.status(500).type("text/plain").send("Service unavailable"); + }); + }); + } + return finalize(); +}); + +app.all("/_stealth/nginx-auth", async (req, res) => { + if (!STEALTH_ACTIVE) return res.status(204).end(); + if (await hasStealthAccess(req)) return res.status(204).end(); + return res.status(401).end(); +}); + +app.use(async (req, res, next) => { + if (!STEALTH_ACTIVE) return next(); + if (STEALTH_ALLOW_HEALTHCHECK && req.path === "/healthz") return next(); + if (req.path.startsWith("/_stealth/")) return next(); + if (req.path.startsWith("/.well-known/acme-challenge/")) return next(); + + const pathName = String(req.path || "").trim(); + const isProtectedLoginPath = isStealthProtectedLoginPath(pathName); + const isProtectedAssetPath = isStealthProtectedAssetPath(pathName); + if (!isProtectedLoginPath && !isProtectedAssetPath) return next(); + + try { + if (await hasStealthAccess(req)) return next(); + } catch (err) { + return next(err); + } + + if (pathName === "/favicon.ico") { + return sendStealthEmptyFavicon(res).catch(next); + } + + if (isProtectedAssetPath) { + return sendStealthNotFound(res).catch(next); + } + + if (req.method !== "GET" && req.method !== "HEAD") { + res.setHeader("Cache-Control", "no-store, private"); + return res.redirect(303, "/login"); + } + + return sendStealthBootstrap(req, res, req.originalUrl || pathName).catch(next); +}); + +// ── Database Proxy Middleware (before body parsers to enable streaming) ── +app.use(dbProxy.createProxyMiddleware()); + +const JSON_BODY_LIMIT = process.env.JSON_BODY_LIMIT || "50mb"; +const FILE_WRITE_JSON_LIMIT = process.env.FILE_WRITE_JSON_LIMIT || "50mb"; +const AI_CHAT_JSON_LIMIT = process.env.AI_CHAT_JSON_LIMIT || "50mb"; +const BRANDING_MEDIA_JSON_LIMIT = process.env.BRANDING_MEDIA_JSON_LIMIT || "80mb"; +const URLENCODED_BODY_LIMIT = process.env.URLENCODED_BODY_LIMIT || "50mb"; +const jsonParserDefault = express.json({ limit: JSON_BODY_LIMIT }); +const jsonParserFileWrite = express.json({ limit: FILE_WRITE_JSON_LIMIT }); +const jsonParserAiChat = express.json({ limit: AI_CHAT_JSON_LIMIT }); +const jsonParserBrandingMedia = express.json({ limit: BRANDING_MEDIA_JSON_LIMIT }); + +app.use((req, res, next) => { + if (req._staticAsset || req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return next(); + if (req.method === "PUT" && /^\/api\/servers\/[^/]+\/files\/write$/.test(req.path || "")) { + return jsonParserFileWrite(req, res, next); + } + if (req.method === "POST" && /^\/api\/admin\/(branding\/update|login-background)$/.test(req.path || "")) { + return jsonParserBrandingMedia(req, res, next); + } + if (req.method === "POST" && /^\/api\/ai\/(chat|chats\/\d+\/messages)/.test(req.path || "")) { + return jsonParserAiChat(req, res, next); + } + return jsonParserDefault(req, res, next); +}); +const _urlencodedParser = express.urlencoded({ extended: true, limit: URLENCODED_BODY_LIMIT }); +app.use((req, res, next) => { + if (req._staticAsset || req.method === "GET" || req.method === "HEAD" || req.method === "OPTIONS") return next(); + return _urlencodedParser(req, res, next); +}); +app.use(hpp()); +const SUSPICIOUS_PATH_PATTERNS = [/etc\/passwd/, /proc\/self/, /\.env/]; +app.use((req, res, next) => { + const pathToCheck = req.path || ""; + if (SUSPICIOUS_PATH_PATTERNS.some((pattern) => pattern.test(pathToCheck))) { + securityLog("Potential Path Traversal Attempt", req); + return res.status(403).send("Forbidden"); + } + return next(); +}); +app.use((req, _res, next) => { + if (req._staticAsset) return next(); + const seen = new Set(); + const maxDepth = 10; + + const scrub = (obj, depth = 0) => { + if (!obj || typeof obj !== "object") return; + if (seen.has(obj)) return; + if (depth > maxDepth) return; + if (Array.isArray(obj)) { + seen.add(obj); + for (const item of obj) scrub(item, depth + 1); + return; + } + if (!isPlainObject(obj)) return; + seen.add(obj); + for (const key of Object.keys(obj)) { + if (POLLUTION_KEYS.has(key)) { + console.warn(`[SECURITY] Prototype pollution attempt from IP: ${getRequestIp(req)}`); + delete obj[key]; + continue; + } + scrub(obj[key], depth + 1); + } + }; + + scrub(req.body); + scrub(req.query); + scrub(req.params); + return next(); +}); +if (NODE_COMPRESSION) { + const COMPRESSION_THRESHOLD = 512; + const BROTLI_QUALITY = Math.min(11, Math.max(0, parseInt(process.env.BROTLI_QUALITY || "4", 10))); + const GZIP_LEVEL = 4; + const COMPRESSIBLE_RE = /^text\/|^application\/(json|javascript|xml|xhtml\+xml|x-javascript|ld\+json|manifest\+json|vnd\.api\+json)|image\/svg\+xml/i; + + function isCompressible(contentType) { + if (!contentType) return true; + return COMPRESSIBLE_RE.test(contentType); + } + + app.use((req, res, next) => { + const acceptEncoding = req.headers["accept-encoding"] || ""; + const supportsBrotli = /\bbr\b/.test(acceptEncoding); + const supportsGzip = /\bgzip\b/.test(acceptEncoding); + + if (!supportsBrotli && !supportsGzip) return next(); + + const origWriteHead = res.writeHead; + const origWrite = res.write; + const origEnd = res.end; + let compressStream = null; + let decided = false; + let bypassed = false; + + // Intercept writeHead to detect proxy/pipe scenarios + res.writeHead = function(statusCode, ...args) { + if (!decided) { + decided = true; + bypassed = true; + } + return origWriteHead.call(res, statusCode, ...args); + }; + + function decide() { + if (decided) return; + decided = true; + + const ct = String(res.getHeader("Content-Type") || ""); + if (ct === "text/event-stream" || !isCompressible(ct)) { + bypassed = true; + return; + } + + res.removeHeader("Content-Length"); + res.setHeader("Vary", "Accept-Encoding"); + + if (supportsBrotli) { + compressStream = zlib.createBrotliCompress({ + params: { + [zlib.constants.BROTLI_PARAM_QUALITY]: BROTLI_QUALITY, + [zlib.constants.BROTLI_PARAM_MODE]: zlib.constants.BROTLI_MODE_TEXT, + } + }); + res.setHeader("Content-Encoding", "br"); + } else { + compressStream = zlib.createGzip({ level: GZIP_LEVEL, threshold: COMPRESSION_THRESHOLD }); + res.setHeader("Content-Encoding", "gzip"); + } + + compressStream.on("data", (chunk) => origWrite.call(res, chunk)); + compressStream.on("end", () => origEnd.call(res)); + compressStream.on("error", () => { + // On compression error, try to end gracefully + try { origEnd.call(res); } catch {} + }); + } + + res.write = function(chunk, encoding, cb) { + if (!decided) decide(); + if (bypassed) return origWrite.call(res, chunk, encoding, cb); + if (compressStream) return compressStream.write(chunk, encoding, cb); + return origWrite.call(res, chunk, encoding, cb); + }; + + res.end = function(chunk, encoding, cb) { + if (typeof chunk === "function") { cb = chunk; chunk = undefined; encoding = undefined; } + if (typeof encoding === "function") { cb = encoding; encoding = undefined; } + if (!decided) decide(); + if (bypassed) return origEnd.call(res, chunk, encoding, cb); + if (compressStream) { + if (cb) compressStream.once("end", cb); + if (chunk) compressStream.end(chunk, encoding); + else compressStream.end(); + } else { + return origEnd.call(res, chunk, encoding, cb); + } + }; + + next(); + }); +} + +app.set("views", path.join(__dirname, "views")); +app.set("view engine", "ejs"); +app.set("view cache", false); + +app.use((req, res, next) => { + if (req._staticAsset) return next(); + return brandingMiddleware(req, res, next); +}); +app.use((req, _res, next) => { + if (req._staticAsset) return next(); + maybeScheduleLoginBackgroundMirror(); + next(); +}); + +const BRANDING_REMOTE_ASSET_CACHE_TTL_MS = parseInt(process.env.BRANDING_REMOTE_ASSET_CACHE_TTL_MS || "300000", 10); +const BRANDING_REMOTE_ASSET_CACHE = new TTLCache({ + name: "brandingRemoteAssets", + ttlMs: BRANDING_REMOTE_ASSET_CACHE_TTL_MS, + maxSize: scaleForMemory(100), + sweepMs: 60_000 +}); +const LOGIN_BACKGROUND_IMAGE_MAX_BYTES = 5 * 1024 * 1024; +const LOGIN_BACKGROUND_VIDEO_MAX_BYTES = 40 * 1024 * 1024; +const FIXED_FAVICON_REMOTE_URL = "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/adpanel-dark.webp"; +let loginBackgroundMirrorPromise = null; + +function getBrandingRemoteAssetCacheKey(kind, sourceUrl) { + return `${String(kind || "").trim().toLowerCase()}|${String(sourceUrl || "").trim()}`; +} + +function getCachedBrandingRemoteAsset(cacheKey) { + const cached = BRANDING_REMOTE_ASSET_CACHE.get(cacheKey); + return cached || null; +} + +function setCachedBrandingRemoteAsset(cacheKey, asset) { + BRANDING_REMOTE_ASSET_CACHE.set(cacheKey, asset); +} + +function clearBrandingRemoteAssetCache(kind = "") { + const normalizedKind = String(kind || "").trim().toLowerCase(); + if (!normalizedKind) { + BRANDING_REMOTE_ASSET_CACHE.clear(); + return; + } + BRANDING_REMOTE_ASSET_CACHE.clear((key) => key.startsWith(`${normalizedKind}|`)); +} + +function getBrandingRemoteAssetConfig(kind, branding) { + const normalizedKind = String(kind || "").trim().toLowerCase(); + if (normalizedKind === "login-watermark") { + const sourceUrl = String(branding?.loginWatermarkUrl || "").trim(); + const ext = getExtensionFromUrl(sourceUrl); + if (!sourceUrl || !ext) return null; + return { + kind: normalizedKind, + sourceUrl, + ext, + mediaType: "image", + mimeType: getMimeTypeForExtension(ext) || "image/webp", + maxBytes: 5 * 1024 * 1024, + }; + } + + if (normalizedKind === "login-background") { + const sourceUrl = String(branding?.loginBackgroundExternalUrl || "").trim(); + const ext = getExtensionFromUrl(sourceUrl); + const mediaType = branding?.loginBackgroundType || getMediaTypeFromUrl(sourceUrl); + if (!sourceUrl || !ext || !mediaType) return null; + return { + kind: normalizedKind, + sourceUrl, + ext, + mediaType, + mimeType: getMimeTypeForExtension(ext) || (mediaType === "image" ? "image/webp" : "video/webm"), + maxBytes: mediaType === "image" ? 5 * 1024 * 1024 : 40 * 1024 * 1024, + }; + } + + return null; +} + +async function loadBrandingRemoteAsset(assetConfig) { + const cacheKey = getBrandingRemoteAssetCacheKey(assetConfig.kind, assetConfig.sourceUrl); + const cached = getCachedBrandingRemoteAsset(cacheKey); + if (cached) { + return cached; + } + + const rawBuffer = await httpGetRaw(assetConfig.sourceUrl, { maxBytes: assetConfig.maxBytes }); + const base64 = rawBuffer.toString("base64"); + const validation = assetConfig.mediaType === "video" + ? validateBase64Video(base64, assetConfig.ext) + : validateBase64Image(base64); + + if (!validation?.valid) { + throw new Error(validation?.error || "Invalid branding media"); + } + + const asset = { + buffer: validation.data || rawBuffer, + mimeType: assetConfig.mimeType, + }; + setCachedBrandingRemoteAsset(cacheKey, asset); + return asset; +} + +app.get("/branding-media/:kind", async (req, res) => { + try { + const branding = loadBrandingConfig(); + const assetConfig = getBrandingRemoteAssetConfig(req.params.kind, branding); + if (!assetConfig) { + return res.status(404).end("not found"); + } + + const asset = await loadBrandingRemoteAsset(assetConfig); + res.setHeader("Content-Type", asset.mimeType); + res.setHeader("Cache-Control", "public, max-age=300"); + res.setHeader("X-Content-Type-Options", "nosniff"); + return res.send(asset.buffer); + } catch (err) { + console.error("[branding-media] Failed to serve remote asset:", err.message); + return res.status(502).end("branding media unavailable"); + } +}); + +function resolvePublicImagePath(filename) { + const safeName = path.basename(String(filename || "").trim()); + if (!safeName || safeName === "." || safeName === "..") return null; + const filePath = path.join(__dirname, "public", "images", safeName); + return fs.existsSync(filePath) ? filePath : null; +} + +function sendPrivateAssetFile(res, filePath, fallbackType = "application/octet-stream") { + const ext = path.extname(String(filePath || "")).slice(1).toLowerCase(); + const mimeType = getMimeTypeForExtension(ext) || fallbackType; + res.setHeader("Cache-Control", "no-store, private"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.type(mimeType); + return res.sendFile(filePath); +} + +async function sendPrivateRemoteAsset(res, assetConfig) { + const asset = await loadBrandingRemoteAsset(assetConfig); + res.setHeader("Cache-Control", "no-store, private"); + res.setHeader("X-Content-Type-Options", "nosniff"); + res.type(asset.mimeType || "application/octet-stream"); + return res.send(asset.buffer); +} + +function getDefaultLogoPath() { + return resolvePublicImagePath("adpanel-dark.webp") || resolvePublicImagePath("logo.webp"); +} + +function getDefaultChristmasLogoPath() { + return resolvePublicImagePath("ADPanel-christmas.webp") || resolvePublicImagePath("ADPanel-christmas.png"); +} + +function getDefaultFaviconPath() { + return resolvePublicImagePath("favicon.ico") || getDefaultLogoPath(); +} + +app.get("/auth-assets/login.css", (req, res) => { + res.setHeader("Cache-Control", "no-store, private"); + res.setHeader("X-Content-Type-Options", "nosniff"); + return res.type("text/css").send(getInlineLoginCss()); +}); + +app.get("/auth-assets/logo", async (req, res) => { + try { + const branding = loadBrandingConfig(); + const localPath = resolvePublicImagePath(branding.localLogoPath) || getDefaultLogoPath(); + if (localPath) { + return sendPrivateAssetFile(res, localPath, "image/webp"); + } + + const remoteLogoUrl = String(branding.logoUrl || "").trim(); + const ext = getExtensionFromUrl(remoteLogoUrl); + if (remoteLogoUrl && ext) { + return await sendPrivateRemoteAsset(res, { + kind: "logo", + sourceUrl: remoteLogoUrl, + ext, + mediaType: "image", + mimeType: getMimeTypeForExtension(ext) || "image/webp", + maxBytes: 5 * 1024 * 1024, + }); + } + + return res.status(404).end("not found"); + } catch (err) { + console.error("[auth-assets] Failed to serve logo:", err.message); + return res.status(502).end("branding media unavailable"); + } +}); + +app.get("/auth-assets/christmas-logo", (req, res) => { + const filePath = getDefaultChristmasLogoPath(); + if (!filePath) return res.status(404).end("not found"); + return sendPrivateAssetFile(res, filePath, "image/webp"); +}); + +app.get("/auth-assets/watermark", async (req, res) => { + try { + const branding = loadBrandingConfig(); + const localPath = resolvePublicImagePath(branding.localLoginWatermarkPath); + if (localPath) { + return sendPrivateAssetFile(res, localPath, "image/webp"); + } + + const assetConfig = getBrandingRemoteAssetConfig("login-watermark", branding); + if (!assetConfig) return res.status(404).end("not found"); + return await sendPrivateRemoteAsset(res, assetConfig); + } catch (err) { + console.error("[auth-assets] Failed to serve watermark:", err.message); + return res.status(502).end("branding media unavailable"); + } +}); + +app.get("/auth-assets/background", async (req, res) => { + try { + const branding = loadBrandingConfig(); + const localPath = resolvePublicImagePath(branding.localLoginBackgroundPath); + if (localPath) { + return sendPrivateAssetFile( + res, + localPath, + branding.loginBackgroundType === "image" ? "image/webp" : (branding.loginBackgroundMimeType || "video/webm") + ); + } + + const assetConfig = getBrandingRemoteAssetConfig("login-background", branding); + if (assetConfig) { + return await sendPrivateRemoteAsset(res, assetConfig); + } + + const fallbackPath = resolvePublicImagePath("bgvid.webm"); + if (fallbackPath) { + return sendPrivateAssetFile(res, fallbackPath, "video/webm"); + } + + return res.status(404).end("not found"); + } catch (err) { + console.error("[auth-assets] Failed to serve background:", err.message); + return res.status(502).end("branding media unavailable"); + } +}); + +app.get("/auth-assets/favicon", async (req, res) => { + try { + const remoteFaviconExt = getExtensionFromUrl(FIXED_FAVICON_REMOTE_URL); + if (remoteFaviconExt) { + return await sendPrivateRemoteAsset(res, { + kind: "favicon", + sourceUrl: FIXED_FAVICON_REMOTE_URL, + ext: remoteFaviconExt, + mediaType: "image", + mimeType: getMimeTypeForExtension(remoteFaviconExt) || "image/webp", + maxBytes: 5 * 1024 * 1024, + }); + } + + const localPath = resolvePublicImagePath("adpanel-dark.webp") || getDefaultLogoPath() || getDefaultFaviconPath(); + if (localPath) { + return sendPrivateAssetFile(res, localPath, "image/webp"); + } + + return res.status(404).end("not found"); + } catch (err) { + console.error("[auth-assets] Failed to serve favicon:", err.message); + const localPath = resolvePublicImagePath("adpanel-dark.webp") || getDefaultLogoPath() || getDefaultFaviconPath(); + if (localPath) { + return sendPrivateAssetFile(res, localPath, "image/webp"); + } + return res.status(502).end("branding media unavailable"); + } +}); + +app.get("/favicon.ico", async (req, res) => { + if (STEALTH_ACTIVE && !(await hasStealthAccess(req))) { + return sendStealthEmptyFavicon(res); + } + return res.redirect(302, "/auth-assets/favicon"); +}); + +if (SERVE_STATIC) { + app.use(express.static(path.join(__dirname, "public"), { + maxAge: "30d", + etag: true, + lastModified: true, + immutable: true, + })); +} + + +const STATUS_CACHE_TTL_MS = parseInt(process.env.STATUS_CACHE_TTL_MS || "10000", 10); +const NODE_POLL_INTERVAL_MS = parseInt(process.env.NODE_POLL_INTERVAL_MS || "15000", 10); +const NODE_POLL_TIMEOUT_MS = parseInt(process.env.NODE_POLL_TIMEOUT_MS || "5000", 10); +const NODE_POLL_CONCURRENCY = parseInt(process.env.NODE_POLL_CONCURRENCY || "10", 10); + +const statusCache = { + servers: new TTLCache({ name: "statusServers", ttlMs: 5 * 60 * 1000, sweepMs: 60_000 }), + + nodes: new TTLCache({ name: "statusNodes", ttlMs: 5 * 60 * 1000, sweepMs: 60_000 }), + + lastFullRefresh: 0, + + refreshing: false +}; + +const REDIS_KEYS = { + serverStatus: (name) => `adpanel:status:server:${name}`, + nodeStatus: (id) => `adpanel:status:node:${id}`, + allServers: 'adpanel:status:servers:all', + allNodes: 'adpanel:status:nodes:all' +}; + + +async function getCachedServerStatus(serverName) { + const name = String(serverName || '').trim(); + if (!name) return null; + + if (redisClient) { + try { + const cached = await redisClient.get(REDIS_KEYS.serverStatus(name)); + if (cached) { + const parsed = normalizeServerStatusRecord(JSON.parse(cached)); + if (Date.now() - parsed.updatedAt < STATUS_CACHE_TTL_MS) { + return parsed; + } + } + } catch { } + } + + const memCached = statusCache.servers.get(name); + if (memCached && Date.now() - memCached.updatedAt < STATUS_CACHE_TTL_MS) { + return normalizeServerStatusRecord(memCached); + } + + return null; +} + +const SSR_CACHE_LENIENT_MS = 60000; +async function getCachedServerStatusLenient(serverName) { + const name = String(serverName || '').trim(); + if (!name) return null; + + if (redisClient) { + try { + const cached = await redisClient.get(REDIS_KEYS.serverStatus(name)); + if (cached) { + const parsed = normalizeServerStatusRecord(JSON.parse(cached)); + if (Date.now() - parsed.updatedAt < SSR_CACHE_LENIENT_MS) { + return parsed; + } + } + } catch { } + } + + const memCached = statusCache.servers.get(name); + if (memCached && Date.now() - memCached.updatedAt < SSR_CACHE_LENIENT_MS) { + return normalizeServerStatusRecord(memCached); + } + + return null; +} + +async function getCachedNodeStatus(nodeId) { + const id = String(nodeId || '').trim(); + if (!id) return null; + + if (redisClient) { + try { + const cached = await redisClient.get(REDIS_KEYS.nodeStatus(id)); + if (cached) { + const parsed = JSON.parse(cached); + if (Date.now() - parsed.updatedAt < STATUS_CACHE_TTL_MS * 3) { + return parsed; + } + } + } catch { } + } + + const memCached = statusCache.nodes.get(id); + if (memCached && Date.now() - memCached.updatedAt < STATUS_CACHE_TTL_MS * 3) { + return memCached; + } + + return null; +} + +async function getAllCachedServerStatuses(serverNames) { + const results = new Map(); + const missing = []; + + for (const name of serverNames) { + const cached = await getCachedServerStatus(name); + if (cached) { + results.set(name, cached); + } else { + missing.push(name); + } + } + + return { results, missing }; +} + +async function getAllCachedServerStatusesLenient(serverNames) { + const results = new Map(); + const BATCH = 200; + for (let i = 0; i < serverNames.length; i += BATCH) { + const batch = serverNames.slice(i, i + BATCH); + const entries = await Promise.all(batch.map(async (name) => { + const cached = await getCachedServerStatusLenient(name); + return cached ? [name, cached] : null; + })); + for (const entry of entries) { + if (entry) results.set(entry[0], entry[1]); + } + } + return { results }; +} + + +let broadcastDashboardUpdate = null; +let broadcastNodeUpdate = null; + +async function setCachedServerStatus(serverName, status) { + const name = String(serverName || '').trim(); + if (!name) return; + + // Keep metrics human-scale; long floats add no UI value and can trigger false-positive PII scanners. + const data = normalizeServerStatusRecord({ + name, + status: status.status || 'unknown', + cpu: status.cpu ?? null, + cpuLimit: status.cpuLimit ?? null, + memory: status.memory ?? null, + disk: status.disk ?? null, + uptime: status.uptime ?? null, + nodeOnline: status.nodeOnline !== false, + nodeId: status.nodeId || null, + updatedAt: Date.now() + }); + + const previous = statusCache.servers.get(name); + const statusChanged = !previous || previous.status !== data.status || + previous.nodeOnline !== data.nodeOnline; + + statusCache.servers.set(name, data); + + if (redisClient) { + try { + const ttlSeconds = Math.max(1, Math.floor(STATUS_CACHE_TTL_MS / 1000) * 2); + await redisClient.setEx( + REDIS_KEYS.serverStatus(name), + ttlSeconds, + JSON.stringify(data) + ); + } catch (err) { + } + } + + if (statusChanged && broadcastDashboardUpdate) { + broadcastDashboardUpdate(name, data); + } +} + +async function setCachedNodeStatus(nodeId, status) { + const id = String(nodeId || '').trim(); + if (!id) return; + + const data = { + id, + online: status.online !== false, + latency: status.latency ?? null, + lastSeen: status.online ? Date.now() : (status.lastSeen || null), + serverCount: status.serverCount ?? 0, + resources: status.resources || null, + updatedAt: Date.now() + }; + + const previous = statusCache.nodes.get(id); + const statusChanged = !previous || previous.online !== data.online; + + statusCache.nodes.set(id, data); + + if (redisClient) { + try { + const ttlSeconds = Math.max(1, Math.floor(STATUS_CACHE_TTL_MS / 1000) * 6); + await redisClient.setEx( + REDIS_KEYS.nodeStatus(id), + ttlSeconds, + JSON.stringify(data) + ); + } catch (err) { + } + } + + if (statusChanged && broadcastNodeUpdate) { + broadcastNodeUpdate(id, data); + } + + if (statusChanged) { + db.query( + 'UPDATE nodes SET online = ?, port_ok = ?, last_seen = ?, last_check = ? WHERE id = ? OR uuid = ?', + [data.online ? 1 : 0, data.online ? 1 : 0, data.online ? Date.now() : null, Date.now(), id, id] + ).catch(() => { }); + } +} + + +async function fetchNodeServerStatuses(node) { + const nodeId = node.uuid || node.id || node.name; + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + + if (!baseUrl) { + await setCachedNodeStatus(nodeId, { online: false }); + return { nodeId, online: false, servers: [] }; + } + + const headers = nodeAuthHeadersFor(node, true); + const startTime = Date.now(); + + try { + const { status, json } = await httpRequestJson( + `${baseUrl}/v1/servers`, + 'GET', + headers, + null, + NODE_POLL_TIMEOUT_MS + ); + + const latency = Date.now() - startTime; + + if (status === 0) { + await setCachedNodeStatus(nodeId, { online: false, latency: null }); + return { nodeId, online: false, servers: [], latency: null }; + } + + if (status !== 200 || !json) { + await setCachedNodeStatus(nodeId, { online: true, latency }); + return { nodeId, online: true, servers: [], latency }; + } + + const servers = Array.isArray(json.servers) ? json.servers : + Array.isArray(json) ? json : []; + + await setCachedNodeStatus(nodeId, { + online: true, + latency, + serverCount: servers.length, + resources: json.resources || null + }); + + for (const server of servers) { + if (!server.name) continue; + await setCachedServerStatus(server.name, { + status: normalizeStatusLabel(server.status || server.state) || 'unknown', + cpu: server.cpu ?? server.cpuPercent ?? null, + cpuLimit: server.cpuLimit ?? null, + memory: server.memory ?? server.memoryMb ?? null, + disk: server.disk ?? server.diskMb ?? null, + uptime: server.uptime ?? null, + nodeOnline: true, + nodeId + }); + } + + return { nodeId, online: true, servers, latency }; + + } catch (err) { + await setCachedNodeStatus(nodeId, { online: false }); + return { nodeId, online: false, servers: [], error: err.message }; + } +} + +async function pollAllNodes() { + if (statusCache.refreshing) { + return; + } + + statusCache.refreshing = true; + + try { + const nodes = await loadNodes(); + + if (!nodes.length) { + statusCache.lastFullRefresh = Date.now(); + return; + } + + const results = []; + for (let i = 0; i < nodes.length; i += NODE_POLL_CONCURRENCY) { + const batch = nodes.slice(i, i + NODE_POLL_CONCURRENCY); + const batchResults = await Promise.all( + batch.map(node => fetchNodeServerStatuses(node).catch(err => ({ + nodeId: node.uuid || node.id, + online: false, + error: err.message + }))) + ); + results.push(...batchResults); + } + + const seenServers = new Set(); + for (const result of results) { + if (result.servers) { + for (const s of result.servers) { + if (s.name) seenServers.add(s.name); + } + } + } + + const serverIndex = await loadServersIndex(); + const nodeToServers = new Map(); + for (const entry of serverIndex) { + if (!entry?.name || seenServers.has(entry.name) || !entry.nodeId) continue; + const list = nodeToServers.get(entry.nodeId) || []; + list.push(entry.name); + nodeToServers.set(entry.nodeId, list); + } + const nodeIds = [...nodeToServers.keys()]; + const BATCH = 50; + for (let i = 0; i < nodeIds.length; i += BATCH) { + const batch = nodeIds.slice(i, i + BATCH); + const nodeStatuses = await Promise.all(batch.map(nid => getCachedNodeStatus(nid).then(s => [nid, s]))); + const offlineUpdates = []; + for (const [nid, nodeStatus] of nodeStatuses) { + if (nodeStatus && !nodeStatus.online) { + for (const serverName of nodeToServers.get(nid)) { + offlineUpdates.push(setCachedServerStatus(serverName, { + status: 'unknown', + nodeOnline: false, + nodeId: nid + })); + } + } + } + if (offlineUpdates.length) await Promise.all(offlineUpdates); + } + + statusCache.lastFullRefresh = Date.now(); + + const onlineNodes = results.filter(r => r.online).length; + const totalServers = results.reduce((sum, r) => sum + (r.servers?.length || 0), 0); + console.log(`[StatusCache] Refreshed: ${onlineNodes}/${nodes.length} nodes online, ${totalServers} servers`); + + } catch (err) { + console.error('[StatusCache] Poll failed:', err); + } finally { + statusCache.refreshing = false; + } +} + + +let _WebSocket; function getLazyWebSocket() { if (!_WebSocket) _WebSocket = require('ws'); return _WebSocket; } + +const WS_RECONNECT_BASE_MS = 2000; +const WS_RECONNECT_MAX_MS = 60000; +const WS_FALLBACK_POLL_MS = 60000; + +const nodeWsConnections = new Map(); + +function getNodeWsUrl(node) { + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return null; + return baseUrl.replace(/^http/, 'ws') + '/v1/ws'; +} + +function connectNodeWebSocket(node) { + const nodeId = node.uuid || node.id || node.name; + const wsUrl = getNodeWsUrl(node); + if (!wsUrl) { + startNodeFallbackPolling(node); + return; + } + + const existing = nodeWsConnections.get(nodeId); + if (existing && existing.ws && existing.ws.readyState === getLazyWebSocket().OPEN) return; + + const token = node.token || node.secret || node.api_key || ''; + const state = existing || { + ws: null, + reconnectTimer: null, + reconnectDelay: WS_RECONNECT_BASE_MS, + fallbackInterval: null, + node + }; + nodeWsConnections.set(nodeId, state); + + try { + const ws = new (getLazyWebSocket())(wsUrl, { + headers: { + 'Authorization': `Bearer ${token}`, + 'X-Node-Token': token + }, + handshakeTimeout: 5000, + maxPayload: 4 * 1024 * 1024 + }); + + state.ws = ws; + + ws.on('open', () => { + console.log(`[NodeWS] Connected to ${node.name || nodeId}`); + state.reconnectDelay = WS_RECONNECT_BASE_MS; + stopNodeFallbackPolling(nodeId); + }); + + ws.on('message', async (data) => { + try { + const msg = JSON.parse(data.toString()); + + if (msg.type === 'status' && msg.ok) { + const latency = null; + const servers = Array.isArray(msg.servers) ? msg.servers : []; + + await setCachedNodeStatus(nodeId, { + online: true, + latency, + serverCount: servers.length, + resources: msg.resources || null + }); + + for (const server of servers) { + if (!server.name) continue; + await setCachedServerStatus(server.name, { + status: normalizeStatusLabel(server.status || server.state) || 'unknown', + cpu: server.cpu ?? server.cpuPercent ?? null, + cpuLimit: server.cpuLimit ?? null, + memory: server.memory ?? server.memoryMb ?? null, + disk: server.disk ?? server.diskMb ?? null, + uptime: server.uptime ?? null, + nodeOnline: true, + nodeId + }); + } + } else if (msg.type === 'event') { + if (msg.server) { + await setCachedServerStatus(msg.server, { + status: normalizeStatusLabel(msg.status) || 'unknown', + nodeOnline: true, + nodeId + }); + } + } + } catch (err) { + } + }); + + ws.on('close', (code) => { + if (isShuttingDown) return; + console.log(`[NodeWS] Disconnected from ${node.name || nodeId} (code: ${code})`); + scheduleReconnect(node); + }); + + ws.on('error', (err) => { + if (isShuttingDown) return; + }); + } catch (err) { + console.error(`[NodeWS] Failed to connect to ${node.name || nodeId}:`, err.message); + scheduleReconnect(node); + } +} + +function scheduleReconnect(node) { + const nodeId = node.uuid || node.id || node.name; + const state = nodeWsConnections.get(nodeId); + if (!state || isShuttingDown) return; + + setCachedNodeStatus(nodeId, { online: false }).catch(() => { }); + + startNodeFallbackPolling(node); + + if (state.reconnectTimer) clearTimeout(state.reconnectTimer); + const jitter = Math.random() * 1000; + const delay = Math.min(state.reconnectDelay + jitter, WS_RECONNECT_MAX_MS); + + state.reconnectTimer = setTimeout(async () => { + const freshNode = await findNodeByIdOrName(nodeId).catch(() => null); + if (freshNode) { + connectNodeWebSocket(freshNode); + } else { + cleanupNodeWs(nodeId); + } + }, delay); + + state.reconnectDelay = Math.min(state.reconnectDelay * 2, WS_RECONNECT_MAX_MS); +} + +function startNodeFallbackPolling(node) { + const nodeId = node.uuid || node.id || node.name; + const state = nodeWsConnections.get(nodeId); + if (!state) return; + if (state.fallbackInterval) return; + + state.fallbackInterval = setInterval(async () => { + try { + await fetchNodeServerStatuses(node); + } catch { } + }, WS_FALLBACK_POLL_MS); + fetchNodeServerStatuses(node).catch(() => { }); +} + +function stopNodeFallbackPolling(nodeId) { + const state = nodeWsConnections.get(nodeId); + if (!state || !state.fallbackInterval) return; + clearInterval(state.fallbackInterval); + state.fallbackInterval = null; +} + +function cleanupNodeWs(nodeId) { + const state = nodeWsConnections.get(nodeId); + if (!state) return; + if (state.ws) { + try { state.ws.close(1000); } catch { } + } + if (state.reconnectTimer) clearTimeout(state.reconnectTimer); + if (state.fallbackInterval) clearInterval(state.fallbackInterval); + nodeWsConnections.delete(nodeId); +} + +function cleanupAllNodeWs() { + for (const [nodeId] of nodeWsConnections) { + cleanupNodeWs(nodeId); + } +} + + +let pollInterval = null; + +async function initNodeConnections() { + const nodes = await loadNodes(); + if (!nodes.length) return; + + await pollAllNodes().catch(console.error); + + for (const node of nodes) { + connectNodeWebSocket(node); + } + + console.log(`[NodeWS] Initialized WebSocket connections to ${nodes.length} node(s)`); +} + +function startStatusPolling() { + if (pollInterval) return; + + setTimeout(() => { + initNodeConnections().catch(console.error); + }, 500); + + pollInterval = setInterval(async () => { + try { + const nodes = await loadNodes(); + const currentIds = new Set(nodes.map(n => n.uuid || n.id || n.name)); + + for (const node of nodes) { + const nodeId = node.uuid || node.id || node.name; + const existing = nodeWsConnections.get(nodeId); + if (!existing || !existing.ws || existing.ws.readyState !== getLazyWebSocket().OPEN) { + connectNodeWebSocket(node); + } + } + + for (const [nodeId] of nodeWsConnections) { + if (!currentIds.has(nodeId)) { + console.log(`[NodeWS] Node ${nodeId} removed, cleaning up`); + cleanupNodeWs(nodeId); + } + } + } catch (err) { + console.error('[NodeWS] Node sync error:', err.message); + } + }, 60_000); + + console.log(`[NodeWS] WebSocket-first status system started`); +} + +function stopStatusPolling() { + if (pollInterval) { + clearInterval(pollInterval); + pollInterval = null; + } + cleanupAllNodeWs(); +} + + +let isShuttingDown = false; +async function gracefulShutdown(signal) { + if (isShuttingDown) return; + isShuttingDown = true; + console.log(`\n[ADPanel] Received ${signal}, shutting down gracefully...`); + + stopStatusPolling(); + + if (typeof stopStatusCleanup === 'function') { + try { stopStatusCleanup(); } catch { } + } + + if (typeof shutdownScheduler === 'function') { + try { await shutdownScheduler(); } catch { } + } + + if (httpServer) { + httpServer.close(() => console.log('[ADPanel] HTTP server closed')); + } + + if (httpsServer) { + httpsServer.close(() => console.log('[ADPanel] HTTPS server closed')); + } + + if (io) { + io.close(() => console.log('[ADPanel] Socket.IO closed')); + } + + try { + await db.close(); + console.log('[ADPanel] Database pool closed'); + } catch (err) { + console.error('[ADPanel] Error closing database:', err?.message || err); + } + + if (redisClient) { + try { + await redisClient.quit(); + console.log('[ADPanel] Redis connection closed'); + } catch (err) { + console.error('[ADPanel] Error closing Redis:', err?.message || err); + } + } + + console.log('[ADPanel] Shutdown complete'); + process.exit(0); +} + +process.on('SIGTERM', () => gracefulShutdown('SIGTERM')); +process.on('SIGINT', () => gracefulShutdown('SIGINT')); + +const STATUS_CLEANUP_INTERVAL_MS = parseInt(process.env.STATUS_CLEANUP_INTERVAL_MS || "", 10) || 60 * 1000; +let statusCleanupInterval = null; + +async function cleanupExpiredStatuses() { + try { + const now = Date.now(); + await db.query("DELETE FROM user_status WHERE expires_at IS NOT NULL AND expires_at <= ?", [now]); + } catch (err) { + } +} + +function startStatusCleanup() { + if (statusCleanupInterval) return; + statusCleanupInterval = setInterval(cleanupExpiredStatuses, STATUS_CLEANUP_INTERVAL_MS); + statusCleanupInterval.unref(); +} + +function stopStatusCleanup() { + if (statusCleanupInterval) { + clearInterval(statusCleanupInterval); + statusCleanupInterval = null; + } +} + +startStatusCleanup(); + +const SCHEDULER_ENABLED = parseBoolean(process.env.SCHEDULER_ENABLED, true); +let schedulerQueue = null; +let schedulerWorker = null; +let schedulerQueueEvents = null; + +function parseRedisUrlForBullMQ(redisUrl) { + if (!redisUrl) { + return { host: "127.0.0.1", port: 6379 }; + } + try { + const url = new URL(redisUrl); + const opts = { + host: url.hostname || "127.0.0.1", + port: parseInt(url.port, 10) || 6379 + }; + if (url.password) opts.password = decodeURIComponent(url.password); + if (url.username && url.username !== "default") opts.username = decodeURIComponent(url.username); + if (url.pathname && url.pathname.length > 1) { + const dbNum = parseInt(url.pathname.slice(1), 10); + if (!isNaN(dbNum)) opts.db = dbNum; + } + return opts; + } catch { + return { host: "127.0.0.1", port: 6379 }; + } +} + +const SCHEDULER_REDIS_URL = REDIS_URL || process.env.SCHEDULER_REDIS_URL || ""; + +async function initializeScheduler() { + if (!SCHEDULER_ENABLED || !SCHEDULER_REDIS_URL) { + if (!SCHEDULER_REDIS_URL) { + console.log("[scheduler] Scheduler disabled - REDIS_URL not configured"); + } + return; + } + + try { + const { Queue, Worker, QueueEvents } = require("bullmq"); + + const bullmqConnectionOpts = parseRedisUrlForBullMQ(SCHEDULER_REDIS_URL); + const bullmqConnection = { connection: bullmqConnectionOpts }; + + schedulerQueue = new Queue("adpanel-scheduler", bullmqConnection); + + schedulerQueueEvents = new QueueEvents("adpanel-scheduler", bullmqConnection); + + schedulerWorker = new Worker("adpanel-scheduler", async (job) => { + const { actionType, serverName, payload, userId, userName } = job.data; + console.log(`[scheduler] Processing job ${job.id}: ${actionType} for server ${serverName}`); + + try { + switch (actionType) { + case "console_command": { + const command = payload?.command; + if (!command) throw new Error("No command specified"); + + const nodesModule = require("./nodes.js"); + const ctx = await nodesModule.remoteContext(serverName); + if (!ctx.exists) throw new Error("Server not found"); + if (!ctx.remote || !ctx.node) throw new Error("Server is not remote"); + + const result = await nodesModule.httpJson( + nodesModule.nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(serverName)}/command`), + { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodesModule.nodeHeaders(ctx.node)), + body: { command }, + timeoutMs: 15000 + } + ); + + if (result.status !== 200 || !result.json?.ok) { + throw new Error(result.json?.error || `Command failed: ${result.status}`); + } + + console.log(`[scheduler] Console command executed: ${command}`); + return { success: true, action: "console_command", command }; + } + + case "server_start": { + const nodesModule = require("./nodes.js"); + const ctx = await nodesModule.remoteContext(serverName); + if (!ctx.exists) throw new Error("Server not found"); + if (!ctx.remote || !ctx.node) throw new Error("Server is not remote"); + + const result = await nodesModule.httpJson( + nodesModule.nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(serverName)}/start`), + { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodesModule.nodeHeaders(ctx.node)), + body: {}, + timeoutMs: 60000 + } + ); + + if (result.status !== 200 || !result.json?.ok) { + throw new Error(result.json?.error || `Start failed: ${result.status}`); + } + + console.log(`[scheduler] Server started: ${serverName}`); + return { success: true, action: "server_start", server: serverName }; + } + + case "server_stop": { + const nodesModule = require("./nodes.js"); + const ctx = await nodesModule.remoteContext(serverName); + if (!ctx.exists) throw new Error("Server not found"); + if (!ctx.remote || !ctx.node) throw new Error("Server is not remote"); + + const result = await nodesModule.httpJson( + nodesModule.nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(serverName)}/stop`), + { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodesModule.nodeHeaders(ctx.node)), + timeoutMs: 30000 + } + ); + + if (result.status !== 200 || !result.json?.ok) { + throw new Error(result.json?.error || `Stop failed: ${result.status}`); + } + + console.log(`[scheduler] Server stopped: ${serverName}`); + return { success: true, action: "server_stop", server: serverName }; + } + + case "create_file": { + const { filePath: targetPath, content } = payload || {}; + if (!targetPath) throw new Error("No file path specified"); + + const nodesModule = require("./nodes.js"); + const ctx = await nodesModule.remoteContext(serverName); + if (!ctx.exists) throw new Error("Server not found"); + if (!ctx.remote || !ctx.node) throw new Error("Server is not remote"); + + const result = await nodesModule.httpJson( + nodesModule.nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(serverName)}/files/${encodeURIComponent(targetPath)}`), + { + method: "PUT", + headers: Object.assign({ "Content-Type": "application/json" }, nodesModule.nodeHeaders(ctx.node)), + body: { content: content || "" }, + timeoutMs: 30000 + } + ); + + if (result.status !== 200 || !result.json?.ok) { + throw new Error(result.json?.error || `File create failed: ${result.status}`); + } + + console.log(`[scheduler] File created: ${targetPath}`); + return { success: true, action: "create_file", path: targetPath }; + } + + case "modify_file": { + const { filePath: targetPath, content } = payload || {}; + if (!targetPath) throw new Error("No file path specified"); + + const nodesModule = require("./nodes.js"); + const ctx = await nodesModule.remoteContext(serverName); + if (!ctx.exists) throw new Error("Server not found"); + if (!ctx.remote || !ctx.node) throw new Error("Server is not remote"); + + const result = await nodesModule.httpJson( + nodesModule.nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(serverName)}/files/${encodeURIComponent(targetPath)}`), + { + method: "PUT", + headers: Object.assign({ "Content-Type": "application/json" }, nodesModule.nodeHeaders(ctx.node)), + body: { content: content || "" }, + timeoutMs: 30000 + } + ); + + if (result.status !== 200 || !result.json?.ok) { + throw new Error(result.json?.error || `File modify failed: ${result.status}`); + } + + console.log(`[scheduler] File modified: ${targetPath}`); + return { success: true, action: "modify_file", path: targetPath }; + } + + case "backup": { + const { backupName, description } = payload || {}; + + const nodesModule = require("./nodes.js"); + const ctx = await nodesModule.remoteContext(serverName); + if (!ctx.exists) throw new Error("Server not found"); + if (!ctx.remote || !ctx.node) throw new Error("Server is not remote"); + + const result = await nodesModule.httpJson( + nodesModule.nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(serverName)}/backups`), + { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodesModule.nodeHeaders(ctx.node)), + body: { name: backupName || `Scheduled Backup ${new Date().toISOString()}`, description: description || "Created by scheduler" }, + timeoutMs: 120000 + } + ); + + if (result.status !== 200 || !result.json?.ok) { + throw new Error(result.json?.error || `Backup failed: ${result.status}`); + } + + console.log(`[scheduler] Backup created: ${backupName || "auto"}`); + return { success: true, action: "backup", backupId: result.json?.backup?.id }; + } + + case "planner_next_to_agent": { + const result = await queueSchedulerPlannerNextToAgent({ serverName, payload, userId, userName }); + console.log(`[scheduler] Queued planner prompt for ADPanel Agent: job ${result.jobId}`); + return { success: true, action: "planner_next_to_agent", ...result }; + } + + case "agent_prompt": { + const result = await queueSchedulerPromptToAgent({ serverName, payload, userId, userName }); + console.log(`[scheduler] Queued custom prompt for ADPanel Agent: job ${result.jobId}`); + return { success: true, action: "agent_prompt", ...result }; + } + + default: + throw new Error(`Unknown action type: ${actionType}`); + } + } catch (err) { + console.error(`[scheduler] Job ${job.id} failed:`, err?.message || err); + throw err; + } + }, { + connection: bullmqConnectionOpts, + concurrency: 5, + removeOnComplete: { count: 100 }, + removeOnFail: { count: 50 } + }); + + schedulerWorker.on("completed", (job, result) => { + console.log(`[scheduler] Job ${job.id} completed:`, result); + }); + + schedulerWorker.on("failed", (job, err) => { + console.error(`[scheduler] Job ${job?.id} failed:`, err?.message || err); + }); + + console.log("[scheduler] BullMQ scheduler initialized successfully"); + } catch (err) { + console.warn("[scheduler] Failed to initialize BullMQ scheduler:", err?.message || err); + schedulerQueue = null; + schedulerWorker = null; + } +} + +function scheduleToCron(scheduleType, scheduleValue, scheduleTime) { + if (scheduleType === "seconds") { + const seconds = parseInt(scheduleValue, 10) || 30; + return { type: "interval", ms: seconds * 1000 }; + } + if (scheduleType === "minutes") { + const minutes = parseInt(scheduleValue, 10) || 5; + return `*/${minutes} * * * *`; + } + if (scheduleType === "hourly") { + const hours = parseInt(scheduleValue, 10) || 1; + return `0 */${hours} * * *`; + } + if (scheduleType === "weekly") { + const day = parseInt(scheduleValue, 10) || 0; + const [hour, minute] = (scheduleTime || "00:00").split(":").map(n => parseInt(n, 10) || 0); + return `${minute} ${hour} * * ${day}`; + } + if (scheduleType === "daily") { + const [hour, minute] = (scheduleTime || "00:00").split(":").map(n => parseInt(n, 10) || 0); + return `${minute} ${hour} * * *`; + } + return null; +} + +async function shutdownScheduler() { + if (schedulerWorker) { + try { + await schedulerWorker.close(); + console.log("[scheduler] Worker closed"); + } catch (err) { + console.error("[scheduler] Error closing worker:", err?.message || err); + } + } + if (schedulerQueueEvents) { + try { + await schedulerQueueEvents.close(); + console.log("[scheduler] QueueEvents closed"); + } catch (err) { + console.error("[scheduler] Error closing queue events:", err?.message || err); + } + } + if (schedulerQueue) { + try { + await schedulerQueue.close(); + console.log("[scheduler] Queue closed"); + } catch (err) { + console.error("[scheduler] Error closing queue:", err?.message || err); + } + } +} + +function parseOriginHost(value) { + if (!value) return ""; + try { + const u = new URL(value); + return extractHostnameFromHeader(u.host || u.hostname || ""); + } catch { + return extractHostnameFromHeader(value); + } +} + +function normalizeHostLower(value) { + const raw = String(value || "").trim().toLowerCase(); + if (!raw || raw === "null" || raw === "undefined") return ""; + const h = extractHostnameFromHeader(raw); + if (!h) return ""; + return h.toLowerCase().replace(/\.+$/, ""); +} + +function isLocalHost(name) { + const h = String(name || "").toLowerCase(); + return h === "localhost" || h === "127.0.0.1" || h === "::1" || h === "[::1]"; +} + +function hostAllowed(headerHost, allowedHosts) { + if (!headerHost) return false; + if (!allowedHosts || allowedHosts.size === 0) return false; + if (allowedHosts.has(headerHost)) return true; + for (const allowed of allowedHosts) { + if (!allowed) continue; + if (headerHost === allowed) return true; + if (allowed.startsWith("*.") || allowed.startsWith(".")) { + const base = allowed.replace(/^\*\./, "").replace(/^\./, ""); + if (!base) continue; + if (headerHost === base || headerHost.endsWith(`.${base}`)) return true; + } + } + return false; +} + +const LOCAL_CAPTCHA_EXP_MS = 75 * 1000; +const LOCAL_CAPTCHA_GRID = 9; +const LOCAL_CAPTCHA_CORRECT_MAX = 2; +const LOCAL_CAPTCHA_MAX_STEPS = 3; +const LOCAL_CAPTCHA_SKIPS_SAFE = 2; +const LOCAL_CAPTCHA_SKIPS_SUS = 1; +const LOCAL_CAPTCHA_REQUIRED_SAFE = 2; +const LOCAL_CAPTCHA_REQUIRED_SUS = 3; +const LOCAL_CAPTCHA_MAX_QUESTIONS_SAFE = 5; +const LOCAL_CAPTCHA_MAX_QUESTIONS_SUS = 4; +const LOCAL_CAPTCHA_MAX_WRONG = 3; + +const LOCAL_CAPTCHA_TYPES = [ + { id: "bridges", prompt: "Select all images with bridges", keyword: "bridge" }, + { id: "bikes", prompt: "Select all images with bicycles", keyword: "bicycle" }, + { id: "crosswalks", prompt: "Select all images with crosswalks", keyword: "crosswalk" }, + { id: "trafficlights", prompt: "Select all images with traffic lights", keyword: "traffic light" }, + { id: "mountains", prompt: "Select all images with mountains", keyword: "mountain" }, + { id: "beaches", prompt: "Select all images with beaches", keyword: "beach" }, + { id: "cats", prompt: "Select all images with cats", keyword: "cat" }, + { id: "dogs", prompt: "Select all images with dogs", keyword: "dog" }, + { id: "planes", prompt: "Select all images with airplanes", keyword: "airplane" }, + { id: "boats", prompt: "Select all images with boats", keyword: "boat" }, + { id: "buses", prompt: "Select all images with buses", keyword: "bus" }, + { id: "trains", prompt: "Select all images with trains", keyword: "train" }, + { id: "statues", prompt: "Select all images with statues", keyword: "statue" }, + { id: "stadiums", prompt: "Select all images with stadiums", keyword: "stadium" }, + { id: "flowers", prompt: "Select all images with flowers", keyword: "flower" }, + { id: "coffee", prompt: "Select all images with coffee cups", keyword: "coffee" }, + { id: "laptops", prompt: "Select all images with laptops", keyword: "laptop" }, + { id: "books", prompt: "Select all images with books", keyword: "book" }, + { id: "skylines", prompt: "Select all images with city skylines", keyword: "city skyline" }, + { id: "umbrellas", prompt: "Select all images with umbrellas", keyword: "umbrella" }, +]; + +function imageUrl(keyword, seed) { + const tag = encodeURIComponent(keyword.replace(/\s+/g, ",")); + return `https://loremflickr.com/360/360/${tag}?lock=${encodeURIComponent(seed)}`; +} + +const LOCAL_CAPTCHA_POOL = LOCAL_CAPTCHA_TYPES; + +function randomPick(arr, count) { + const copy = [...arr]; + for (let i = copy.length - 1; i > 0; i--) { + const j = crypto.randomInt(i + 1); + [copy[i], copy[j]] = [copy[j], copy[i]]; + } + return copy.slice(0, count); +} + +function assignLocalCaptcha(req) { + if (!req.session) return null; + const suspicious = getLoginAttemptCount(getRequestIp(req)) >= 6; + const required = suspicious ? LOCAL_CAPTCHA_REQUIRED_SUS : LOCAL_CAPTCHA_REQUIRED_SAFE; + const allowedSkips = suspicious ? LOCAL_CAPTCHA_SKIPS_SUS : LOCAL_CAPTCHA_SKIPS_SAFE; + const maxQuestions = suspicious ? LOCAL_CAPTCHA_MAX_QUESTIONS_SUS : LOCAL_CAPTCHA_MAX_QUESTIONS_SAFE; + const steps = Math.min(LOCAL_CAPTCHA_MAX_STEPS, maxQuestions); + + const buildQuestion = () => { + const type = LOCAL_CAPTCHA_POOL[crypto.randomInt(LOCAL_CAPTCHA_POOL.length)]; + const decoyType = randomPick(LOCAL_CAPTCHA_POOL.filter((t) => t.id !== type.id), 1)[0] || type; + + const correctCount = Math.min(LOCAL_CAPTCHA_CORRECT_MAX, Math.max(2, LOCAL_CAPTCHA_GRID - 1)); + const decoyCount = Math.max(0, LOCAL_CAPTCHA_GRID - correctCount); + + const nowSeed = Date.now(); + const correctImgs = Array.from({ length: correctCount }, (_, i) => imageUrl(type.keyword, `${nowSeed}-${i}`)); + const decoyImgs = Array.from({ length: decoyCount }, (_, i) => imageUrl(decoyType.keyword, `${nowSeed}-d-${i}`)); + + const grid = randomPick( + correctImgs.map((u) => ({ url: u, correct: true })) + .concat(decoyImgs.map((u) => ({ url: u, correct: false }))), + LOCAL_CAPTCHA_GRID + ); + + const correct = []; + grid.forEach((g, idx) => { + if (g.correct) correct.push(idx); + }); + + return { + id: type.id, + prompt: type.prompt, + images: grid.map((g) => g.url), + correct, + prompt: `${type.prompt} (${correctCount} images)`, + token: crypto.randomBytes(12).toString("hex"), + expiresAt: Date.now() + LOCAL_CAPTCHA_EXP_MS, + used: false, + }; + }; + + const questions = []; + for (let i = 0; i < maxQuestions; i++) questions.push(buildQuestion()); + + req.session.captchaRequired = true; + req.session.localCaptcha = { + idx: 0, + total: steps, + required, + maxQuestions, + questions, + allowedSkips, + usedSkips: 0, + incorrectClicks: 0, + maxIncorrect: LOCAL_CAPTCHA_MAX_WRONG, + answered: 0, + }; + + const current = questions[0]; + if (!current) return null; + return { + id: current.id, + prompt: current.prompt, + images: current.images, + token: current.token, + step: 1, + total: steps, + remainingSkips: getRemainingSkips(req.session.localCaptcha), + }; +} + +function clearLocalCaptcha(req) { + if (req.session) { + req.session.captchaRequired = false; + req.session.localCaptcha = null; + } +} + +function validateLocalCaptcha(req, selectedIndexes, token) { + const saved = req.session?.localCaptcha; + if (!saved || !Array.isArray(saved.questions)) return { ok: false, done: false }; + const current = saved.questions[saved.idx]; + if (!current || !Array.isArray(current.correct) || !current.token) return { ok: false, done: false }; + if (!token || !safeCompare(String(token), String(current.token))) return { ok: false, done: false }; + if (current.used) return { ok: false, done: false }; + if (current.expiresAt && current.expiresAt < Date.now()) return { ok: false, done: false, expired: true }; + + const expected = Array.from(new Set(current.correct.map(Number).filter(Number.isInteger))).sort(); + const provided = Array.from(new Set((selectedIndexes || []).map(Number).filter(Number.isInteger))).sort(); + if (provided.length === 0) return { ok: false, done: false }; + if (provided.length !== expected.length) return { ok: false, done: false }; + for (let i = 0; i < expected.length; i++) { + if (expected[i] !== provided[i]) return { ok: false, done: false }; + } + + current.used = true; + saved.idx += 1; + saved.answered = (saved.answered || 0) + 1; + + let done = false; + if (saved.answered >= saved.required) { + done = true; + } else if (saved.idx >= saved.maxQuestions) { + return { ok: false, done: false, error: "not-enough-answers" }; + } + + if (done) { + req.session.captchaRequired = false; + req.session.captchaSolved = true; + req.session.localCaptcha = null; + } else { + req.session.captchaRequired = true; + req.session.localCaptcha = saved; + } + return { ok: true, done, next: saved.idx + 1, total: saved.total, remainingSkips: getRemainingSkips(saved) }; +} + +function skipLocalCaptcha(req) { + const saved = req.session?.localCaptcha; + if (!saved || !Array.isArray(saved.questions)) return { ok: false, done: false, error: "no-captcha" }; + if (getRemainingSkips(saved) <= 0) return { ok: false, done: false, error: "no-skips-left" }; + + saved.usedSkips = (saved.usedSkips || 0) + 1; + saved.idx += 1; + let done = false; + if (saved.answered >= saved.required) { + done = true; + } else if (saved.idx >= saved.maxQuestions && saved.answered >= saved.required) { + done = true; + } else if (saved.idx >= saved.maxQuestions && saved.answered < saved.required) { + return { ok: false, done: false, error: "not-enough-answers" }; + } + + if (done) { + req.session.captchaRequired = false; + req.session.captchaSolved = true; + req.session.localCaptcha = null; + } else { + req.session.captchaRequired = true; + req.session.localCaptcha = saved; + } + + return { ok: true, done, next: saved.idx + 1, total: saved.total, remainingSkips: getRemainingSkips(saved) }; +} + +function getCurrentCaptchaQuestion(req) { + const saved = req.session?.localCaptcha; + if (!saved || !Array.isArray(saved.questions)) return null; + const current = saved.questions[saved.idx]; + if (!current) return null; + if (current.expiresAt && current.expiresAt < Date.now()) return null; + return { + id: current.id, + prompt: current.prompt, + images: current.images, + token: current.token, + step: (saved.idx || 0) + 1, + total: saved.total || saved.questions.length || 1, + remainingSkips: getRemainingSkips(saved), + required: saved.required || 1, + answered: saved.answered || 0, + }; +} + +const _CSRF_EXTRA_ALLOWED = (process.env.CSRF_ALLOWED_HOSTS || "") + .split(",") + .map(s => normalizeHostLower(s.trim())) + .filter(Boolean); +const _CSRF_PANEL_PUBLIC_HOST = normalizeHostLower(parseOriginHost(process.env.PANEL_PUBLIC_URL || "")); + +async function sameOriginProtection(req, res, next) { + try { + const method = (req.method || "").toUpperCase(); + if (method === "GET" || method === "HEAD" || method === "OPTIONS") return next(); + if (await isOpenNodeRoute(req)) return next(); + + const originHost = normalizeHostLower(parseOriginHost(req.headers.origin || req.headers.Origin || "")); + const refererHost = normalizeHostLower(parseOriginHost(req.headers.referer || req.headers.referrer || "")); + const forwardedHost = normalizeHostLower(getTrustedForwardedHost(req) || ""); + const hostHeader = normalizeHostLower(req.headers.host || ""); + const requestHost = forwardedHost || hostHeader; + + const fetchSite = String(req.headers["sec-fetch-site"] || "").toLowerCase(); + const sameSiteFetch = fetchSite === "same-origin" || fetchSite === "same-site"; + + const allowedHosts = new Set( + [requestHost, forwardedHost, hostHeader, _CSRF_PANEL_PUBLIC_HOST, ..._CSRF_EXTRA_ALLOWED].filter(Boolean) + ); + if (isLocalHost(originHost) || isLocalHost(refererHost)) { + allowedHosts.add("localhost"); + allowedHosts.add("127.0.0.1"); + allowedHosts.add("::1"); + } + + + + if (req.headers.origin === "null" || req.headers.referer === "null") { + if (req.headers.cookie && !sameSiteFetch) return res.status(403).send("CSRF blocked"); + } else if (!originHost && !refererHost) { + if (req.headers.cookie && !sameSiteFetch) return res.status(403).send("CSRF blocked"); + return next(); + } + + if ((originHost || refererHost) && (requestHost || allowedHosts.size > 0)) { + const headerHost = originHost || refererHost; + if (headerHost && !hostAllowed(headerHost, allowedHosts) && !sameSiteFetch) { + return res.status(403).send("CSRF blocked"); + } + } + + return next(); + } catch (err) { + return next(err); + } +} + +app.use(sameOriginProtection); + + +try { + if (!fs.existsSync(SECURITY_FILE)) { + safeWriteJson(SECURITY_FILE, security); + } else { + const raw = fs.readFileSync(SECURITY_FILE, "utf8"); + security = safeMerge(security, JSON.parse(raw) || {}); + } +} catch (err) { + console.error("[rate-limiter] Error ensuring security.json:", err); +} + +try { + fs.watch(SECURITY_FILE, (evtType) => { + if (evtType === "change" || evtType === "rename") { + try { + const raw = fs.readFileSync(SECURITY_FILE, "utf8"); + security = safeMerge(security, JSON.parse(raw) || {}); + } catch { } + } + }); +} catch { } + +const rateRequests = new Map(); +const RATE_LIMIT_EXEMPT_PATHS = new Set([ + "/api/me", + "/health", +]); +const RATE_LIMIT_EXEMPT_PATTERNS = [ + /^\/api\/server\/[^/]+\/node-status$/, +]; +function isRateLimitExempt(path) { + if (RATE_LIMIT_EXEMPT_PATHS.has(path)) return true; + for (const pattern of RATE_LIMIT_EXEMPT_PATTERNS) { + if (pattern.test(path)) return true; + } + return false; +} +const RATE_MAX_TRACKED_IPS = scaleForMemory(50000); +function rateLimiterMiddleware(req, res, next) { + try { + if (!security || security.rate_limiting !== true) return next(); + if (redisClient && req.path.startsWith("/api/")) return next(); + if (isRateLimitExempt(req.path)) return next(); + + const ip = getRequestIp(req); + const now = Date.now(); + const windowMs = (security.window_seconds || 120) * 1000; + const limit = security.limit || 5; + + if (!rateRequests.has(ip) && rateRequests.size >= RATE_MAX_TRACKED_IPS) { + return res.status(503).send("503 Service Busy"); + } + + let arr = rateRequests.get(ip) || []; + arr = arr.filter(ts => (now - ts) <= windowMs); + + if (arr.length >= limit) { + const oldest = arr[0] || now; + const retryAfter = Math.ceil((oldest + windowMs - now) / 1000); + res.setHeader("Retry-After", String(retryAfter)); + return res.status(429).send("429 Too Many Requests"); + } + + arr.push(now); + if (arr.length > limit) arr = arr.slice(-limit); + rateRequests.set(ip, arr); + return next(); + } catch { + return next(); + } +} + +setInterval(() => { + try { + const now = Date.now(); + const windowMs = (security.window_seconds || 120) * 1000; + for (const [ip, arr] of rateRequests.entries()) { + const kept = arr.filter(ts => (now - ts) <= windowMs); + if (kept.length > 0) rateRequests.set(ip, kept); + else rateRequests.delete(ip); + } + } catch { } +}, 30_000).unref(); + +app.use(rateLimiterMiddleware); + +async function loadUsers() { + const rows = await db.query( + "SELECT id, email, admin, agent_access FROM users" + ); + return rows.map(r => ({ + id: r.id, + email: r.email, + admin: !!r.admin, + agent_access: !!(r && r.agent_access) + })); +} + +async function findUserByEmail(email) { + if (!email) return null; + + 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", + [email] + ); + } 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", + [email] + ); + } else { + throw err; + } + } + + const row = rows[0]; + if (!row) return null; + const user = mapUserRow(row); + if (user) { + user.agent_access = !!(row && row.agent_access); + user.avatar_url = row.avatar_url || null; + try { + user.preferences = row.preferences ? JSON.parse(row.preferences) : {}; + } catch (_) { + user.preferences = {}; + } + } + return user; +} + +async function findUserById(id) { + if (!id) return null; + + let rows; + try { + rows = await db.query( + "SELECT id, email, password, secret, admin, 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", + [id] + ); + } else { + throw err; + } + } + + const row = rows[0]; + if (!row) return null; + const user = mapUserRow(row); + if (user) { + user.agent_access = !!(row && row.agent_access); + user.avatar_url = row.avatar_url || null; + try { + user.preferences = row.preferences ? (typeof row.preferences === "string" ? JSON.parse(row.preferences) : row.preferences) : null; + } catch { + user.preferences = null; + } + } + return user; +} + +async function getUserIdByEmail(email) { + if (!email) return null; + const rows = await db.query( + "SELECT id FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", + [email] + ); + return rows[0] ? rows[0].id : null; +} + +async function loadUserAccess() { + const rows = await db.query( + "SELECT u.email, ua.server_name FROM user_access ua JOIN users u ON u.id = ua.user_id ORDER BY u.email" + ); + const grouped = new Map(); + for (const row of rows) { + const email = String(row.email || "").toLowerCase(); + if (!email) continue; + if (!grouped.has(email)) grouped.set(email, { email: row.email, servers: [] }); + grouped.get(email).servers.push(row.server_name); + } + return Array.from(grouped.values()); +} + +async function saveUserAccess(arr) { + const list = Array.isArray(arr) ? arr : []; + const conn = await db.pool.getConnection(); + try { + await conn.beginTransaction(); + for (const rec of list) { + const email = String(rec?.email || "").trim(); + if (!email) continue; + const [userRows] = await conn.execute( + "SELECT id FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", + [email] + ); + if (!userRows[0]) continue; + const userId = userRows[0].id; + await conn.execute("DELETE FROM user_access WHERE user_id = ?", [userId]); + const servers = Array.isArray(rec.servers) ? rec.servers : []; + for (const server of servers) { + await conn.execute( + "INSERT IGNORE INTO user_access (user_id, server_name) VALUES (?, ?)", + [userId, server] + ); + } + } + await conn.commit(); + return true; + } catch (err) { + try { await conn.rollback(); } catch { } + console.error("[db] saveUserAccess failed:", err); + return false; + } finally { + conn.release(); + } +} + +async function getAccessListForEmail(email) { + if (!email) return []; + const rows = await db.query( + "SELECT ua.server_name FROM user_access ua JOIN users u ON u.id = ua.user_id WHERE LOWER(u.email) = LOWER(?)", + [email] + ); + return rows.map(r => r.server_name); +} + +async function addAccessForEmail(email, server) { + if (!email || !server) return false; + const userId = await getUserIdByEmail(email); + if (!userId) return false; + await db.query( + "INSERT IGNORE INTO user_access (user_id, server_name) VALUES (?, ?)", + [userId, server] + ); + return true; +} + +async function removeAccessForEmail(email, server) { + if (!email || !server) return false; + const userId = await getUserIdByEmail(email); + if (!userId) return false; + await db.query( + "DELETE FROM user_access WHERE user_id = ? AND server_name = ?", + [userId, server] + ); + return true; +} + +async function removeAccessForServerName(server) { + if (!server) return false; + await db.query("DELETE FROM user_access WHERE server_name = ?", [server]); + return true; +} + +async function userHasAccessToServer(email, botName) { + if (!email) return false; + const u = await findUserByEmail(email); + if (u && u.admin) return true; + const access = await getAccessListForEmail(email); + if (!access || access.length === 0) return false; + + const lowerAccess = access.map(s => String(s).toLowerCase()); + const lowerBot = String(botName).toLowerCase(); + + if (lowerAccess.includes("all")) return true; + return lowerAccess.includes(lowerBot); +} + +async function getLoggedInUser(req) { + if (!req) return null; + if (Object.prototype.hasOwnProperty.call(req, "currentUser")) { + return req.currentUser; + } + const email = req.session && req.session.user; + if (!email) { + req.currentUser = null; + return null; + } + const user = await findUserByEmail(email); + req.currentUser = user || null; + return req.currentUser; +} + +async function isAuthenticated(req) { + return !!(await getLoggedInUser(req)); +} + +async function isAdmin(req) { + const u = await getLoggedInUser(req); + return !!(u && u.admin); +} + +app.use(async (req, _res, next) => { + if (req._staticAsset) return next(); + try { + req.isAdmin = await isAdmin(req); + next(); + } catch (err) { + next(err); + } +}); + +const MAINTENANCE_BYPASS_PATHS = new Set([ + "/login", + "/logout", + "/api/maintenance/status", + "/favicon.ico", + "/register", + "/forgot-password" +]); + +app.use(async (req, res, next) => { + try { + if (MAINTENANCE_BYPASS_PATHS.has(req.path) || + req.path.startsWith("/css") || + req.path.startsWith("/js") || + req.path.startsWith("/images") || + req.path.startsWith("/css-ext") || + req.path.endsWith(".css") || + req.path.endsWith(".js") || + req.path.endsWith(".webp") || + req.path.endsWith(".png") || + req.path.endsWith(".avif") || + req.path.endsWith(".ico") || + req.path.endsWith(".woff2")) { + return next(); + } + + if (!isMaintenanceActive()) return next(); + + if (req.isAdmin) return next(); + + if (req.path.startsWith("/api/")) { + return res.status(503).json({ + error: "maintenance", + message: "The panel is currently under maintenance. Please try again later." + }); + } + + const state = getMaintenanceState(); + return res.status(503).render("maintenance", { + reason: state.reason || null, + cspNonce: res.locals.cspNonce || "" + }); + } catch (err) { + return next(err); + } +}); + +let _siCache = null; +let _siCacheTs = 0; +let _siInflight = null; +const SI_CACHE_TTL = parseInt(process.env.SERVER_INDEX_CACHE_TTL_MS || "5000", 10) || 5000; + +async function loadServersIndex() { + const now = Date.now(); + 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" + ).then(rows => { + const mapped = rows.map(mapServerRow); + _siCache = mapped; + _siCacheTs = Date.now(); + return mapped; + }).finally(() => { _siInflight = null; }); + return (await _siInflight).slice(); +} + +function invalidateServerIndexCache() { + _siCache = null; + _siCacheTs = 0; +} + +async function saveServersIndex(list) { + const safeList = Array.isArray(list) ? list : []; + const names = safeList.map(s => s && s.name).filter(Boolean); + const nameSet = new Set(names); + const conn = await db.pool.getConnection(); + try { + await conn.beginTransaction(); + const [existingRows] = await conn.execute("SELECT name FROM servers"); + const existing = new Set(existingRows.map(r => r.name)); + + const toDelete = [...existing].filter(n => !nameSet.has(n)); + if (toDelete.length > 0) { + const DBATCH = 500; + for (let i = 0; i < toDelete.length; i += DBATCH) { + const batch = toDelete.slice(i, i + DBATCH); + const placeholders = batch.map(() => '?').join(','); + await conn.execute(`DELETE FROM servers WHERE name IN (${placeholders})`, batch); + } + } + + for (const entry of safeList) { + if (!entry || !entry.name) continue; + const cleanEntry = { ...entry }; + delete cleanEntry.startupCommand; + if (cleanEntry.runtime && typeof cleanEntry.runtime === "object") { + cleanEntry.runtime = { ...cleanEntry.runtime }; + delete cleanEntry.runtime.startupCommand; + } + if (cleanEntry.docker && typeof cleanEntry.docker === "object") { + cleanEntry.docker = { ...cleanEntry.docker }; + delete cleanEntry.docker.startupCommand; + } + const legacyId = cleanEntry.id ? String(cleanEntry.id) : null; + const runtime = toDbJson(cleanEntry.runtime); + const docker = toDbJson(cleanEntry.docker); + const acl = toDbJson(cleanEntry.acl); + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + display_name = COALESCE(VALUES(display_name), display_name), + legacy_id = VALUES(legacy_id), + bot = VALUES(bot), + template = VALUES(template), + start = VALUES(start), + node_id = VALUES(node_id), + ip = VALUES(ip), + port = VALUES(port), + status = VALUES(status), + runtime = VALUES(runtime), + docker = VALUES(docker), + acl = VALUES(acl), + resources = VALUES(resources)`, + [ + cleanEntry.name, + cleanEntry.displayName || null, + legacyId, + cleanEntry.bot || null, + cleanEntry.template || null, + cleanEntry.start || null, + cleanEntry.nodeId || null, + cleanEntry.ip || null, + cleanEntry.port == null ? null : Number(cleanEntry.port), + cleanEntry.status || null, + runtime, + docker, + acl, + resources, + ] + ); + } + await conn.commit(); + invalidateServerIndexCache(); + return true; + } catch (err) { + try { await conn.rollback(); } catch { } + console.error("[db] saveServersIndex failed:", err); + return false; + } finally { + conn.release(); + } +} + +async function upsertServerIndexEntry(entry) { + if (!entry || !entry.name) return false; + const existing = await findServer(entry.name); + const merged = existing ? safeMerge(Object.assign({}, existing), entry) : entry; + if (merged && typeof merged === "object") { + delete merged.startupCommand; + if (merged.runtime && typeof merged.runtime === "object") { + delete merged.runtime.startupCommand; + } + if (merged.docker && typeof merged.docker === "object") { + delete merged.docker.startupCommand; + } + } + 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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE + display_name = COALESCE(VALUES(display_name), display_name), + legacy_id = VALUES(legacy_id), + bot = VALUES(bot), + template = VALUES(template), + start = VALUES(start), + node_id = VALUES(node_id), + ip = VALUES(ip), + port = VALUES(port), + status = VALUES(status), + runtime = VALUES(runtime), + docker = VALUES(docker), + acl = VALUES(acl), + resources = VALUES(resources)`, + [ + merged.name, + merged.displayName || null, + legacyId, + merged.bot || null, + merged.template || null, + merged.start || null, + merged.nodeId || null, + merged.ip || null, + merged.port == null ? null : Number(merged.port), + merged.status || null, + toDbJson(merged.runtime), + toDbJson(merged.docker), + toDbJson(merged.acl), + toDbJson(merged.resources), + ] + ); + invalidateServerIndexCache(); + return true; +} + +function isIgnorableServerCleanupDbError(err) { + const code = String(err?.code || ""); + const msg = String(err?.message || "").toLowerCase(); + return code === "ER_NO_SUCH_TABLE" || + code === "ER_BAD_FIELD_ERROR" || + msg.includes("doesn't exist") || + msg.includes("unknown table") || + msg.includes("unknown column"); +} + +async function bestEffortServerCleanup(query, params) { + try { + await db.query(query, params); + } catch (err) { + if (!isIgnorableServerCleanupDbError(err)) throw err; + } +} + +function sqlPlaceholders(values) { + return values.map(() => "?").join(","); +} + +async function removeServerIndexEntry(name) { + const rawName = String(name || "").trim(); + if (!rawName) return false; + + const needle = rawName.toLowerCase(); + const rows = await db.query( + `SELECT id, name, legacy_id, bot FROM servers + WHERE LOWER(name) = ? OR LOWER(legacy_id) = ? OR LOWER(bot) = ?`, + [needle, needle, needle] + ).catch(() => []); + + const aliases = new Set([rawName]); + const serverIds = []; + for (const row of rows || []) { + if (row?.id != null) serverIds.push(row.id); + for (const key of ["name", "legacy_id", "bot"]) { + const value = String(row?.[key] || "").trim(); + if (value) aliases.add(value); + } + } + + const aliasList = [...aliases]; + if (aliasList.length > 0) { + const ph = sqlPlaceholders(aliasList); + await bestEffortServerCleanup(`DELETE FROM user_access WHERE server_name IN (${ph})`, aliasList); + await bestEffortServerCleanup(`DELETE FROM server_planner_items WHERE server_name IN (${ph})`, aliasList); + await bestEffortServerCleanup(`DELETE FROM sftp_credentials WHERE server_name IN (${ph})`, aliasList); + await bestEffortServerCleanup(`DELETE FROM ai_agent_jobs WHERE server_name IN (${ph})`, aliasList); + } + + if (serverIds.length > 0) { + const idPh = sqlPlaceholders(serverIds); + await bestEffortServerCleanup(`DELETE FROM subdomains WHERE server_id IN (${idPh})`, serverIds); + } + + if (aliasList.length > 0) { + const ph = sqlPlaceholders(aliasList); + await db.query( + `DELETE FROM servers WHERE name IN (${ph}) OR legacy_id IN (${ph}) OR bot IN (${ph})`, + [...aliasList, ...aliasList, ...aliasList] + ); + } else { + await db.query("DELETE FROM servers WHERE name = ?", [rawName]); + } + + invalidateServerIndexCache(); + return true; +} + +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 + FROM servers + WHERE LOWER(name) = ? OR LOWER(legacy_id) = ? OR LOWER(bot) = ? + LIMIT 1`, + [needle, needle, needle] + ); + return mapServerRow(rows[0]) || null; +} + +function findServerIndex(list, botName) { + const needle = String(botName || "").trim().toLowerCase(); + if (!needle) return -1; + return list.findIndex(s => { + if (!s) return false; + if (s.name && String(s.name).toLowerCase() === needle) return true; + if (s.id && String(s.id).toLowerCase() === needle) return true; + if (s.bot && String(s.bot).toLowerCase() === needle) return true; + return false; + }); +} + +function isRemoteEntry(entry) { + return !!(entry && entry.nodeId && entry.nodeId !== "local"); +} + +const ALLOWED_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", + "server_reinstall", +]; + +async function getEffectivePermsForUserOnServer(email, serverName) { + const permsTemplate = { + files_read: false, + files_delete: false, + files_rename: false, + files_archive: false, + console_read: false, + console_write: false, + server_stop: false, + server_start: false, + files_upload: false, + files_create: false, + activity_logs: false, + backups_view: false, + backups_create: false, + backups_delete: false, + scheduler_access: false, + scheduler_create: false, + scheduler_delete: false, + store_access: false, + server_reinstall: false, + }; + + if (!email || !serverName) return permsTemplate; + + const u = await findUserByEmail(email); + + const needle = String(serverName).trim().toLowerCase(); + const entry = await findServer(needle); + const acl = entry && entry.acl && typeof entry.acl === "object" ? entry.acl : null; + const rec = acl ? acl[String(email).toLowerCase()] : null; + + if (u && u.admin) { + const allTrue = {}; + for (const k of Object.keys(permsTemplate)) allTrue[k] = true; + return allTrue; + } + + if (rec && typeof rec === "object") { + const merged = { ...permsTemplate }; + for (const k of Object.keys(merged)) merged[k] = !!rec[k]; + if (!Object.prototype.hasOwnProperty.call(rec, "console_read") && rec.console_write) { + merged.console_read = true; + } + if (rec.backups_manage) { + merged.backups_view = true; + merged.backups_create = true; + merged.backups_delete = true; + } + return merged; + } + + return permsTemplate; +} + +nodesRouter.setPermissionCheckers(getEffectivePermsForUserOnServer, isAdmin, userHasAccessToServer); + +async function loadNodes() { + const rows = await db.query( + "SELECT id, uuid, name, address, ram_mb, disk_gb, ports, token_id, token, created_at, api_port, sftp_port, max_upload_mb, port_ok, last_seen, last_check, online, build_config FROM nodes" + ); + return rows.map(mapNodeRow); +} + +async function findNodeByIdOrName(idOrName) { + const key = String(idOrName || "").trim().toLowerCase(); + if (!key) return null; + const rows = await db.query( + `SELECT id, uuid, name, address, ram_mb, disk_gb, ports, token_id, token, created_at, api_port, sftp_port, max_upload_mb, port_ok, last_seen, last_check, online, build_config + FROM nodes + WHERE LOWER(id) = ? OR LOWER(uuid) = ? OR LOWER(name) = ? + LIMIT 1`, + [key, key, key] + ); + return mapNodeRow(rows[0]) || null; +} + +function buildNodeBaseUrl(address, port, sslEnabled, underCloudflare = false) { + let base = String(address || "").trim(); + if (!base) return null; + const cloudflareProxy = truthyFlag(underCloudflare); + if (/^https?:\/\//i.test(base)) { + try { + const u = new URL(base); + if (u.username || u.password) return null; + u.hash = ""; + u.search = ""; + u.pathname = ""; + if (cloudflareProxy) { + u.protocol = "https:"; + const edgePort = cloudflareHttpsEdgePort(u.port || port); + u.port = edgePort === 443 ? "" : String(edgePort); + return u.origin; + } + if (!u.port) u.port = String(clampApiPort(port || 8080)); + return u.origin; + } catch { } + } + if (cloudflareProxy) { + base = base.split(/[/?#]/)[0]; + const edgePort = cloudflareHttpsEdgePort(explicitHostPort(base) || port); + base = stripExplicitHostPort(base); + if (edgePort !== 443) base += `:${edgePort}`; + return `https://${base}`; + } + const defaultScheme = sslEnabled ? "https" : (process.env.NODE_DEFAULT_SCHEME || "http"); + return `${defaultScheme}://${base}:${clampApiPort(port || 8080)}`; +} + +function nodeAuthHeadersFor(node, isRemote) { + const h = { "Content-Type": "application/json" }; + const remoteToken = node && (node.token || node.secret || node.api_key); + if (isRemote && remoteToken) { + h.Authorization = `Bearer ${remoteToken}`; + h["X-Node-Token"] = remoteToken; + if (node.token_id) h["X-Node-Token-Id"] = node.token_id; + return h; + } + if (!isRemote && LOCAL_NODE_TOKEN) { + h.Authorization = `Bearer ${LOCAL_NODE_TOKEN}`; + h["X-Node-Token"] = LOCAL_NODE_TOKEN; + } + return h; +} + +function signPanelAdminReinstallHeaders(headers, node, serverName, templateId) { + if (!headers || typeof headers !== "object") return false; + const role = "admin"; + const ts = String(Date.now()); + const name = String(serverName || "").trim(); + const template = String(templateId || "").trim().toLowerCase(); + if (!name || !template) return false; + + const nodeToken = String((node && (node.token || node.secret || node.api_key)) || "").trim(); + const signingSecret = PANEL_HMAC_SECRET || nodeToken; + if (!signingSecret) return false; + + const base = `${name}|reinstall|${template}|${role}|${ts}`; + const sig = crypto.createHmac("sha256", signingSecret).update(base).digest("hex"); + + headers["x-panel-role"] = role; + headers["x-panel-ts"] = ts; + headers["x-panel-sign"] = sig; + return true; +} + + +async function verifyExternalCaptcha(token, remoteIp) { + if (!EXTERNAL_CAPTCHA_ENABLED) return { ok: true }; + if (!token) return { ok: false, error: "missing-captcha-token" }; + + if (EXTERNAL_CAPTCHA_IS_CF) { + const body = JSON.stringify({ + secret: EXTERNAL_CAPTCHA_SECRET, + response: token, + remoteip: remoteIp || undefined, + }); + + const res = await new Promise((resolve) => { + const req = https.request( + "https://challenges.cloudflare.com/turnstile/v0/siteverify", + { + method: "POST", + headers: { + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(body), + }, + timeout: 6000, + }, + (r) => { + const chunks = []; + r.on("data", (d) => chunks.push(d)); + r.on("end", () => { + try { + const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); + resolve({ status: r.statusCode || 0, json: parsed }); + } catch { + resolve({ status: r.statusCode || 0, json: null }); + } + }); + } + ); + + req.on("error", () => resolve({ status: 0, json: null })); + req.on("timeout", () => { + try { req.destroy(); } catch { } + resolve({ status: 0, json: null }); + }); + + req.write(body); + req.end(); + }); + + if (res.status !== 200 || !(res.json && res.json.success)) { + return { ok: false, error: "captcha-validation-failed" }; + } + return { ok: true }; + } + + if (EXTERNAL_CAPTCHA_IS_HCAPTCHA) { + const payload = `secret=${encodeURIComponent(EXTERNAL_CAPTCHA_SECRET)}&response=${encodeURIComponent(token)}&remoteip=${encodeURIComponent(remoteIp || "")}&sitekey=${encodeURIComponent(EXTERNAL_CAPTCHA_SITE_KEY)}`; + + const res = await new Promise((resolve) => { + const req = https.request( + "https://api.hcaptcha.com/siteverify", + { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + "Content-Length": Buffer.byteLength(payload), + }, + timeout: 6000, + }, + (r) => { + const chunks = []; + r.on("data", (d) => chunks.push(d)); + r.on("end", () => { + try { + const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); + resolve({ status: r.statusCode || 0, json: parsed }); + } catch { + resolve({ status: r.statusCode || 0, json: null }); + } + }); + } + ); + + req.on("error", () => resolve({ status: 0, json: null })); + req.on("timeout", () => { + try { req.destroy(); } catch { } + resolve({ status: 0, json: null }); + }); + + req.write(payload); + req.end(); + }); + + if (res.status !== 200 || !(res.json && res.json.success)) { + return { ok: false, error: "captcha-validation-failed" }; + } + return { ok: true }; + } + + const payload = `secret=${encodeURIComponent(EXTERNAL_CAPTCHA_SECRET)}&response=${encodeURIComponent(token)}${remoteIp ? `&remoteip=${encodeURIComponent(remoteIp)}` : ""}`; + + const res = await new Promise((resolve) => { + const req = https.request( + "https://www.google.com/recaptcha/api/siteverify", + { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + "Content-Length": Buffer.byteLength(payload), + }, + timeout: 6000, + }, + (r) => { + const chunks = []; + r.on("data", (d) => chunks.push(d)); + r.on("end", () => { + try { + const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8")); + resolve({ status: r.statusCode || 0, json: parsed }); + } catch { + resolve({ status: r.statusCode || 0, json: null }); + } + }); + } + ); + + req.on("error", () => resolve({ status: 0, json: null })); + req.on("timeout", () => { + try { req.destroy(); } catch { } + resolve({ status: 0, json: null }); + }); + + req.write(payload); + req.end(); + }); + + if (res.status !== 200 || !(res.json && res.json.success)) { + return { ok: false, error: "captcha-validation-failed" }; + } + + return { ok: true }; +} + +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"); + + const info = await httpRequestJson(`${baseUrl}/v1/info`, "GET", { Authorization: `Bearer ${node.token}` }, null, 5000); + if (info.status !== 200 || !(info.json && info.json.ok)) throw new Error("node not reachable"); + + const headers = { Authorization: `Bearer ${node.token}`, "Content-Type": "application/json" }; + + let res = await httpRequestJson( + `${baseUrl}/v1/servers/create`, + "POST", + headers, + payload, + 600_000 + ); + + if (isRecoverableNodeCreateStatus(res.status)) { + console.warn(`[createOnRemoteNode] recoverable transport status ${res.status} — verifying server on node...`); + const recovered = await waitForServerReady(node, payload.name, { + timeoutMs: nodeUnderCloudflare(node) ? 180_000 : 30_000, + intervalMs: 3000, + }); + if (recovered) { + return { ok: true, name: payload.name, recovered: true }; + } + res = await httpRequestJson( + `${baseUrl}/v1/servers/create`, + "POST", + headers, + payload, + 600_000 + ); + } + + if (res.status !== 200 || !(res.json && res.json.ok)) { + const errorText = String(res.json?.error || "").trim(); + const detailText = String(res.json?.detail || "").trim(); + const msg = detailText + ? (errorText ? `${errorText}: ${detailText}` : detailText) + : (errorText || `remote create failed (${res.status})`); + throw new Error(msg); + } + + return res.json; +} + +function nodeIdentitySet(node) { + return new Set([ + node?.uuid, + node?.id, + node?.name, + node?.address, + ].map(v => String(v || "").trim().toLowerCase()).filter(Boolean)); +} + +function entryBelongsToNode(entry, node) { + if (!entry || !node) return false; + const ids = nodeIdentitySet(node); + const nodeId = String(entry.nodeId || "").trim().toLowerCase(); + const ip = String(entry.ip || "").trim().toLowerCase(); + return (!!nodeId && ids.has(nodeId)) || (!!ip && ids.has(ip)); +} + +async function findServerUsingNodePort(node, port, excludeName = "") { + const p = validatePort(port); + if (!p) return null; + const excluded = String(excludeName || "").trim().toLowerCase(); + const list = await loadServersIndex(); + for (const entry of list) { + 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; + } + return null; +} + +async function checkRemoteNodePortAvailability(node, port) { + 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 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 }; + } + return { ok: false, verified: false, status: r.status, error: r.json?.error || "port-check-unavailable" }; +} + +function configuredNodeCapacity(node) { + return { + ramMb: Math.max(0, Math.trunc(Number(node?.ram_mb || node?.buildConfig?.ram_mb || 0))), + cpuCores: Math.max(0, Number(node?.buildConfig?.cpu_cores || node?.buildConfig?.cpuCores || node?.cpu_cores || 0)), + diskGb: Math.max(0, Number(node?.disk_gb || node?.buildConfig?.disk_gb || node?.buildConfig?.diskGb || 0)), + }; +} + +function mergeNodeCapacityValue(configured, live, round = false, preferLive = false) { + const cfg = Number(configured); + const detected = Number(live); + let value = 0; + if (preferLive && Number.isFinite(detected) && detected > 0) value = detected; + else if (Number.isFinite(cfg) && cfg > 0 && Number.isFinite(detected) && detected > 0) value = Math.min(cfg, detected); + else if (Number.isFinite(detected) && detected > 0) value = detected; + else if (Number.isFinite(cfg) && cfg > 0) value = cfg; + return round ? Math.trunc(value) : value; +} + +function resolveEffectiveNodeCapacity(node, liveCapacity = null) { + const configured = configuredNodeCapacity(node); + const live = (liveCapacity && typeof liveCapacity === "object") ? liveCapacity : {}; + return { + ramMb: mergeNodeCapacityValue(configured.ramMb, live.ramMb, true, true), + cpuCores: mergeNodeCapacityValue(configured.cpuCores, live.cpuCores, false), + diskGb: mergeNodeCapacityValue(configured.diskGb, live.diskGb, false), + }; +} + +async function fetchLiveNodeCapacity(node) { + if (!node) return null; + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return null; + + const headers = nodeAuthHeadersFor(node, !isLocalHost(node.address)); + const result = await httpRequestJson(`${baseUrl}/api/system/stats`, "GET", headers, null, 8000); + if (!result || result.status !== 200 || !result.json || !result.json.ok) return null; + + const data = result.json; + return { + ramMb: Math.max(0, Math.trunc(Number(data.ram_total_mb || data.memory_total_mb || 0))), + cpuCores: Math.max(0, Number(data.cpu_cores || data.cores || 0)), + diskGb: Math.max(0, Number(data.disk_total_gb || 0)), + }; +} + +async function getEffectiveNodeCapacity(node) { + let liveCapacity = null; + try { + liveCapacity = await fetchLiveNodeCapacity(node); + } catch { } + return resolveEffectiveNodeCapacity(node, liveCapacity); +} + +function safeJoinUnix(baseDir, rel) { + const base = path.posix.normalize(String(baseDir ?? "")).replace(/\0/g, ""); + const raw = String(rel ?? "").replace(/\0/g, ""); + if (path.posix.isAbsolute(raw)) throw new Error("Absolute path not allowed"); + + const normalized = path.posix.normalize("/" + raw).replace(/^\/+/, ""); + if (normalized === ".." || normalized.startsWith("../") || normalized.includes("/../")) { + throw new Error("Unix path traversal detected"); + } + return path.posix.join(base, normalized); +} + +const PATH_TRAVERSAL_ERRORS = new Set(["Absolute path not allowed", "Unix path traversal detected"]); + +function maskPathErrorMessage(err, traversalFallback, defaultFallback) { + const msg = String(err?.message || ""); + if (PATH_TRAVERSAL_ERRORS.has(msg)) return traversalFallback; + return msg || defaultFallback; +} + +function sanitizeUploadFilename(name) { + const raw = String(name ?? "").replace(/\0/g, "").trim(); + if (!raw) return null; + const base = path.posix.basename(raw); + const withoutSlashes = base.replace(/[\\/]/g, ""); + const cleaned = withoutSlashes.replace(/^\.+/, "").replace(/[^\w.\- ]+/g, "_").trim(); + if (!cleaned || cleaned === "." || cleaned === "..") return null; + return cleaned.slice(0, 255); +} + +function normalizeExtensionList(input) { + return new Set( + String(input || "") + .split(",") + .map(s => s.trim().toLowerCase()) + .filter(Boolean) + .map(ext => (ext.startsWith(".") ? ext : `.${ext}`)) + ); +} + +const UPLOAD_ALLOWED_EXTENSIONS = normalizeExtensionList(process.env.UPLOAD_ALLOWED_EXTENSIONS); +const UPLOAD_BLOCKED_EXTENSIONS = normalizeExtensionList(process.env.UPLOAD_BLOCKED_EXTENSIONS); +const UPLOAD_MULTIPART_EXTENSIONS = [".tar.gz", ".tar.bz2", ".tar.xz", ".tar.zst"]; + +function getUploadExtension(filename) { + const lower = String(filename || "").toLowerCase(); + for (const ext of UPLOAD_MULTIPART_EXTENSIONS) { + if (lower.endsWith(ext)) return ext; + } + const single = path.posix.extname(lower); + return single || ""; +} + +function isUploadExtensionAllowed(filename) { + const ext = getUploadExtension(filename); + if (ext && UPLOAD_BLOCKED_EXTENSIONS.has(ext)) return false; + if (UPLOAD_ALLOWED_EXTENSIONS.size === 0) return true; + return !!(ext && UPLOAD_ALLOWED_EXTENSIONS.has(ext)); +} + +async function nodeFsPost(node, endpoint, payload, timeoutMs = 20000) { + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return { status: 0, json: null }; + const headers = nodeAuthHeadersFor(node, true); + return httpRequestJson(`${baseUrl}${endpoint}`, "POST", headers, payload, timeoutMs); +} + +function finiteUploadNumber(value) { + const num = Number(value); + return Number.isFinite(num) ? num : null; +} + +function formatUploadBytes(bytes) { + const num = finiteUploadNumber(bytes); + if (!num || num <= 0) return "0 B"; + const units = ["B", "KB", "MB", "GB", "TB"]; + let value = num; + let index = 0; + while (value >= 1024 && index < units.length - 1) { + value /= 1024; + index += 1; + } + return `${value.toFixed(value >= 10 || index === 0 ? 0 : 1)} ${units[index]}`; +} + +function parseNodeDiskSnapshot(payload) { + const disk = payload?.disk || {}; + const statsDisk = payload?.stats?.disk || {}; + let usedBytes = finiteUploadNumber(disk.usedBytes); + let limitBytes = finiteUploadNumber(disk.limitBytes); + + if (usedBytes == null) { + const usedMb = finiteUploadNumber(disk.usedMb ?? statsDisk.usedMb); + const usedGb = finiteUploadNumber(disk.usedGb ?? statsDisk.usedGb); + if (usedMb != null) usedBytes = usedMb * 1024 * 1024; + else if (usedGb != null) usedBytes = usedGb * 1024 * 1024 * 1024; + } + if (limitBytes == null) { + const limitMb = finiteUploadNumber(disk.limitMb ?? statsDisk.limitMb); + const limitGb = finiteUploadNumber(disk.limitGb ?? statsDisk.limitGb); + if (limitMb != null) limitBytes = limitMb * 1024 * 1024; + else if (limitGb != null) limitBytes = limitGb * 1024 * 1024 * 1024; + } + + usedBytes = Math.max(0, Math.round(usedBytes || 0)); + limitBytes = limitBytes && limitBytes > 0 ? Math.round(limitBytes) : 0; + return { + usedBytes, + limitBytes, + remainingBytes: limitBytes > 0 ? Math.max(0, limitBytes - usedBytes) : null, + }; +} + +async function fetchNodeDiskSnapshot(node, serverName, timeoutMs = 5000) { + const baseUrl = buildNodeBaseUrl(node?.address, node?.api_port || 8080, node?.ssl_enabled, nodeUnderCloudflare(node)); + const safeServerName = sanitizeServerName(serverName) || String(serverName || "").trim(); + if (!baseUrl || !safeServerName) return null; + const result = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(safeServerName)}`, + "GET", + nodeAuthHeadersFor(node, true), + null, + timeoutMs + ); + if (result.status !== 200 || !result.json) return null; + return parseNodeDiskSnapshot(result.json); +} + +function buildDiskLimitUploadError(snapshot, incomingBytes, replacedBytes = 0) { + const limitBytes = finiteUploadNumber(snapshot?.limitBytes); + if (!limitBytes || limitBytes <= 0) return null; + const usedBytes = Math.max(0, Math.round(finiteUploadNumber(snapshot?.usedBytes) || 0)); + const uploadBytes = Math.max(0, Math.round(finiteUploadNumber(incomingBytes) || 0)); + const replaceBytes = Math.max(0, Math.round(finiteUploadNumber(replacedBytes) || 0)); + const extraBytes = Math.max(0, uploadBytes - replaceBytes); + const projectedBytes = usedBytes + extraBytes; + if (projectedBytes <= limitBytes) return null; + const remainingBytes = Math.max(0, limitBytes - usedBytes); + return { + ok: false, + error: "disk_limit_exceeded", + message: `Upload would exceed this server's disk limit. Used: ${formatUploadBytes(usedBytes)} / ${formatUploadBytes(limitBytes)}. File: ${formatUploadBytes(uploadBytes)}. Remaining: ${formatUploadBytes(remainingBytes)}.`, + usedBytes, + limitBytes, + remainingBytes, + incomingBytes: uploadBytes, + projectedBytes, + usedMb: usedBytes / (1024 * 1024), + limitMb: limitBytes / (1024 * 1024), + }; +} + +function sanitizeNodeUploadFilename(raw) { + let s = String(raw || "").trim().replace(/\\/g, "/"); + s = path.posix.basename(s); + s = s.replace(/\s+/g, "-").replace(/[^\w\-_.]+/g, "").replace(/^[-_.]+|[-_.]+$/g, ""); + while (s && !/^[A-Za-z0-9]/.test(s)) s = s.slice(1); + if (s.length > 120) s = s.slice(0, 120); + return s || "upload.bin"; +} + +async function fetchNodeReplacementBytes(node, targetDir, uploadName, timeoutMs = 5000) { + const safeName = sanitizeNodeUploadFilename(uploadName); + if (!safeName) return null; + const { status, json } = await nodeFsPost(node, "/v1/fs/list", { path: targetDir, depth: 1 }, timeoutMs); + if (status !== 200 || !json || json.ok !== true || !Array.isArray(json.entries)) return null; + const existing = json.entries.find((entry) => entry && entry.name === safeName); + if (!existing || existing.type === "dir" || existing.isDir) return 0; + const size = finiteUploadNumber(existing.size); + return size && size > 0 ? size : 0; +} + +async function resolveRemoteFsContext(botName) { + const entry = await findServer(botName); + if (!isRemoteEntry(entry)) return { remote: false }; + const node = await findNodeByIdOrName(entry.nodeId); + 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 }; +} + +app.use("/api/dashboard-assistant", createDashboardAssistantRouter({ + db, + isAuthenticated, + isAdmin, + getDashboardAssistantConfig, + saveDashboardAssistantConfig, + isDashboardAssistantEnabledForNormalUsers, + findUserByEmail, + getAccessListForEmail, + loadServersIndex, + loadNodes, + loadTemplatesFile, + getEffectivePermsForUserOnServer, + readEnvFile, + writeEnvFileBatch, + issueActionToken, + requireActionTokenOr403, + recordActivity, + findNodeByIdOrName, + buildNodeBaseUrl, + nodeUnderCloudflare, + nodeAuthHeadersFor, + httpRequestJson, + nodeFsPost, + resolveRemoteFsContext, + upsertServerIndexEntry, + createOnRemoteNode, + isPortInNodeAllocation, + validateDockerCommandPorts, + assertSafeRemoteUrl, + isValidArchiveUrl, + normalizeTemplateId, + sanitizeServerName, + sanitizeDisplayName, + clampPort, + clampAppPort, + deleteServerByName: (name) => deleteServerByName({ + findServer, + isRemoteEntry, + findNodeByIdOrName, + buildNodeBaseUrl, + nodeUnderCloudflare, + nodeAuthHeadersFor, + httpRequestJson, + deleteServerSchedules, + removeServerIndexEntry, + removeAccessForServerName, + }, name), + applyRemoteAssetToServer: (params) => applyRemoteAssetToServer({ + findServer, + isRemoteEntry, + findNodeByIdOrName, + buildNodeBaseUrl, + nodeUnderCloudflare, + nodeAuthHeadersFor, + httpRequestJson, + assertSafeRemoteUrl, + resolveRemoteFsContext, + nodeFsPost, + httpGetRaw, + remoteApplyProxyDownload: REMOTE_APPLY_PROXY_DOWNLOAD, + remoteApplyMaxBytes: REMOTE_APPLY_MAX_BYTES, + remoteApplyTimeoutMs: REMOTE_APPLY_TIMEOUT_MS, + remoteFetchMaxRedirects: REMOTE_FETCH_MAX_REDIRECTS, + }, params), +})); + +const DEFAULT_TEMPLATES = [ + { + id: "minecraft", + name: "Minecraft", + description: "You can create minecraft servers on this platform", + templateImage: "https://images.unsplash.com/photo-1501446529957-6226bd447c46?auto=format&fit=crop&w=1200&q=80", + docker: { + image: "eclipse-temurin", + tag: "21-jre", + ports: [], + env: {}, + volumes: ["{BOT_DIR}:/data"], + workdir: "/data", + command: "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui", + restart: "unless-stopped", + }, + }, + { + id: "nodejs", + name: "Node.js", + description: "Run Node.JS applications", + templateImage: "https://images.unsplash.com/photo-1518770660439-4636190af475?auto=format&fit=crop&w=1200&q=80", + docker: { + image: "node", + tag: "20-alpine", + ports: [], + env: { NODE_ENV: "production" }, + volumes: ["{BOT_DIR}:/app"], + workdir: "/app", + command: "node /app/index.js", + restart: "unless-stopped", + }, + }, + { + id: "vanilla", + name: "Vanilla", + description: "Choose what platform you want", + templateImage: "https://images.unsplash.com/photo-1498050108023-c5249f4df085?auto=format&fit=crop&w=1200&q=80", + docker: { image: "alpine", tag: "latest", ports: [], env: {}, volumes: [], workdir: "/data", command: "sleep 3600", restart: "no" }, + }, +]; + +const DEFAULT_MINECRAFT_PROCESS_IMAGE = "eclipse-temurin"; +const DEFAULT_MINECRAFT_PROCESS_TAG = "21-jre"; +const DEFAULT_MINECRAFT_PROCESS_COMMAND = "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui"; +const FALLBACK_MINECRAFT_JAVA_VERSIONS = Object.freeze(["8", "11", "17", "21", "22", "23", "24", "25", "26"]); +const MINECRAFT_JAVA_MIN_VERSION = 8; +const MINECRAFT_JAVA_MAX_VERSION = 99; +const MINECRAFT_JAVA_DISCOVERY_URL = "https://hub.docker.com/v2/repositories/library/eclipse-temurin/tags?page_size=100&name=-jre"; +const MINECRAFT_JAVA_DISCOVERY_TTL_MS = 6 * 60 * 60 * 1000; +const MINECRAFT_JAVA_DISCOVERY_FAIL_TTL_MS = 5 * 60 * 1000; +let minecraftJavaVersionsCache = null; +let minecraftJavaVersionsCacheExpiresAt = 0; +let minecraftJavaVersionsPending = null; + +function normalizeMinecraftJavaVersionInput(value) { + const raw = String(value ?? "").trim().toLowerCase(); + if (!raw) return ""; + const match = raw.match(/^(\d{1,2})(?:\D.*)?$/); + if (!match) return ""; + const version = match[1]; + const numeric = Number(version); + if (!Number.isInteger(numeric) || numeric < MINECRAFT_JAVA_MIN_VERSION || numeric > MINECRAFT_JAVA_MAX_VERSION) return ""; + return String(numeric); +} + +function minecraftJavaTag(version) { + const clean = normalizeMinecraftJavaVersionInput(version); + return clean ? `${clean}-jre` : DEFAULT_MINECRAFT_PROCESS_TAG; +} + +function minecraftJavaVersionFromTag(tag) { + const raw = String(tag ?? "").trim().toLowerCase(); + const match = raw.match(/^(\d{1,2})(?:[._-].*)?$/); + return match ? normalizeMinecraftJavaVersionInput(match[1]) : ""; +} + +function isMinecraftTemplateLike(templateId, templateName = "") { + const id = normalizeTemplateId(templateId); + if (id === "minecraft") return true; + if (id.includes("minecraft")) return true; + return String(templateName || "").trim().toLowerCase().includes("minecraft"); +} + +function mergeMinecraftJavaVersions(discovered = []) { + const seen = new Set(); + for (const version of FALLBACK_MINECRAFT_JAVA_VERSIONS) { + const clean = normalizeMinecraftJavaVersionInput(version); + if (clean) seen.add(clean); + } + for (const version of discovered) { + const clean = normalizeMinecraftJavaVersionInput(version); + if (clean) seen.add(clean); + } + return [...seen].sort((a, b) => Number(a) - Number(b)); +} + +function extractMinecraftJavaVersionsFromTagsPayload(payload) { + const versions = []; + const results = Array.isArray(payload?.results) ? payload.results : []; + for (const item of results) { + const tagName = String(item?.name || "").trim().toLowerCase(); + const match = tagName.match(/^(\d{1,2})-jre$/); + if (!match) continue; + const version = normalizeMinecraftJavaVersionInput(match[1]); + if (version) versions.push(version); + } + return versions; +} + +async function discoverMinecraftJavaVersionsFromDockerHub() { + const discovered = []; + let nextUrl = MINECRAFT_JAVA_DISCOVERY_URL; + let ok = false; + for (let page = 0; page < 5 && nextUrl; page += 1) { + const result = await httpRequestJson(nextUrl, "GET", { Accept: "application/json" }, null, 4500); + if (result.status !== 200 || !result.json) break; + ok = true; + discovered.push(...extractMinecraftJavaVersionsFromTagsPayload(result.json)); + const next = String(result.json.next || "").trim(); + if (!next || !next.startsWith("https://hub.docker.com/v2/repositories/library/eclipse-temurin/tags")) break; + nextUrl = next; + } + return { ok, versions: mergeMinecraftJavaVersions(discovered) }; +} + +async function getMinecraftJavaVersions() { + const now = Date.now(); + if (minecraftJavaVersionsCache && now < minecraftJavaVersionsCacheExpiresAt) { + return minecraftJavaVersionsCache.slice(); + } + if (!minecraftJavaVersionsPending) { + minecraftJavaVersionsPending = discoverMinecraftJavaVersionsFromDockerHub() + .then(({ ok, versions }) => { + const merged = mergeMinecraftJavaVersions(versions); + minecraftJavaVersionsCache = merged; + minecraftJavaVersionsCacheExpiresAt = Date.now() + (ok ? MINECRAFT_JAVA_DISCOVERY_TTL_MS : MINECRAFT_JAVA_DISCOVERY_FAIL_TTL_MS); + return merged.slice(); + }) + .catch(() => { + const fallback = mergeMinecraftJavaVersions(); + minecraftJavaVersionsCache = fallback; + minecraftJavaVersionsCacheExpiresAt = Date.now() + MINECRAFT_JAVA_DISCOVERY_FAIL_TTL_MS; + return fallback.slice(); + }) + .finally(() => { + minecraftJavaVersionsPending = null; + }); + } + return minecraftJavaVersionsPending; +} + +async function minecraftJavaOptionsPayload(selectedVersion = "") { + let versions = await getMinecraftJavaVersions(); + const selected = normalizeMinecraftJavaVersionInput(selectedVersion) || + minecraftJavaVersionFromTag(DEFAULT_MINECRAFT_PROCESS_TAG) || + (versions.includes("21") ? "21" : versions[0]) || + "21"; + if (!versions.includes(selected)) { + versions = mergeMinecraftJavaVersions([...versions, selected]); + } + return { + selected, + image: DEFAULT_MINECRAFT_PROCESS_IMAGE, + tag: minecraftJavaTag(selected), + options: versions.map((version) => ({ + version, + tag: minecraftJavaTag(version), + label: `Java ${version}`, + })), + }; +} + +function sanitizeRuntimeCommandInput(value) { + return String(value ?? "").replace(/\r\n?/g, "\n").trim().slice(0, 4000); +} + +function sanitizeADPanelStartupInput(value) { + return String(value ?? "") + .replace(/\0/g, "") + .replace(/\r\n?/g, "\n") + .trim() + .slice(0, 32768); +} + +function normalizeRuntimeWorkdirInput(value) { + let workdir = String(value ?? "").replace(/\0/g, "").trim(); + if (!workdir) return ""; + workdir = workdir.replace(/\\/g, "/"); + if (!workdir.startsWith("/")) return ""; + workdir = path.posix.normalize(workdir); + if (!workdir || workdir === ".") return ""; + if (!workdir.startsWith("/")) workdir = `/${workdir}`; + return workdir; +} + +const RUNTIME_PROCESS_BLOCKED_EXECUTABLES = new Set([ + 'sh', '/bin/sh', 'bash', '/bin/bash', 'ash', '/bin/ash', 'dash', '/bin/dash', 'zsh', '/bin/zsh', 'ksh', '/bin/ksh', +]); +const RUNTIME_PROCESS_BLOCKED_CONTAINER_EXECUTABLES = new Set([ + 'docker', 'docker-compose', 'podman', 'podman-compose', 'nerdctl', 'ctr', +]); +const RUNTIME_PROCESS_ENV_WRAPPERS = new Set(['env']); +const RUNTIME_PROCESS_BLOCKED_TOKENS = new Set([ + '&&', '||', '|', ';', '&', '>', '>>', '<', '<<', '2>', '2>>', '2>&1', '|&', +]); + +function parseRuntimeProcessArgsInput(value) { + const input = String(value || ''); + const args = []; + let current = ''; + let quote = ''; + let escape = false; + + for (let i = 0; i < input.length; i += 1) { + const ch = input[i]; + if (escape) { + current += ch; + escape = false; + continue; + } + if (ch === '\\') { + escape = true; + continue; + } + if (quote) { + if (ch === quote) quote = ''; + else current += ch; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + continue; + } + if (/\s/.test(ch)) { + if (current) { + args.push(current); + current = ''; + } + continue; + } + current += ch; + } + if (current) args.push(current); + return args; +} + +function getRuntimeProcessExecutableBaseNameInput(value) { + const raw = String(value || '').trim(); + if (!raw) return ''; + let candidate = raw; + if (/\s/.test(candidate)) { + const nestedArgs = parseRuntimeProcessArgsInput(candidate); + if (nestedArgs.length) candidate = String(nestedArgs[0] || '').trim(); + } + const normalized = candidate.toLowerCase().replace(/\\/g, '/'); + const parts = normalized.split('/').filter(Boolean); + return parts.pop() || normalized; +} + +function isRuntimeEnvAssignmentTokenInput(value) { + const token = String(value || '').trim(); + if (!token || token.startsWith('-')) return false; + const eqIdx = token.indexOf('='); + if (eqIdx <= 0) return false; + return /^[A-Za-z_][A-Za-z0-9_]*$/.test(token.slice(0, eqIdx)); +} + +function resolveRuntimeProcessExecutableArgsInput(args) { + const parts = Array.isArray(args) ? args : []; + if (!parts.length) return { execName: '', index: -1 }; + let index = 0; + while (index < parts.length) { + const token = String(parts[index] || '').trim(); + if (!token) { + index += 1; + continue; + } + const execName = getRuntimeProcessExecutableBaseNameInput(token); + if (RUNTIME_PROCESS_ENV_WRAPPERS.has(execName)) { + index += 1; + while (index < parts.length) { + const envToken = String(parts[index] || '').trim(); + if (!envToken) { + index += 1; + continue; + } + if (envToken === '--') { + index += 1; + break; + } + if (envToken.startsWith('-') || isRuntimeEnvAssignmentTokenInput(envToken)) { + index += 1; + continue; + } + break; + } + continue; + } + return { execName, index }; + } + return { execName: '', index: -1 }; +} + +function validateRuntimeContainerLauncherInput(args) { + const { execName } = resolveRuntimeProcessExecutableArgsInput(args); + if (RUNTIME_PROCESS_BLOCKED_CONTAINER_EXECUTABLES.has(execName)) { + return 'Container runtime CLI commands like "docker run" are not allowed here. Configure image, ports, volumes, env, and the in-container process separately.'; + } + return null; +} + +function isBlockedRuntimeShellExecutableInput(value) { + const execName = getRuntimeProcessExecutableBaseNameInput(value); + return RUNTIME_PROCESS_BLOCKED_EXECUTABLES.has(execName); +} + +function isRuntimeShellWrapperArgsInput(args, execIndex) { + if (!Array.isArray(args) || execIndex < 0 || execIndex >= args.length) return false; + if (!isBlockedRuntimeShellExecutableInput(args[execIndex])) return false; + const flags = String(args[execIndex + 1] || '').trim().toLowerCase(); + return flags.startsWith('-') && flags.includes('c'); +} + +function unwrapRuntimeShellWrapperInput(value) { + const args = parseRuntimeProcessArgsInput(value); + if (args.length < 3) return null; + const shellFlags = String(args[1] || '').trim().toLowerCase(); + if (!isBlockedRuntimeShellExecutableInput(args[0])) return null; + if (!shellFlags.startsWith('-') || !shellFlags.includes('c')) return null; + return String(args[2] || '').trim() || null; +} + +function normalizeLegacyRuntimeProcessCommandInput(templateId, value) { + let command = sanitizeRuntimeCommandInput(value); + if (!command) return ''; + for (let i = 0; i < 2; i += 1) { + const unwrapped = unwrapRuntimeShellWrapperInput(command); + if (!unwrapped) break; + command = sanitizeRuntimeCommandInput(unwrapped); + } + const normalizedTemplateId = normalizeTemplateId(templateId); + if (normalizedTemplateId === 'nodejs' || normalizedTemplateId === 'discord-bot') { + const lower = command.toLowerCase(); + const nodeIdx = lower.lastIndexOf('node '); + if (nodeIdx >= 0 && (lower.includes('&&') || lower.startsWith('npm ') || lower.startsWith('cd '))) { + command = sanitizeRuntimeCommandInput(command.slice(nodeIdx)); + } + } + return command; +} + +function validateRuntimeProcessCommandInput(value) { + const command = sanitizeRuntimeCommandInput(value); + if (!command) return null; + if (command.length > 4000) { + return 'Process command is too long.'; + } + if (command.includes('\n')) { + return 'Process command must be a single line.'; + } + if (command.includes('`') || command.includes('$(')) { + return 'Shell expansions are not allowed in process commands.'; + } + const args = parseRuntimeProcessArgsInput(command); + if (!args.length) { + return 'Process command is empty.'; + } + const { execName: resolvedExecName, index: execIndex } = resolveRuntimeProcessExecutableArgsInput(args); + const containerRuntimeError = validateRuntimeContainerLauncherInput(args); + if (containerRuntimeError) { + return containerRuntimeError; + } + if (isBlockedRuntimeShellExecutableInput(resolvedExecName || args[0]) && isRuntimeShellWrapperArgsInput(args, execIndex)) { + return 'Shell wrappers like sh -c or bash -lc are not allowed. Provide the executable and arguments directly.'; + } + for (const arg of args) { + const token = String(arg || '').trim(); + if (RUNTIME_PROCESS_BLOCKED_TOKENS.has(token)) { + return `Shell control operator "${token}" is not allowed in process commands.`; + } + } + return null; +} + +function looksLikeWrapperEntrypointOnlyCommand(value, entrypoint = null, cmd = null) { + const args = parseRuntimeProcessArgsInput(value); + if (args.length !== 1) return false; + + const token = String(args[0] || '').trim().toLowerCase(); + if (!token.startsWith('/')) return false; + + const baseName = token.split('/').filter(Boolean).pop() || token; + const wrapperLike = baseName.includes('entrypoint'); + if (!wrapperLike) return false; + + const epList = Array.isArray(entrypoint) + ? entrypoint.map((item) => String(item || '').trim()).filter(Boolean) + : []; + const cmdList = Array.isArray(cmd) + ? cmd.map((item) => String(item || '').trim()).filter(Boolean) + : []; + + if (cmdList.length > 0) return false; + if (epList.length > 1) return false; + return true; +} + +function looksLikePathOnlyScriptCommand(value) { + const args = parseRuntimeProcessArgsInput(value); + if (args.length !== 1) return false; + const token = String(args[0] || '').trim().toLowerCase(); + if (!token.startsWith('/')) return false; + if (token.includes('entrypoint')) return true; + if (token.endsWith('.sh') || token.endsWith('.bash')) return true; + return false; +} + +function defaultRuntimeCommandForTemplate(templateId, dockerConfig = null, startFile = null) { + const normalized = normalizeTemplateId(templateId); + const explicit = normalizeLegacyRuntimeProcessCommandInput(normalized, dockerConfig?.command); + if (explicit) return explicit; + const start = String(startFile || defaultStartFileForTemplate(normalized) || "").trim(); + const configuredWorkdir = normalizeRuntimeWorkdirInput( + dockerConfig?.workdir || dockerConfig?.workingDir || dockerConfig?.working_dir + ); + const appDir = configuredWorkdir || "/app"; + if (normalized === "minecraft") { + return DEFAULT_MINECRAFT_PROCESS_COMMAND; + } + if (normalized === "python") { + return `python ${appDir}/${start || "main.py"}`; + } + if (normalized === "nodejs" || normalized === "discord-bot") { + return `node ${appDir}/${start || "index.js"}`; + } + return ""; +} + +function runtimeDataDirForTemplate(templateId, dockerConfig = null) { + const explicitWorkdir = normalizeRuntimeWorkdirInput( + dockerConfig?.workdir || dockerConfig?.workingDir || dockerConfig?.working_dir + ); + if (explicitWorkdir) return explicitWorkdir; + + const normalized = normalizeTemplateId(templateId); + const volumes = Array.isArray(dockerConfig?.volumes) ? dockerConfig.volumes : []; + for (const volumeRaw of volumes) { + const volume = String(volumeRaw || "").trim(); + if (!volume || !volume.includes(':')) continue; + const parts = volume.split(':'); + if (parts.length < 2) continue; + let containerPath = String(parts[1] || "").trim(); + if (!containerPath) continue; + const optionsIdx = containerPath.lastIndexOf(':'); + if (optionsIdx > 0) containerPath = containerPath.slice(0, optionsIdx).trim(); + if (containerPath.startsWith('/')) return containerPath; + } + if (normalized === 'python' || normalized === 'nodejs' || normalized === 'discord-bot' || normalized === 'runtime') { + return '/app'; + } + return '/data'; +} + +function defaultTemplateBotDirVolumeForWorkdir(workdir) { + const normalizedWorkdir = normalizeRuntimeWorkdirInput(workdir) || '/data'; + return `{BOT_DIR}:${normalizedWorkdir}`; +} + +function shouldAutoAlignBotDirVolume(volumes) { + if (!Array.isArray(volumes)) return true; + const cleaned = volumes.map((v) => String(v || '').trim()).filter(Boolean); + if (cleaned.length === 0) return true; + if (cleaned.length !== 1) return false; + return cleaned[0].startsWith('{BOT_DIR}:'); +} + +function normalizeTemplateDockerForRuntime(templateId, dockerConfig = null, startFile = null) { + const normalized = normalizeTemplateId(templateId); + const managedTemplate = ["minecraft", "python", "nodejs", "discord-bot", "runtime"].includes(normalized); + const requestedMinecraftJavaVersion = normalizeMinecraftJavaVersionInput(dockerConfig?.javaVersion || dockerConfig?.java || ""); + let docker = sanitizeDockerTemplatePayload(dockerConfig || {}) || {}; + docker = { + image: String(docker.image || "").trim(), + tag: String(docker.tag || "").trim(), + ports: Array.isArray(docker.ports) ? docker.ports.slice() : [], + 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 } : {}, + command: normalizeLegacyRuntimeProcessCommandInput(normalized, docker.command), + adpanelStartup: sanitizeADPanelStartupInput( + docker.adpanelStartup || + docker.adpanel_startup || + docker.pterodactylStartup || + docker.pterodactyl_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" }, + }; + if (!docker.workdir && managedTemplate) { + docker.workdir = runtimeDataDirForTemplate(normalized, docker); + } + if (managedTemplate && !docker.volumes.length && docker.workdir) { + docker.volumes = [defaultTemplateBotDirVolumeForWorkdir(docker.workdir)]; + } else if (managedTemplate && docker.workdir && shouldAutoAlignBotDirVolume(docker.volumes)) { + docker.volumes = [defaultTemplateBotDirVolumeForWorkdir(docker.workdir)]; + } + if (docker.command && validateRuntimeProcessCommandInput(docker.command)) { + docker.command = ""; + } + + if (normalized === "minecraft") { + const selectedJavaVersion = requestedMinecraftJavaVersion || minecraftJavaVersionFromTag(docker.tag); + docker.image = DEFAULT_MINECRAFT_PROCESS_IMAGE; + docker.tag = minecraftJavaTag(selectedJavaVersion); + docker.javaVersion = minecraftJavaVersionFromTag(docker.tag) || "21"; + docker.volumes = docker.volumes.length ? docker.volumes : ["{BOT_DIR}:/data"]; + docker.workdir = docker.workdir || "/data"; + docker.env = {}; + docker.command = docker.command || defaultRuntimeCommandForTemplate(normalized, docker, startFile); + return docker; + } + + docker.command = docker.command || defaultRuntimeCommandForTemplate(normalized, docker, startFile); + return docker; +} + +function normalizeTemplateDefinition(template) { + if (!template || typeof template !== "object") return template; + const normalizedId = normalizeTemplateId(template.id); + if (!template.docker || !normalizedId) return template; + return { + ...template, + docker: normalizeTemplateDockerForRuntime( + normalizedId, + { + ...(template.docker || {}), + install: template.docker?.install || template.install, + adpanelStartup: + template.docker?.adpanelStartup || + template.docker?.adpanel_startup || + template.docker?.pterodactylStartup || + template.docker?.pterodactyl_startup || + template.adpanelStartup || + template.pterodactylStartup || + template.pterodactyl_startup, + }, + template.start || defaultStartFileForTemplate(normalizedId) + ), + }; +} + +function ensureTemplatesFile() { + try { + if (!fs.existsSync(TEMPLATES_FILE)) { + fs.writeFileSync(TEMPLATES_FILE, JSON.stringify(DEFAULT_TEMPLATES, null, 2), "utf8"); + } + } catch { } +} + +let _templatesCache = null; +let _templatesCacheTs = 0; +const TEMPLATES_CACHE_TTL_MS = 30000; + +function loadTemplatesFile() { + const now = Date.now(); + if (_templatesCache && (now - _templatesCacheTs) < TEMPLATES_CACHE_TTL_MS) return _templatesCache; + try { + ensureTemplatesFile(); + const raw = fs.readFileSync(TEMPLATES_FILE, "utf8"); + if (!raw.trim()) { + _templatesCache = DEFAULT_TEMPLATES; + _templatesCacheTs = now; + return DEFAULT_TEMPLATES; + } + const parsed = JSON.parse(raw); + if (Array.isArray(parsed)) { + _templatesCache = parsed.map((template) => normalizeTemplateDefinition(template)); + _templatesCacheTs = now; + return _templatesCache; + } + } catch { } + _templatesCache = DEFAULT_TEMPLATES.map((template) => normalizeTemplateDefinition(template)); + _templatesCacheTs = now; + return _templatesCache; +} + +function saveTemplatesFile(list) { + try { + fs.writeFileSync(TEMPLATES_FILE, JSON.stringify(list, null, 2), "utf8"); + _templatesCache = null; + _templatesCacheTs = 0; + return true; + } catch { + return false; + } +} + +function findTemplateById(id) { + const key = normalizeTemplateId(id); + const fromFile = loadTemplatesFile().find(t => normalizeTemplateId(t?.id) === key); + if (fromFile) return fromFile; + const fromDefaults = DEFAULT_TEMPLATES.find(t => normalizeTemplateId(t?.id) === key); + return fromDefaults ? normalizeTemplateDefinition(fromDefaults) : null; +} + +function defaultStartFileForTemplate(templateId) { + const normalized = normalizeTemplateId(templateId); + if (normalized === "minecraft") return "server.jar"; + if (normalized === "nodejs" || normalized === "discord-bot") return "index.js"; + if (normalized === "python") return "main.py"; + return null; +} + +ensureTemplatesFile(); + +let versionsConfig = { providers: [] }; +try { + const rawVersions = fs.readFileSync(versionsPath, "utf8"); + versionsConfig = JSON.parse(rawVersions); +} catch { } + +function providerTemplates(provider) { + if (!provider) return []; + const base = []; + if (provider.templates && Array.isArray(provider.templates)) base.push(...provider.templates.map(normalizeTemplateId)); + else if (provider.template) base.push(normalizeTemplateId(provider.template)); + else base.push("minecraft"); + if (base.includes("discord-bot")) ["nodejs", "python"].forEach(a => { if (!base.includes(a)) base.push(a); }); + return base; +} + +function providerSupportsTemplate(provider, tpl) { + const normalized = normalizeTemplateId(tpl); + if (!normalized) return true; + return providerTemplates(provider).includes(normalized); +} + +function providersForTemplate(tpl) { + const providers = Array.isArray(versionsConfig) ? versionsConfig : (versionsConfig.providers || []); + return providers.filter(p => providerSupportsTemplate(p, tpl)); +} + +function findProviderConfig(providerId) { + const providers = Array.isArray(versionsConfig) ? versionsConfig : (versionsConfig.providers || []); + return providers.find(p => String(p.id) === String(providerId)) || null; +} + +function findProviderVersionConfig(providerId, versionId) { + const provider = findProviderConfig(providerId); + if (!provider) return null; + const versions = Array.isArray(provider.versions) ? provider.versions : []; + return versions.find(v => String(v.id || v.name || v.version) === String(versionId)) || null; +} + +function sanitizePythonVersionTag(version) { + const raw = (version || "").toString().trim(); + if (!raw) return null; + const clean = raw.replace(/^python[-_]?/i, "").replace(/^v/i, ""); + if (!/^\d+\.\d+(?:\.\d+)?$/.test(clean)) return null; + return clean; +} + +function sanitizeNodeVersionTag(version) { + const raw = (version || "").toString().trim(); + if (!raw) return null; + const clean = raw.replace(/^node[-_]?/i, "").replace(/^v/i, ""); + if (!/^\d+(?:\.\d+){0,2}$/.test(clean)) return null; + return clean; +} + +function versionParts(version) { + const clean = String(version || "").replace(/^v/i, "").split(".").map(n => parseInt(n, 10)); + return [clean[0] || 0, clean[1] || 0, clean[2] || 0]; +} + +function compareVersionDesc(a, b) { + const aa = versionParts(a); + const bb = versionParts(b); + for (let i = 0; i < 3; i += 1) { + if (bb[i] !== aa[i]) return bb[i] - aa[i]; + } + return 0; +} + +function pythonDockerMinor(version) { + const clean = sanitizePythonVersionTag(version); + if (!clean) return null; + const parts = clean.split("."); + return `${parts[0]}.${parts[1]}`; +} + +function nodeDockerMajor(version) { + const clean = sanitizeNodeVersionTag(version); + if (!clean) return null; + return clean.split(".")[0]; +} + +function inferPythonStart(entry) { + const candidates = [entry?.start, "main.py"]; + for (const c of candidates) { + if (!c) continue; + const s = String(c).trim(); + if (s.toLowerCase().endsWith(".py") && /^[A-Za-z0-9._\/-]+$/.test(s) && !s.includes("..") && !s.startsWith("/")) return s; + } + return "main.py"; +} + +function inferNodeStart(entry) { + const candidates = [entry?.start, "index.js"]; + for (const c of candidates) { + if (!c) continue; + const s = String(c).trim(); + if (s.toLowerCase().endsWith(".js") && /^[A-Za-z0-9._\/-]+$/.test(s) && !s.includes("..") && !s.startsWith("/")) return s; + } + return "index.js"; +} + +function buildPythonVersionConfig(versionId, entry) { + const clean = pythonDockerMinor(versionId); + if (!clean) return null; + const startFile = inferPythonStart(entry); + return { + id: versionId, + name: clean, + label: `Python ${clean}`, + start: startFile, + docker: { image: "python", tag: `${clean}-slim`, command: `python /app/${startFile}` }, + }; +} + +function buildNodeVersionConfig(versionId, entry) { + const clean = nodeDockerMajor(versionId); + if (!clean) return null; + const startFile = inferNodeStart(entry); + return { + id: versionId, + name: clean, + label: `Node.js ${clean}`, + start: startFile, + docker: { image: "node", tag: `${clean}-alpine`, command: `node /app/${startFile}` }, + }; +} + +const FIVEM_ARTIFACTS_BASE_URL = "https://runtime.fivem.net/artifacts/fivem/build_proot_linux/master/"; +const FIVEM_ARTIFACTS_INDEX_CACHE_TTL_MS = 60_000; +let fivemArtifactsIndexCache = null; + +function stripHtmlTags(value) { + return String(value || "") + .replace(//gi, " ") + .replace(//gi, " ") + .replace(/<[^>]+>/g, " ") + .replace(/ /gi, " ") + .replace(///g, "/") + .replace(/&/gi, "&") + .replace(/\s+/g, " ") + .trim(); +} + +function isFivemArtifactDownloadUrl(value) { + try { + const u = new URL(String(value || "")); + return u.protocol === "https:" && + u.hostname === "runtime.fivem.net" && + /^\/artifacts\/fivem\/build_proot_linux\/master\/\d+-[a-f0-9]+\/fx\.tar\.xz$/i.test(u.pathname); + } catch { + return false; + } +} + +function parseFivemArtifactsIndex(html) { + const out = []; + const seen = new Set(); + const source = String(html || ""); + const anchorRe = /]*href\s*=\s*["']?\s*([^"'\s>]+)\s*["']?[^>]*>([\s\S]*?)<\/a>/gi; + let match; + while ((match = anchorRe.exec(source))) { + const href = String(match[1] || "").trim(); + if (!/fx\.tar\.xz(?:$|[?#])/i.test(href)) continue; + + let url; + try { + url = new URL(href, FIVEM_ARTIFACTS_BASE_URL).toString(); + } catch { + continue; + } + if (!isFivemArtifactDownloadUrl(url)) continue; + + const versionMatch = new URL(url).pathname.match(/\/(\d+)-([a-f0-9]+)\/fx\.tar\.xz$/i); + if (!versionMatch) continue; + + const build = versionMatch[1]; + const id = `${versionMatch[1]}-${versionMatch[2]}`; + if (seen.has(id)) continue; + seen.add(id); + + const text = stripHtmlTags(match[2]); + const channel = /latest\s+recommended/i.test(text) + ? "recommended" + : (/latest\s+optional/i.test(text) ? "optional" : ""); + const dateMatch = text.match(/(\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2})/); + + out.push({ + id, + build, + hash: versionMatch[2], + url, + channel, + releaseDate: dateMatch ? dateMatch[1] : "", + }); + } + return out; +} + +async function fetchFivemArtifactEntries({ force = false } = {}) { + const now = Date.now(); + if (!force && fivemArtifactsIndexCache && (now - fivemArtifactsIndexCache.ts) < FIVEM_ARTIFACTS_INDEX_CACHE_TTL_MS) { + return fivemArtifactsIndexCache.entries; + } + + const buffer = await httpGetRaw(FIVEM_ARTIFACTS_BASE_URL, { + maxBytes: 5 * 1024 * 1024, + timeoutMs: 15_000, + maxRedirects: 2, + }); + const entries = parseFivemArtifactsIndex(buffer.toString("utf8")); + fivemArtifactsIndexCache = { ts: now, entries }; + return entries; +} + +async function getFivemArtifactChannelVersions() { + const entries = await fetchFivemArtifactEntries(); + const byChannel = new Map(); + for (const entry of entries) { + if (entry.channel && !byChannel.has(entry.channel)) byChannel.set(entry.channel, entry); + } + + return ["recommended", "optional"].map((channel) => { + const entry = byChannel.get(channel); + if (!entry) return null; + const label = channel === "recommended" ? "Latest Recommended" : "Latest Optional"; + const tag = channel === "recommended" ? "RECOMMENDED" : "OPTIONAL"; + return { + id: `latest-${channel}`, + name: entry.build, + label: `${label} (${entry.build})`, + artifactVersion: entry.id, + releaseDate: entry.releaseDate, + tags: ["FIVEM", tag], + downloadUrl: entry.url, + url: entry.url, + }; + }).filter(Boolean); +} + +async function resolveFivemArtifactVersion(versionId) { + const raw = String(versionId || "").trim(); + const normalized = raw.toLowerCase().replace(/[\s_]+/g, "-"); + if (!normalized) { + const err = new Error("missing-fivem-version"); + err.statusCode = 400; + throw err; + } + + const entries = await fetchFivemArtifactEntries(); + let entry = null; + if (["latest-recommended", "recommended"].includes(normalized)) { + entry = entries.find(e => e.channel === "recommended") || null; + } else if (["latest-optional", "optional"].includes(normalized)) { + entry = entries.find(e => e.channel === "optional") || null; + } else if (/^\d+$/.test(normalized)) { + entry = entries.find(e => e.build === normalized) || null; + } else if (/^\d+-[a-f0-9]+$/i.test(normalized)) { + entry = entries.find(e => e.id.toLowerCase() === normalized) || null; + } else { + const err = new Error("invalid-fivem-version"); + err.statusCode = 400; + throw err; + } + + if (!entry) { + const err = new Error("fivem-version-not-found"); + err.statusCode = 404; + throw err; + } + + return { + providerId: "fivem", + versionId: normalized, + id: entry.id, + build: entry.build, + channel: entry.channel || "custom", + url: entry.url, + label: entry.channel === "recommended" + ? `Latest Recommended (${entry.build})` + : (entry.channel === "optional" ? `Latest Optional (${entry.build})` : `FiveM artifact ${entry.build}`), + }; +} + +function isNodeMissingPathResponse(status, json) { + const raw = String(json?.error || json?.detail || json?.message || "").toLowerCase(); + return status === 404 || raw.includes("not found") || raw.includes("no such file"); +} + +async function nodeDeletePathIfPresent(node, fullPath, isDir, timeoutMs = 120_000) { + const { status, json } = await nodeFsPost(node, "/v1/fs/delete", { path: fullPath, isDir: !!isDir }, timeoutMs); + if (status === 200 && json?.ok) return { ok: true }; + if (isNodeMissingPathResponse(status, json)) return { ok: true, missing: true }; + return { + ok: false, + status, + error: json?.error || json?.detail || json?.message || "node-delete-failed", + }; +} + +function nodeFsErrorPayload(status, json, fallback) { + const detailText = json?.error || json?.detail || json?.message || `node-status-${status}`; + if (String(detailText || "").toLowerCase().includes("unsupported archive type")) { + return { + ok: false, + statusCode: 502, + error: "node-agent-tarxz-unsupported", + detail: "This node agent does not support .tar.xz extraction yet. Update and restart the node agent, then retry the FiveM artifact install.", + }; + } + if (status === 507 && json?.error === "disk_limit_exceeded") { + return Object.assign({ ok: false, statusCode: 507 }, json); + } + if (status === 413 && json) { + return Object.assign({ ok: false, statusCode: 413 }, json); + } + if (status === 401 || status === 403) { + return { + ok: false, + statusCode: 502, + error: "node-auth-failed", + detail: "Token mismatch. Re-deploy config.yml to the node.", + }; + } + if (status === 0) { + return { + ok: false, + statusCode: 502, + error: "node-unreachable", + detail: "Cannot connect to node agent.", + }; + } + return { + ok: false, + statusCode: 502, + error: fallback, + detail: detailText, + }; +} + +async function applyFivemArtifactToServer({ bot, entry, artifact }) { + const ctx = await resolveRemoteFsContext(bot); + if (!ctx.remote || !ctx.node) { + return { ok: false, statusCode: 404, error: "server-not-on-node" }; + } + if (!isFivemArtifactDownloadUrl(artifact?.url)) { + return { ok: false, statusCode: 400, error: "invalid-fivem-artifact-url" }; + } + + const archivePath = safeJoinUnix(ctx.baseDir, "fx.tar.xz"); + const alpinePath = safeJoinUnix(ctx.baseDir, "alpine"); + + await nodeDeletePathIfPresent(ctx.node, archivePath, false, 60_000); + + const upload = await nodeFsPost( + ctx.node, + "/v1/fs/uploadUrl", + { dir: ctx.baseDir, url: artifact.url }, + 30 * 60 * 1000 + ); + if (upload.status !== 200 || !upload.json?.ok) { + return nodeFsErrorPayload(upload.status, upload.json, "fivem-artifact-download-failed"); + } + + const deleteAlpine = await nodeDeletePathIfPresent(ctx.node, alpinePath, true, 180_000); + if (!deleteAlpine.ok) { + return { + ok: false, + statusCode: 502, + error: "fivem-artifact-delete-failed", + detail: deleteAlpine.error, + }; + } + + const extract = await nodeFsPost(ctx.node, "/v1/fs/extract", { path: archivePath }, 10 * 60 * 1000); + if (extract.status !== 200 || !extract.json?.ok) { + return nodeFsErrorPayload(extract.status, extract.json, "fivem-artifact-extract-failed"); + } + + await nodeDeletePathIfPresent(ctx.node, archivePath, false, 60_000); + + const runtime = { + providerId: "fivem", + versionId: artifact.id, + artifactBuild: artifact.build, + channel: artifact.channel || "custom", + url: artifact.url, + installedAt: new Date().toISOString(), + }; + + await upsertServerIndexEntry({ + ...entry, + template: "fivem", + runtime, + port: clampAppPort(entry.port ?? 30120, 30120), + }); + + return { + ok: true, + remote: true, + msg: "fivem-artifacts-updated", + message: `Installed ${artifact.label || `FiveM artifact ${artifact.build}`}`, + runtime, + }; +} + +const REMOTE_FETCH_MAX_BYTES = parseInt(process.env.REMOTE_FETCH_MAX_BYTES || "", 10) || 25 * 1024 * 1024; +const REMOTE_FETCH_TIMEOUT_MS = parseInt(process.env.REMOTE_FETCH_TIMEOUT_MS || "", 10) || 20000; +const REMOTE_FETCH_MAX_REDIRECTS = parseInt(process.env.REMOTE_FETCH_MAX_REDIRECTS || "", 10) || 5; +const REMOTE_FETCH_ALLOW_ANY_PORT = process.env.REMOTE_FETCH_ALLOW_ANY_PORT === "1"; +const REMOTE_APPLY_PROXY_DOWNLOAD = parseBoolean(process.env.REMOTE_APPLY_PROXY_DOWNLOAD, true); +const REMOTE_APPLY_MAX_BYTES = parseInt(process.env.REMOTE_APPLY_MAX_BYTES || "", 10) || 1024 * 1024 * 1024; +const REMOTE_APPLY_TIMEOUT_MS = parseInt(process.env.REMOTE_APPLY_TIMEOUT_MS || "", 10) || 300000; + +function ipv4ToInt(ip) { + const parts = ip.split("."); + if (parts.length !== 4) return null; + let n = 0; + for (const p of parts) { + const v = Number(p); + if (!Number.isInteger(v) || v < 0 || v > 255) return null; + n = (n << 8) + v; + } + return n >>> 0; +} + +function isPrivateIPv4(ip) { + const n = ipv4ToInt(ip); + if (n === null) return true; + const ranges = [ + [ipv4ToInt("0.0.0.0"), ipv4ToInt("0.255.255.255")], + [ipv4ToInt("10.0.0.0"), ipv4ToInt("10.255.255.255")], + [ipv4ToInt("100.64.0.0"), ipv4ToInt("100.127.255.255")], + [ipv4ToInt("127.0.0.0"), ipv4ToInt("127.255.255.255")], + [ipv4ToInt("169.254.0.0"), ipv4ToInt("169.254.255.255")], + [ipv4ToInt("172.16.0.0"), ipv4ToInt("172.31.255.255")], + [ipv4ToInt("192.168.0.0"), ipv4ToInt("192.168.255.255")], + [ipv4ToInt("192.0.2.0"), ipv4ToInt("192.0.2.255")], + [ipv4ToInt("198.18.0.0"), ipv4ToInt("198.19.255.255")], + [ipv4ToInt("198.51.100.0"), ipv4ToInt("198.51.100.255")], + [ipv4ToInt("203.0.113.0"), ipv4ToInt("203.0.113.255")], + [ipv4ToInt("224.0.0.0"), ipv4ToInt("255.255.255.255")], + ]; + return ranges.some(([a, b]) => n >= a && n <= b); +} + +function isPrivateIPv6(ip) { + const v = String(ip || "").toLowerCase(); + if (v === "::" || v === "::1") return true; + if (v.startsWith("fc") || v.startsWith("fd")) return true; + if (v.startsWith("fe8") || v.startsWith("fe9") || v.startsWith("fea") || v.startsWith("feb")) return true; + if (v.startsWith("::ffff:")) { + const tail = v.slice("::ffff:".length); + if (net.isIP(tail) === 4) return isPrivateIPv4(tail); + } + return false; +} + +function isPrivateAddress(ip) { + const t = net.isIP(ip); + if (t === 4) return isPrivateIPv4(ip); + if (t === 6) return isPrivateIPv6(ip); + return true; +} + +async function assertSafeRemoteUrl(inputUrl) { + let u; + try { + u = new URL(String(inputUrl)); + } catch { + throw new Error("Invalid URL"); + } + + const proto = (u.protocol || "").toLowerCase(); + if (proto !== "http:" && proto !== "https:") throw new Error("Only http(s) URLs are allowed"); + if (u.username || u.password) throw new Error("Credentials in URL are not allowed"); + + const hostname = u.hostname; + if (!hostname) throw new Error("Invalid hostname"); + + const hostLower = hostname.toLowerCase(); + if (hostLower === "localhost" || hostLower.endsWith(".localhost") || hostLower.endsWith(".local")) { + throw new Error("Localhost URLs are not allowed"); + } + + const port = u.port ? Number(u.port) : (u.protocol === "https:" ? 443 : 80); + if (!REMOTE_FETCH_ALLOW_ANY_PORT && port !== 80 && port !== 443) throw new Error("Only ports 80/443 are allowed"); + + if (net.isIP(hostname)) { + if (isPrivateAddress(hostname)) throw new Error("Private IP is not allowed"); + } else { + const answers = await dns.lookup(hostname, { all: true, verbatim: true }); + if (!answers || answers.length === 0) throw new Error("DNS lookup failed"); + for (const a of answers) { + if (a && a.address && isPrivateAddress(a.address)) throw new Error("Hostname resolves to a private/internal IP"); + } + } + + return u; +} + +function safeLookup(hostname, options, cb) { + dns.lookup(hostname, { all: true, verbatim: true }) + .then((answers) => { + if (!answers || answers.length === 0) return cb(new Error("DNS lookup failed")); + for (const a of answers) { + if (a && a.address && !isPrivateAddress(a.address)) return cb(null, a.address, a.family || net.isIP(a.address)); + } + return cb(new Error("Hostname resolves to a private/internal IP")); + }) + .catch((err) => cb(err)); +} + + +const SSRF_SAFE_AGENTS = new Map(); + +setInterval(() => { + try { + const now = Date.now(); + const AGENT_TTL = 60 * 60 * 1000; + for (const [key, agent] of SSRF_SAFE_AGENTS.entries()) { + if (agent._lastUsed && (now - agent._lastUsed > AGENT_TTL)) { + try { agent.destroy(); } catch { } + SSRF_SAFE_AGENTS.delete(key); + } else if (!agent._lastUsed) { + agent._lastUsed = now; + } + } + } catch (err) { console.debug("[ssrf-agents] sweep error:", err.message); } +}, 10 * 60 * 1000).unref(); + +function createSsrfSafeAgent(resolvedIp, protocol, originalHostname) { + const key = `${protocol}://${resolvedIp}`; + if (SSRF_SAFE_AGENTS.has(key)) { + const agent = SSRF_SAFE_AGENTS.get(key); + agent._lastUsed = Date.now(); + return agent; + } + + const AgentClass = protocol === 'https:' ? https.Agent : httpMod.Agent; + const agent = new AgentClass({ + lookup: (hostname, options, callback) => { + const family = net.isIP(resolvedIp); + callback(null, resolvedIp, family || 4); + }, + keepAlive: false, + maxSockets: 1, + }); + + agent._lastUsed = Date.now(); + if (SSRF_SAFE_AGENTS.size >= 500) { + const oldestKey = SSRF_SAFE_AGENTS.keys().next().value; + if (oldestKey !== undefined) { try { SSRF_SAFE_AGENTS.get(oldestKey).destroy(); } catch {} SSRF_SAFE_AGENTS.delete(oldestKey); } + } + SSRF_SAFE_AGENTS.set(key, agent); + return agent; +} + +async function assertSafeRemoteUrlWithResolvedIp(inputUrl) { + let u; + try { + u = new URL(String(inputUrl)); + } catch { + throw new Error("Invalid URL"); + } + + const proto = (u.protocol || "").toLowerCase(); + if (proto !== "http:" && proto !== "https:") throw new Error("Only http(s) URLs are allowed"); + if (u.username || u.password) throw new Error("Credentials in URL are not allowed"); + + const hostname = u.hostname; + if (!hostname) throw new Error("Invalid hostname"); + + const hostLower = hostname.toLowerCase(); + if (hostLower === "localhost" || hostLower.endsWith(".localhost") || hostLower.endsWith(".local")) { + throw new Error("Localhost URLs are not allowed"); + } + + const port = u.port ? Number(u.port) : (u.protocol === "https:" ? 443 : 80); + if (!REMOTE_FETCH_ALLOW_ANY_PORT && port !== 80 && port !== 443) throw new Error("Only ports 80/443 are allowed"); + + let resolvedIp = null; + + if (net.isIP(hostname)) { + if (isPrivateAddress(hostname)) throw new Error("Private IP is not allowed"); + resolvedIp = hostname; + } else { + const answers = await dns.lookup(hostname, { all: true, verbatim: true }); + if (!answers || answers.length === 0) throw new Error("DNS lookup failed"); + + for (const a of answers) { + if (a && a.address && !isPrivateAddress(a.address)) { + resolvedIp = a.address; + break; + } + } + + if (!resolvedIp) throw new Error("Hostname resolves to a private/internal IP"); + + for (const a of answers) { + if (a && a.address && isPrivateAddress(a.address)) { + throw new Error("Hostname resolves to a private/internal IP"); + } + } + } + + return { url: u, resolvedIp, originalHostname: hostname }; +} + +function httpGetRaw(url, opts = {}) { + const maxBytes = Number.isFinite(opts.maxBytes) ? opts.maxBytes : REMOTE_FETCH_MAX_BYTES; + const timeoutMs = Number.isFinite(opts.timeoutMs) ? opts.timeoutMs : REMOTE_FETCH_TIMEOUT_MS; + const maxRedirects = Number.isFinite(opts.maxRedirects) ? opts.maxRedirects : REMOTE_FETCH_MAX_REDIRECTS; + const redirects = Number.isFinite(opts._redirects) ? opts._redirects : 0; + + return new Promise(async (resolve, reject) => { + let validated; + try { + validated = await assertSafeRemoteUrlWithResolvedIp(url); + } catch (e) { + return reject(e); + } + + const { url: u, resolvedIp, originalHostname } = validated; + const lib = u.protocol === "https:" ? https : httpMod; + + const agent = createSsrfSafeAgent(resolvedIp, u.protocol, originalHostname); + + const requestOptions = { + method: "GET", + hostname: resolvedIp, + port: u.port || (u.protocol === "https:" ? 443 : 80), + path: u.pathname + u.search, + headers: { + "User-Agent": "ADPanel/1.0", + "Accept": "*/*", + "Host": originalHostname, + }, + agent: agent, + timeout: timeoutMs, + ...(u.protocol === "https:" ? { servername: originalHostname } : {}), + }; + + const req = lib.request(requestOptions, (res) => { + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + if (redirects >= maxRedirects) { + res.resume(); + return reject(new Error("Too many redirects")); + } + const nextUrl = new URL(res.headers.location, u).toString(); + res.resume(); + return resolve(httpGetRaw(nextUrl, { maxBytes, timeoutMs, maxRedirects, _redirects: redirects + 1 })); + } + + if (res.statusCode !== 200) { + res.resume(); + return reject(new Error(`HTTP ${res.statusCode}`)); + } + + const chunks = []; + let total = 0; + + res.on("data", (chunk) => { + total += chunk.length; + if (total > maxBytes) { + req.destroy(new Error("Download too large")); + return; + } + chunks.push(chunk); + }); + + res.on("end", () => resolve(Buffer.concat(chunks))); + }); + + req.on("error", reject); + req.on("timeout", () => { + req.destroy(new Error("Request timeout")); + }); + req.end(); + }); +} + +function httpRequestJson(fullUrl, method = "GET", headers = {}, body = null, timeoutMs = 15000) { + return new Promise(async (resolve) => { + let settled = false; + const finish = (out) => { + if (settled) return; + settled = true; + try { clearTimeout(hardTimer); } catch { } + resolve(out); + }; + + let hardTimer = null; + + try { + const isInternalNodeRequest = headers && (headers["X-Node-Token"] || headers["Authorization"]); + + let requestOptions; + let lib; + + if (isInternalNodeRequest) { + const isHttps = fullUrl.startsWith("https:"); + lib = isHttps ? https : httpMod; + requestOptions = { method, headers }; + if (isHttps && nodeMtlsAgent) requestOptions.agent = nodeMtlsAgent; + } else { + let validated; + try { + validated = await assertSafeRemoteUrlWithResolvedIp(fullUrl); + } catch (e) { + return finish({ status: 0, json: null }); + } + + const { url: u, resolvedIp, originalHostname } = validated; + lib = u.protocol === "https:" ? https : httpMod; + + const agent = createSsrfSafeAgent(resolvedIp, u.protocol, originalHostname); + + requestOptions = { + method, + hostname: resolvedIp, + port: u.port || (u.protocol === "https:" ? 443 : 80), + path: u.pathname + u.search, + headers: { + ...headers, + "Host": originalHostname, + }, + agent: agent, + ...(u.protocol === "https:" ? { servername: originalHostname } : {}), + }; + + fullUrl = null; + } + + const req = fullUrl + ? lib.request(fullUrl, requestOptions, handleResponse) + : lib.request(requestOptions, handleResponse); + + const MAX_RESPONSE_BYTES = 5 * 1024 * 1024; + function handleResponse(res) { + const statusCode = res.statusCode || 0; + const chunks = []; + let totalBytes = 0; + + res.on("data", (d) => { + totalBytes += d.length; + if (totalBytes > MAX_RESPONSE_BYTES) { + try { res.destroy(); } catch { } + return finish({ status: 0, json: null }); + } + chunks.push(d); + }); + res.on("end", () => { + const bodyStr = Buffer.concat(chunks).toString("utf8"); + try { + const json = bodyStr ? JSON.parse(bodyStr) : null; + finish({ status: statusCode, json }); + } catch { + finish({ status: statusCode, json: null }); + } + }); + } + + hardTimer = setTimeout(() => { + try { req.destroy(); } catch { } + finish({ status: 0, json: null }); + }, timeoutMs); + + req.on("timeout", () => { + try { req.destroy(); } catch { } + finish({ status: 0, json: null }); + }); + + req.on("error", () => finish({ status: 0, json: null })); + + req.setTimeout(timeoutMs); + + if (body != null) req.write(typeof body === "string" ? body : JSON.stringify(body)); + req.end(); + } catch { + finish({ status: 0, json: null }); + } + }); +} + +async function fetchJson(u) { + const buf = await httpGetRaw(u); + return JSON.parse(buf.toString("utf8")); +} + +app.post("/api/captcha/local", (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" }); + + const action = String(req.body?.action || "").toLowerCase(); + const token = req.body?.token || req.body?.localCaptchaToken; + const rawSelection = req.body?.selection || req.body?.captchaSelection; + + let selection = []; + if (Array.isArray(rawSelection)) selection = rawSelection.map(Number); + else if (typeof rawSelection === "string") { + selection = rawSelection + .split(",") + .map(s => Number(s.trim())) + .filter(Number.isInteger); + } + + if (action === "skip") { + const r = skipLocalCaptcha(req); + if (!r.ok) { + if (r.error === "no-skips-left") return res.status(429).json({ ok: false, error: "no-skips-left" }); + if (r.error === "not-enough-answers") return res.status(400).json({ ok: false, error: "not-enough-answers" }); + 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 nextQ = getCurrentCaptchaQuestion(req); + return res.json({ ok: true, done: false, question: nextQ, remainingSkips: r.remainingSkips }); + } + + const r = validateLocalCaptcha(req, selection, token); + if (!r.ok) { + if (r.fail) return res.status(400).json({ ok: false, error: "too-many-wrong" }); + if (r.expired) return res.status(410).json({ ok: false, error: "expired" }); + if (r.error === "not-enough-answers") return res.status(400).json({ ok: false, error: "not-enough-answers" }); + return res.status(400).json({ ok: false, error: "invalid" }); + } + if (r.done) { + return req.session.save(() => res.json({ ok: true, done: true })); + } + + const nextQ = getCurrentCaptchaQuestion(req); + return res.json({ ok: true, done: false, question: nextQ, remainingSkips: r.remainingSkips }); +}); + +app.post("/api/captcha/verify", async (req, res) => { + if (!req.session) return res.status(400).json({ ok: false }); + 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" }); + + const clientIp = getRequestIp(req); + const result = await verifyExternalCaptcha(token, clientIp); + if (!result.ok) return res.status(400).json({ ok: false, error: "verification-failed" }); + + req.session.captchaSolved = true; + req.session.captchaRequired = false; + clearLocalCaptcha(req); + return req.session.save(() => res.json({ ok: true })); +}); + +const DOCKER_TAG_CACHE_TTL_MS = 10 * 60 * 1000; +const dockerTagCache = new Map(); + +async function fetchDockerHubLibraryTags(image, maxPages = 6) { + const safeImage = String(image || "").trim().toLowerCase(); + if (!/^[a-z0-9._-]+$/.test(safeImage)) return []; + const cacheKey = `${safeImage}:${maxPages}`; + const cached = dockerTagCache.get(cacheKey); + if (cached && Date.now() - cached.at < DOCKER_TAG_CACHE_TTL_MS) { + return cached.tags.slice(); + } + const tags = []; + let nextUrl = `https://registry.hub.docker.com/v2/repositories/library/${safeImage}/tags?page_size=100`; + for (let page = 0; page < maxPages && nextUrl; page += 1) { + const data = await fetchJson(nextUrl); + if (Array.isArray(data?.results)) tags.push(...data.results); + nextUrl = typeof data?.next === "string" && data.next.startsWith("https://registry.hub.docker.com/") + ? data.next + : ""; + } + dockerTagCache.set(cacheKey, { at: Date.now(), tags: tags.slice() }); + return tags; +} + +async function fetchPythonDockerTags() { + return await fetchDockerHubLibraryTags("python", 2); +} + +function mapPythonTagsToVersions(tags) { + const list = Array.isArray(tags) ? tags : []; + const byMinor = new Map(); + for (const tag of list) { + const raw = (tag && tag.name) ? String(tag.name) : ""; + const match = raw.match(/^(\d+)\.(\d+)(?:\.\d+)?-slim$/); + if (!match) continue; + const minor = `${match[1]}.${match[2]}`; + const clean = raw.replace(/-slim$/, ""); + const existing = byMinor.get(minor); + if (!existing || compareVersionDesc(clean, existing.patchVersion) < 0) { + byMinor.set(minor, { + id: minor, + name: minor, + patchVersion: clean, + label: `Python ${minor}`, + releaseDate: "", + tags: ["PYTHON", "STABLE"] + }); + } + } + const versions = [...byMinor.values()] + .sort((a, b) => compareVersionDesc(a.name, b.name)) + .map(({ patchVersion, ...entry }, index) => ({ + ...entry, + tags: index === 0 ? [...new Set([...(entry.tags || []), "LATEST"])] : entry.tags + })); + return versions; +} + +async function fetchNodeDockerTags() { + return await fetchDockerHubLibraryTags("node", 6); +} + +function mapNodeVersionsToList(list) { + const arr = Array.isArray(list) ? list : []; + const byMajor = new Map(); + for (const v of arr) { + if (!v) continue; + const raw = String(v.name || v.version || ""); + const match = raw.match(/^(\d+)-alpine$/); + const major = match ? match[1] : nodeDockerMajor(raw); + if (!major || byMajor.has(major)) continue; + const tags = ["DOCKER"]; + if (raw.endsWith("-alpine")) tags.push("ALPINE"); + byMajor.set(major, { + id: major, + name: major, + label: `Node.js ${major}`, + releaseDate: v.last_updated || v.date || "", + tags + }); + } + return [...byMajor.values()].sort((a, b) => compareVersionDesc(a.name, b.name)); +} + +const REDIRECT_ALLOWED_HOSTS = new Set( + (process.env.REDIRECT_ALLOWED_HOSTS || "") + .split(",").map(s => s.trim().toLowerCase()).filter(Boolean) +); + +app.use((req, res, next) => { + if (httpsAvailable && FORCE_HTTPS && !req.secure) { + const headerHost = req.headers.host || ""; + const requestedHostname = extractHostnameFromHeader(headerHost).toLowerCase(); + const hostname = (requestedHostname && (requestedHostname === HOST.toLowerCase() || REDIRECT_ALLOWED_HOSTS.has(requestedHostname))) + ? requestedHostname + : HOST; + const portSegment = HTTPS_PORT === 443 ? "" : `:${HTTPS_PORT}`; + return res.redirect(301, `https://${hostname}${portSegment}${req.originalUrl}`); + } + next(); +}); + +function getBearerToken(req) { + const authHeader = req.get("authorization") || ""; + if (!authHeader) return ""; + if (authHeader.toLowerCase().startsWith("bearer ")) return authHeader.slice(7).trim(); + return ""; +} + +const ALLOW_QUERY_TOKENS = parseBoolean(process.env.ALLOW_QUERY_TOKENS, false); +if (ALLOW_QUERY_TOKENS) console.warn("[SECURITY] ALLOW_QUERY_TOKENS is enabled — tokens may leak via URL query strings and logs"); +if (ALLOW_QUERY_TOKENS && process.env.NODE_ENV === "production") + console.error("[SECURITY] ALLOW_QUERY_TOKENS is ON in production — tokens may leak via URL query strings and referrer headers"); + +function getNodeTokenFromRequest(req) { + const headerToken = req.get("x-node-token") || ""; + const queryToken = ALLOW_QUERY_TOKENS ? (req.query?.token || "") : ""; + const bodyToken = ALLOW_QUERY_TOKENS ? (req.body?.token || "") : ""; + return (getBearerToken(req) || headerToken || queryToken || bodyToken || "").toString().trim(); +} + +function getBootstrapTokenFromRequest(req) { + const queryBootstrap = ALLOW_QUERY_TOKENS ? (req.query?.bootstrap || "") : ""; + return (req.get("x-node-bootstrap") || queryBootstrap || "").toString().trim(); +} + +function isAllowedNodeToken(token, node) { + if (!token) return false; + if (NODE_TOKEN && safeCompare(String(token), String(NODE_TOKEN))) return true; + if (LOCAL_NODE_TOKEN && safeCompare(String(token), String(LOCAL_NODE_TOKEN))) return true; + if (node) { + if (node.token && safeCompare(String(token), String(node.token))) return true; + if (node.secret && safeCompare(String(token), String(node.secret))) return true; + if (node.api_key && safeCompare(String(token), String(node.api_key))) return true; + } + return false; +} + +async function isOpenNodeRoute(req) { + const p = req.path || ""; + const match = /^\/api\/nodes\/([^/]+)\/(heartbeat|config\.yml)$/.exec(p); + if (!match) return false; + + const nodeId = match[1]; + const isConfigYml = match[2] === "config.yml"; + if (isConfigYml && !isRequestSecure(req) && !ALLOW_INSECURE_NODE_BOOTSTRAP) { + return false; + } + + if (isConfigYml && NODE_BOOTSTRAP_TOKEN) { + const bootstrapToken = getBootstrapTokenFromRequest(req); + if (!safeCompare(String(bootstrapToken), String(NODE_BOOTSTRAP_TOKEN))) return false; + return true; + } + + const node = await findNodeByIdOrName(nodeId); + const token = getNodeTokenFromRequest(req); + return isAllowedNodeToken(token, node); +} + +const HTML_NO_STORE_CACHE_CONTROL = "no-store, no-cache, must-revalidate, private"; + +// Prevent browser/proxy caching of HTML documents and auth redirects while +// leaving long-lived caching intact for static assets. +app.use((req, res, next) => { + if (req._staticAsset || req.path.startsWith("/api/")) return next(); + + const method = String(req.method || "").toUpperCase(); + if (method !== "GET" && method !== "HEAD") return next(); + + const accept = String(req.get("accept") || "").toLowerCase(); + const pathName = String(req.path || ""); + const looksLikeDocument = !/\.[a-z0-9]+$/i.test(pathName); + const wantsHtml = + accept.includes("text/html") || + accept.includes("application/xhtml+xml") || + accept.includes("*/*"); + + if (looksLikeDocument && wantsHtml) { + res.setHeader("Cache-Control", HTML_NO_STORE_CACHE_CONTROL); + res.setHeader("Pragma", "no-cache"); + res.append("Vary", "Cookie"); + res.append("Vary", "Accept"); + } + + return next(); +}); + +// Prevent CDN/proxy caching of authenticated API responses +app.use((req, res, next) => { + if (req.path.startsWith("/api/")) { + res.setHeader("Cache-Control", HTML_NO_STORE_CACHE_CONTROL); + res.setHeader("Pragma", "no-cache"); + res.setHeader("Vary", "Cookie"); + } + next(); +}); + +app.get(["/healthz", "/healtz"], (req, res) => { + res.setHeader("Cache-Control", "no-store"); + return res.status(200).json({ + ok: true, + service: "adpanel", + ts: Date.now(), + }); +}); + +app.use(async (req, res, next) => { + try { + if ( + req.path.startsWith("/login") || + req.path.startsWith("/register") || + req.path.startsWith("/forgot-password") || + req.path.startsWith("/db-access/") || + req.path === "/healthz" || + req.path === "/healtz" || + req.path === "/api/me" || + await isOpenNodeRoute(req) + ) { + return next(); + } + + if (!(await isAuthenticated(req))) { + if (req.path.startsWith("/api/")) return res.status(401).json({ error: "not authenticated" }); + return res.redirect("/login"); + } + + return next(); + } catch (err) { + return next(err); + } +}); + +app.use(async (req, res, next) => { + try { + if (!req.path.startsWith("/api/nodes")) return next(); + if (await isOpenNodeRoute(req)) return next(); + if (req.path.startsWith("/api/nodes/server/")) return next(); + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/admin", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/settings/security", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +function parseDbAccessTokenRequest(req) { + let token; + if (req.body && typeof req.body === "object") { + token = req.body.token; + } + if (!token && typeof req.body === "string") { + try { + const parsed = JSON.parse(req.body); + token = parsed.token; + } catch { } + } + return { token }; +} + +// Token heartbeat/revocation (before admin guard — token is the secret, no auth needed) +app.post("/api/settings/database/access-heartbeat", (req, res) => { + const { token } = parseDbAccessTokenRequest(req); + if (!token || typeof token !== "string") return res.status(400).json({ error: "Missing token" }); + if (!dbProxy.touchToken(token)) return res.status(404).end(); + return res.status(204).end(); +}); + +app.post("/api/settings/database/revoke-token", (req, res) => { + const { token } = parseDbAccessTokenRequest(req); + if (token && typeof token === "string") dbProxy.revokeToken(token); + return res.status(204).end(); +}); + +app.use("/api/settings/database", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/settings/templates", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/settings/accounts", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/settings/servers", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/settings/webhooks", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/settings/panel-update", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/settings/node-update", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use("/api/settings/maintenance", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + return next(); + } catch (err) { + return next(err); + } +}); + +app.use(nodesRouter); +app.use("/api/subdomains", subdomainsRouter); + +let _hostIpCache = { host: null, ip: null, ts: 0 }; + +function extractHostnameFromHeader(hostHeader) { + if (!hostHeader) return null; + const first = String(hostHeader).split(",")[0].trim(); + if (first.startsWith("[")) { + const end = first.indexOf("]"); + if (end !== -1) return first.slice(1, end); + } + return first.split(":")[0]; +} + +async function resolvePublicIpFromHost(hostname) { + if (!hostname) return null; + if (net.isIP(hostname)) return hostname; + + try { + const a = await dns.resolve4(hostname); + if (Array.isArray(a) && a.length) return a[0]; + } catch { } + + try { + const list = await dns.lookup(hostname, { all: true }); + const v4 = list.find(r => r && r.family === 4); + if (v4) return v4.address; + if (list[0] && list[0].address) return list[0].address; + } catch { } + + try { + const aaaa = await dns.resolve6(hostname); + if (Array.isArray(aaaa) && aaaa.length) return aaaa[0]; + } catch { } + + return null; +} + +app.get("/api/ssh-terminal/session", async (req, res) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + const token = issueSshTerminalToken(req); + return res.json({ ok: true, launchUrl: `/ssh-terminal/?token=${encodeURIComponent(token)}` }); + } catch (err) { + return res.status(500).json({ error: "failed to create terminal session" }); + } +}); + +async function proxySshTerminalIndex(req, res) { + if (!(await isAuthenticated(req))) { + return res.status(401).type("text/plain").send("not authenticated"); + } + + const incomingToken = String(req.query?.token || "").trim(); + const retryFlag = String(req.query?._retry || "") === "1"; + const token = incomingToken || issueSshTerminalToken(req); + const upstreamOrigin = getSshTerminalOrigin(req); + const upstreamUrl = new URL("/", upstreamOrigin); + upstreamUrl.searchParams.set("token", token); + + let upstream; + try { + upstream = await fetch(upstreamUrl.toString(), { + method: "GET", + headers: { + "x-forwarded-for": getRequestIp(req), + "x-forwarded-proto": isRequestSecure(req) ? "https" : "http", + "x-forwarded-host": req.get("host") || "", + }, + }); + } catch { + return res.status(502).type("text/plain").send("ssh terminal service unavailable"); + } + + if (upstream.status === 401 && !retryFlag) { + const fresh = issueSshTerminalToken(req); + return res.redirect(`/ssh-terminal/?token=${encodeURIComponent(fresh)}&_retry=1`); + } + + const bodyText = await upstream.text(); + const headers = sanitizeProxyResponseHeaders(Object.fromEntries(upstream.headers.entries())); + res.status(upstream.status); + for (const [k, v] of Object.entries(headers)) { + try { res.setHeader(k, v); } catch { } + } + return res.send(bodyText); +} + +app.get("/ssh-terminal", proxySshTerminalIndex); +app.get("/ssh-terminal/", proxySshTerminalIndex); + +app.get("/api/server-info", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + const hostname = HOST; + const now = Date.now(); + + if (_hostIpCache.host === hostname && _hostIpCache.ip && (now - _hostIpCache.ts) < 5 * 60 * 1000) { + return res.json({ publicIp: _hostIpCache.ip }); + } + + const ip = await resolvePublicIpFromHost(hostname); + _hostIpCache = { host: hostname, ip, ts: now }; + return res.json({ publicIp: ip }); + } catch (err) { + return res.status(500).json({ error: "failed to resolve host ip" }); + } +}); + +app.get("/api/server-info/:name", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const raw = String(req.params.name || "").trim(); + const safeName = sanitizeServerName(raw) || raw; + const entry = (await findServer(safeName)) || {}; + const serverName = entry.name || safeName; + + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, serverName))) { + return res.status(403).json({ error: "no-access-to-server" }); + } + + const template = normalizeTemplateId(entry.template); + + const hostname = HOST; + const now = Date.now(); + + let ip = entry.ip || null; + if (!ip) { + if (_hostIpCache.host === hostname && _hostIpCache.ip && (now - _hostIpCache.ts) < 5 * 60 * 1000) ip = _hostIpCache.ip; + else { + ip = await resolvePublicIpFromHost(hostname); + _hostIpCache = { host: hostname, ip, ts: now }; + } + } + + const port = (entry.port !== undefined && entry.port !== null) + ? entry.port + : (template === "minecraft" ? 25565 : null); + + return res.json({ + name: entry.name || raw, + start: entry.start || null, + ip: ip || null, + port, + template: template || null, + runtime: entry.runtime || null, + nodeId: entry.nodeId || null, + }); + } catch (err) { + return res.status(500).json({ error: "failed to resolve host ip" }); + } +}); + +app.post("/api/servers/:bot/template", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ ok: false, error: "not-authenticated" }); + + const raw = String(req.params.bot || "").trim(); + if (!requireActionTokenOr403(req, res, "POST /api/servers/:bot/template", { serverName: raw })) return; + const entry = await findServer(raw); + const isAdminUser = await isAdmin(req); + + if (!entry) return res.status(404).json({ ok: false, error: "server-not-found" }); + if (!isAdminUser && !(await userHasAccessToServer(req.session.user, entry.name || raw))) { + return res.status(403).json({ ok: false, error: "no-access-to-server" }); + } + if (!isAdminUser) { + const perms = await getEffectivePermsForUserOnServer(req.session.user, entry.name || raw); + if (!perms.store_access) { + return res.status(403).json({ ok: false, error: "not-authorized", permission: "store_access" }); + } + } + + const templateId = normalizeTemplateId(req.body?.template || req.body?.tpl || ""); + const allowedTemplates = new Set(["discord-bot", "minecraft", "nodejs", "python"]); + + if (!templateId) return res.status(400).json({ ok: false, error: "missing-template" }); + if (!allowedTemplates.has(templateId)) { + return res.status(400).json({ ok: false, error: "unsupported-template" }); + } + + const list = await loadServersIndex(); + const idx = findServerIndex(list, entry.name || raw); + if (idx === -1) return res.status(404).json({ ok: false, error: "server-not-found" }); + + list[idx] = Object.assign({}, list[idx], { template: templateId }); + if (!(await saveServersIndex(list))) return res.status(500).json({ ok: false, error: "persist-failed" }); + + return res.json({ ok: true, template: templateId }); + } catch (err) { + return next(err); + } +}); + +const LOGIN_WINDOW_MS = 2 * 60 * 1000; +const LOGIN_MAX_ATTEMPTS = 10; +const LOGIN_BLOCK_MS = 10 * 60 * 1000; +const LOGIN_DELAY_BASE_MS = 400; +const LOGIN_DELAY_JITTER_MS = 400; +const LOGIN_SUSPICIOUS_WINDOW_MS = parseInt(process.env.LOGIN_SUSPICIOUS_WINDOW_MS || String(LOGIN_WINDOW_MS), 10); +const LOGIN_SUSPICIOUS_ATTEMPTS = parseInt(process.env.LOGIN_SUSPICIOUS_ATTEMPTS || "3", 10); +const LOGIN_SUSPICIOUS_FAST_WINDOW_MS = parseInt(process.env.LOGIN_SUSPICIOUS_FAST_WINDOW_MS || "20000", 10); +const LOGIN_SUSPICIOUS_FAST_ATTEMPTS = parseInt(process.env.LOGIN_SUSPICIOUS_FAST_ATTEMPTS || "2", 10); +const LOGIN_SUSPICIOUS_SCORE_THRESHOLD = parseInt(process.env.LOGIN_SUSPICIOUS_SCORE_THRESHOLD || "3", 10); +const LOGIN_MAP_MAX_SIZE = scaleForMemory(10000); +const loginAttempts = new Map(); + +const LOGIN_ATTACK_WINDOW_MS = parseInt(process.env.LOGIN_ATTACK_WINDOW_MS || "1000", 10) || 1000; +const LOGIN_ATTACK_UNIQUE_IPS = parseInt(process.env.LOGIN_ATTACK_UNIQUE_IPS || "100", 10) || 100; +const LOGIN_ATTACK_HOLD_MS = parseInt(process.env.LOGIN_ATTACK_HOLD_MS || "60000", 10) || 60000; +const LOGIN_ATTACK_IP_WINDOW_MS = parseInt(process.env.LOGIN_ATTACK_IP_WINDOW_MS || "3000", 10) || 3000; +const LOGIN_ATTACK_IP_MAX = parseInt(process.env.LOGIN_ATTACK_IP_MAX || "25", 10) || 25; + +const loginAttackIps = new Map(); +const loginAttackIpHits = new Map(); +let loginUnderAttackUntil = 0; + +function cleanLoginAttempts() { + const now = Date.now(); + for (const [ip, rec] of loginAttempts.entries()) { + const attempts = (rec?.attempts || []).filter(ts => now - ts < LOGIN_WINDOW_MS); + const blockedUntil = rec?.blockedUntil || 0; + if (attempts.length === 0 && (!blockedUntil || blockedUntil < now)) { + loginAttempts.delete(ip); + } else { + loginAttempts.set(ip, { attempts, blockedUntil }); + } + } + + for (const [ip, hits] of loginAttackIpHits.entries()) { + const valid = (hits || []).filter(ts => now - ts <= LOGIN_ATTACK_IP_WINDOW_MS); + if (valid.length === 0) { + loginAttackIpHits.delete(ip); + } else { + loginAttackIpHits.set(ip, valid); + } + } +} +setInterval(cleanLoginAttempts, 5 * 60 * 1000).unref(); + +function recordLoginAttempt(ip) { + const now = Date.now(); + if (!loginAttempts.has(ip) && loginAttempts.size >= LOGIN_MAP_MAX_SIZE) { + const oldest = loginAttempts.keys().next().value; + if (oldest !== undefined) loginAttempts.delete(oldest); + } + const rec = loginAttempts.get(ip) || { attempts: [], blockedUntil: 0 }; + rec.attempts = (rec.attempts || []).filter(ts => now - ts < LOGIN_WINDOW_MS); + rec.attempts.push(now); + if (rec.attempts.length > LOGIN_MAX_ATTEMPTS) { + rec.blockedUntil = now + LOGIN_BLOCK_MS; + } + loginAttempts.set(ip, rec); + return rec; +} + +function isLoginBlocked(ip) { + const now = Date.now(); + const rec = loginAttempts.get(ip); + return rec && rec.blockedUntil && rec.blockedUntil > now; +} + +function resetLoginAttempts(ip) { + if (!ip) return; + loginAttempts.set(ip, { attempts: [], blockedUntil: 0 }); +} + +function loginDelay() { + const jitter = Math.floor(Math.random() * LOGIN_DELAY_JITTER_MS); + const ms = LOGIN_DELAY_BASE_MS + jitter; + return new Promise((resolve) => setTimeout(resolve, ms)); +} + +function markLoginTraffic(ip) { + if (!ip || LOGIN_ATTACK_UNIQUE_IPS <= 0) return; + const now = Date.now(); + for (const [key, ts] of loginAttackIps.entries()) { + if (now - ts > LOGIN_ATTACK_WINDOW_MS) loginAttackIps.delete(key); + } + if (!loginAttackIps.has(ip) && loginAttackIps.size >= LOGIN_MAP_MAX_SIZE) { + const oldest = loginAttackIps.keys().next().value; + if (oldest !== undefined) loginAttackIps.delete(oldest); + } + loginAttackIps.set(ip, now); + if (loginAttackIps.size >= LOGIN_ATTACK_UNIQUE_IPS) { + loginUnderAttackUntil = Math.max(loginUnderAttackUntil, now + LOGIN_ATTACK_HOLD_MS); + } +} + +function isLoginUnderAttack() { + return Date.now() < loginUnderAttackUntil; +} + +function isAggressiveLoginIp(ip) { + if (!ip || LOGIN_ATTACK_IP_MAX <= 0) return false; + const now = Date.now(); + let arr = loginAttackIpHits.get(ip) || []; + arr = arr.filter(ts => now - ts <= LOGIN_ATTACK_IP_WINDOW_MS); + arr.push(now); + + if (arr.length > LOGIN_ATTACK_IP_MAX * 5) { + arr = arr.slice(-LOGIN_ATTACK_IP_MAX * 2); + } + + if (!loginAttackIpHits.has(ip) && loginAttackIpHits.size >= LOGIN_MAP_MAX_SIZE) { + const oldest = loginAttackIpHits.keys().next().value; + if (oldest !== undefined) loginAttackIpHits.delete(oldest); + } + loginAttackIpHits.set(ip, arr); + return arr.length > LOGIN_ATTACK_IP_MAX; +} + +const NON_BROWSER_UA_RE = /^(curl|wget|httpie|python-|go-http|java\/|libwww|axios\/|node-fetch|undici\/|got\/|got |superagent|postman|insomnia|rest-client|apache-httpclient|okhttp|dart|ruby|perl|php|powershell|winhttp|scrapy|mechanize|phantomjs|headlesschrome|selenium|puppeteer|playwright)/i; + +function isNonBrowserRequest(req) { + const ua = (req.get("user-agent") || "").trim(); + const secFetchDest = (req.get("sec-fetch-dest") || "").toLowerCase(); + + if (NON_BROWSER_UA_RE.test(ua)) return true; + + if (!ua) return true; + + if (secFetchDest && secFetchDest !== "document" && secFetchDest !== "empty") return true; + + return false; +} + +function countAttemptsWithin(rec, windowMs) { + if (!rec || !Array.isArray(rec.attempts)) return 0; + const now = Date.now(); + return rec.attempts.reduce((acc, ts) => acc + (now - ts <= windowMs ? 1 : 0), 0); +} + +function suspiciousScoreForLogin(req, rec) { + const ua = String(req.get("user-agent") || "").trim(); + const acceptLang = String(req.get("accept-language") || "").trim(); + const accept = String(req.get("accept") || "").trim(); + let score = 0; + + const fastAttempts = countAttemptsWithin(rec, LOGIN_SUSPICIOUS_FAST_WINDOW_MS); + const windowAttempts = countAttemptsWithin(rec, LOGIN_SUSPICIOUS_WINDOW_MS); + + if (windowAttempts >= LOGIN_SUSPICIOUS_ATTEMPTS) score += 2; + if (fastAttempts >= LOGIN_SUSPICIOUS_FAST_ATTEMPTS) score += 2; + if (!ua || ua.length < 8) score += 2; + if (!acceptLang) score += 1; + if (!accept) score += 1; + + return score; +} + +function isSuspiciousLogin(req, rec) { + return suspiciousScoreForLogin(req, rec) >= LOGIN_SUSPICIOUS_SCORE_THRESHOLD; +} + +const BOTPROOF_TTL_MS = parseInt(process.env.BOTPROOF_TTL_MS || "900000", 10); + +function ensureBotProofSeed(req, res) { + if (!req || !res || !req.session) return ""; + const now = Date.now(); + let seed = req.session.botProofSeed; + const ts = req.session.botProofSeedTs || 0; + if (!seed || !ts || (now - ts) > BOTPROOF_TTL_MS) { + seed = crypto.randomBytes(18).toString("hex"); + req.session.botProofSeed = seed; + req.session.botProofSeedTs = now; + } + try { + res.cookie("adpanel.bp", seed, { + httpOnly: true, + sameSite: "lax", + secure: isRequestSecure(req), + maxAge: BOTPROOF_TTL_MS, + }); + } catch { } + return seed; +} + +function isBotProofValid(req, value) { + const expected = req?.session?.botProofSeed || ""; + if (!expected) return false; + return !!value && value === expected; +} + +setInterval(() => { + try { + const now = Date.now(); + for (const [ip, ts] of loginAttackIps.entries()) { + if (now - ts > LOGIN_ATTACK_WINDOW_MS) loginAttackIps.delete(ip); + } + for (const [ip, arr] of loginAttackIpHits.entries()) { + const kept = arr.filter(ts => now - ts <= LOGIN_ATTACK_IP_WINDOW_MS); + if (kept.length) loginAttackIpHits.set(ip, kept); + else loginAttackIpHits.delete(ip); + } + } catch (err) { console.debug("[loginAttack] sweep error:", err.message); } +}, 15_000); + +function loginAttackMiddleware(req, res, next) { + const ip = getRequestIp(req); + markLoginTraffic(ip); + const underAttack = isLoginUnderAttack(); + res.locals.underAttack = underAttack; + if (underAttack && isAggressiveLoginIp(ip)) { + res.setHeader("Retry-After", "5"); + return res.status(429).send("Too Many Requests"); + } + return next(); +} + +app.use("/login", loginAttackMiddleware); + +function getLoginPageAssetsForSecurity(res) { + const branding = (res && res.locals && res.locals.branding) || {}; + return { + loginBackgroundType: String(branding.loginBackgroundType || "video").toLowerCase(), + loginBackgroundUrl: String(branding.loginBackgroundUrl || "").trim(), + loginWatermarkUrl: String(branding.loginWatermarkUrl || "").trim(), + }; +} + +function applyLoginPageSecurityHeaders(req, res, options = {}) { + const assets = getLoginPageAssetsForSecurity(res); + const imgOrigins = ["https://cdn.jsdelivr.net"]; + const mediaOrigins = []; + + const watermarkOrigin = getOriginFromUrlLike(assets.loginWatermarkUrl); + if (watermarkOrigin) imgOrigins.push(watermarkOrigin); + + const backgroundOrigin = getOriginFromUrlLike(assets.loginBackgroundUrl); + if (backgroundOrigin) { + if (assets.loginBackgroundType === "image") imgOrigins.push(backgroundOrigin); + else mediaOrigins.push(backgroundOrigin); + } + + res.setHeader("Cache-Control", "no-store"); + res.setHeader("Content-Security-Policy", buildAuthPageCsp(req, res, { + includeFontAwesome: true, + includeGoogleFonts: false, + includeCaptcha: !!options.useExternalCaptcha, + captchaProvider: options.externalCaptchaProvider || "", + allowInlineStyleAttrs: !!options.useExternalCaptcha, + additionalImgOrigins: imgOrigins, + additionalMediaOrigins: mediaOrigins, + })); +} + +function applyForgotPasswordPageSecurityHeaders(req, res) { + res.setHeader("Cache-Control", "no-store"); + res.setHeader("Content-Security-Policy", buildAuthPageCsp(req, res, { + includeFontAwesome: false, + includeGoogleFonts: false, + includeCaptcha: false, + allowInlineStyleAttrs: false, + additionalImgOrigins: ["https://cdn.jsdelivr.net"], + })); +} + +const LOGIN_CSS_PATH = path.join(__dirname, "public", "login.css"); +let loginCssInlineCache = { mtimeMs: 0, content: "" }; + +function getInlineLoginCss() { + try { + const stat = fs.statSync(LOGIN_CSS_PATH); + if (!loginCssInlineCache.content || loginCssInlineCache.mtimeMs !== stat.mtimeMs) { + loginCssInlineCache = { + mtimeMs: stat.mtimeMs, + content: fs.readFileSync(LOGIN_CSS_PATH, "utf8"), + }; + } + return loginCssInlineCache.content; + } catch (err) { + console.error("[login] Failed to load inline CSS:", err.message); + return ""; + } +} + +app.get("/login", (req, res) => { + if (req.session?.user) { + return res.redirect(303, "/"); + } + + const botProofSeed = ensureBotProofSeed(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(); + + if (req.session && req.session.captchaSolved) { + clearLocalCaptcha(req); + req.session.captchaRequired = false; + } + + if (req.session && !req.session.captchaRequired && !hasError && !underAttack) { + 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); + } + + applyLoginPageSecurityHeaders(req, res, { + useExternalCaptcha, + externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, + }); + + return res.render("login", { + error: qErr || null, + botProofSeed, + csrfToken, + loginCss: getInlineLoginCss(), + useExternalCaptcha, + externalCaptchaAutoStart, + externalCaptchaSiteKey: EXTERNAL_CAPTCHA_SITE_KEY, + externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, + showLocalCaptcha: shouldShowLocal && !!captchaQuestion, + captchaQuestion, + }); +}); + +app.get("/register", (req, res) => { + const secret = speakeasy.generateSecret({ length: 20 }); + req.session.secret = secret.base32; + res.render("register", { secret: req.session.secret }); +}); + +app.get("/forgot-password", (req, res) => { + applyForgotPasswordPageSecurityHeaders(req, res); + res.render("forgot-password", { error: null, success: null }); +}); + +app.post("/login", async (req, res) => { + const accept = String(req.get("accept") || ""); + const contentType = String(req.get("content-type") || ""); + const wantsJson = + accept.includes("application/json") || + 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 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); + } + + applyLoginPageSecurityHeaders(req, res, { + useExternalCaptcha, + externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, + }); + + const renderData = { + error: message, + botProofSeed, + csrfToken, + loginCss: getInlineLoginCss(), + useExternalCaptcha, + externalCaptchaAutoStart, + externalCaptchaSiteKey: EXTERNAL_CAPTCHA_SITE_KEY, + externalCaptchaProvider: EXTERNAL_CAPTCHA_PROVIDER, + showLocalCaptcha: shouldShowLocal && !!captchaQuestion, + captchaQuestion, + }; + + if (req.session?.save) { + return req.session.save(() => res.status(status).render("login", renderData)); + } + return res.status(status).render("login", renderData); + }; + + const sendOk = () => { + res.setHeader("Cache-Control", "no-store"); + if (wantsJson) return res.json({ ok: true, redirect: "/" }); + return res.redirect(303, "/"); + }; + + if (!isValidLoginCsrfToken(req, req.body?._csrf)) { + return sendError(403, "Security token expired. Please refresh and try again.", { preserveCaptchaState: true }); + } + + const withTimeout = (p, ms, label) => + Promise.race([ + p, + new Promise((_, rej) => setTimeout(() => rej(new Error(label || "timeout")), ms)), + ]); + + try { + if (isNonBrowserRequest(req)) { + return res.status(403).set("Content-Type", "text/plain").send("Forbidden"); + } + + const { email, password, code } = req.body || {}; + 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 || ""); + const codeStr = String(code || "").trim(); + + const clientIp = getRequestIp(req); + + if (isLoginBlocked(clientIp)) { + await loginDelay(); + return sendError(429, "Try again later."); + } + + const rec = recordLoginAttempt(clientIp); + await loginDelay(); + if (rec.blockedUntil && rec.blockedUntil > Date.now()) { + 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) { + return sendError(400, "The fields are empty."); + } + + const user = await findUserByEmail(emailStr); + if (!user || !user.password) { + return sendError(400, "Invalid credentials"); + } + + const match = await withTimeout(bcrypt.compare(passStr, user.password), 8000, "bcrypt-timeout"); + if (!match) { + 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"); + } + + const isActuallySecure = isRequestSecure(req); + if (SESSION_COOKIE_SECURE && !isActuallySecure) { + return sendError( + 500, + "Config problem: SESSION_COOKIE_SECURE is on, but the request is seen as HTTP. Check reverse proxy to send X-Forwarded-Proto: https or set proxy trust correctly." + ); + } + + 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); + upsertActiveBrowserSessionCacheEntry(req.sessionID, req.session); + + await withTimeout( + new Promise((resolve, reject) => req.session.save((err) => (err ? reject(err) : resolve()))), + 5000, + "session-save-timeout" + ); + + setRememberLoginCookie(req, res, user); + clearLocalCaptcha(req); + resetLoginAttempts(clientIp); + return sendOk(); + } catch (err) { + console.error("[login] error:", err); + return sendError(500, "Internal login error."); + } +}); + +app.post("/logout", (req, res) => { + const clear = () => { + res.clearCookie("adpanel.sid", { + httpOnly: true, + sameSite: "lax", + secure: SESSION_COOKIE_SECURE, + path: "/", + }); + clearRememberLoginCookie(res); + }; + + if (req.session) { + const rememberLoginId = String(req.session.rememberLoginId || req.session.browserSessionAudit?.rememberLoginId || "").trim(); + if (rememberLoginId) revokeRememberLoginRegistryEntry(rememberLoginId); + removeActiveBrowserSessionCacheEntry(req.sessionID); + invalidateActiveBrowserSessionCache(); + req.session.destroy(err => { + if (err) return res.status(500).json({ error: "Failed to logout" }); + clear(); + return res.json({ success: true }); + }); + } else { + clear(); + return res.json({ success: true }); + } +}); + +const ENV_FILE_PATH = path.join(__dirname, ".env"); + +function readEnvFile() { + try { + if (!fs.existsSync(ENV_FILE_PATH)) return {}; + const content = fs.readFileSync(ENV_FILE_PATH, "utf8"); + const env = {}; + for (const line of content.split("\n")) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith("#")) continue; + const eqIdx = trimmed.indexOf("="); + if (eqIdx === -1) continue; + const key = trimmed.slice(0, eqIdx).trim(); + let val = trimmed.slice(eqIdx + 1).trim(); + if ((val.startsWith('"') && val.endsWith('"')) || (val.startsWith("'") && val.endsWith("'"))) { + val = val.slice(1, -1); + } + env[key] = val; + } + return env; + } catch { + return {}; + } +} + +function writeEnvValue(key, value) { + try { + let content = ""; + if (fs.existsSync(ENV_FILE_PATH)) { + content = fs.readFileSync(ENV_FILE_PATH, "utf8"); + } + const lines = content.split("\n"); + let found = false; + const cleaned = String(value ?? "").replace(/\0/g, "").replace(/[\r\n]+/g, ""); + const safeValue = cleaned.includes(" ") || cleaned.includes('"') ? `"${cleaned.replace(/"/g, '\\"')}"` : `"${cleaned}"`; + + for (let i = 0; i < lines.length; i++) { + const trimmed = lines[i].trim(); + if (trimmed.startsWith("#")) continue; + const eqIdx = trimmed.indexOf("="); + if (eqIdx === -1) continue; + const lineKey = trimmed.slice(0, eqIdx).trim(); + if (lineKey === key) { + lines[i] = `${key}=${safeValue}`; + found = true; + break; + } + } + + if (!found) { + lines.push(`${key}=${safeValue}`); + } + + fs.writeFileSync(ENV_FILE_PATH, lines.join("\n"), "utf8"); + try { fs.chmodSync(ENV_FILE_PATH, 0o600); } catch { } + return true; + } catch (err) { + console.error("[security] Failed to write .env:", err); + return false; + } +} + +app.get("/api/settings/security", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const envData = readEnvFile(); + const captchaEnabled = !!(envData.SITE_KEY && envData.SECRET_KEY && envData.SITE_KEY.trim() && envData.SECRET_KEY.trim()); + + return res.json({ + rate_limiting: security.rate_limiting, + limit: security.limit, + window_seconds: security.window_seconds, + 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 }) + } + }); +}); + +app.post("/api/settings/security", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/security")) return; + + const { rate_limiting, limit, window_seconds, trusted_subnets } = req.body || {}; + + const newLimit = Math.max(1, Math.min(10000, parseInt(limit, 10) || 5)); + const newWindow = Math.max(1, Math.min(86400, parseInt(window_seconds, 10) || 120)); + + security.rate_limiting = !!rate_limiting; + security.limit = newLimit; + security.window_seconds = newWindow; + if (Array.isArray(trusted_subnets)) { + security.trusted_subnets = trusted_subnets.filter(s => typeof s === "string" && s.length > 0).slice(0, 50); + } + + try { + safeWriteJson(SECURITY_FILE, security); + return res.json({ ok: true }); + } catch (err) { + console.error("[security] Failed to save security.json:", err); + return res.status(500).json({ error: "failed to save" }); + } +}); + +app.post("/api/settings/captcha", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/captcha")) return; + + const { site_key, secret_key, enabled } = req.body || {}; + + if (enabled === false) { + const siteOk = writeEnvValue("SITE_KEY", ""); + const secretOk = writeEnvValue("SECRET_KEY", ""); + if (!siteOk || !secretOk) { + return res.status(500).json({ error: "failed to update configuration" }); + } + return res.json({ ok: true, captcha_enabled: false }); + } + + const cleanSiteKey = String(site_key || "").trim(); + const cleanSecretKey = String(secret_key || "").trim(); + + if (!cleanSiteKey || cleanSiteKey.length < 10) { + return res.status(400).json({ error: "invalid site key" }); + } + if (!cleanSecretKey || cleanSecretKey.length < 10) { + return res.status(400).json({ error: "invalid secret key" }); + } + + const siteOk = writeEnvValue("SITE_KEY", cleanSiteKey); + const secretOk = writeEnvValue("SECRET_KEY", cleanSecretKey); + + if (!siteOk || !secretOk) { + return res.status(500).json({ error: "failed to update configuration" }); + } + + return res.json({ ok: true, captcha_enabled: true, note: "Restart server for changes to take effect" }); +}); + + +app.get("/api/maintenance/status", async (req, res) => { + const state = getMaintenanceState(); + const active = isMaintenanceActive(); + return res.json({ + active, + reason: active ? (state.reason || null) : null, + scheduled_at: (!active && state.scheduled_at) ? state.scheduled_at : null + }); +}); + +app.get("/api/settings/maintenance", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const state = getMaintenanceState(); + return res.json({ + ...state, + is_active: isMaintenanceActive(), + actionTokens: { + enableMaintenance: issueActionToken(req, "POST /api/settings/maintenance", {}, { ttlSeconds: 300 }), + disableMaintenance: issueActionToken(req, "DELETE /api/settings/maintenance", {}, { ttlSeconds: 300 }) + } + }); +}); + +app.post("/api/settings/maintenance", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/maintenance")) return; + + const { reason, scheduled_at, immediate, pre_alert_show, pre_alert_message, pre_alert_minutes_before } = req.body || {}; + + const user = await findUserByEmail(req.session.user); + if (!user || !user.admin) return res.status(403).json({ error: "not authorized" }); + + const state = getMaintenanceState(); + + if (scheduled_at && !immediate) { + const scheduledTime = new Date(scheduled_at).getTime(); + if (isNaN(scheduledTime)) { + return res.status(400).json({ error: "Invalid scheduled date" }); + } + if (scheduledTime <= Date.now()) { + return res.status(400).json({ error: "Scheduled time must be in the future" }); + } + state.scheduled_at = new Date(scheduledTime).toISOString(); + state.enabled = false; + } else { + state.enabled = true; + state.enabled_at = new Date().toISOString(); + state.scheduled_at = null; + } + + state.enabled_by = user.email; + state.reason = reason ? String(reason).slice(0, 500) : null; + + state.pre_alert = { + show: !!pre_alert_show, + message: pre_alert_message ? String(pre_alert_message).slice(0, 300) : null, + minutes_before: pre_alert_minutes_before ? Math.max(1, Math.min(525600, parseInt(pre_alert_minutes_before, 10) || 30)) : null, + _alert_injected: false, + _injected_alert_message: null + }; + + if (state.enabled && state.pre_alert.show && state.pre_alert.message) { + const currentAlert = getActiveGlobalAlert(); + if (currentAlert) { + state.previous_alert_backup = currentAlert; + } + addGlobalAlert(state.pre_alert.message, new Date().toISOString()); + state.pre_alert._alert_injected = true; + state.pre_alert._injected_alert_message = state.pre_alert.message; + } + + if (!saveMaintenanceState(state)) { + return res.status(500).json({ error: "Failed to save maintenance state" }); + } + + 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 } }); +}); + +app.delete("/api/settings/maintenance", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "DELETE /api/settings/maintenance")) return; + + const user = await findUserByEmail(req.session.user); + if (!user || !user.admin) return res.status(403).json({ error: "not authorized" }); + + const state = getMaintenanceState(); + + restoreAlertAfterMaintenance(state); + + const newState = { + enabled: false, + scheduled_at: null, + enabled_by: null, + enabled_at: null, + reason: null, + pre_alert: { show: false, message: null, minutes_before: null }, + previous_alert_backup: null + }; + + if (!saveMaintenanceState(newState)) { + return res.status(500).json({ error: "Failed to save maintenance state" }); + } + + console.log(`[maintenance] Disabled by ${user.email}`); + return res.json({ ok: true }); +}); + +app.get("/api/settings/sessions", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + res.set("Cache-Control", "no-store"); + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + return res.status(403).json({ error: "not authorized" }); + } + + const rawSearch = String(req.query?.search || "").trim().toLowerCase(); + const search = rawSearch.slice(0, 160); + const searchActive = !!search; + const requestedPage = Math.max(1, parseInt(req.query?.page, 10) || 1); + + try { + const activeSessions = await getCachedActiveBrowserSessions(); + const sortedSessions = [...activeSessions].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); + }); + + const filteredSessions = searchActive + ? sortedSessions.filter((entry) => String(entry.email || "").toLowerCase().includes(search)) + : sortedSessions; + + const total = filteredSessions.length; + const totalPages = searchActive ? 1 : Math.max(1, Math.ceil(total / ACTIVE_BROWSER_SESSION_PAGE_SIZE)); + const page = searchActive ? 1 : Math.min(requestedPage, totalPages); + const startIndex = searchActive ? 0 : (page - 1) * ACTIVE_BROWSER_SESSION_PAGE_SIZE; + const endIndex = searchActive ? total : Math.min(startIndex + ACTIVE_BROWSER_SESSION_PAGE_SIZE, total); + const items = filteredSessions + .slice(startIndex, searchActive ? undefined : endIndex) + .map((entry) => ({ + sessionId: getSessionDisplayId(entry.sessionId), + displayId: getSessionDisplayId(entry.sessionId), + 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), + })); + + const revokeGrace = getSessionRevokeGraceState(req); + + return res.json({ + items, + total, + page, + pageSize: ACTIVE_BROWSER_SESSION_PAGE_SIZE, + totalPages, + search, + searchActive, + from: total > 0 ? startIndex + 1 : 0, + to: total > 0 ? (searchActive ? total : endIndex) : 0, + revokeSecurity: { + twoFactorEnabled: !!currentUser.secret, + requiresTwoFactor: !revokeGrace, + graceExpiresAt: revokeGrace?.expiresAt || 0, + }, + actionTokens: { + revokeSession: issueActionToken(req, "POST /api/settings/sessions/revoke", {}, { ttlSeconds: 600 }), + }, + }); + } catch (err) { + console.error("[security] Failed to load active browser sessions:", err); + return res.status(500).json({ error: "failed to load sessions" }); + } +}); + +app.post("/api/settings/sessions/revoke", 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/sessions/revoke")) return; + + const currentUser = await findUserByEmail(req.session.user); + if (!currentUser || !currentUser.admin) { + 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(); + let sessionId = resolveSessionRevokeTargetToken(req, revokeToken); + if (!sessionId && req.body?.sessionId) { + sessionId = String(req.body.sessionId || "").trim(); + } + if (!sessionId) { + 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)) { + return res.status(400).json({ error: "Invalid session id", code: "invalid-session-id" }); + } + const targetDisplayId = getSessionDisplayId(sessionId); + + let graceState = getSessionRevokeGraceState(req); + let usedFreshTwoFactor = false; + + 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 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" }); + } + + usedFreshTwoFactor = true; + } + + let targetSession = null; + try { + targetSession = await callSessionStore("get", sessionId); + } catch (err) { + console.error("[security] Failed to read target session:", err); + return res.status(500).json({ error: "failed to read target session" }); + } + + if (!targetSession || !targetSession.user) { + clearSessionRevokeTargetToken(req, revokeToken); + removeActiveBrowserSessionCacheEntry(sessionId); + invalidateActiveBrowserSessionCache(); + return res.status(404).json({ error: "Session not found or already inactive", code: "session-not-active" }); + } + + const targetRecord = buildActiveBrowserSessionRecord(sessionId, targetSession) || { + sessionId, + email: String(targetSession.user || "").trim().toLowerCase(), + rememberLoginId: String(targetSession.rememberLoginId || targetSession.browserSessionAudit?.rememberLoginId || "").trim(), + }; + const targetEmail = String(targetRecord.email || "").trim().toLowerCase(); + const targetRememberLoginId = String(targetRecord.rememberLoginId || "").trim(); + const isCurrentSession = sessionId === String(req.sessionID || ""); + + if (targetRememberLoginId) { + revokeRememberLoginRegistryEntry(targetRememberLoginId); + } else { + try { + const targetUser = targetEmail ? await findUserByEmail(targetEmail) : null; + if (targetUser?.id) { + setRememberLoginLegacyCutoff(targetUser.id); + } + } catch (legacyErr) { + console.warn("[security] Failed to persist legacy remember-login cutoff:", legacyErr?.message || legacyErr); + } + } + + try { + if (isCurrentSession) { + await new Promise((resolve, reject) => { + req.session.destroy((err) => (err ? reject(err) : resolve())); + }); + removeActiveBrowserSessionCacheEntry(sessionId); + invalidateActiveBrowserSessionCache(); + res.clearCookie("adpanel.sid", { + httpOnly: true, + sameSite: "lax", + secure: SESSION_COOKIE_SECURE, + path: "/", + }); + clearRememberLoginCookie(res); + + console.log(`[SECURITY] Browser session revoked | Admin: ${currentUser.email} | Target: ${targetEmail} | Session: ${targetDisplayId} | Self: yes | IP: ${getRequestIp(req)}`); + return res.json({ + ok: true, + revoked: true, + sessionId: targetDisplayId, + displayId: targetDisplayId, + targetEmail, + revokedCurrentSession: true, + graceExpiresAt: 0, + }); + } + + await callSessionStore("destroy", sessionId); + clearSessionRevokeTargetToken(req, revokeToken); + 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; + } + } + + console.log(`[SECURITY] Browser session revoked | Admin: ${currentUser.email} | Target: ${targetEmail} | Session: ${targetDisplayId} | Self: no | IP: ${getRequestIp(req)}`); + return res.json({ + ok: true, + revoked: true, + sessionId: targetDisplayId, + displayId: targetDisplayId, + targetEmail, + revokedCurrentSession: false, + graceExpiresAt: graceExpiresAt || graceState?.expiresAt || 0, + }); + } catch (err) { + console.error("[security] Failed to revoke target session:", err); + return res.status(500).json({ error: "failed to revoke session" }); + } +}); + +const PANEL_INFO_FILE = path.join(__dirname, "panel-information.json"); +const PANEL_UPDATE_GITHUB_API = "https://api.github.com/repos/antonndev/ADPanel/releases"; +const PANEL_AUTO_UPDATE_INTERVAL_MS = 60 * 60 * 1000; + +const PROTECTED_FILES = new Set([ + "security.json", + "templates.json", + "webhooks-config.json", + "pgadmin-config.json", + "quick-actions.json", + "nodes.json", + "mongodb-config.json", + "database-config.json", + "user.json", + "user-access.json", + ".env", + "store-templates.json", + "versions.json", + "node_modules", + ".git", + ".sessions", + ".activity-logs", + "data", + "package-lock.json", + "go.mod", + "go.sum", + "venv", +]); + +const UPDATABLE_PATHS = new Set([ + "index.js", + "db.js", + "nodes.js", + "init_subdomains.js", + "panel-information.json", + "package.json", + "start.sh", +]); +const UPDATABLE_DIRS = ["scripts", "public", "views", "middleware", "utils", "routes"]; + +const NODE_UPDATE_GITHUB_API = "https://api.github.com/repos/antonndev/adaemon/releases"; +const NODE_AUTO_UPDATE_INTERVAL_MS = 60 * 60 * 1000; +const NODE_UPDATE_MAX_DOWNLOAD_SIZE = 80 * 1024 * 1024; + +let panelRestartScheduled = false; + +function schedulePanelRestart(reason = "panel-update") { + if (panelRestartScheduled) return; + panelRestartScheduled = true; + + const script = [ + "sleep 2", + "if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then", + " systemctl restart adpanel 2>/dev/null || sudo -n systemctl restart adpanel 2>/dev/null || true", + "elif command -v rc-service >/dev/null 2>&1; then", + " rc-service adpanel restart 2>/dev/null || sudo -n rc-service adpanel restart 2>/dev/null || true", + "elif command -v service >/dev/null 2>&1; then", + " service adpanel restart 2>/dev/null || sudo -n service adpanel restart 2>/dev/null || true", + "elif command -v pm2 >/dev/null 2>&1; then", + " pm2 restart adpanel --update-env >/dev/null 2>&1 || true", + "fi", + ].join("\n"); + + try { + const child = spawn("bash", ["-lc", script], { + detached: true, + stdio: "ignore", + env: process.env, + }); + child.unref(); + console.log(`[panel-update] Panel restart scheduled (${reason}).`); + } catch (err) { + panelRestartScheduled = false; + console.error("[panel-update] Failed to schedule panel restart:", err?.message || err); + } +} + +function normalizeUpdateVersionTag(version) { + const clean = String(version || "").trim(); + if (!clean) return ""; + return clean.toLowerCase().startsWith("v") ? `v${clean.slice(1)}` : `v${clean}`; +} + +function isValidUpdateVersion(version) { + return /^v?\d+\.\d+\.\d+([\-+][A-Za-z0-9_.-]+)?$/.test(String(version || "").trim()); +} + +function isAllowedNodeReleasePath(relativePath) { + const raw = String(relativePath || "").trim().replace(/\\/g, "/"); + if (!raw || raw.includes("/") || raw.startsWith(".") || raw.includes("..")) return false; + if (raw === "go.mod" || raw === "go.sum") return true; + return /^[A-Za-z0-9_.-]+\.go$/.test(raw); +} + +function readPanelInfo() { + const data = readJson(PANEL_INFO_FILE, [{}]); + const info = Array.isArray(data) ? (data[0] || {}) : (data || {}); + return { + version: String(info["panel-version"] || "unknown"), + architecture: String(info["panel-architecture"] || "unknown"), + autoUpdate: ["1", "true", "yes", "on"].includes(String(info["panel-auto-update"] ?? "false").trim().toLowerCase()), + }; +} + +function readPanelInfoObject() { + const data = readJson(PANEL_INFO_FILE, [{}]); + const arr = Array.isArray(data) ? data : [data || {}]; + const info = (arr[0] && typeof arr[0] === "object") ? arr[0] : {}; + return { arr, info }; +} + +function setPanelAutoUpdateEnabled(enabled) { + try { + const { arr, info } = readPanelInfoObject(); + info["panel-auto-update"] = !!enabled; + arr[0] = info; + return safeWriteJson(PANEL_INFO_FILE, arr); + } catch { + return false; + } +} + +async function fetchPanelReleases() { + const result = await httpRequestJson(PANEL_UPDATE_GITHUB_API, "GET", { + "Accept": "application/vnd.github.v3+json", + "User-Agent": "ADPanel-Updater", + }); + if (!result || result.status !== 200 || !Array.isArray(result.json)) { + const err = new Error("failed to fetch releases from GitHub"); + err.statusCode = 502; + throw err; + } + return result.json; +} + +function getLatestStableRelease(releases) { + let latestRelease = null; + for (const release of releases) { + if (release.draft || release.prerelease) continue; + const tagName = String(release.tag_name || ""); + if (!tagName) continue; + if (!latestRelease || compareVersions(latestRelease.tag_name, tagName) > 0) { + latestRelease = release; + } + } + return latestRelease; +} + +async function checkPanelUpdateInternal() { + const currentInfo = readPanelInfo(); + const currentVersion = currentInfo.version; + const releases = await fetchPanelReleases(); + + if (releases.length === 0) { + return { updateAvailable: false, currentVersion, latestVersion: currentVersion, latestRelease: null }; + } + + const latestRelease = getLatestStableRelease(releases); + if (!latestRelease) { + return { updateAvailable: false, currentVersion, latestVersion: currentVersion, latestRelease: null }; + } + + const latestVersion = String(latestRelease.tag_name); + const updateAvailable = compareVersions(currentVersion, latestVersion) > 0; + return { updateAvailable, currentVersion, latestVersion, latestRelease }; +} + +async function installPanelUpdateInternal(targetVersion, source = "manual") { + const cleanTargetVersion = String(targetVersion || "").trim(); + if (!cleanTargetVersion || !/^v?\d+\.\d+\.\d+/.test(cleanTargetVersion)) { + const err = new Error("invalid version format"); + err.statusCode = 400; + throw err; + } + + const currentInfo = readPanelInfo(); + if (compareVersions(currentInfo.version, cleanTargetVersion) <= 0) { + console.log(`[panel-update] Installing version ${cleanTargetVersion} (current: ${currentInfo.version}) — same or older version requested (${source}).`); + } + + const releases = await fetchPanelReleases(); + const targetRelease = releases.find(r => { + const tag = String(r.tag_name || ""); + return tag === cleanTargetVersion || tag === `v${cleanTargetVersion.replace(/^v/, "")}`; + }); + + if (!targetRelease) { + const err = new Error(`release ${cleanTargetVersion} not found`); + err.statusCode = 404; + throw err; + } + + const zipballUrl = targetRelease.zipball_url; + if (!zipballUrl) { + const err = new Error("no download URL available for this release"); + err.statusCode = 502; + throw err; + } + + const MAX_DOWNLOAD_SIZE = 200 * 1024 * 1024; + let zipBuffer; + try { + zipBuffer = await httpGetRaw(zipballUrl, { + maxBytes: MAX_DOWNLOAD_SIZE, + timeoutMs: 120000, + maxRedirects: 5, + }); + } catch (dlErr) { + console.error("[panel-update] Download failed:", dlErr); + const err = new Error("failed to download update archive"); + err.statusCode = 502; + throw err; + } + + if (!zipBuffer || zipBuffer.length < 100) { + const err = new Error("downloaded archive is empty or too small"); + err.statusCode = 502; + throw err; + } + + const AdmZip = require("adm-zip"); + const tmpDir = path.join(os.tmpdir(), `adpanel-update-${Date.now()}`); + + try { + const zip = new AdmZip(zipBuffer); + const entries = zip.getEntries(); + + if (entries.length === 0) { + const err = new Error("update archive is empty"); + err.statusCode = 502; + throw err; + } + + let prefix = ""; + for (const entry of entries) { + const name = entry.entryName || ""; + if (name.includes("/")) { + const candidate = name.split("/")[0] + "/"; + if (!prefix) prefix = candidate; + break; + } + } + + const panelRoot = __dirname; + let filesUpdated = 0; + let filesSkipped = 0; + + for (const entry of entries) { + if (entry.isDirectory) continue; + + const fullEntryPath = entry.entryName || ""; + const relativePath = prefix && fullEntryPath.startsWith(prefix) + ? fullEntryPath.slice(prefix.length) + : fullEntryPath; + + if (!relativePath) continue; + + const normalizedRelative = path.normalize(relativePath); + if (normalizedRelative.startsWith("..") || path.isAbsolute(normalizedRelative)) { + filesSkipped++; + continue; + } + + const topLevel = normalizedRelative.split(path.sep)[0]; + if (PROTECTED_FILES.has(topLevel)) { + filesSkipped++; + continue; + } + if (PROTECTED_FILES.has(normalizedRelative)) { + filesSkipped++; + continue; + } + + const isUpdatableFile = UPDATABLE_PATHS.has(normalizedRelative); + const isUpdatableDir = UPDATABLE_DIRS.some(dir => + normalizedRelative === dir || normalizedRelative.startsWith(dir + path.sep) + ); + + if (!isUpdatableFile && !isUpdatableDir) { + filesSkipped++; + continue; + } + + const targetPath = path.join(panelRoot, normalizedRelative); + + const resolvedTarget = path.resolve(targetPath); + if (!resolvedTarget.startsWith(path.resolve(panelRoot) + path.sep) && resolvedTarget !== path.resolve(panelRoot)) { + filesSkipped++; + continue; + } + + const parentDir = path.dirname(targetPath); + if (!fs.existsSync(parentDir)) { + fs.mkdirSync(parentDir, { recursive: true }); + } + + fs.writeFileSync(targetPath, entry.getData()); + filesUpdated++; + } + + const panelInfoData = readJson(PANEL_INFO_FILE, [{}]); + const infoObj = Array.isArray(panelInfoData) ? (panelInfoData[0] || {}) : (panelInfoData || {}); + infoObj["panel-version"] = cleanTargetVersion.startsWith("v") ? cleanTargetVersion : `v${cleanTargetVersion}`; + const newInfoArray = [infoObj]; + safeWriteJson(PANEL_INFO_FILE, newInfoArray); + + console.log(`[panel-update] Update to ${cleanTargetVersion} completed. ${filesUpdated} files updated, ${filesSkipped} files skipped (protected/excluded). Source: ${source}.`); + schedulePanelRestart(`panel-update:${source}`); + + return { + ok: true, + version: cleanTargetVersion, + filesUpdated, + filesSkipped, + restartScheduled: true, + message: "Update installed successfully. Panel restart scheduled.", + }; + } finally { + try { + if (fs.existsSync(tmpDir)) { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + } catch { } + } +} + +let panelAutoUpdateInterval = null; +let panelAutoUpdateRunning = false; + +async function runPanelAutoUpdateCycle(trigger = "interval") { + if (panelAutoUpdateRunning) return; + + const panelInfo = readPanelInfo(); + if (!panelInfo.autoUpdate) return; + + panelAutoUpdateRunning = true; + try { + const check = await checkPanelUpdateInternal(); + if (!check.updateAvailable) { + console.log(`[panel-auto-update] No update available (trigger: ${trigger}, current: ${check.currentVersion}).`); + return; + } + + console.log(`[panel-auto-update] Update found ${check.currentVersion} -> ${check.latestVersion} (trigger: ${trigger}). Installing...`); + await installPanelUpdateInternal(check.latestVersion, `auto:${trigger}`); + console.log(`[panel-auto-update] Installed ${check.latestVersion}. Panel restart scheduled.`); + } catch (err) { + console.error("[panel-auto-update] Cycle failed:", err?.message || err); + } finally { + panelAutoUpdateRunning = false; + } +} + +function startPanelAutoUpdateScheduler() { + if (panelAutoUpdateInterval) return; + + panelAutoUpdateInterval = setInterval(() => { + runPanelAutoUpdateCycle("interval").catch(() => { }); + }, PANEL_AUTO_UPDATE_INTERVAL_MS); + panelAutoUpdateInterval.unref(); + + setTimeout(() => { + runPanelAutoUpdateCycle("startup").catch(() => { }); + }, 10000).unref(); +} + +function compareVersions(a, b) { + const parse = (v) => { + const m = String(v || "").replace(/^v/i, "").match(/^(\d+)\.(\d+)\.(\d+)/); + return m ? [parseInt(m[1], 10), parseInt(m[2], 10), parseInt(m[3], 10)] : [0, 0, 0]; + }; + const [a1, a2, a3] = parse(a); + const [b1, b2, b3] = parse(b); + if (b1 !== a1) return b1 - a1; + if (b2 !== a2) return b2 - a2; + return b3 - a3; +} + +app.get("/api/settings/panel-info", async (req, res) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const info = readPanelInfo(); + return res.json({ + version: info.version, + architecture: info.architecture, + autoUpdateEnabled: !!info.autoUpdate, + actionTokens: { + checkUpdate: issueActionToken(req, "POST /api/settings/panel-update/check", {}, { ttlSeconds: 300 }), + installUpdate: issueActionToken(req, "POST /api/settings/panel-update/install", {}, { ttlSeconds: 600, oneTime: true }), + setAutoUpdate: issueActionToken(req, "POST /api/settings/panel-update/auto", {}, { ttlSeconds: 300 }), + }, + }); + } catch (err) { + console.error("[panel-info] Error reading panel info:", err); + return res.status(500).json({ error: "failed to read panel information" }); + } +}); + +app.post("/api/settings/panel-update/check", async (req, res) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/panel-update/check")) return; + const checkResult = await checkPanelUpdateInternal(); + const { updateAvailable, currentVersion, latestVersion } = checkResult; + + return res.json({ + updateAvailable, + currentVersion, + latestVersion, + ...(updateAvailable ? { + actionTokens: { + installUpdate: issueActionToken(req, "POST /api/settings/panel-update/install", {}, { ttlSeconds: 600, oneTime: true }), + }, + } : {}), + }); + } catch (err) { + console.error("[panel-update] Error checking for updates:", err); + return res.status(500).json({ error: "failed to check for updates" }); + } +}); + +app.post("/api/settings/panel-update/install", async (req, res) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/panel-update/install")) return; + + const targetVersion = String(req.body?.version || "").trim(); + const installResult = await installPanelUpdateInternal(targetVersion, "manual"); + return res.json(installResult); + } catch (err) { + console.error("[panel-update] Error installing update:", err); + const status = Number(err?.statusCode) || 500; + const message = (status >= 500) ? "update installation failed" : (err?.message || "update installation failed"); + return res.status(status).json({ error: message }); + } +}); + +app.post("/api/settings/panel-update/auto", async (req, res) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/panel-update/auto")) return; + + const enabled = !!req.body?.enabled; + const ok = setPanelAutoUpdateEnabled(enabled); + if (!ok) { + return res.status(500).json({ error: "failed to save auto update setting" }); + } + + if (enabled) { + setTimeout(() => { + runPanelAutoUpdateCycle("enabled-toggle").catch(() => { }); + }, 1000).unref(); + } + + return res.json({ ok: true, autoUpdateEnabled: enabled }); + } catch (err) { + console.error("[panel-auto-update] Failed to toggle:", err); + return res.status(500).json({ error: "failed to update auto update setting" }); + } +}); + +async function fetchNodeReleases() { + const result = await httpRequestJson(NODE_UPDATE_GITHUB_API, "GET", { + "Accept": "application/vnd.github.v3+json", + "User-Agent": "ADPanel-Node-Updater", + }); + if (!result || result.status !== 200 || !Array.isArray(result.json)) { + const err = new Error("failed to fetch node releases from GitHub"); + err.statusCode = 502; + throw err; + } + return result.json; +} + +function nodeActionResource(node) { + return { nodeId: String(node?.id || node?.uuid || "") }; +} + +function publicNodeUpdateSummary(node) { + const lastSeen = Number(node?.last_seen || 0); + const fresh = lastSeen > 0 && (Date.now() - lastSeen) < 120000; + return { + id: node?.id || node?.uuid || "", + uuid: node?.uuid || node?.id || "", + name: node?.name || "Node", + address: node?.address || "", + api_port: Number(node?.api_port || 8080), + online: node?.online === true || (fresh && node?.port_ok === true), + }; +} + +function buildNodeUpdateUrl(node, suffix) { + const base = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!base) return null; + return `${base}${String(suffix || "").startsWith("/") ? suffix : `/${suffix || ""}`}`; +} + +function signPanelNodeUpdateHeaders(headers, node, action, subject) { + const role = "admin"; + const ts = String(Date.now()); + const nodeToken = String((node && (node.token || node.secret || node.api_key)) || "").trim(); + const signingSecret = PANEL_HMAC_SECRET || nodeToken; + if (!signingSecret) return false; + + const base = `${String(node?.uuid || node?.id || "").trim()}|${String(action || "").trim()}|${String(subject || "").trim()}|${role}|${ts}`; + const sig = crypto.createHmac("sha256", signingSecret).update(base).digest("hex"); + headers["x-panel-role"] = role; + headers["x-panel-ts"] = ts; + headers["x-panel-sign"] = sig; + return true; +} + +async function callNodeUpdateApi(node, suffix, { method = "GET", body = null, timeoutMs = 15000, action = "", subject = "" } = {}) { + const url = buildNodeUpdateUrl(node, suffix); + if (!url) return { status: 0, json: null, error: "invalid node url" }; + const headers = nodeAuthHeadersFor(node, true); + if (action) { + const signed = signPanelNodeUpdateHeaders(headers, node, action, subject); + if (!signed) return { status: 0, json: null, error: "missing node signing secret" }; + } + return httpRequestJson(url, method, headers, body, timeoutMs); +} + +async function fetchNodeRuntimeInfo(node) { + const updateInfo = await callNodeUpdateApi(node, "/v1/update/info", { method: "GET", timeoutMs: 7000 }); + if (updateInfo.status === 200 && updateInfo.json && updateInfo.json.ok) { + return { + version: normalizeUpdateVersionTag(updateInfo.json.version || "v0.0.0"), + architecture: String(updateInfo.json.architecture || "unknown"), + autoUpdateEnabled: !!updateInfo.json.autoUpdateEnabled, + updateApiAvailable: true, + }; + } + + const fallback = await callNodeUpdateApi(node, "/v1/info", { method: "GET", timeoutMs: 5000 }); + if (fallback.status === 200 && fallback.json && fallback.json.node) { + return { + version: normalizeUpdateVersionTag(fallback.json.node.version || "v0.0.0"), + architecture: String(fallback.json.node.architecture || "unknown"), + autoUpdateEnabled: !!fallback.json.node.autoUpdate, + updateApiAvailable: false, + }; + } + + const err = new Error("node is unreachable or unauthorized"); + err.statusCode = 502; + err.nodeStatus = updateInfo.status || fallback.status || 0; + throw err; +} + +async function checkNodeUpdateInternal(currentVersion) { + const releases = await fetchNodeReleases(); + const latestRelease = getLatestStableRelease(releases); + const safeCurrent = normalizeUpdateVersionTag(currentVersion || "v0.0.0") || "v0.0.0"; + + if (!latestRelease) { + return { updateAvailable: false, currentVersion: safeCurrent, latestVersion: safeCurrent, latestRelease: null }; + } + + const latestVersion = normalizeUpdateVersionTag(latestRelease.tag_name || ""); + const updateAvailable = compareVersions(safeCurrent, latestVersion) > 0; + return { updateAvailable, currentVersion: safeCurrent, latestVersion, latestRelease }; +} + +function extractNodeUpdateFilesFromRelease(targetRelease, zipBuffer) { + const AdmZip = require("adm-zip"); + const zip = new AdmZip(zipBuffer); + const entries = zip.getEntries(); + if (!entries.length) { + const err = new Error("node update archive is empty"); + err.statusCode = 502; + throw err; + } + + let prefix = ""; + for (const entry of entries) { + const name = entry.entryName || ""; + if (name.includes("/")) { + prefix = name.split("/")[0] + "/"; + break; + } + } + + const files = []; + let skipped = 0; + for (const entry of entries) { + if (entry.isDirectory) continue; + const fullEntryPath = String(entry.entryName || ""); + const relativePath = prefix && fullEntryPath.startsWith(prefix) + ? fullEntryPath.slice(prefix.length) + : fullEntryPath; + const rawRelative = relativePath.replace(/\\/g, "/"); + if (rawRelative.includes("/") || rawRelative.includes("..")) { + skipped++; + continue; + } + const normalized = path.posix.normalize(rawRelative); + if (!isAllowedNodeReleasePath(normalized)) { + skipped++; + continue; + } + const data = entry.getData(); + if (!data || data.length === 0 || data.length > 8 * 1024 * 1024) { + skipped++; + continue; + } + files.push({ + path: normalized, + contentBase64: data.toString("base64"), + }); + } + + if (!files.some(file => file.path === "main.go")) { + const err = new Error("node release does not contain main.go"); + err.statusCode = 502; + throw err; + } + + return { + files, + filesSkipped: skipped, + sourceTag: targetRelease?.tag_name || "", + }; +} + +async function prepareNodeUpdatePayload(targetVersion) { + const cleanTargetVersion = normalizeUpdateVersionTag(targetVersion); + if (!cleanTargetVersion || !isValidUpdateVersion(cleanTargetVersion)) { + const err = new Error("invalid version format"); + err.statusCode = 400; + throw err; + } + + const releases = await fetchNodeReleases(); + const targetRelease = releases.find(r => { + const tag = normalizeUpdateVersionTag(r.tag_name || ""); + return tag === cleanTargetVersion; + }); + + if (!targetRelease) { + const err = new Error(`node release ${cleanTargetVersion} not found`); + err.statusCode = 404; + throw err; + } + + if (!targetRelease.zipball_url) { + const err = new Error("no node download URL available for this release"); + err.statusCode = 502; + throw err; + } + + let zipBuffer; + try { + zipBuffer = await httpGetRaw(targetRelease.zipball_url, { + maxBytes: NODE_UPDATE_MAX_DOWNLOAD_SIZE, + timeoutMs: 120000, + maxRedirects: 5, + }); + } catch (dlErr) { + console.error("[node-update] Download failed:", dlErr); + const err = new Error("failed to download node update archive"); + err.statusCode = 502; + throw err; + } + + if (!zipBuffer || zipBuffer.length < 100) { + const err = new Error("downloaded node archive is empty or too small"); + err.statusCode = 502; + throw err; + } + + return { + version: cleanTargetVersion, + ...extractNodeUpdateFilesFromRelease(targetRelease, zipBuffer), + }; +} + +async function installNodeUpdateInternal(node, targetVersion, source = "manual") { + const payload = await prepareNodeUpdatePayload(targetVersion); + const result = await callNodeUpdateApi(node, "/v1/update/install", { + method: "POST", + body: { + version: payload.version, + files: payload.files, + }, + timeoutMs: 180000, + action: "node-update-install", + subject: payload.version, + }); + + if (result.status !== 200 || !result.json || result.json.ok !== true) { + const detail = result.json?.error || result.error || `node updater returned status ${result.status || 0}`; + const err = new Error(detail); + err.statusCode = result.status === 400 || result.status === 403 || result.status === 404 ? result.status : 502; + throw err; + } + + console.log(`[node-update] ${node.name || node.id} updated to ${payload.version}. Source: ${source}.`); + return { + ok: true, + version: payload.version, + filesUpdated: result.json.filesUpdated ?? payload.files.length, + filesSkipped: payload.filesSkipped, + restartCommand: result.json.restartCommand || "systemctl restart adaemon", + message: result.json.message || "Node update installed.", + }; +} + +let nodeAutoUpdateInterval = null; +let nodeAutoUpdateRunning = false; + +async function runNodeAutoUpdateCycle(trigger = "interval") { + if (nodeAutoUpdateRunning) return; + nodeAutoUpdateRunning = true; + try { + const nodes = await loadNodes(); + if (!nodes.length) return; + + const releases = await fetchNodeReleases(); + const latestRelease = getLatestStableRelease(releases); + if (!latestRelease) return; + const latestVersion = normalizeUpdateVersionTag(latestRelease.tag_name || ""); + if (!latestVersion) return; + + for (const node of nodes) { + try { + const info = await fetchNodeRuntimeInfo(node); + if (!info.autoUpdateEnabled) continue; + if (compareVersions(info.version, latestVersion) <= 0) { + console.log(`[node-auto-update] ${node.name || node.id} is already current (${info.version}).`); + continue; + } + console.log(`[node-auto-update] Updating ${node.name || node.id}: ${info.version} -> ${latestVersion} (trigger: ${trigger}).`); + await installNodeUpdateInternal(node, latestVersion, `auto:${trigger}`); + } catch (err) { + console.error(`[node-auto-update] ${node.name || node.id} failed:`, err?.message || err); + } + } + } catch (err) { + console.error("[node-auto-update] Cycle failed:", err?.message || err); + } finally { + nodeAutoUpdateRunning = false; + } +} + +function startNodeAutoUpdateScheduler() { + if (nodeAutoUpdateInterval) return; + + nodeAutoUpdateInterval = setInterval(() => { + runNodeAutoUpdateCycle("interval").catch(() => { }); + }, NODE_AUTO_UPDATE_INTERVAL_MS); + nodeAutoUpdateInterval.unref(); + + setTimeout(() => { + runNodeAutoUpdateCycle("startup").catch(() => { }); + }, 15000).unref(); +} + +app.get("/api/settings/node-update/info", async (req, res) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const nodes = await loadNodes(); + const publicNodes = nodes.map(publicNodeUpdateSummary); + const requestedNodeId = String(req.query?.nodeId || "").trim(); + const selectedNode = requestedNodeId + ? await findNodeByIdOrName(requestedNodeId) + : nodes[0] || null; + + if (!selectedNode) { + return res.json({ + nodes: publicNodes, + selectedNode: null, + version: "unknown", + architecture: "unknown", + autoUpdateEnabled: false, + updateApiAvailable: false, + actionTokens: {}, + }); + } + + let runtimeInfo; + let runtimeError = null; + try { + runtimeInfo = await fetchNodeRuntimeInfo(selectedNode); + } catch (err) { + runtimeError = err?.message || "failed to read node information"; + runtimeInfo = { + version: "unknown", + architecture: "unknown", + autoUpdateEnabled: false, + updateApiAvailable: false, + }; + } + + const resource = nodeActionResource(selectedNode); + return res.json({ + nodes: publicNodes, + selectedNode: publicNodeUpdateSummary(selectedNode), + version: runtimeInfo.version, + architecture: runtimeInfo.architecture, + autoUpdateEnabled: runtimeInfo.autoUpdateEnabled, + updateApiAvailable: runtimeInfo.updateApiAvailable, + error: runtimeError, + actionTokens: { + checkUpdate: issueActionToken(req, "POST /api/settings/node-update/check", resource, { ttlSeconds: 300 }), + installUpdate: issueActionToken(req, "POST /api/settings/node-update/install", resource, { ttlSeconds: 600, oneTime: true }), + setAutoUpdate: issueActionToken(req, "POST /api/settings/node-update/auto", resource, { ttlSeconds: 300 }), + }, + }); + } catch (err) { + console.error("[node-update] Error reading node info:", err); + return res.status(500).json({ error: "failed to read node update information" }); + } +}); + +app.post("/api/settings/node-update/check", async (req, res) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const node = await findNodeByIdOrName(req.body?.nodeId); + if (!node) return res.status(404).json({ error: "node not found" }); + const resource = nodeActionResource(node); + if (!requireActionTokenOr403(req, res, "POST /api/settings/node-update/check", resource)) return; + + const runtimeInfo = await fetchNodeRuntimeInfo(node); + const checkResult = await checkNodeUpdateInternal(runtimeInfo.version); + const { updateAvailable, currentVersion, latestVersion } = checkResult; + + return res.json({ + updateAvailable, + currentVersion, + latestVersion, + updateApiAvailable: runtimeInfo.updateApiAvailable, + ...(updateAvailable ? { + actionTokens: { + installUpdate: issueActionToken(req, "POST /api/settings/node-update/install", resource, { ttlSeconds: 600, oneTime: true }), + }, + } : {}), + }); + } catch (err) { + console.error("[node-update] Error checking for updates:", err); + const status = Number(err?.statusCode) || 500; + return res.status(status >= 500 ? 500 : status).json({ error: status >= 500 ? "failed to check node updates" : err.message }); + } +}); + +app.post("/api/settings/node-update/install", async (req, res) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const node = await findNodeByIdOrName(req.body?.nodeId); + if (!node) return res.status(404).json({ error: "node not found" }); + const resource = nodeActionResource(node); + if (!requireActionTokenOr403(req, res, "POST /api/settings/node-update/install", resource)) return; + + const targetVersion = String(req.body?.version || "").trim(); + const installResult = await installNodeUpdateInternal(node, targetVersion, "manual"); + return res.json(installResult); + } catch (err) { + console.error("[node-update] Error installing update:", err); + const status = Number(err?.statusCode) || 500; + const message = (status >= 500) ? "node update installation failed" : (err?.message || "node update installation failed"); + return res.status(status).json({ error: message }); + } +}); + +app.post("/api/settings/node-update/auto", async (req, res) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const node = await findNodeByIdOrName(req.body?.nodeId); + if (!node) return res.status(404).json({ error: "node not found" }); + const resource = nodeActionResource(node); + if (!requireActionTokenOr403(req, res, "POST /api/settings/node-update/auto", resource)) return; + + const enabled = !!req.body?.enabled; + const subject = enabled ? "on" : "off"; + const result = await callNodeUpdateApi(node, "/v1/update/auto", { + method: "POST", + body: { enabled }, + timeoutMs: 15000, + action: "node-update-auto", + subject, + }); + + if (result.status !== 200 || !result.json || result.json.ok !== true) { + return res.status(result.status === 403 || result.status === 404 ? result.status : 502).json({ + error: result.json?.error || "failed to update node auto update setting", + }); + } + + if (enabled) { + setTimeout(() => { + runNodeAutoUpdateCycle("enabled-toggle").catch(() => { }); + }, 1000).unref(); + } + + return res.json({ ok: true, autoUpdateEnabled: !!result.json.autoUpdateEnabled }); + } catch (err) { + console.error("[node-auto-update] Failed to toggle:", err); + return res.status(500).json({ error: "failed to update node auto update setting" }); + } +}); + +const AI_PROVIDER_CONFIGS = { + openai: { + name: 'OpenAI', + keyEnv: 'OPENAI_API_KEY', + requiresKey: true, + chatProtocol: 'openai-compatible', + chatEndpoint: 'https://api.openai.com/v1/chat/completions', + modelDiscovery: 'openai-style', + modelListUrls: ['https://api.openai.com/v1/models'] + }, + anthropic: { + name: 'Anthropic', + keyEnv: 'ANTHROPIC_API_KEY', + requiresKey: true, + chatProtocol: 'anthropic', + chatEndpoint: 'https://api.anthropic.com/v1/messages', + modelDiscovery: 'anthropic', + modelListUrls: ['https://api.anthropic.com/v1/models'] + }, + 'openai-compatible': { + name: 'OpenAI Compatible', + keyEnv: 'OPENAI_COMPATIBLE_API_KEY', + baseUrlEnv: 'OPENAI_COMPATIBLE_BASE_URL', + requiresKey: false, + requiresBaseUrl: true, + chatProtocol: 'openai-compatible', + modelDiscovery: 'openai-compatible' + }, + google: { + name: 'Google AI', + keyEnv: 'GOOGLE_AI_KEY', + requiresKey: true, + chatProtocol: 'google', + modelDiscovery: 'google' + }, + groq: { + name: 'Groq', + keyEnv: 'GROQ_API_KEY', + requiresKey: true, + chatProtocol: 'openai-compatible', + chatEndpoint: 'https://api.groq.com/openai/v1/chat/completions', + modelDiscovery: 'openai-style', + modelListUrls: ['https://api.groq.com/openai/v1/models'] + }, + huggingface: { + name: 'HuggingFace', + keyEnv: 'HUGGINGFACE_API_KEY', + requiresKey: true, + chatProtocol: 'huggingface', + chatEndpoint: 'https://router.huggingface.co/v1/chat/completions', + modelDiscovery: 'huggingface' + }, + together: { + name: 'Together AI', + keyEnv: 'TOGETHER_API_KEY', + requiresKey: true, + chatProtocol: 'openai-compatible', + chatEndpoint: 'https://api.together.ai/v1/chat/completions', + modelDiscovery: 'together', + modelListUrls: ['https://api.together.ai/v1/models'] + }, + cohere: { + name: 'Cohere', + keyEnv: 'COHERE_API_KEY', + requiresKey: true, + chatProtocol: 'cohere', + modelDiscovery: 'cohere' + }, + openrouter: { + name: 'OpenRouter', + keyEnv: 'OPENROUTER_API_KEY', + requiresKey: true, + chatProtocol: 'openai-compatible', + chatEndpoint: 'https://openrouter.ai/api/v1/chat/completions', + modelDiscovery: 'openrouter', + modelListUrls: ['https://openrouter.ai/api/v1/models?output_modalities=text'] + } +}; + +const ANTHROPIC_API_VERSION = '2023-06-01'; + +const AI_KEY_ENV_MAPPING = Object.fromEntries( + Object.entries(AI_PROVIDER_CONFIGS) + .filter(([, config]) => !!config.keyEnv) + .map(([provider, config]) => [provider, config.keyEnv]) +); + + + +function writeEnvFileBatch(updates) { + try { + let lines = []; + if (fs.existsSync(ENV_FILE_PATH)) { + lines = fs.readFileSync(ENV_FILE_PATH, 'utf8').split('\n'); + } + + const updatedKeys = new Set(); + const newLines = []; + + for (const line of lines) { + const trimmed = line.trim(); + if (!trimmed || trimmed.startsWith('#')) { + newLines.push(line); + continue; + } + const eqIdx = trimmed.indexOf('='); + if (eqIdx === -1) { + newLines.push(line); + continue; + } + const key = trimmed.slice(0, eqIdx).trim(); + if (updates.hasOwnProperty(key)) { + const cleaned = String(updates[key] ?? "").replace(/\0/g, "").replace(/[\r\n]+/g, ""); + newLines.push(`${key}="${cleaned.replace(/"/g, '\\"')}"`); + updatedKeys.add(key); + } else { + newLines.push(line); + } + } + + for (const [key, value] of Object.entries(updates)) { + if (!updatedKeys.has(key)) { + const cleaned = String(value ?? "").replace(/\0/g, "").replace(/[\r\n]+/g, ""); + newLines.push(`${key}="${cleaned.replace(/"/g, '\\"')}"`); + } + } + + fs.writeFileSync(ENV_FILE_PATH, newLines.join('\n'), 'utf8'); + try { fs.chmodSync(ENV_FILE_PATH, 0o600); } catch { } + return true; + } catch (err) { + console.error('[ai-keys] Failed to write .env:', err); + return false; + } +} + +async function hasAgentAccess(req) { + if (await isAdmin(req)) return true; + const email = req.session?.user; + if (!email) return false; + const user = await findUserByEmail(email); + return !!(user && user.agent_access); +} + +function getAiProviderConfig(provider) { + return AI_PROVIDER_CONFIGS[String(provider || '').trim().toLowerCase()] || null; +} + +function normalizeAiSecretValue(value) { + return String(value == null ? '' : value).trim(); +} + +function maskAiSecretValue(value) { + const normalized = normalizeAiSecretValue(value); + if (!normalized) return ''; + return normalized.length > 8 ? `${normalized.slice(0, 4)}...${normalized.slice(-4)}` : '****'; +} + +function normalizeOpenAiCompatibleBaseUrl(input) { + const raw = normalizeAiSecretValue(input); + if (!raw) return ''; + + let parsed; + try { + parsed = new URL(raw); + } catch { + throw new Error('Please enter a valid Base URL.'); + } + + if (!['http:', 'https:'].includes(parsed.protocol)) { + throw new Error('Base URL must start with http:// or https://.'); + } + + parsed.hash = ''; + parsed.search = ''; + + let pathname = parsed.pathname || ''; + pathname = pathname.replace(/\/+$/, ''); + pathname = pathname.replace(/\/(?:chat\/completions|completions|responses|models)$/i, ''); + parsed.pathname = pathname || '/'; + + return parsed.toString().replace(/\/$/, ''); +} + +function buildOpenAiCompatibleBaseUrlCandidates(input) { + const normalized = normalizeOpenAiCompatibleBaseUrl(input); + const parsed = new URL(normalized); + const pathname = parsed.pathname.replace(/\/+$/, '').toLowerCase(); + const candidates = [normalized]; + + if (!/\/v\d+$/.test(pathname) && !/\/openai\/v\d+$/.test(pathname)) { + candidates.push(`${normalized}/v1`); + } + + return Array.from(new Set(candidates.map((value) => value.replace(/\/+$/, '')))); +} + +function appendPathToBaseUrl(baseUrl, path) { + return `${String(baseUrl || '').replace(/\/+$/, '')}/${String(path || '').replace(/^\/+/, '')}`; +} + +function getStoredAiProviderSettings(provider, env = null) { + const providerConfig = getAiProviderConfig(provider); + if (!providerConfig) return { apiKey: '', baseUrl: '' }; + + const source = env || readEnvFile(); + const apiKey = providerConfig.keyEnv + ? normalizeAiSecretValue(source[providerConfig.keyEnv] || process.env[providerConfig.keyEnv] || '') + : ''; + const baseUrl = providerConfig.baseUrlEnv + ? normalizeAiSecretValue(source[providerConfig.baseUrlEnv] || process.env[providerConfig.baseUrlEnv] || '') + : ''; + return { apiKey, baseUrl }; +} + +function isAiProviderConfigured(provider, settings) { + const providerConfig = getAiProviderConfig(provider); + if (!providerConfig) return false; + const resolved = settings || getStoredAiProviderSettings(provider); + if (providerConfig.requiresKey !== false && !resolved.apiKey) return false; + if (providerConfig.requiresBaseUrl && !resolved.baseUrl) return false; + return true; +} + +function buildAiProviderState(provider, settings, { includeBaseUrl = false } = {}) { + const providerConfig = getAiProviderConfig(provider); + const resolved = settings || getStoredAiProviderSettings(provider); + return { + configured: isAiProviderConfigured(provider, resolved), + keyConfigured: !!resolved.apiKey, + maskedKey: maskAiSecretValue(resolved.apiKey), + baseUrlConfigured: !!resolved.baseUrl, + baseUrl: includeBaseUrl ? resolved.baseUrl : '', + keyRequired: providerConfig?.requiresKey !== false, + baseUrlRequired: !!providerConfig?.requiresBaseUrl + }; +} + +function buildAiProviderAuthHeaders(provider, apiKey) { + const headers = {}; + if (provider === 'anthropic') { + if (apiKey) { + headers['x-api-key'] = apiKey; + } + headers['anthropic-version'] = ANTHROPIC_API_VERSION; + } else if (apiKey) { + headers['Authorization'] = `Bearer ${apiKey}`; + } + + if (provider === 'openrouter') { + headers['HTTP-Referer'] = process.env.APP_URL || 'https://adpanel.local'; + headers['X-Title'] = 'ADPanel'; + } + + return headers; +} + +function extractAiErrorMessage(response) { + const payload = response?.data || {}; + return payload?.error?.message || payload?.error || payload?.message || payload?.raw || `API error: ${response?.status || 'request failed'}`; +} + +function sortAndDedupeModelIds(modelIds) { + const seen = new Set(); + const unique = []; + for (const value of modelIds || []) { + const modelId = normalizeAiSecretValue(value); + const key = modelId.toLowerCase(); + if (!modelId || seen.has(key)) continue; + seen.add(key); + unique.push(modelId); + } + return unique.sort((a, b) => a.localeCompare(b, undefined, { sensitivity: 'base' })); +} + +function isLikelyChatCapableOpenAiStyleModel(modelId) { + const lower = String(modelId || '').toLowerCase(); + if (!lower) return false; + if (/(^|[-_/])(embedding|rerank|re-rank|moderation|whisper|transcrib|tts|speech|audio|image)([-_/]|$)/.test(lower)) { + return false; + } + if (lower.includes('omni-moderation')) return false; + return true; +} + +function parseOpenAiStyleModels(payload) { + const entries = Array.isArray(payload?.data) + ? payload.data + : Array.isArray(payload?.models) + ? payload.models + : Array.isArray(payload) + ? payload + : []; + + return sortAndDedupeModelIds( + entries + .map((entry) => { + if (typeof entry === 'string') return entry; + return entry?.id || entry?.name || entry?.model || ''; + }) + .filter(isLikelyChatCapableOpenAiStyleModel) + ); +} + +function parseNextLinkHeader(linkHeader) { + const match = String(linkHeader || '').match(/<([^>]+)>\s*;\s*rel="next"/i); + return match ? match[1] : ''; +} + +async function fetchPaginatedJsonArray(url, headers = {}, { maxPages = 10, timeoutMs = 15000 } = {}) { + const items = []; + let nextUrl = url; + let pageCount = 0; + + while (nextUrl && pageCount < maxPages) { + const response = await proxyAiRequest(nextUrl, { method: 'GET', headers }, timeoutMs); + if (response.status < 200 || response.status >= 300) { + throw new Error(extractAiErrorMessage(response)); + } + if (!Array.isArray(response.data)) break; + items.push(...response.data); + nextUrl = parseNextLinkHeader(response.headers?.link); + pageCount += 1; + } + + return items; +} + +async function fetchOpenAiStyleProviderModels(provider, settings) { + const providerConfig = getAiProviderConfig(provider); + const headers = buildAiProviderAuthHeaders(provider, settings.apiKey); + let lastError = null; + + for (const url of providerConfig?.modelListUrls || []) { + const response = await proxyAiRequest(url, { method: 'GET', headers }, 15000); + if (response.status >= 200 && response.status < 300) { + const models = parseOpenAiStyleModels(response.data); + if (models.length > 0) { + return { models }; + } + lastError = new Error(`No chat-capable models were returned by ${providerConfig.name}.`); + continue; + } + lastError = new Error(extractAiErrorMessage(response)); + if (![404, 405].includes(response.status)) break; + } + + throw lastError || new Error(`Failed to load models from ${providerConfig?.name || provider}.`); +} + +async function fetchAnthropicProviderModels(settings) { + const headers = buildAiProviderAuthHeaders('anthropic', settings.apiKey); + const models = []; + let afterId = ''; + let pageCount = 0; + + while (pageCount < 10) { + const url = new URL('https://api.anthropic.com/v1/models'); + url.searchParams.set('limit', '1000'); + if (afterId) { + url.searchParams.set('after_id', afterId); + } + + const response = await proxyAiRequest(url.toString(), { method: 'GET', headers }, 15000); + if (response.status < 200 || response.status >= 300) { + throw new Error(extractAiErrorMessage(response)); + } + + const pageModels = Array.isArray(response.data?.data) + ? response.data.data + : []; + + models.push(...pageModels.map((entry) => entry?.id || '').filter(Boolean)); + + if (!response.data?.has_more || !response.data?.last_id) { + break; + } + + afterId = normalizeAiSecretValue(response.data.last_id); + if (!afterId) break; + pageCount += 1; + } + + const result = sortAndDedupeModelIds(models); + if (!result.length) { + throw new Error('No Anthropic models were returned.'); + } + return { models: result }; +} + +async function fetchOpenAiCompatibleModels(settings) { + const headers = buildAiProviderAuthHeaders('openai-compatible', settings.apiKey); + let lastError = null; + + for (const rootUrl of buildOpenAiCompatibleBaseUrlCandidates(settings.baseUrl)) { + const response = await proxyAiRequest(appendPathToBaseUrl(rootUrl, 'models'), { method: 'GET', headers }, 15000); + if (response.status >= 200 && response.status < 300) { + const models = parseOpenAiStyleModels(response.data); + if (models.length > 0) { + return { models, resolvedBaseUrl: rootUrl }; + } + lastError = new Error('The OpenAI-compatible API did not return any chat-capable models.'); + continue; + } + lastError = new Error(extractAiErrorMessage(response)); + if (![404, 405].includes(response.status)) break; + } + + throw lastError || new Error('Failed to load models from the OpenAI-compatible API.'); +} + +async function fetchGoogleProviderModels(settings) { + const models = []; + let pageToken = ''; + let pageCount = 0; + + do { + const url = new URL('https://generativelanguage.googleapis.com/v1beta/models'); + url.searchParams.set('key', settings.apiKey); + url.searchParams.set('pageSize', '1000'); + if (pageToken) { + url.searchParams.set('pageToken', pageToken); + } + + const response = await proxyAiRequest(url.toString(), { method: 'GET' }, 15000); + if (response.status < 200 || response.status >= 300) { + throw new Error(extractAiErrorMessage(response)); + } + + for (const entry of response.data?.models || []) { + const methods = Array.isArray(entry?.supportedGenerationMethods) + ? entry.supportedGenerationMethods + : Array.isArray(entry?.supportedActions) + ? entry.supportedActions + : []; + if (!methods.includes('generateContent')) continue; + models.push(String(entry?.name || '').replace(/^models\//, '')); + } + + pageToken = normalizeAiSecretValue(response.data?.nextPageToken); + pageCount += 1; + } while (pageToken && pageCount < 10); + + const result = sortAndDedupeModelIds(models); + if (!result.length) { + throw new Error('No Gemini models with generateContent support were returned.'); + } + return { models: result }; +} + +async function fetchTogetherProviderModels(settings) { + const headers = buildAiProviderAuthHeaders('together', settings.apiKey); + const response = await proxyAiRequest('https://api.together.ai/v1/models', { method: 'GET', headers }, 15000); + if (response.status < 200 || response.status >= 300) { + throw new Error(extractAiErrorMessage(response)); + } + + const entries = Array.isArray(response.data) + ? response.data + : Array.isArray(response.data?.data) + ? response.data.data + : []; + + const result = sortAndDedupeModelIds( + entries + .filter((entry) => ['chat', 'language', 'code'].includes(String(entry?.type || '').toLowerCase())) + .map((entry) => entry?.id || '') + ); + + if (!result.length) { + throw new Error('No Together chat-capable models were returned.'); + } + return { models: result }; +} + +async function fetchCohereProviderModels(settings) { + const headers = buildAiProviderAuthHeaders('cohere', settings.apiKey); + const response = await proxyAiRequest('https://api.cohere.ai/v1/models', { method: 'GET', headers }, 15000); + if (response.status < 200 || response.status >= 300) { + throw new Error(extractAiErrorMessage(response)); + } + + const result = sortAndDedupeModelIds( + (response.data?.models || []) + .filter((entry) => { + if (entry?.is_deprecated) return false; + const endpoints = Array.isArray(entry?.endpoints) ? entry.endpoints : []; + const defaultEndpoints = Array.isArray(entry?.default_endpoints) ? entry.default_endpoints : []; + const features = Array.isArray(entry?.features) ? entry.features : []; + return endpoints.includes('chat') || defaultEndpoints.includes('chat') || features.includes('chat-completions'); + }) + .map((entry) => entry?.name || '') + ); + + if (!result.length) { + throw new Error('No Cohere chat-capable models were returned.'); + } + return { models: result }; +} + +async function fetchOpenRouterProviderModels(settings) { + const headers = buildAiProviderAuthHeaders('openrouter', settings.apiKey); + const response = await proxyAiRequest('https://openrouter.ai/api/v1/models?output_modalities=text', { method: 'GET', headers }, 15000); + if (response.status < 200 || response.status >= 300) { + throw new Error(extractAiErrorMessage(response)); + } + + const result = sortAndDedupeModelIds( + (response.data?.data || []) + .filter((entry) => { + const architecture = entry?.architecture || {}; + const inputModalities = Array.isArray(architecture.input_modalities) + ? architecture.input_modalities.map((value) => String(value).toLowerCase()) + : []; + const outputModalities = Array.isArray(architecture.output_modalities) + ? architecture.output_modalities.map((value) => String(value).toLowerCase()) + : []; + const modality = String(architecture.modality || '').toLowerCase(); + const acceptsText = inputModalities.length === 0 || inputModalities.includes('text'); + const emitsText = outputModalities.length > 0 ? outputModalities.includes('text') : modality.endsWith('->text'); + return acceptsText && emitsText; + }) + .map((entry) => entry?.id || '') + ); + + if (!result.length) { + throw new Error('No OpenRouter text-output models were returned.'); + } + return { models: result }; +} + +function isLikelyHuggingFaceChatModel(entry) { + const pipelineTag = String(entry?.pipeline_tag || '').toLowerCase(); + const tags = Array.isArray(entry?.tags) ? entry.tags.map((tag) => String(tag).toLowerCase()) : []; + const modelId = String(entry?.id || entry?.modelId || '').toLowerCase(); + + if (pipelineTag === 'image-text-to-text') return true; + if (pipelineTag !== 'text-generation') return false; + if (tags.includes('conversational')) return true; + return /(chat|instruct|assistant|vision)/.test(modelId); +} + +async function fetchHuggingFaceProviderModels(settings) { + const headers = buildAiProviderAuthHeaders('huggingface', settings.apiKey); + const textModels = await fetchPaginatedJsonArray( + 'https://huggingface.co/api/models?inference_provider=all&pipeline_tag=text-generation&limit=200', + headers, + { maxPages: 10, timeoutMs: 15000 } + ); + const visionModels = await fetchPaginatedJsonArray( + 'https://huggingface.co/api/models?inference_provider=all&pipeline_tag=image-text-to-text&limit=200', + headers, + { maxPages: 10, timeoutMs: 15000 } + ); + + const result = sortAndDedupeModelIds( + [...textModels, ...visionModels] + .filter(isLikelyHuggingFaceChatModel) + .map((entry) => entry?.id || entry?.modelId || '') + ); + + if (!result.length) { + throw new Error('No Hugging Face chat-capable models were returned.'); + } + return { models: result }; +} + +async function fetchAvailableAiModels(provider, settings) { + const providerConfig = getAiProviderConfig(provider); + if (!providerConfig) { + throw new Error('Unknown AI provider.'); + } + + switch (providerConfig.modelDiscovery) { + case 'anthropic': + return fetchAnthropicProviderModels(settings); + case 'openai-compatible': + return fetchOpenAiCompatibleModels(settings); + case 'google': + return fetchGoogleProviderModels(settings); + case 'together': + return fetchTogetherProviderModels(settings); + case 'cohere': + return fetchCohereProviderModels(settings); + case 'openrouter': + return fetchOpenRouterProviderModels(settings); + case 'huggingface': + return fetchHuggingFaceProviderModels(settings); + case 'openai-style': + default: + return fetchOpenAiStyleProviderModels(provider, settings); + } +} + +app.get("/api/ai/keys", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + const env = readEnvFile(); + const configured = {}; + const canManageProviders = await isAdmin(req); + + for (const provider of Object.keys(AI_PROVIDER_CONFIGS)) { + configured[provider] = buildAiProviderState(provider, getStoredAiProviderSettings(provider, env), { + includeBaseUrl: canManageProviders + }); + } + + const actionTokens = { + setKey: issueActionToken(req, "POST /api/ai/keys", {}, { ttlSeconds: 300 }) + }; + for (const provider of Object.keys(AI_PROVIDER_CONFIGS)) { + actionTokens[`deleteKey_${provider}`] = issueActionToken(req, "DELETE /api/ai/keys/:provider", { provider }, { ttlSeconds: 120, oneTime: true }); + } + + return res.json({ ok: true, providers: configured, actionTokens }); +}); + + + +app.post("/api/ai/keys", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "admin required to configure AI keys" }); + if (!requireActionTokenOr403(req, res, "POST /api/ai/keys")) return; + + const { provider, key, baseUrl } = req.body || {}; + const providerLower = String(provider || '').toLowerCase(); + const providerConfig = getAiProviderConfig(providerLower); + + if (!providerConfig) return res.status(400).json({ error: "invalid provider" }); + + try { + const env = readEnvFile(); + const storedSettings = getStoredAiProviderSettings(providerLower, env); + const nextSettings = { + apiKey: normalizeAiSecretValue(key) || storedSettings.apiKey, + baseUrl: providerConfig.requiresBaseUrl + ? (normalizeAiSecretValue(baseUrl) || storedSettings.baseUrl) + : '' + }; + + if (providerConfig.requiresKey !== false && !nextSettings.apiKey) { + return res.status(400).json({ error: `Please enter a valid ${providerConfig.name} API key.` }); + } + + if (providerConfig.requiresBaseUrl && !nextSettings.baseUrl) { + return res.status(400).json({ error: 'Please enter a valid Base URL.' }); + } + + if (providerConfig.requiresBaseUrl) { + nextSettings.baseUrl = normalizeOpenAiCompatibleBaseUrl(nextSettings.baseUrl); + } + + const discovery = await fetchAvailableAiModels(providerLower, nextSettings); + if (discovery?.resolvedBaseUrl) { + nextSettings.baseUrl = discovery.resolvedBaseUrl; + } + if (!Array.isArray(discovery?.models) || discovery.models.length === 0) { + return res.status(400).json({ error: 'No models were returned for this provider.' }); + } + + const envUpdates = {}; + if (providerConfig.keyEnv) envUpdates[providerConfig.keyEnv] = nextSettings.apiKey || ''; + if (providerConfig.baseUrlEnv) envUpdates[providerConfig.baseUrlEnv] = nextSettings.baseUrl || ''; + + const success = writeEnvFileBatch(envUpdates); + if (!success) { + return res.status(500).json({ error: 'failed to save provider configuration' }); + } + + if (providerConfig.keyEnv) { + if (nextSettings.apiKey) { + process.env[providerConfig.keyEnv] = nextSettings.apiKey; + } else { + delete process.env[providerConfig.keyEnv]; + } + } + if (providerConfig.baseUrlEnv) { + if (nextSettings.baseUrl) { + process.env[providerConfig.baseUrlEnv] = nextSettings.baseUrl; + } else { + delete process.env[providerConfig.baseUrlEnv]; + } + } + + return res.json({ + ok: true, + provider: providerLower, + models: discovery.models, + providerState: buildAiProviderState(providerLower, nextSettings, { includeBaseUrl: true }) + }); + } catch (err) { + console.error(`[ai-keys] Failed to save ${providerLower}:`, err.message); + return res.status(400).json({ error: err.message || 'failed to save provider configuration' }); + } +}); + +app.delete("/api/ai/keys/:provider", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "admin required to configure AI keys" }); + if (!requireActionTokenOr403(req, res, "DELETE /api/ai/keys/:provider", { provider: String(req.params.provider || '').toLowerCase() })) return; + + const provider = String(req.params.provider || '').toLowerCase(); + const providerConfig = getAiProviderConfig(provider); + + if (!providerConfig) return res.status(400).json({ error: "invalid provider" }); + + const envUpdates = {}; + if (providerConfig.keyEnv) envUpdates[providerConfig.keyEnv] = ''; + if (providerConfig.baseUrlEnv) envUpdates[providerConfig.baseUrlEnv] = ''; + + const success = writeEnvFileBatch(envUpdates); + + if (!success) { + return res.status(500).json({ error: "failed to remove provider configuration" }); + } + + if (providerConfig.keyEnv) delete process.env[providerConfig.keyEnv]; + if (providerConfig.baseUrlEnv) delete process.env[providerConfig.baseUrlEnv]; + + return res.json({ ok: true, provider }); +}); + +async function proxyAiRequest(url, options, timeoutMs = 60000) { + return new Promise((resolve, reject) => { + const parsedUrl = new URL(url); + const isHttps = parsedUrl.protocol === 'https:'; + const httpModule = isHttps ? https : httpMod; + + const reqOptions = { + hostname: parsedUrl.hostname, + port: parsedUrl.port || (isHttps ? 443 : 80), + path: parsedUrl.pathname + parsedUrl.search, + method: options.method || 'POST', + headers: options.headers || {}, + timeout: timeoutMs + }; + + const req = httpModule.request(reqOptions, (res) => { + let data = ''; + res.setEncoding('utf8'); + res.on('data', chunk => { data += chunk; }); + res.on('end', () => { + try { + const json = JSON.parse(data); + resolve({ status: res.statusCode, data: json, headers: res.headers }); + } catch { + resolve({ status: res.statusCode, data: { raw: data }, headers: res.headers }); + } + }); + }); + + req.on('error', reject); + req.on('timeout', () => { + req.destroy(); + reject(new Error('Request timeout')); + }); + + if (options.body) { + req.write(options.body); + } + req.end(); + }); +} + +const BOT_AI_TOOL_NAMES = new Set(BOT_TOOL_DEFINITIONS.map((tool) => String(tool?.name || "").trim())); +const BOT_AI_MAX_CONTEXT_MESSAGES = 18; +const BOT_AI_MAX_TOOL_RESULT_CHARS = 14000; +const BOT_AI_MAX_CONSOLE_LINES = 100; +const BOT_AI_DEFAULT_CONSOLE_LINES = 60; +const BOT_AI_MAX_BACKUPS = 50; + +function normalizeAiConversationMessages(messages) { + return (Array.isArray(messages) ? messages : []) + .slice(-BOT_AI_MAX_CONTEXT_MESSAGES) + .map((entry) => { + const role = String(entry?.role || "").trim().toLowerCase(); + if (!["system", "user", "assistant"].includes(role)) return null; + const content = typeof entry?.content === "string" ? entry.content : String(entry?.content || ""); + const message = { + role, + content: content.slice(0, 32000), + }; + if (typeof entry?.image === "string" && entry.image.startsWith("data:image/")) { + message.image = entry.image; + } + return message; + }) + .filter((entry) => entry && (entry.content || entry.image)); +} + +function stripBotToolPlanMarkup(value) { + return String(value || "").replace(/[\s\S]*?<\/adpanel_tool_plan>/gi, "").trim(); +} + +function isWeakBotAiReply(value) { + const text = String(value || "").trim(); + if (!text) return true; + if (/^[`'"“”‘’()[\]{}<>.,:;!?*_~\\/\-|+=\s]+$/.test(text)) return true; + return /^(?:done|ok|okay|sure|completed|finished|all set|it is done|i did it)\.?$/i.test(text); +} + +function normalizeBotPowerAction(value) { + const action = String(value || "").trim().toLowerCase(); + if (action === "run" || action === "boot") return "start"; + if (["start", "stop", "restart", "kill"].includes(action)) return action; + return ""; +} + +function looksLikeLeakedBotReasoning(value) { + const normalized = String(value || "").replace(/\s+/g, " ").trim(); + if (!normalized) return false; + const leakedInstructionTalk = [ + /\bwait,\s*the prompt says\b/i, + /\bthe prompt says\b/i, + /\bprevious reply was invalid\b/i, + /\bentire reply must be one\b/i, + //i, + /\bcurrent page server is\b/i, + /\bcurrent page server:\b/i, + /\bthe user wants to\b/i, + /\bi have the\b/i, + /\bi can use\b/i, + /\bi should use\b/i, + /\bi need to use\b/i, + /\blet'?s refine\b/i, + /\brespond with exactly one\b/i, + /\bi need to check\b/i, + /\btool which can be used\b/i, + ].some((pattern) => pattern.test(normalized)); + const leakedToolReference = /\b(?:power_server|inspect_server|query_console|send_console_command|list_backups|create_backup|restore_backup|delete_backup)\b/i.test(normalized); + const truncatedReasoning = /(?:i should use the|i can use the|i need to use the)\s*`?$/i.test(normalized); + return leakedInstructionTalk || (leakedToolReference && /\b(?:the user wants to|i have the|i can use|i should use|i need to use|let'?s refine|i need to check|tool which can be used)\b/i.test(normalized)) || truncatedReasoning; +} + +function sanitizeBotVisibleReplyText(value) { + const cleaned = String(value || "") + .replace(/[\s\S]*?<\/think>/gi, " ") + .replace(/[\s\S]*?<\/thinking>/gi, " ") + .replace(/^\s*(?:thought|thinking|reasoning|analysis)\s*:\s*[\s\S]*$/gim, " ") + .trim(); + if (!cleaned) return ""; + if (/^[`'"“”‘’()[\]{}<>.,:;!?*_~\\/\-|+=\s]+$/.test(cleaned)) return ""; + if (looksLikeLeakedBotReasoning(cleaned)) return ""; + return cleaned; +} + +function finalizeBotAssistantReply(candidateReply, lastToolName = "", lastToolResult = null) { + let finalReply = sanitizeBotVisibleReplyText(candidateReply); + if (isWeakBotAiReply(finalReply) && lastToolResult) { + finalReply = sanitizeBotVisibleReplyText(buildBotReplyFromToolResult(lastToolName, lastToolResult)); + } + if (!finalReply && lastToolResult) { + finalReply = sanitizeBotVisibleReplyText(buildBotReplyFromToolResult(lastToolName, lastToolResult)); + } + return finalReply; +} + +function needsBotToolPlanRepair(value) { + const raw = String(value || "").trim(); + if (!raw) return false; + if (looksLikeLeakedBotReasoning(raw)) return true; + return /\b(?:power_server|inspect_server|query_console|send_console_command|list_backups|create_backup|restore_backup|delete_backup)\b/i.test(raw); +} + +function extractBotAssistantServerCandidate(value, currentServerName) { + const raw = String(value || "").trim(); + const candidates = [ + raw.match(/\bcurrent page server\s*:\s*([a-zA-Z0-9._-]+)/i)?.[1], + raw.match(/\bserver\s+(?:is|:)\s*([a-zA-Z0-9._-]+)/i)?.[1], + raw.match(/\bon\s+([a-zA-Z0-9._-]+)\b/i)?.[1], + ]; + + for (const candidate of candidates) { + const normalized = String(candidate || "").trim(); + if (normalized) return normalized; + } + return String(currentServerName || "").trim(); +} + +function extractBotAssistantQuotedFragment(value) { + const raw = String(value || ""); + const match = raw.match(/[`"']([^`"']+)[`"']/); + return String(match?.[1] || "").trim(); +} + +function decodeBotAssistantJsonStringFragment(value) { + const raw = String(value || ""); + if (!raw) return ""; + try { + return String(JSON.parse(`"${raw}"`) || "").trim(); + } catch { + return raw + .replace(/\\n/g, "\n") + .replace(/\\r/g, "\r") + .replace(/\\t/g, "\t") + .replace(/\\(["'`\\/])/g, "$1") + .trim(); + } +} + +function extractBotAssistantNamedStringArg(value, key) { + const raw = String(value || ""); + const safeKey = String(key || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + if (!raw || !safeKey) return ""; + + const doubleQuoted = raw.match(new RegExp(`["']?${safeKey}["']?\\s*:\\s*"((?:\\\\.|[^"\\\\]){1,1024})"`, "i")); + if (doubleQuoted?.[1]) return decodeBotAssistantJsonStringFragment(doubleQuoted[1]); + + const singleQuoted = raw.match(new RegExp(`["']?${safeKey}["']?\\s*:\\s*'([^'\\r\\n]{1,1024})'`, "i")); + if (singleQuoted?.[1]) return String(singleQuoted[1]).trim(); + + const backticked = raw.match(new RegExp(`["']?${safeKey}["']?\\s*:\\s*\`([^\`\\r\\n]{1,1024})\``, "i")); + if (backticked?.[1]) return String(backticked[1]).trim(); + + return ""; +} + +function detectBotAssistantPowerAction(value) { + const text = String(value || "").trim().toLowerCase(); + if (!text) return ""; + if (/\bforce\s*stop|hard\s*stop|kill|terminate\b/.test(text)) return "kill"; + if (/\brestart|reboot\b/.test(text)) return "restart"; + if (/\bstop|shutdown\b/.test(text)) return "stop"; + if (/\bstart|run|boot\b/.test(text)) return "start"; + return ""; +} + +function extractBotAssistantRequestedConsoleLimit(value) { + const raw = String(value || ""); + const match = raw.match(/\b(\d{1,3})\s*(?:console\s*)?(?:lines?|entries?)\b/i); + if (!match) return BOT_AI_DEFAULT_CONSOLE_LINES; + const parsed = parseInt(match[1], 10); + if (!Number.isFinite(parsed)) return BOT_AI_DEFAULT_CONSOLE_LINES; + return Math.min(Math.max(parsed, 10), BOT_AI_MAX_CONSOLE_LINES); +} + +function getLatestBotUserMessageContent(messages) { + const list = Array.isArray(messages) ? messages : []; + for (let i = list.length - 1; i >= 0; i -= 1) { + const entry = list[i]; + if (String(entry?.role || "").trim().toLowerCase() === "user") { + return String(entry?.content || "").trim(); + } + } + return ""; +} + +function extractExplicitBotConsoleCommandRequest(value) { + const raw = String(value || "").trim(); + if (!raw) return ""; + + const explicitIntent = /\b(?:run|send|execute|type|write|issue|dispatch|trimite|ruleaza|executa|scrie|baga|da)\b/i.test(raw) + && /\b(?:console|consola|command|comanda|cmd)\b/i.test(raw); + if (!explicitIntent) return ""; + + const quoted = raw.match(/(?:run|send|execute|type|write|issue|dispatch|trimite|ruleaza|executa|scrie|baga|da)[\s\S]{0,120}?(?:console|consola|command|comanda|cmd)[\s\S]{0,80}?[`"']([^`"'\r\n]{1,512})[`"']/i) + || raw.match(/(?:run|send|execute|type|write|issue|dispatch|trimite|ruleaza|executa|scrie|baga|da)[\s\S]{0,80}?[`"']([^`"'\r\n]{1,512})[`"'][\s\S]{0,120}?(?:console|consola|command|comanda|cmd)/i) + || raw.match(/(?:console|consola|command|comanda|cmd)[\s\S]{0,80}?[`"']([^`"'\r\n]{1,512})[`"']/i); + if (quoted?.[1]) return quoted[1].trim(); + + const colon = raw.match(/(?:console\s*command|command|cmd|comanda(?:\s+(?:in|la|pe)\s+consola)?|(?:in|la|pe)\s+consola)\s*[:=-]\s*([^\r\n]{1,512})/i); + if (colon?.[1]) return colon[1].trim(); + + return ""; +} + +function buildBotToolCallFromAssistantToolName(toolName, rawValue, currentServerName) { + const raw = String(rawValue || "").trim(); + if (!raw) return null; + const server = extractBotAssistantServerCandidate(raw, currentServerName); + const quoted = extractBotAssistantQuotedFragment(raw); + const normalizedToolName = String(toolName || "").trim(); + + switch (normalizedToolName) { + case "inspect_server": + return { name: "inspect_server", args: { server } }; + case "power_server": { + const action = detectBotAssistantPowerAction(raw); + if (!action) return null; + return { name: "power_server", args: { server, action } }; + } + case "query_console": + return { + name: "query_console", + args: { + server, + limit: extractBotAssistantRequestedConsoleLimit(raw), + }, + }; + case "list_backups": + return { name: "list_backups", args: { server } }; + case "create_backup": + return { name: "create_backup", args: { server } }; + case "send_console_command": { + const command = extractBotAssistantNamedStringArg(raw, "command") || quoted; + return command ? { name: "send_console_command", args: { server, command } } : null; + } + case "restore_backup": + return quoted ? { name: "restore_backup", args: { server, backup: quoted } } : null; + case "delete_backup": + return quoted ? { name: "delete_backup", args: { server, backup: quoted } } : null; + default: + return null; + } +} + +function salvageBotToolCallsFromAssistantText(value, currentServerName) { + const raw = String(value || "").trim(); + if (!raw) return []; + + const parsedPlan = parseBotAssistantToolPlan(raw); + if (parsedPlan && Array.isArray(parsedPlan.tool_calls) && parsedPlan.tool_calls.length > 0) { + const seenPlanCalls = new Set(); + return parsedPlan.tool_calls + .filter((entry) => entry && BOT_AI_TOOL_NAMES.has(String(entry.name || "").trim())) + .map((entry) => ({ + name: String(entry.name || "").trim(), + args: entry.args && typeof entry.args === "object" && !Array.isArray(entry.args) ? entry.args : {}, + })) + .filter((entry) => { + const key = `${entry.name}:${JSON.stringify(entry.args || {})}`; + if (seenPlanCalls.has(key)) return false; + seenPlanCalls.add(key); + return true; + }); + } + + const toolMatches = []; + const patterns = [ + { name: "inspect_server", regex: /\binspect_server\b/gi }, + { name: "power_server", regex: /\bpower_server\b/gi }, + { name: "query_console", regex: /\bquery_console\b/gi }, + { name: "send_console_command", regex: /\bsend_console_command\b/gi }, + { name: "list_backups", regex: /\blist_backups\b/gi }, + { name: "create_backup", regex: /\bcreate_backup\b/gi }, + { name: "restore_backup", regex: /\brestore_backup\b/gi }, + { name: "delete_backup", regex: /\bdelete_backup\b/gi }, + ]; + + for (const pattern of patterns) { + pattern.regex.lastIndex = 0; + let match; + while ((match = pattern.regex.exec(raw)) !== null) { + toolMatches.push({ index: match.index, name: pattern.name }); + } + } + + if (!toolMatches.length) { + return []; + } + + toolMatches.sort((left, right) => left.index - right.index); + + const seen = new Set(); + const toolCalls = []; + for (const match of toolMatches) { + const toolCall = buildBotToolCallFromAssistantToolName(match.name, raw, currentServerName); + if (!toolCall) continue; + const dedupeKey = `${toolCall.name}:${JSON.stringify(toolCall.args || {})}`; + if (seen.has(dedupeKey)) continue; + seen.add(dedupeKey); + toolCalls.push(toolCall); + } + + return toolCalls; +} + +function salvageBotToolCallFromAssistantText(value, currentServerName) { + return salvageBotToolCallsFromAssistantText(value, currentServerName)[0] || null; +} + +function describeBotPermissionKey(permKey) { + const labels = { + server_start: "start this server", + server_stop: "stop this server", + console_read: "read the console", + console_write: "send console commands", + backups_view: "view backups", + backups_create: "create or restore backups", + backups_delete: "delete backups", + }; + return labels[permKey] || permKey.replace(/_/g, " "); +} + +function buildBotServerSummary(entry, perms = null) { + return { + name: entry?.name || null, + displayName: entry?.displayName || entry?.name || null, + status: entry?.status || "unknown", + template: entry?.template || "custom", + permissions: perms || undefined, + }; +} + +async function getAccessibleServerEntriesForAi(userEmail, isAdminUser = false) { + const allServers = (await loadServersIndex()) || []; + if (isAdminUser) { + return allServers.filter((entry) => entry?.name); + } + + const accessList = await getAccessListForEmail(userEmail); + const accessSet = new Set((Array.isArray(accessList) ? accessList : []).map((entry) => String(entry || "").trim().toLowerCase())); + if (!accessSet.size) return []; + if (accessSet.has("all")) { + return allServers.filter((entry) => entry?.name); + } + + return allServers.filter((entry) => accessSet.has(String(entry?.name || "").trim().toLowerCase())); +} + +function sanitizeBotToolArgs(toolName, rawArgs) { + const args = rawArgs && typeof rawArgs === "object" && !Array.isArray(rawArgs) ? rawArgs : {}; + + switch (String(toolName || "").trim()) { + case "inspect_server": + case "list_backups": + return { server: String(args.server || args.query || "").trim() }; + case "power_server": + return { + server: String(args.server || args.query || "").trim(), + action: normalizeBotPowerAction(args.action), + }; + case "query_console": + return { + server: String(args.server || args.query || "").trim(), + question: String(args.question || "").trim().slice(0, 300), + limit: Math.min(Math.max(parseInt(args.limit, 10) || BOT_AI_DEFAULT_CONSOLE_LINES, 10), BOT_AI_MAX_CONSOLE_LINES), + }; + case "send_console_command": + return { + server: String(args.server || args.query || "").trim(), + command: String(args.command || "").trim(), + }; + case "create_backup": + return { + server: String(args.server || args.query || "").trim(), + name: String(args.name || "").trim().slice(0, 120), + description: String(args.description || "").trim().slice(0, 280), + }; + case "restore_backup": + return { + server: String(args.server || args.query || "").trim(), + backup: String(args.backup || args.backupId || args.name || "").trim(), + deleteOldFiles: !!args.deleteOldFiles, + }; + case "delete_backup": + return { + server: String(args.server || args.query || "").trim(), + backup: String(args.backup || args.backupId || args.name || "").trim(), + }; + default: + return {}; + } +} + +function isSameBotServer(left, right) { + return String(left || "").trim().toLowerCase() === String(right || "").trim().toLowerCase(); +} + +async function getBotConsoleHistorySnapshot(serverName, limit = BOT_AI_DEFAULT_CONSOLE_LINES) { + const safeLimit = Math.min(Math.max(parseInt(limit, 10) || BOT_AI_DEFAULT_CONSOLE_LINES, 10), BOT_AI_MAX_CONSOLE_LINES); + const snapshot = await getConsoleHistorySnapshot(serverName, safeLimit, { includeCommands: true }); + return snapshot.lines.map((item) => ({ + line: String(item?.line || "").slice(0, 400), + ts: Number(item?.ts || 0) || Date.now(), + source: String(item?.source || "output"), + })); +} + +function summarizeBackupsForBot(backups) { + return (Array.isArray(backups) ? backups : []).slice(0, BOT_AI_MAX_BACKUPS).map((backup) => ({ + id: backup?.id || backup?.uuid || null, + name: backup?.name || backup?.archive_name || backup?.archiveName || null, + size: backup?.size ?? null, + completedAt: backup?.completed_at || backup?.completedAt || backup?.created_at || backup?.createdAt || null, + locked: !!backup?.is_locked, + })); +} + +function buildBotToolResultContextMessage(toolResults) { + const compactResults = (Array.isArray(toolResults) ? toolResults : []).map((entry) => { + const result = entry?.result && typeof entry.result === "object" ? { ...entry.result } : {}; + if (Array.isArray(result.lines)) { + result.lines = result.lines.slice(-BOT_AI_MAX_CONSOLE_LINES); + } + if (Array.isArray(result.backups)) { + result.backups = result.backups.slice(0, BOT_AI_MAX_BACKUPS); + } + if (Array.isArray(result.servers)) { + result.servers = result.servers.slice(0, 50); + } + return { + name: String(entry?.name || "").trim(), + result, + }; + }); + + const serialized = JSON.stringify(compactResults); + const payload = serialized.length > BOT_AI_MAX_TOOL_RESULT_CHARS + ? `${serialized.slice(0, BOT_AI_MAX_TOOL_RESULT_CHARS)}...[truncated]` + : serialized; + + return [ + "Verified ADPanel native tool results are below.", + "Use them as the source of truth.", + "If a tool returned ok false, explain the failure briefly and do not claim success.", + "If a tool returned raw console lines, analyze them directly and answer the user's question.", + "If more verified information or action is still needed, return another tool plan immediately instead of narrating a plan.", + payload, + ].join(" "); +} + +function buildBotContinueAfterToolInstruction() { + return [ + "Continue solving the user's request.", + "If you need another native action or more verified data, reply with exactly one JSON block and nothing else.", + "Otherwise reply with one short user-facing answer only.", + "Do not narrate planning, tool selection, or hidden reasoning.", + ].join(" "); +} + +function buildSyntheticNativeToolCalls(toolCalls, prefix = "synthetic_tool_call") { + return (Array.isArray(toolCalls) ? toolCalls : []) + .filter((entry) => entry && typeof entry === "object" && String(entry.name || "").trim()) + .map((entry, index) => ({ + id: `${prefix}_${index + 1}`, + type: "function", + function: { + name: String(entry.name || "").trim(), + arguments: JSON.stringify(entry.args && typeof entry.args === "object" ? entry.args : {}), + }, + })); +} + +function summarizeBotConsoleLinesForFallback(lines) { + const normalizedLines = (Array.isArray(lines) ? lines : []) + .map((entry) => String(entry?.line || "").trim()) + .filter(Boolean); + if (!normalizedLines.length) return ""; + + const interestingLines = normalizedLines.filter((line) => ( + /\b(?:error|exception|failed|invalid|warning|warn|terminated|crash|denied|refused|unable)\b/i.test(line) + )); + const selectedLines = (interestingLines.length ? interestingLines : normalizedLines).slice(-3); + if (!selectedLines.length) return ""; + + const snippet = selectedLines + .map((line) => (line.length > 180 ? `${line.slice(0, 177)}...` : line)) + .join(" | "); + return `Recent console output: ${snippet}`; +} + +function buildBotReplyFromToolHistory(toolHistory) { + const history = Array.isArray(toolHistory) ? toolHistory : []; + if (!history.length) return ""; + + const latestSuccessfulInspect = [...history].reverse().find((entry) => ( + entry?.name === "inspect_server" && entry?.result && entry.result.ok !== false + )); + const latestSuccessfulConsole = [...history].reverse().find((entry) => ( + entry?.name === "query_console" && entry?.result && entry.result.ok !== false + )); + + const parts = []; + if (latestSuccessfulInspect?.result?.server?.name) { + const server = latestSuccessfulInspect.result.server; + parts.push(`${server.displayName || server.name} is ${server.status || "unknown"}.`); + } + + if (latestSuccessfulConsole?.result?.lines) { + const consoleSummary = summarizeBotConsoleLinesForFallback(latestSuccessfulConsole.result.lines); + if (consoleSummary) parts.push(consoleSummary); + } + + if (parts.length) { + return parts.join(" "); + } + + const lastEntry = [...history].reverse().find((entry) => entry?.result); + if (!lastEntry) return ""; + return buildBotReplyFromToolResult(lastEntry.name, lastEntry.result); +} + +const OPENAI_STYLE_NATIVE_BOT_TOOL_PROVIDERS = new Set([ + "openai", + "openai-compatible", + "groq", + "together", + "openrouter", + "huggingface", +]); +const ANTHROPIC_NATIVE_BOT_TOOL_PROVIDERS = new Set(["anthropic"]); +const COHERE_NATIVE_BOT_TOOL_PROVIDERS = new Set(["cohere"]); +const GOOGLE_NATIVE_BOT_TOOL_PROVIDERS = new Set(["google"]); +const BOT_ANTHROPIC_TOOL_DEFINITIONS = Object.freeze( + BOT_OPENAI_TOOL_DEFINITIONS + .map((tool) => ({ + name: String(tool?.function?.name || "").trim(), + description: String(tool?.function?.description || "").trim(), + input_schema: tool?.function?.parameters || { type: "object", properties: {}, required: [] }, + })) + .filter((tool) => tool.name) +); + +function buildAiProxyError(message, status = 500, responseData = null) { + const error = new Error(message || "AI request failed."); + error.status = Number(status || 500) || 500; + if (responseData !== undefined) { + error.responseData = responseData; + } + return error; +} + +function isNativeBotToolFallbackError(error) { + const status = Number(error?.status || 0) || 0; + const message = String(error?.message || "").toLowerCase(); + const responseString = JSON.stringify(error?.responseData || {}).toLowerCase(); + const combined = `${message}\n${responseString}`; + + if (status && ![400, 404, 405, 406, 409, 415, 422, 429, 500, 501, 503].includes(status)) { + return false; + } + + return [ + "tool", + "tool_calls", + "tool_use", + "tool_result", + "tool_choice", + "parallel_tool_calls", + "function call", + "function_call", + "functiondeclarations", + "function declarations", + "functionresponse", + "generic fallback", + "needs generic fallback", + "planning text", + "unsupported", + "not support", + "not supported", + "unknown field", + "unknown name", + "invalid argument", + "invalid_request_error", + "response schema", + "internal error encountered", + "internal error", + "try again later", + ].some((fragment) => combined.includes(fragment)); +} + +function normalizeOpenAiNativeTextContent(content) { + if (Array.isArray(content)) { + return content + .map((part) => { + if (typeof part === "string") return part; + if (part && typeof part.text === "string") return part.text; + if (part && part.type === "text" && typeof part.text === "string") return part.text; + if (part && part.type === "output_text" && typeof part.text === "string") return part.text; + return ""; + }) + .join("") + .trim(); + } + return String(content || "").trim(); +} + +function normalizeCohereNativeTextContent(content) { + if (Array.isArray(content)) { + return content + .map((part) => { + if (typeof part === "string") return part; + if (typeof part?.text === "string") return part.text; + if (part?.type === "text" && typeof part?.text === "string") return part.text; + return ""; + }) + .join("") + .trim(); + } + return String(content || "").trim(); +} + +function normalizeAnthropicTextContent(content) { + if (Array.isArray(content)) { + return content + .map((part) => { + if (typeof part === "string") return part; + if (part?.type === "text" && typeof part?.text === "string") return part.text; + if (typeof part?.text === "string") return part.text; + return ""; + }) + .join("") + .trim(); + } + return String(content || "").trim(); +} + +function appendThinkingPart(parts, value) { + const text = String(value || "").trim(); + if (!text) return; + const normalized = text.replace(/\s+/g, " ").trim(); + if (!normalized) return; + if (!parts.some((entry) => entry.replace(/\s+/g, " ").trim() === normalized)) { + parts.push(text); + } +} + +function extractThinkingSectionsFromTaggedText(rawText) { + const thinkingParts = []; + let visible = String(rawText || ""); + + const patterns = [ + /([\s\S]*?)<\/think(?:ing)?>/gi, + /\[thinking\]([\s\S]*?)\[\/thinking\]/gi, + ]; + + for (const pattern of patterns) { + visible = visible.replace(pattern, (_, inner) => { + appendThinkingPart(thinkingParts, inner); + return " "; + }); + } + + return { + content: visible.trim(), + thinking_content: thinkingParts.join("\n\n").trim(), + }; +} + +function collectThinkingFromReasoningDetails(details) { + const parts = []; + + const visit = (node) => { + if (node == null) return; + + if (typeof node === "string") { + appendThinkingPart(parts, node); + return; + } + + if (Array.isArray(node)) { + for (const entry of node) visit(entry); + return; + } + + if (typeof node !== "object") return; + + const type = String(node.type || "").trim().toLowerCase(); + const isReasoningLike = /reason|think|summary|analysis/.test(type); + + if (typeof node.thinking === "string") appendThinkingPart(parts, node.thinking); + if (typeof node.reasoning === "string") appendThinkingPart(parts, node.reasoning); + if (typeof node.summary === "string") appendThinkingPart(parts, node.summary); + + if (isReasoningLike && typeof node.text === "string") { + appendThinkingPart(parts, node.text); + } + if (isReasoningLike && typeof node.content === "string") { + appendThinkingPart(parts, node.content); + } + + if (Array.isArray(node.summary)) visit(node.summary); + if (Array.isArray(node.parts)) visit(node.parts); + if (Array.isArray(node.reasoning_details)) visit(node.reasoning_details); + }; + + visit(details); + return parts.join("\n\n").trim(); +} + +function parseOpenAiCompatibleResponsePayload(payload) { + const data = payload && typeof payload === "object" ? payload : {}; + const thinkingParts = []; + const visibleParts = []; + + const choice = data?.choices?.[0] || {}; + const message = choice?.message || {}; + const rawContent = message?.content; + + if (Array.isArray(rawContent)) { + for (const part of rawContent) { + if (typeof part === "string") { + visibleParts.push(part); + continue; + } + if (!part || typeof part !== "object") continue; + + const partType = String(part.type || "").trim().toLowerCase(); + const text = typeof part.text === "string" ? part.text : ""; + + if (!partType || partType === "text" || partType === "output_text") { + if (text) visibleParts.push(text); + continue; + } + + if (/reason|think|summary|analysis/.test(partType)) { + appendThinkingPart(thinkingParts, text); + appendThinkingPart(thinkingParts, part.thinking); + appendThinkingPart(thinkingParts, part.reasoning); + appendThinkingPart(thinkingParts, part.summary); + continue; + } + + if (typeof part.thinking === "string") appendThinkingPart(thinkingParts, part.thinking); + if (typeof part.reasoning === "string") appendThinkingPart(thinkingParts, part.reasoning); + if (text) visibleParts.push(text); + } + } else if (typeof rawContent === "string") { + visibleParts.push(rawContent); + } else { + const fallback = normalizeOpenAiNativeTextContent(rawContent); + if (fallback) visibleParts.push(fallback); + } + + appendThinkingPart(thinkingParts, message?.reasoning); + appendThinkingPart(thinkingParts, message?.reasoning_content); + appendThinkingPart(thinkingParts, message?.thinking); + appendThinkingPart(thinkingParts, collectThinkingFromReasoningDetails(message?.reasoning_details)); + + if (Array.isArray(data?.output)) { + for (const item of data.output) { + if (!item || typeof item !== "object") continue; + const itemType = String(item.type || "").trim().toLowerCase(); + + if (itemType === "reasoning") { + appendThinkingPart(thinkingParts, item?.text); + appendThinkingPart(thinkingParts, collectThinkingFromReasoningDetails(item?.summary)); + appendThinkingPart(thinkingParts, collectThinkingFromReasoningDetails(item?.reasoning_details)); + continue; + } + + if (itemType === "message" && Array.isArray(item.content)) { + for (const part of item.content) { + if (!part || typeof part !== "object") continue; + const partType = String(part.type || "").trim().toLowerCase(); + if ((partType === "output_text" || partType === "text") && typeof part.text === "string") { + visibleParts.push(part.text); + } else if (/reason|think|summary|analysis/.test(partType)) { + appendThinkingPart(thinkingParts, part.text); + appendThinkingPart(thinkingParts, part.reasoning); + appendThinkingPart(thinkingParts, part.thinking); + appendThinkingPart(thinkingParts, part.summary); + } + } + } + } + } + + const extracted = extractThinkingSectionsFromTaggedText(visibleParts.join("").trim()); + appendThinkingPart(thinkingParts, extracted.thinking_content); + + return { + content: extracted.content, + thinking_content: thinkingParts.join("\n\n").trim(), + }; +} + +function parseGoogleResponsePayload(payload) { + const data = payload && typeof payload === "object" ? payload : {}; + const thinkingParts = []; + const visibleParts = []; + + const candidate = data?.candidates?.[0] || {}; + const parts = Array.isArray(candidate?.content?.parts) ? candidate.content.parts : []; + + for (const part of parts) { + if (!part || typeof part !== "object") continue; + const partType = String(part.type || "").trim().toLowerCase(); + const isThought = part?.thought === true || /think|reason|summary|analysis/.test(partType); + + if (typeof part.thinking === "string") appendThinkingPart(thinkingParts, part.thinking); + if (typeof part.reasoning === "string") appendThinkingPart(thinkingParts, part.reasoning); + + const text = typeof part.text === "string" ? part.text : ""; + if (text) { + if (isThought) appendThinkingPart(thinkingParts, text); + else visibleParts.push(text); + } + } + + appendThinkingPart(thinkingParts, candidate?.reasoning); + appendThinkingPart(thinkingParts, collectThinkingFromReasoningDetails(candidate?.reasoning_details)); + + const extracted = extractThinkingSectionsFromTaggedText(visibleParts.join("").trim()); + appendThinkingPart(thinkingParts, extracted.thinking_content); + + return { + content: extracted.content, + thinking_content: thinkingParts.join("\n\n").trim(), + }; +} + +function parseCohereResponsePayload(payload) { + const data = payload && typeof payload === "object" ? payload : {}; + const thinkingParts = []; + const visibleParts = []; + + const messageContent = data?.message?.content; + if (Array.isArray(messageContent)) { + for (const part of messageContent) { + if (typeof part === "string") { + visibleParts.push(part); + continue; + } + if (!part || typeof part !== "object") continue; + + const partType = String(part.type || "").trim().toLowerCase(); + const text = typeof part.text === "string" ? part.text : ""; + + if (!partType || partType === "text") { + if (text) visibleParts.push(text); + continue; + } + + if (/think|reason|summary|analysis/.test(partType)) { + appendThinkingPart(thinkingParts, text); + appendThinkingPart(thinkingParts, part.thinking); + appendThinkingPart(thinkingParts, part.reasoning); + appendThinkingPart(thinkingParts, part.summary); + continue; + } + + if (text) visibleParts.push(text); + } + } else { + const fallback = normalizeCohereNativeTextContent(messageContent) || String(data?.text || "").trim(); + if (fallback) visibleParts.push(fallback); + } + + appendThinkingPart(thinkingParts, data?.message?.reasoning); + appendThinkingPart(thinkingParts, data?.message?.thinking); + appendThinkingPart(thinkingParts, collectThinkingFromReasoningDetails(data?.message?.reasoning_details)); + + const extracted = extractThinkingSectionsFromTaggedText(visibleParts.join("").trim()); + appendThinkingPart(thinkingParts, extracted.thinking_content); + + return { + content: extracted.content, + thinking_content: thinkingParts.join("\n\n").trim(), + }; +} + +function parseAnthropicResponsePayload(payload) { + const data = payload && typeof payload === "object" ? payload : {}; + const thinkingParts = []; + const visibleParts = []; + const contentBlocks = Array.isArray(data?.content) ? data.content : []; + + for (const block of contentBlocks) { + if (!block || typeof block !== "object") continue; + const blockType = String(block.type || "").trim().toLowerCase(); + + if (blockType === "text") { + if (typeof block.text === "string") { + visibleParts.push(block.text); + } + continue; + } + + if (blockType === "thinking") { + appendThinkingPart(thinkingParts, block.thinking); + appendThinkingPart(thinkingParts, block.text); + continue; + } + + if (blockType === "redacted_thinking") { + continue; + } + + if (/think|reason|summary|analysis/.test(blockType)) { + appendThinkingPart(thinkingParts, block.thinking); + appendThinkingPart(thinkingParts, block.text); + appendThinkingPart(thinkingParts, block.summary); + continue; + } + } + + const extracted = extractThinkingSectionsFromTaggedText(visibleParts.join("").trim()); + appendThinkingPart(thinkingParts, extracted.thinking_content); + + return { + content: extracted.content, + thinking_content: thinkingParts.join("\n\n").trim(), + }; +} + +function normalizeOpenAiNativeToolCalls(rawToolCalls) { + return (Array.isArray(rawToolCalls) ? rawToolCalls : []) + .map((call, index) => { + const functionName = String(call?.function?.name || "").trim(); + if (!functionName) return null; + let argsRaw = call?.function?.arguments; + if (typeof argsRaw !== "string") { + try { + argsRaw = JSON.stringify(argsRaw || {}); + } catch { + argsRaw = "{}"; + } + } + return { + id: String(call?.id || `tool_call_${index + 1}`).trim(), + type: "function", + function: { + name: functionName, + arguments: argsRaw || "{}", + }, + }; + }) + .filter(Boolean); +} + +function normalizeLegacyOpenAiFunctionCall(rawFunctionCall) { + const functionName = String(rawFunctionCall?.name || "").trim(); + if (!functionName) return []; + let argsRaw = rawFunctionCall?.arguments; + if (typeof argsRaw !== "string") { + try { + argsRaw = JSON.stringify(argsRaw || {}); + } catch { + argsRaw = "{}"; + } + } + return [{ + id: "legacy_function_call_1", + type: "function", + function: { + name: functionName, + arguments: argsRaw || "{}", + }, + }]; +} + +function buildOpenAiCompatibleNativeMessages(messages) { + return (Array.isArray(messages) ? messages : []) + .map((message) => { + const role = String(message?.role || "").trim().toLowerCase(); + if (!role) return null; + + if (role === "tool") { + const toolCallId = String(message?.tool_call_id || "").trim(); + if (!toolCallId) return null; + return { + role: "tool", + tool_call_id: toolCallId, + content: typeof message?.content === "string" + ? message.content + : JSON.stringify(message?.content || {}), + }; + } + + if (role === "assistant") { + const payload = { role: "assistant" }; + const textContent = normalizeOpenAiNativeTextContent(message?.content); + const toolCalls = normalizeOpenAiNativeToolCalls(message?.tool_calls); + if (textContent) { + payload.content = textContent; + } + if (toolCalls.length > 0) { + payload.tool_calls = toolCalls; + } + if (!("content" in payload) && !payload.tool_calls) { + payload.content = ""; + } + return payload; + } + + if (message?.image && typeof message.image === "string" && message.image.startsWith("data:image/")) { + return { + role, + content: [ + { type: "text", text: message.content || "" }, + { type: "image_url", image_url: { url: message.image } }, + ], + }; + } + + return { + role, + content: typeof message?.content === "string" ? message.content : String(message?.content || ""), + }; + }) + .filter(Boolean); +} + +function buildCohereNativeMessages(messages) { + return (Array.isArray(messages) ? messages : []) + .map((message) => { + const role = String(message?.role || "").trim().toLowerCase(); + if (!role) return null; + + if (role === "tool") { + const toolCallId = String(message?.tool_call_id || "").trim(); + if (!toolCallId) return null; + let data; + try { + data = JSON.stringify(message?.content ?? {}); + } catch { + data = JSON.stringify({ ok: false, error: "Failed to serialize tool result." }); + } + return { + role: "tool", + tool_call_id: toolCallId, + content: [ + { + type: "document", + document: { data }, + }, + ], + }; + } + + if (role === "assistant") { + const payload = { role: "assistant" }; + const textContent = normalizeCohereNativeTextContent(message?.content); + const toolCalls = normalizeOpenAiNativeToolCalls(message?.tool_calls); + const toolPlan = String(message?.tool_plan || "").trim(); + if (textContent) { + payload.content = textContent; + } + if (toolPlan) { + payload.tool_plan = toolPlan; + } + if (toolCalls.length > 0) { + payload.tool_calls = toolCalls; + } + if (!("content" in payload) && !payload.tool_calls) { + payload.content = ""; + } + return payload; + } + + return { + role, + content: typeof message?.content === "string" ? message.content : String(message?.content || ""), + }; + }) + .filter(Boolean); +} + +function buildAnthropicSystemMessage(messages) { + return (Array.isArray(messages) ? messages : []) + .filter((message) => String(message?.role || "").trim().toLowerCase() === "system") + .map((message) => String(message?.content || "").trim()) + .filter(Boolean) + .join("\n\n"); +} + +function buildAnthropicContentBlocks(message) { + if (Array.isArray(message?.anthropicContent)) { + return message.anthropicContent; + } + + const role = String(message?.role || "").trim().toLowerCase(); + const blocks = []; + const textContent = normalizeAnthropicTextContent(message?.content); + + if (textContent) { + blocks.push({ type: "text", text: textContent }); + } + + if (role === "user" && message?.image && typeof message.image === "string" && message.image.startsWith("data:image/")) { + const match = message.image.match(/^data:(image\/[^;]+);base64,(.+)$/); + if (match) { + blocks.push({ + type: "image", + source: { + type: "base64", + media_type: match[1], + data: match[2], + }, + }); + } + } + + return blocks; +} + +function buildAnthropicInitialMessages(messages) { + return (Array.isArray(messages) ? messages : []) + .filter((message) => { + const role = String(message?.role || "").trim().toLowerCase(); + return role === "user" || role === "assistant"; + }) + .map((message) => ({ + role: String(message?.role || "").trim().toLowerCase(), + content: buildAnthropicContentBlocks(message), + })) + .filter((message) => Array.isArray(message.content) && message.content.length > 0); +} + +function extractAnthropicNativeToolCalls(contentBlocks) { + return (Array.isArray(contentBlocks) ? contentBlocks : []) + .map((block, index) => { + if (!block || typeof block !== "object") return null; + if (String(block.type || "").trim().toLowerCase() !== "tool_use") return null; + const name = String(block.name || "").trim(); + if (!name) return null; + return { + id: String(block.id || `anthropic_tool_call_${index + 1}`).trim(), + type: "function", + function: { + name, + arguments: JSON.stringify(block.input && typeof block.input === "object" ? block.input : {}), + }, + }; + }) + .filter(Boolean); +} + +function buildAnthropicToolResultUserMessage(toolCalls, toolResults) { + const resultById = new Map((Array.isArray(toolResults) ? toolResults : []).map((entry) => [String(entry?.id || "").trim(), entry])); + const content = []; + + for (const toolCall of Array.isArray(toolCalls) ? toolCalls : []) { + const match = resultById.get(String(toolCall?.id || "").trim()); + const toolResult = match?.result ?? { ok: false, error: "Missing tool result." }; + content.push({ + type: "tool_result", + tool_use_id: String(toolCall?.id || "").trim(), + is_error: toolResult?.ok === false, + content: JSON.stringify(toolResult || {}), + }); + } + + return { + role: "user", + content, + }; +} + +function buildOpenAiNativeEndpoint(provider, settings) { + const providerConfig = getAiProviderConfig(provider); + if (provider === "openai-compatible") { + return appendPathToBaseUrl(settings.baseUrl, "chat/completions"); + } + return providerConfig?.chatEndpoint || ""; +} + +async function requestOpenAiNativeBotToolTurn(provider, settings, model, messages, options = {}) { + const endpoint = buildOpenAiNativeEndpoint(provider, settings); + if (!endpoint) { + throw buildAiProxyError("Unknown provider.", 400); + } + + const headers = { + "Content-Type": "application/json", + ...buildAiProviderAuthHeaders(provider, settings.apiKey), + }; + + const body = JSON.stringify({ + model, + messages: buildOpenAiCompatibleNativeMessages(messages), + max_tokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 1800, + temperature: Number.isFinite(options.temperature) ? options.temperature : 0.2, + tools: BOT_OPENAI_TOOL_DEFINITIONS, + tool_choice: "auto", + }); + + const response = await proxyAiRequest(endpoint, { method: "POST", headers, body }); + if (response.status !== 200) { + throw buildAiProxyError(extractAiErrorMessage(response), response.status, response.data); + } + + const choice = response.data?.choices?.[0] || {}; + const responseMessage = choice?.message || {}; + const parsed = parseOpenAiCompatibleResponsePayload(response.data); + const toolCalls = normalizeOpenAiNativeToolCalls(responseMessage?.tool_calls); + const finalToolCalls = toolCalls.length > 0 + ? toolCalls + : normalizeLegacyOpenAiFunctionCall(responseMessage?.function_call); + const content = parsed.content || normalizeOpenAiNativeTextContent(responseMessage?.content); + + return { + content, + thinking_content: parsed.thinking_content || "", + toolCalls: finalToolCalls, + assistantMessage: { + role: "assistant", + content: content || "", + tool_calls: finalToolCalls, + }, + finishReason: String(choice?.finish_reason || "").trim().toLowerCase(), + }; +} + +async function requestCohereNativeBotToolTurn(apiKey, model, messages, options = {}) { + const endpoint = "https://api.cohere.com/v2/chat"; + const body = JSON.stringify({ + stream: false, + model, + messages: buildCohereNativeMessages(messages), + max_tokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 1800, + temperature: Number.isFinite(options.temperature) ? options.temperature : 0.2, + tools: BOT_OPENAI_TOOL_DEFINITIONS, + }); + + const response = await proxyAiRequest(endpoint, { + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: `Bearer ${apiKey}`, + }, + body, + }); + + if (response.status !== 200) { + if ([404, 405].includes(response.status)) { + throw buildAiProxyError( + "Cohere native tool calling is not available on this deployment.", + response.status, + response.data + ); + } + throw buildAiProxyError( + response.data?.message || response.data?.error || `API error: ${response.status}`, + response.status, + response.data + ); + } + + const responseMessage = response.data?.message || {}; + const parsed = parseCohereResponsePayload(response.data); + const toolCalls = normalizeOpenAiNativeToolCalls(responseMessage?.tool_calls); + const content = parsed.content || normalizeCohereNativeTextContent(responseMessage?.content) || String(response.data?.text || "").trim(); + const toolPlan = String(responseMessage?.tool_plan || "").trim(); + + return { + content, + thinking_content: parsed.thinking_content || "", + toolCalls, + assistantMessage: { + role: "assistant", + content: content || "", + tool_plan: toolPlan, + tool_calls: toolCalls, + }, + finishReason: String(response.data?.finish_reason || "").trim().toLowerCase(), + }; +} + +function buildGoogleNativeSystemInstruction(messages) { + const systemText = (Array.isArray(messages) ? messages : []) + .filter((message) => String(message?.role || "").trim().toLowerCase() === "system") + .map((message) => String(message?.content || "").trim()) + .filter(Boolean) + .join("\n\n"); + + return systemText ? { parts: [{ text: systemText }] } : null; +} + +function buildGoogleNativeInitialContents(messages) { + return (Array.isArray(messages) ? messages : []) + .filter((message) => String(message?.role || "").trim().toLowerCase() !== "system") + .map((message) => { + const role = String(message?.role || "").trim().toLowerCase(); + const parts = []; + + if (typeof message?.content === "string" && message.content) { + parts.push({ text: message.content }); + } + + if (message?.image && typeof message.image === "string" && message.image.startsWith("data:image/")) { + const match = message.image.match(/^data:(image\/[^;]+);base64,(.+)$/); + if (match) { + parts.push({ + inline_data: { + mime_type: match[1], + data: match[2], + }, + }); + } + } + + return { + role: role === "assistant" ? "model" : "user", + parts: parts.length ? parts : [{ text: "" }], + }; + }); +} + +function extractGoogleNativeToolCalls(candidateContent) { + return (Array.isArray(candidateContent?.parts) ? candidateContent.parts : []) + .map((part, index) => { + const functionCall = part?.functionCall || part?.function_call; + const functionName = String(functionCall?.name || "").trim(); + if (!functionName) return null; + return { + id: String(functionCall?.id || `google_tool_call_${index + 1}`).trim(), + type: "function", + function: { + name: functionName, + arguments: JSON.stringify(functionCall?.args || {}), + }, + }; + }) + .filter(Boolean); +} + +function extractGoogleNativeText(candidateContent) { + return (Array.isArray(candidateContent?.parts) ? candidateContent.parts : []) + .map((part) => (typeof part?.text === "string" ? part.text : "")) + .join("") + .trim(); +} + +function buildGoogleFunctionResponseContent(toolCalls, toolResults) { + const parts = []; + const byId = new Map((Array.isArray(toolResults) ? toolResults : []).map((entry) => [String(entry?.id || "").trim(), entry])); + + for (const toolCall of Array.isArray(toolCalls) ? toolCalls : []) { + const match = byId.get(String(toolCall?.id || "").trim()); + const toolResult = match?.result ?? { ok: false, error: "Missing tool result." }; + parts.push({ + functionResponse: { + id: String(toolCall?.id || "").trim() || undefined, + name: String(toolCall?.function?.name || "").trim(), + response: { result: toolResult }, + }, + }); + } + + return { + role: "user", + parts, + }; +} + +async function requestGoogleNativeBotToolTurn(apiKey, model, contents, systemInstruction, options = {}) { + const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`; + const requestBody = { + contents, + generationConfig: { + maxOutputTokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 1800, + temperature: Number.isFinite(options.temperature) ? options.temperature : 0.2, + }, + tools: [{ + functionDeclarations: BOT_GOOGLE_FUNCTION_DECLARATIONS, + }], + }; + + if (systemInstruction) { + requestBody.systemInstruction = systemInstruction; + } + + const response = await proxyAiRequest(endpoint, { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(requestBody), + }); + + if (response.status !== 200) { + throw buildAiProxyError(response.data?.error?.message || `API error: ${response.status}`, response.status, response.data); + } + + const candidateContent = response.data?.candidates?.[0]?.content || { role: "model", parts: [] }; + const parsed = parseGoogleResponsePayload(response.data); + return { + content: parsed.content || extractGoogleNativeText(candidateContent), + thinking_content: parsed.thinking_content || "", + toolCalls: extractGoogleNativeToolCalls(candidateContent), + candidateContent, + finishReason: String(response.data?.candidates?.[0]?.finishReason || "").trim().toLowerCase(), + }; +} + +async function requestAnthropicNativeBotToolTurn(apiKey, model, messages, systemInstruction, options = {}) { + const endpoint = 'https://api.anthropic.com/v1/messages'; + const body = { + model, + max_tokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 1800, + messages, + tools: BOT_ANTHROPIC_TOOL_DEFINITIONS, + }; + + if (systemInstruction) { + body.system = systemInstruction; + } + if (Number.isFinite(options.temperature)) { + body.temperature = options.temperature; + } + + const response = await proxyAiRequest(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...buildAiProviderAuthHeaders('anthropic', apiKey), + }, + body: JSON.stringify(body), + }); + + if (response.status !== 200) { + throw buildAiProxyError(extractAiErrorMessage(response), response.status, response.data); + } + + const contentBlocks = Array.isArray(response.data?.content) ? response.data.content : []; + const parsed = parseAnthropicResponsePayload(response.data); + + return { + content: parsed.content || normalizeAnthropicTextContent(contentBlocks), + thinking_content: parsed.thinking_content || '', + toolCalls: extractAnthropicNativeToolCalls(contentBlocks), + assistantMessage: { + role: 'assistant', + anthropicContent: contentBlocks, + }, + finishReason: String(response.data?.stop_reason || '').trim().toLowerCase(), + }; +} + +function isTransientAiChatProviderError(error) { + const message = String(error?.message || "").toLowerCase(); + return [ + "internal error encountered", + "internal error", + "temporarily unavailable", + "overloaded", + "upstream request timeout", + "request timeout", + "socket hang up", + "econnreset", + "502", + "503", + ].some((fragment) => message.includes(fragment)); +} + +async function callAiChatProviderOnce(provider, settings, model, messages, options = {}) { + switch (getAiProviderConfig(provider)?.chatProtocol) { + case "anthropic": + return proxyAnthropicAi(settings.apiKey, model, messages, options); + case "google": + return proxyGoogleAi(settings.apiKey, model, messages, options); + case "cohere": + return proxyCohereAi(settings.apiKey, model, messages, options); + case "huggingface": + return proxyHuggingFaceAi(settings.apiKey, model, messages, options); + default: + return proxyOpenAiCompatible(provider, settings, model, messages, options); + } +} + +async function callAiChatProvider(provider, settings, model, messages, options = {}) { + let lastError = null; + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + return await callAiChatProviderOnce(provider, settings, model, messages, options); + } catch (err) { + lastError = err; + if (attempt > 0 || !isTransientAiChatProviderError(err)) throw err; + await delay(350); + } + } + throw lastError || new Error("AI request failed"); +} + +function extractAiPanelResultError(result, fallbackMessage) { + const body = result && typeof result.body === "object" && result.body ? result.body : {}; + const detail = body.detail || body.error || body.message || fallbackMessage; + return String(detail || fallbackMessage || "That action failed.").trim(); +} + +async function performAiServerPowerAction(req, serverName, action) { + const result = await nodesRouter.performPanelServerAction(req, serverName, action); + if (!result || result.status !== 200) { + throw new Error(extractAiPanelResultError(result, "Failed to perform that server action.")); + } + return { ok: true, response: result.body || { ok: true } }; +} + +async function performAiConsoleCommand(req, serverName, command) { + const commandCheck = typeof nodesRouter.sanitizeConsoleCommand === "function" + ? nodesRouter.sanitizeConsoleCommand(command) + : { ok: true, command: String(command || "").trim() }; + if (!commandCheck.ok) { + throw new Error(String(commandCheck.detail || commandCheck.error || "Invalid console command.")); + } + + const result = await nodesRouter.performPanelConsoleCommand(req, serverName, commandCheck.command); + if (!result || result.status !== 200) { + throw new Error(extractAiPanelResultError(result, "Failed to send that console command.")); + } + + rememberConsoleCommand(serverName, commandCheck.command); + return { ok: true, command: commandCheck.command }; +} + +async function listAiServerBackups(req, serverName) { + const result = await nodesRouter.performPanelListBackups(req, serverName); + if (!result || result.status !== 200) { + throw new Error(extractAiPanelResultError(result, "Failed to load backups.")); + } + return Array.isArray(result.body?.backups) ? result.body.backups : []; +} + +async function createAiServerBackup(req, serverName, backupName, description) { + const result = await nodesRouter.performPanelCreateBackup(req, serverName, backupName, description); + if (!result || result.status !== 200) { + throw new Error(extractAiPanelResultError(result, "Failed to create the backup.")); + } + return result.body?.backup || null; +} + +async function restoreAiServerBackup(req, serverName, backupId, deleteOldFiles) { + const result = await nodesRouter.performPanelRestoreBackup(req, serverName, backupId, deleteOldFiles); + if (!result || result.status !== 200) { + throw new Error(extractAiPanelResultError(result, "Failed to restore that backup.")); + } + return true; +} + +async function deleteAiServerBackup(req, serverName, backupId) { + const result = await nodesRouter.performPanelDeleteBackup(req, serverName, backupId); + if (!result || result.status !== 200) { + throw new Error(extractAiPanelResultError(result, "Failed to delete that backup.")); + } + return true; +} + +async function resolveBotToolServerOrError({ accessibleServers, requestedServer, currentServerName, userEmail, requiredPerms = [] }) { + const resolved = resolveServerFromAccessibleList(accessibleServers, requestedServer, currentServerName); + if (!resolved.entry) { + return { + error: { + ok: false, + error: resolved.error || "Server not found.", + candidates: resolved.candidates || undefined, + }, + }; + } + + const perms = await getEffectivePermsForUserOnServer(userEmail, resolved.entry.name); + const missingPerms = requiredPerms.filter((permKey) => !perms?.[permKey]); + if (missingPerms.length) { + return { + error: { + ok: false, + error: missingPerms.length === 1 + ? `You do not have permission to ${describeBotPermissionKey(missingPerms[0])} on ${resolved.entry.displayName || resolved.entry.name}.` + : `You do not have all required permissions on ${resolved.entry.displayName || resolved.entry.name}.`, + permissions: missingPerms, + }, + entry: resolved.entry, + perms, + }; + } + + return { entry: resolved.entry, perms }; +} + +function queueBotClientAction(clientActions, nextAction) { + if (!Array.isArray(clientActions) || !nextAction || typeof nextAction !== "object") return; + + const type = String(nextAction.type || "").trim().toLowerCase(); + const server = String(nextAction.server || "").trim().toLowerCase(); + if (!type) return; + + if (type === "refresh_power_state" || type === "backups_updated") { + const existingIndex = clientActions.findIndex((entry) => ( + String(entry?.type || "").trim().toLowerCase() === type && + String(entry?.server || "").trim().toLowerCase() === server + )); + if (existingIndex !== -1) { + clientActions[existingIndex] = { ...clientActions[existingIndex], ...nextAction }; + return; + } + } + + if (type === "console_command_executed") { + const command = String(nextAction.command || "").trim(); + const sentAt = Number(nextAction.sentAt) || 0; + const duplicate = clientActions.some((entry) => ( + String(entry?.type || "").trim().toLowerCase() === type && + String(entry?.server || "").trim().toLowerCase() === server && + String(entry?.command || "").trim() === command && + (Number(entry?.sentAt) || 0) === sentAt + )); + if (duplicate) return; + } + + clientActions.push(nextAction); +} + +function normalizeBotToolCacheValue(value) { + if (Array.isArray(value)) { + return value.map((entry) => normalizeBotToolCacheValue(entry)); + } + if (value && typeof value === "object") { + return Object.keys(value).sort().reduce((accumulator, key) => { + accumulator[key] = normalizeBotToolCacheValue(value[key]); + return accumulator; + }, {}); + } + return value; +} + +function buildBotToolExecutionCacheKey(name, args, currentServerName) { + return JSON.stringify({ + name: String(name || "").trim(), + currentServerName: String(currentServerName || "").trim().toLowerCase(), + args: normalizeBotToolCacheValue(args && typeof args === "object" ? args : {}), + }); +} + +async function maybeExecuteDirectBotConsoleCommand({ + req, + safeMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, +}) { + const latestUserMessage = getLatestBotUserMessageContent(safeMessages); + const command = extractExplicitBotConsoleCommandRequest(latestUserMessage); + if (!command) return null; + + const requestedServer = extractBotAssistantServerCandidate(latestUserMessage, currentServerName) || currentServerName; + const toolResult = await runBotAssistantTool({ + req, + name: "send_console_command", + args: { server: requestedServer, command }, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + + return { + content: buildBotReplyFromToolResult("send_console_command", toolResult) || "Done.", + thinking_time_ms: 0, + thinking_content: "", + clientActions, + nativeToolMode: "direct-console-command", + }; +} + +async function executeBotAssistantToolWithCache({ + toolExecutionCache, + name, + args, + currentServerName, + ...rest +}) { + const cacheKey = buildBotToolExecutionCacheKey(name, args, currentServerName); + if (toolExecutionCache instanceof Map && toolExecutionCache.has(cacheKey)) { + return toolExecutionCache.get(cacheKey); + } + + const result = await runBotAssistantTool({ + ...rest, + name, + args, + currentServerName, + }); + + if (toolExecutionCache instanceof Map) { + toolExecutionCache.set(cacheKey, result); + } + return result; +} + +async function runBotAssistantTool({ req, name, args, currentServerName, accessibleServers, userEmail, userIp, clientActions }) { + const toolName = String(name || "").trim(); + if (!BOT_AI_TOOL_NAMES.has(toolName)) { + return { ok: false, error: "Unknown tool." }; + } + + switch (toolName) { + case "list_accessible_servers": + return { + ok: true, + servers: accessibleServers.slice(0, 100).map((entry) => buildBotServerSummary(entry)), + }; + + case "inspect_server": { + const { entry, perms, error } = await resolveBotToolServerOrError({ + accessibleServers, + requestedServer: args.server, + currentServerName, + userEmail, + }); + if (error) return error; + return { + ok: true, + server: buildBotServerSummary(entry, perms), + }; + } + + case "power_server": { + const action = normalizeBotPowerAction(args.action); + if (!action) return { ok: false, error: "Invalid power action." }; + const requiredPerms = action === "start" + ? ["server_start"] + : action === "restart" + ? ["server_stop", "server_start"] + : ["server_stop"]; + + const { entry, perms, error } = await resolveBotToolServerOrError({ + accessibleServers, + requestedServer: args.server, + currentServerName, + userEmail, + requiredPerms, + }); + if (error) return error; + + await performAiServerPowerAction(req, entry.name, action); + if (Array.isArray(clientActions) && isSameBotServer(entry.name, currentServerName)) { + queueBotClientAction(clientActions, { type: "refresh_power_state", server: entry.name, action }); + } + + return { + ok: true, + action, + server: buildBotServerSummary(entry, perms), + }; + } + + case "query_console": { + const { entry, perms, error } = await resolveBotToolServerOrError({ + accessibleServers, + requestedServer: args.server, + currentServerName, + userEmail, + requiredPerms: ["console_read"], + }); + if (error) return error; + + const lines = await getBotConsoleHistorySnapshot(entry.name, args.limit); + return { + ok: true, + server: buildBotServerSummary(entry, perms), + question: String(args.question || "").trim(), + total: lines.length, + lines, + }; + } + + case "send_console_command": { + const { entry, perms, error } = await resolveBotToolServerOrError({ + accessibleServers, + requestedServer: args.server, + currentServerName, + userEmail, + requiredPerms: ["console_write"], + }); + if (error) return error; + + if (!String(args.command || "").trim()) { + return { ok: false, error: "A console command is required." }; + } + + let commandResult; + try { + commandResult = await performAiConsoleCommand(req, entry.name, args.command); + } catch (error) { + return { + ok: false, + error: String(error?.message || "Failed to send that console command.").trim(), + }; + } + + if (Array.isArray(clientActions) && isSameBotServer(entry.name, currentServerName)) { + queueBotClientAction(clientActions, { + type: "console_command_executed", + server: entry.name, + command: commandResult.command, + sentAt: Date.now(), + }); + } + + return { + ok: true, + server: buildBotServerSummary(entry, perms), + command: commandResult.command, + }; + } + + case "list_backups": { + const { entry, perms, error } = await resolveBotToolServerOrError({ + accessibleServers, + requestedServer: args.server, + currentServerName, + userEmail, + requiredPerms: ["backups_view"], + }); + if (error) return error; + + const backups = await listAiServerBackups(req, entry.name); + return { + ok: true, + server: buildBotServerSummary(entry, perms), + total: backups.length, + backups: summarizeBackupsForBot(backups), + }; + } + + case "create_backup": { + const { entry, perms, error } = await resolveBotToolServerOrError({ + accessibleServers, + requestedServer: args.server, + currentServerName, + userEmail, + requiredPerms: ["backups_create"], + }); + if (error) return error; + + const backup = await createAiServerBackup(req, entry.name, args.name, args.description); + if (Array.isArray(clientActions) && isSameBotServer(entry.name, currentServerName)) { + queueBotClientAction(clientActions, { type: "backups_updated", server: entry.name, reason: "create" }); + } + + return { + ok: true, + server: buildBotServerSummary(entry, perms), + backup: backup ? summarizeBackupsForBot([backup])[0] : null, + }; + } + + case "restore_backup": + case "delete_backup": { + const requiredPerms = toolName === "restore_backup" ? ["backups_create"] : ["backups_delete"]; + const { entry, perms, error } = await resolveBotToolServerOrError({ + accessibleServers, + requestedServer: args.server, + currentServerName, + userEmail, + requiredPerms, + }); + if (error) return error; + + const backups = await listAiServerBackups(req, entry.name); + const backupResolution = resolveBackupFromList(backups, args.backup); + if (!backupResolution.backup) { + return { + ok: false, + error: backupResolution.error || "Backup not found.", + candidates: backupResolution.candidates || summarizeBackupsForBot(backups).map((backup) => backup.name || backup.id).filter(Boolean).slice(0, 5), + }; + } + + const backupId = backupResolution.backup.id || backupResolution.backup.uuid; + if (!backupId) { + return { ok: false, error: "That backup does not expose a usable identifier." }; + } + + if (toolName === "restore_backup") { + await restoreAiServerBackup(req, entry.name, backupId, !!args.deleteOldFiles); + } else { + await deleteAiServerBackup(req, entry.name, backupId); + } + + if (Array.isArray(clientActions) && isSameBotServer(entry.name, currentServerName)) { + queueBotClientAction(clientActions, { + type: "backups_updated", + server: entry.name, + reason: toolName === "restore_backup" ? "restore" : "delete", + }); + } + + return { + ok: true, + server: buildBotServerSummary(entry, perms), + backup: summarizeBackupsForBot([backupResolution.backup])[0] || { + id: backupId, + name: backupResolution.backup.name || null, + }, + }; + } + + default: + return { ok: false, error: "Unknown tool." }; + } +} + +function parseNativeBotToolArguments(rawArguments) { + if (!rawArguments) return {}; + if (typeof rawArguments === "object" && !Array.isArray(rawArguments)) { + return rawArguments; + } + try { + const parsed = JSON.parse(String(rawArguments)); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {}; + } catch { + return {}; + } +} + +async function requestBotToolPlanRepair(provider, settings, model, workingMessages, assistantContent) { + let currentAssistantContent = String(assistantContent || "").slice(0, 12000); + + for (let attempt = 0; attempt < 3; attempt += 1) { + const repairMessages = [ + ...(Array.isArray(workingMessages) ? workingMessages : []), + ...((currentAssistantContent && !looksLikeLeakedBotReasoning(currentAssistantContent) && !isWeakBotAiReply(currentAssistantContent)) + ? [{ role: "assistant", content: currentAssistantContent }] + : []), + { + role: "user", + content: [ + "Your previous reply was invalid.", + "If a native server action is needed, your entire reply must be one JSON block with no extra text.", + "If no native action is needed, output one short user-facing sentence only.", + "If you need more than one tool, include multiple tool calls in the same JSON block.", + "Do not mention tools unless they are inside the JSON block.", + "Do not expose reasoning, thinking, or planning.", + 'Examples: {"reply":"Starting it now.","tool_calls":[{"name":"power_server","args":{"server":"current server","action":"start"}}]}', + '{"reply":"Checking it now.","tool_calls":[{"name":"inspect_server","args":{"server":"current server"}}]}', + '{"reply":"Checking that now.","tool_calls":[{"name":"inspect_server","args":{"server":"current server"}},{"name":"query_console","args":{"server":"current server","limit":60}}]}', + '{"reply":"Sending it now.","tool_calls":[{"name":"send_console_command","args":{"server":"current server","command":"say hello"}}]}', + ].join(" "), + }, + ]; + + const repairResponse = await callAiChatProvider(provider, settings, model, repairMessages, { + maxTokens: 900, + temperature: 0, + }); + + currentAssistantContent = String(repairResponse?.content || "").trim(); + if (!currentAssistantContent) break; + if (parseBotAssistantToolPlan(currentAssistantContent)) break; + if (!needsBotToolPlanRepair(currentAssistantContent)) break; + } + + return currentAssistantContent; +} + +async function completeAiChatConversationWithOpenAiNativeTools({ + req, + provider, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, +}) { + let workingMessages = Array.isArray(conversationMessages) ? conversationMessages.slice() : []; + const toolExecutionCache = new Map(); + const thinkingParts = []; + let thinkingTimeMs = 0; + let finalContent = ""; + let lastToolName = ""; + let lastToolResult = null; + const toolHistory = []; + let executedAnyTool = false; + + try { + for (let attempt = 0; attempt < MAX_BOT_TOOL_LOOPS; attempt += 1) { + const startedAt = Date.now(); + const turn = await requestOpenAiNativeBotToolTurn(provider, settings, model, workingMessages, { + maxTokens: 2200, + temperature: 0.2, + }); + thinkingTimeMs += Date.now() - startedAt; + appendThinkingPart(thinkingParts, turn.thinking_content); + + let effectiveToolCalls = Array.isArray(turn.toolCalls) ? turn.toolCalls.slice() : []; + let assistantMessage = turn.assistantMessage; + if (!effectiveToolCalls.length && needsBotToolPlanRepair(turn.content || "")) { + const salvagedToolCalls = salvageBotToolCallsFromAssistantText(turn.content || "", currentServerName); + if (salvagedToolCalls.length > 0) { + effectiveToolCalls = buildSyntheticNativeToolCalls(salvagedToolCalls, `openai_salvaged_${attempt + 1}`); + assistantMessage = { + role: "assistant", + content: "", + tool_calls: effectiveToolCalls, + }; + } else if (!executedAnyTool) { + throw buildAiProxyError("Native tool response needs generic fallback.", 422, { content: turn.content || "" }); + } + } + + if (!effectiveToolCalls.length) { + finalContent = stripBotToolPlanMarkup(turn.content || ""); + break; + } + + workingMessages.push(assistantMessage); + + for (const toolCall of effectiveToolCalls) { + const toolName = String(toolCall?.function?.name || "").trim(); + const toolArgs = sanitizeBotToolArgs(toolName, parseNativeBotToolArguments(toolCall?.function?.arguments)); + const toolResult = await executeBotAssistantToolWithCache({ + toolExecutionCache, + req, + name: toolName, + args: toolArgs, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + executedAnyTool = true; + lastToolName = toolName; + lastToolResult = toolResult; + toolHistory.push({ name: toolName, result: toolResult }); + workingMessages.push({ + role: "tool", + tool_call_id: String(toolCall?.id || "").trim(), + content: JSON.stringify(toolResult || {}), + }); + } + } + } catch (error) { + if (executedAnyTool) { + error.nativeToolProgressStarted = true; + } + throw error; + } + + if (!finalContent) { + finalContent = buildBotReplyFromToolHistory(toolHistory) || buildBotReplyFromToolResult(lastToolName, lastToolResult) || "Done."; + } + finalContent = finalizeBotAssistantReply(finalContent, lastToolName, lastToolResult); + + return { + content: finalContent, + thinking_time_ms: thinkingTimeMs, + thinking_content: thinkingParts.join("\n\n").trim(), + clientActions, + nativeToolMode: "openai-style", + }; +} + +async function completeAiChatConversationWithCohereNativeTools({ + req, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, +}) { + let workingMessages = Array.isArray(conversationMessages) ? conversationMessages.slice() : []; + const toolExecutionCache = new Map(); + const thinkingParts = []; + let thinkingTimeMs = 0; + let finalContent = ""; + let lastToolName = ""; + let lastToolResult = null; + const toolHistory = []; + let executedAnyTool = false; + + try { + for (let attempt = 0; attempt < MAX_BOT_TOOL_LOOPS; attempt += 1) { + const startedAt = Date.now(); + const turn = await requestCohereNativeBotToolTurn(settings.apiKey, model, workingMessages, { + maxTokens: 2200, + temperature: 0.2, + }); + thinkingTimeMs += Date.now() - startedAt; + appendThinkingPart(thinkingParts, turn.thinking_content); + + let effectiveToolCalls = Array.isArray(turn.toolCalls) ? turn.toolCalls.slice() : []; + let assistantMessage = turn.assistantMessage; + if (!effectiveToolCalls.length && needsBotToolPlanRepair(turn.content || "")) { + const salvagedToolCalls = salvageBotToolCallsFromAssistantText(turn.content || "", currentServerName); + if (salvagedToolCalls.length > 0) { + effectiveToolCalls = buildSyntheticNativeToolCalls(salvagedToolCalls, `cohere_salvaged_${attempt + 1}`); + assistantMessage = { + role: "assistant", + content: "", + tool_calls: effectiveToolCalls, + }; + } else if (!executedAnyTool) { + throw buildAiProxyError("Native tool response needs generic fallback.", 422, { content: turn.content || "" }); + } + } + + if (!effectiveToolCalls.length) { + finalContent = stripBotToolPlanMarkup(turn.content || ""); + break; + } + + workingMessages.push(assistantMessage); + + for (const toolCall of effectiveToolCalls) { + const toolName = String(toolCall?.function?.name || "").trim(); + const toolArgs = sanitizeBotToolArgs(toolName, parseNativeBotToolArguments(toolCall?.function?.arguments)); + const toolResult = await executeBotAssistantToolWithCache({ + toolExecutionCache, + req, + name: toolName, + args: toolArgs, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + executedAnyTool = true; + lastToolName = toolName; + lastToolResult = toolResult; + toolHistory.push({ name: toolName, result: toolResult }); + workingMessages.push({ + role: "tool", + tool_call_id: String(toolCall?.id || "").trim(), + content: toolResult || {}, + }); + } + } + } catch (error) { + if (executedAnyTool) { + error.nativeToolProgressStarted = true; + } + throw error; + } + + if (!finalContent) { + finalContent = buildBotReplyFromToolHistory(toolHistory) || buildBotReplyFromToolResult(lastToolName, lastToolResult) || "Done."; + } + finalContent = finalizeBotAssistantReply(finalContent, lastToolName, lastToolResult); + + return { + content: finalContent, + thinking_time_ms: thinkingTimeMs, + thinking_content: thinkingParts.join("\n\n").trim(), + clientActions, + nativeToolMode: "cohere", + }; +} + +async function completeAiChatConversationWithGoogleNativeTools({ + req, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, +}) { + const systemInstruction = buildGoogleNativeSystemInstruction(conversationMessages); + const contents = buildGoogleNativeInitialContents(conversationMessages); + const toolExecutionCache = new Map(); + const thinkingParts = []; + let thinkingTimeMs = 0; + let finalContent = ""; + let lastToolName = ""; + let lastToolResult = null; + const toolHistory = []; + let executedAnyTool = false; + + try { + for (let attempt = 0; attempt < MAX_BOT_TOOL_LOOPS; attempt += 1) { + const startedAt = Date.now(); + const turn = await requestGoogleNativeBotToolTurn(settings.apiKey, model, contents, systemInstruction, { + maxTokens: 2200, + temperature: 0.2, + }); + thinkingTimeMs += Date.now() - startedAt; + appendThinkingPart(thinkingParts, turn.thinking_content); + + let effectiveToolCalls = Array.isArray(turn.toolCalls) ? turn.toolCalls.slice() : []; + let candidateContent = turn.candidateContent; + if (!effectiveToolCalls.length && needsBotToolPlanRepair(turn.content || "")) { + const salvagedToolCalls = salvageBotToolCallsFromAssistantText(turn.content || "", currentServerName); + if (salvagedToolCalls.length > 0) { + effectiveToolCalls = buildSyntheticNativeToolCalls(salvagedToolCalls, `google_salvaged_${attempt + 1}`); + candidateContent = { + role: "model", + parts: effectiveToolCalls.map((toolCall) => ({ + functionCall: { + id: String(toolCall?.id || "").trim(), + name: String(toolCall?.function?.name || "").trim(), + args: parseNativeBotToolArguments(toolCall?.function?.arguments), + }, + })), + }; + } else if (!executedAnyTool) { + throw buildAiProxyError("Native tool response needs generic fallback.", 422, { content: turn.content || "" }); + } + } + + if (!effectiveToolCalls.length) { + finalContent = stripBotToolPlanMarkup(turn.content || ""); + break; + } + + contents.push(candidateContent); + const toolResults = []; + + for (const toolCall of effectiveToolCalls) { + const toolName = String(toolCall?.function?.name || "").trim(); + const toolArgs = sanitizeBotToolArgs(toolName, parseNativeBotToolArguments(toolCall?.function?.arguments)); + const toolResult = await executeBotAssistantToolWithCache({ + toolExecutionCache, + req, + name: toolName, + args: toolArgs, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + executedAnyTool = true; + lastToolName = toolName; + lastToolResult = toolResult; + toolHistory.push({ name: toolName, result: toolResult }); + toolResults.push({ + id: String(toolCall?.id || "").trim(), + name: toolName, + result: toolResult, + }); + } + + contents.push(buildGoogleFunctionResponseContent(effectiveToolCalls, toolResults)); + } + } catch (error) { + if (executedAnyTool) { + error.nativeToolProgressStarted = true; + } + throw error; + } + + if (!finalContent) { + finalContent = buildBotReplyFromToolHistory(toolHistory) || buildBotReplyFromToolResult(lastToolName, lastToolResult) || "Done."; + } + finalContent = finalizeBotAssistantReply(finalContent, lastToolName, lastToolResult); + + return { + content: finalContent, + thinking_time_ms: thinkingTimeMs, + thinking_content: thinkingParts.join("\n\n").trim(), + clientActions, + nativeToolMode: "google", + }; +} + +async function completeAiChatConversationWithAnthropicNativeTools({ + req, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, +}) { + const systemInstruction = buildAnthropicSystemMessage(conversationMessages); + const workingMessages = buildAnthropicInitialMessages(conversationMessages); + const toolExecutionCache = new Map(); + const thinkingParts = []; + let thinkingTimeMs = 0; + let finalContent = ""; + let lastToolName = ""; + let lastToolResult = null; + const toolHistory = []; + let executedAnyTool = false; + + try { + for (let attempt = 0; attempt < MAX_BOT_TOOL_LOOPS; attempt += 1) { + const startedAt = Date.now(); + const turn = await requestAnthropicNativeBotToolTurn(settings.apiKey, model, workingMessages, systemInstruction, { + maxTokens: 2200, + temperature: 0.2, + }); + thinkingTimeMs += Date.now() - startedAt; + appendThinkingPart(thinkingParts, turn.thinking_content); + + let effectiveToolCalls = Array.isArray(turn.toolCalls) ? turn.toolCalls.slice() : []; + let assistantMessage = turn.assistantMessage; + if (!effectiveToolCalls.length && needsBotToolPlanRepair(turn.content || "")) { + const salvagedToolCalls = salvageBotToolCallsFromAssistantText(turn.content || "", currentServerName); + if (salvagedToolCalls.length > 0) { + effectiveToolCalls = buildSyntheticNativeToolCalls(salvagedToolCalls, `anthropic_salvaged_${attempt + 1}`); + assistantMessage = { + role: "assistant", + anthropicContent: effectiveToolCalls.map((toolCall) => ({ + type: "tool_use", + id: String(toolCall?.id || "").trim(), + name: String(toolCall?.function?.name || "").trim(), + input: parseNativeBotToolArguments(toolCall?.function?.arguments), + })), + }; + } else if (!executedAnyTool) { + throw buildAiProxyError("Native tool response needs generic fallback.", 422, { content: turn.content || "" }); + } + } + + if (!effectiveToolCalls.length) { + finalContent = stripBotToolPlanMarkup(turn.content || ""); + break; + } + + workingMessages.push({ + role: "assistant", + content: Array.isArray(assistantMessage?.anthropicContent) ? assistantMessage.anthropicContent : [], + }); + + const toolResults = []; + for (const toolCall of effectiveToolCalls) { + const toolName = String(toolCall?.function?.name || "").trim(); + const toolArgs = sanitizeBotToolArgs(toolName, parseNativeBotToolArguments(toolCall?.function?.arguments)); + const toolResult = await executeBotAssistantToolWithCache({ + toolExecutionCache, + req, + name: toolName, + args: toolArgs, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + executedAnyTool = true; + lastToolName = toolName; + lastToolResult = toolResult; + toolHistory.push({ name: toolName, result: toolResult }); + toolResults.push({ + id: String(toolCall?.id || "").trim(), + name: toolName, + result: toolResult, + }); + } + + workingMessages.push(buildAnthropicToolResultUserMessage(effectiveToolCalls, toolResults)); + } + } catch (error) { + if (executedAnyTool) { + error.nativeToolProgressStarted = true; + } + throw error; + } + + if (!finalContent) { + finalContent = buildBotReplyFromToolHistory(toolHistory) || buildBotReplyFromToolResult(lastToolName, lastToolResult) || "Done."; + } + finalContent = finalizeBotAssistantReply(finalContent, lastToolName, lastToolResult); + + return { + content: finalContent, + thinking_time_ms: thinkingTimeMs, + thinking_content: thinkingParts.join("\n\n").trim(), + clientActions, + nativeToolMode: "anthropic", + }; +} + +async function maybeCompleteAiChatConversationNatively({ + req, + provider, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, +}) { + try { + if (ANTHROPIC_NATIVE_BOT_TOOL_PROVIDERS.has(provider)) { + return await completeAiChatConversationWithAnthropicNativeTools({ + req, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + } + + if (OPENAI_STYLE_NATIVE_BOT_TOOL_PROVIDERS.has(provider)) { + return await completeAiChatConversationWithOpenAiNativeTools({ + req, + provider, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + } + + if (COHERE_NATIVE_BOT_TOOL_PROVIDERS.has(provider)) { + return await completeAiChatConversationWithCohereNativeTools({ + req, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + } + + if (GOOGLE_NATIVE_BOT_TOOL_PROVIDERS.has(provider)) { + return await completeAiChatConversationWithGoogleNativeTools({ + req, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + } + } catch (error) { + if (!error?.nativeToolProgressStarted && isNativeBotToolFallbackError(error)) { + console.warn(`[ai-chat] Native tool mode unsupported for ${provider}, falling back to generic tool plan: ${error.message}`); + return null; + } + throw error; + } + + return null; +} + +async function completeAiChatConversation({ req, provider, settings, model, messages, serverContext }) { + const safeMessages = normalizeAiConversationMessages(messages); + const safeServerContext = serverContext && typeof serverContext === "object" ? serverContext : {}; + const currentServerName = String(safeServerContext.currentServer || safeServerContext.server || "").trim(); + const currentUser = await getLoggedInUser(req); + const userEmail = String(currentUser?.email || req.session?.user || "").trim().toLowerCase(); + const isAdminUser = !!currentUser?.admin; + const userIp = getRequestIp(req); + const clientActions = []; + + if (!currentServerName) { + const startedAt = Date.now(); + const result = await callAiChatProvider(provider, settings, model, safeMessages, {}); + return { + content: finalizeBotAssistantReply(result.content || "", "", null) || "I could not produce a clean answer for that request.", + thinking_time_ms: Date.now() - startedAt, + thinking_content: String(result?.thinking_content || "").trim(), + clientActions, + }; + } + + const accessibleServers = await getAccessibleServerEntriesForAi(userEmail, isAdminUser); + const currentServerResolution = resolveServerFromAccessibleList(accessibleServers, currentServerName, currentServerName); + const currentServerEntry = currentServerResolution.entry || null; + const currentServerPerms = currentServerEntry + ? await getEffectivePermsForUserOnServer(userEmail, currentServerEntry.name) + : null; + + const conversationMessages = [ + { + role: "system", + content: buildBotAssistantSystemPrompt({ + currentServerName, + accessibleServers, + currentServerPerms, + }), + }, + ...safeMessages, + ]; + + const directConsoleCommandResult = await maybeExecuteDirectBotConsoleCommand({ + req, + safeMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + if (directConsoleCommandResult) { + return directConsoleCommandResult; + } + + const nativeResult = await maybeCompleteAiChatConversationNatively({ + req, + provider, + settings, + model, + conversationMessages, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + if (nativeResult) { + const cleanedNativeContent = finalizeBotAssistantReply(nativeResult.content || "", "", null); + const hasNativeActions = Array.isArray(nativeResult.clientActions) && nativeResult.clientActions.length > 0; + if (cleanedNativeContent || hasNativeActions) { + return { + ...nativeResult, + content: cleanedNativeContent || nativeResult.content || "Done.", + }; + } + } + + let workingMessages = conversationMessages.slice(); + const toolExecutionCache = new Map(); + const thinkingParts = []; + + let thinkingTimeMs = 0; + let finalContent = ""; + let lastToolName = ""; + let lastToolResult = null; + const toolHistory = []; + + for (let attempt = 0; attempt < MAX_BOT_TOOL_LOOPS; attempt += 1) { + const startedAt = Date.now(); + const response = await callAiChatProvider(provider, settings, model, workingMessages, { + maxTokens: 2200, + temperature: 0.2, + }); + thinkingTimeMs += Date.now() - startedAt; + appendThinkingPart(thinkingParts, response?.thinking_content); + + let content = String(response?.content || "").trim(); + let plan = parseBotAssistantToolPlan(content); + + if ((!plan || !Array.isArray(plan.tool_calls) || plan.tool_calls.length === 0) && needsBotToolPlanRepair(content)) { + const repairedContent = await requestBotToolPlanRepair(provider, settings, model, workingMessages, content); + if (repairedContent) { + content = repairedContent; + plan = parseBotAssistantToolPlan(repairedContent); + } + } + + if ((!plan || !Array.isArray(plan.tool_calls) || plan.tool_calls.length === 0) && needsBotToolPlanRepair(content)) { + const salvagedToolCalls = salvageBotToolCallsFromAssistantText(content, currentServerName); + if (salvagedToolCalls.length > 0) { + plan = { reply: "", tool_calls: salvagedToolCalls }; + } + } + + if (!plan || !Array.isArray(plan.tool_calls) || plan.tool_calls.length === 0) { + if (needsBotToolPlanRepair(content) && attempt < (MAX_BOT_TOOL_LOOPS - 1)) { + workingMessages = [ + ...workingMessages, + { + role: "system", + content: "The previous reply was invalid. The next reply must be either one JSON block with no extra text or one short final user-facing sentence with no prompt talk and no reasoning.", + }, + ]; + continue; + } + finalContent = stripBotToolPlanMarkup(plan?.reply || content) || plan?.reply || content; + break; + } + + const toolResults = []; + for (const toolCall of plan.tool_calls) { + const toolName = String(toolCall?.name || "").trim(); + const toolArgs = sanitizeBotToolArgs(toolName, toolCall?.args); + const toolResult = await executeBotAssistantToolWithCache({ + toolExecutionCache, + req, + name: toolName, + args: toolArgs, + currentServerName, + accessibleServers, + userEmail, + userIp, + clientActions, + }); + lastToolName = toolName; + lastToolResult = toolResult; + toolHistory.push({ name: toolName, result: toolResult }); + toolResults.push({ name: toolName, result: toolResult }); + } + + const assistantContinuationMessage = looksLikeLeakedBotReasoning(content) + ? null + : { role: "assistant", content: content.slice(0, 12000) }; + + workingMessages = [ + ...workingMessages, + ...(assistantContinuationMessage ? [assistantContinuationMessage] : []), + { role: "system", content: buildBotToolResultContextMessage(toolResults) }, + { role: "user", content: buildBotContinueAfterToolInstruction() }, + ]; + } + + if (!finalContent) { + finalContent = buildBotReplyFromToolHistory(toolHistory) || buildBotReplyFromToolResult(lastToolName, lastToolResult) || "Done."; + } + finalContent = finalizeBotAssistantReply(finalContent, lastToolName, lastToolResult) || "I could not produce a clean answer for that request."; + + return { + content: finalContent, + thinking_time_ms: thinkingTimeMs, + thinking_content: thinkingParts.join("\n\n").trim(), + clientActions, + }; +} + +const AI_AGENT_JOB_CONCURRENCY = Math.max(1, Math.min(10, parseInt(process.env.AI_AGENT_JOB_CONCURRENCY || "2", 10) || 2)); +const AI_AGENT_MAX_PENDING_JOBS = Math.max(10, Math.min(5000, parseInt(process.env.AI_AGENT_MAX_PENDING_JOBS || "500", 10) || 500)); +const AI_AGENT_PROMPT_MAX_CHARS = Math.max(1000, Math.min(32000, parseInt(process.env.AI_AGENT_PROMPT_MAX_CHARS || "12000", 10) || 12000)); +const AI_AGENT_FILE_READ_MAX_CHARS = Math.max(2000, Math.min(50000, parseInt(process.env.AI_AGENT_FILE_READ_MAX_CHARS || "18000", 10) || 18000)); +const AI_AGENT_FILE_LIST_MAX_ITEMS = Math.max(20, Math.min(500, parseInt(process.env.AI_AGENT_FILE_LIST_MAX_ITEMS || "120", 10) || 120)); + +const aiAgentQueuedJobIds = new Set(); +let aiAgentActiveJobs = 0; +let aiAgentPumpScheduled = false; + +function userCanUseAdpanelAgent(user) { + return !!(user && (user.admin || user.agent_access)); +} + +function normalizeAiProviderId(value) { + return String(value || "").trim().toLowerCase().slice(0, 64); +} + +function sanitizeAiModelId(value) { + return normalizeAiSecretValue(value).slice(0, 255); +} + +function sanitizeAiAgentPrompt(value) { + return String(value || "").replace(/\0/g, "").trim().slice(0, AI_AGENT_PROMPT_MAX_CHARS); +} + +function sanitizeAiAgentSource(value) { + return String(value || "manual").replace(/[^a-zA-Z0-9_.:-]/g, "_").slice(0, 64) || "manual"; +} + +function sanitizeAiAgentSourceRef(value) { + const raw = value === undefined || value === null ? "" : String(value); + return raw.replace(/[\0\r\n]/g, "").trim().slice(0, 255) || null; +} + +function formatAiMessageModelLabel(provider, model) { + const providerId = normalizeAiProviderId(provider); + const modelId = sanitizeAiModelId(model); + return `${providerId}:${modelId}`.slice(0, 255); +} + +function normalizeAiModelSelectionPayload(payload = {}) { + const directProvider = payload.provider || payload.providerId; + const directModel = payload.model || payload.modelName; + if (directProvider || directModel) { + return { + provider: normalizeAiProviderId(directProvider), + model: sanitizeAiModelId(directModel), + }; + } + + const rawSelection = String(payload.selection || payload.modelSelection || "").trim(); + if (!rawSelection) return { provider: "", model: "" }; + + try { + const parsed = JSON.parse(rawSelection); + return { + provider: normalizeAiProviderId(parsed?.provider || parsed?.providerId), + model: sanitizeAiModelId(parsed?.model || parsed?.modelName), + }; + } catch { + const separatorIdx = rawSelection.indexOf(":"); + if (separatorIdx === -1) return { provider: "", model: "" }; + return { + provider: normalizeAiProviderId(rawSelection.slice(0, separatorIdx)), + model: sanitizeAiModelId(rawSelection.slice(separatorIdx + 1)), + }; + } +} + +function assertAiProviderReady(provider, model) { + const providerId = normalizeAiProviderId(provider); + const modelId = sanitizeAiModelId(model); + const providerConfig = getAiProviderConfig(providerId); + if (!providerConfig) { + const error = new Error("invalid AI provider"); + error.status = 400; + throw error; + } + if (!modelId) { + const error = new Error("model is required"); + error.status = 400; + throw error; + } + + const settings = getStoredAiProviderSettings(providerId, readEnvFile()); + if (providerConfig.requiresKey !== false && !settings.apiKey) { + const error = new Error("API key not configured for this provider"); + error.status = 400; + throw error; + } + if (providerConfig.requiresBaseUrl && !settings.baseUrl) { + const error = new Error("Base URL not configured for this provider"); + error.status = 400; + throw error; + } + + return { provider: providerId, model: modelId, settings }; +} + +async function getSavedAiModelSelectionForUserId(userId) { + const safeUserId = Number(userId); + if (!Number.isFinite(safeUserId) || safeUserId <= 0) return null; + await ensureAiChatTablesReady(); + const rows = await db.query( + "SELECT provider, model, updated_at FROM user_ai_model_selections WHERE user_id = ? LIMIT 1", + [safeUserId] + ); + const row = rows?.[0]; + if (!row?.provider || !row?.model) return null; + return { + provider: normalizeAiProviderId(row.provider), + model: sanitizeAiModelId(row.model), + updated_at: row.updated_at || null, + }; +} + +async function saveAiModelSelectionForUserId(userId, provider, model) { + const safeUserId = Number(userId); + if (!Number.isFinite(safeUserId) || safeUserId <= 0) { + const error = new Error("invalid user"); + error.status = 400; + throw error; + } + const ready = assertAiProviderReady(provider, model); + await ensureAiChatTablesReady(); + await db.query( + `INSERT INTO user_ai_model_selections (user_id, provider, model) + VALUES (?, ?, ?) + ON DUPLICATE KEY UPDATE provider = VALUES(provider), model = VALUES(model), updated_at = CURRENT_TIMESTAMP`, + [safeUserId, ready.provider, ready.model] + ); + return { provider: ready.provider, model: ready.model }; +} + +function buildBackgroundAgentRequest(user, source = "ai-agent-job") { + const headers = Object.create(null); + return { + method: "POST", + path: `/api/ai/background/${sanitizeAiAgentSource(source)}`, + protocol: "http", + headers, + ip: "127.0.0.1", + connection: { remoteAddress: "127.0.0.1" }, + socket: { remoteAddress: "127.0.0.1" }, + session: { user: user.email }, + sessionID: `background:${user.id}`, + currentUser: user, + get(name) { + return headers[String(name || "").toLowerCase()] || ""; + }, + }; +} + +function deriveAiAgentChatTitle(prompt, fallback = "ADPanel Agent") { + const clean = String(prompt || fallback || "ADPanel Agent").trim().replace(/\s+/g, " "); + if (!clean) return "ADPanel Agent"; + return clean.length > 80 ? `${clean.slice(0, 77)}...` : clean; +} + +async function insertAiAgentChatJob({ user, serverName, prompt, provider, model, source = "manual", sourceRef = null, title = "" }) { + if (!db?.pool) { + const error = new Error("Database not available"); + error.status = 503; + throw error; + } + if (!userCanUseAdpanelAgent(user)) { + const error = new Error("no agent access"); + error.status = 403; + throw error; + } + + const ready = assertAiProviderReady(provider, model); + const safePrompt = sanitizeAiAgentPrompt(prompt); + if (!safePrompt) { + const error = new Error("prompt is required"); + error.status = 400; + throw error; + } + + const entry = await findServer(serverName); + const safeServerName = String(entry?.name || serverName || "").trim(); + if (!entry || !safeServerName) { + const error = new Error("Server not found"); + error.status = 404; + throw error; + } + if (!user.admin && !(await userHasAccessToServer(user.email, safeServerName))) { + const error = new Error("access denied"); + error.status = 403; + throw error; + } + + await ensureAiChatTablesReady(); + + const pendingRows = await db.query( + "SELECT COUNT(*) AS pending_count FROM ai_agent_jobs WHERE status IN ('queued','running')" + ); + if (Number(pendingRows?.[0]?.pending_count || 0) >= AI_AGENT_MAX_PENDING_JOBS) { + const error = new Error("ADPanel Agent queue is full. Please try again shortly."); + error.status = 503; + throw error; + } + + const conn = await db.pool.getConnection(); + try { + await conn.beginTransaction(); + const [chatResult] = await conn.execute( + "INSERT INTO ai_chats (user_email, title) VALUES (?, ?)", + [String(user.email || "").trim().toLowerCase(), String(title || deriveAiAgentChatTitle(safePrompt)).slice(0, 255)] + ); + const chatId = chatResult.insertId; + await conn.execute( + "INSERT INTO ai_messages (chat_id, role, content, image_data, thinking_time_ms, thinking_content, model) VALUES (?, 'user', ?, NULL, NULL, NULL, ?)", + [chatId, safePrompt, formatAiMessageModelLabel(ready.provider, ready.model)] + ); + const [jobResult] = await conn.execute( + `INSERT INTO ai_agent_jobs + (chat_id, user_id, user_email, server_name, provider, model, prompt, status, source, source_ref) + VALUES (?, ?, ?, ?, ?, ?, ?, 'queued', ?, ?)`, + [ + chatId, + user.id, + String(user.email || "").trim().toLowerCase(), + safeServerName, + ready.provider, + ready.model, + safePrompt, + sanitizeAiAgentSource(source), + sanitizeAiAgentSourceRef(sourceRef), + ] + ); + await conn.commit(); + enqueueAiAgentJob(jobResult.insertId); + return { chatId, jobId: jobResult.insertId, provider: ready.provider, model: ready.model }; + } catch (err) { + try { await conn.rollback(); } catch { } + throw err; + } finally { + conn.release(); + } +} + +async function resolveSchedulerAgentUser(userId, userName) { + const byId = await findUserById(userId); + if (byId) return byId; + const email = String(userName || "").trim(); + return email ? findUserByEmail(email) : null; +} + +function buildPlannerAgentPrompt(plannerItem, serverName) { + const prompt = sanitizeAiAgentPrompt(plannerItem?.prompt); + const title = String(plannerItem?.title || "").trim(); + const server = String(serverName || "").trim(); + return [ + "Execute this ADPanel Planner task now.", + server ? `Server: ${server}.` : "", + title ? `Planner task: ${title}.` : "", + "Treat the planner text below as the user's direct ADPanel Agent prompt and complete it naturally.", + "", + prompt + ].filter((part) => part !== "").join("\n"); +} + +async function queueSchedulerPlannerNextToAgent({ serverName, payload = null, userId, userName }) { + const user = await resolveSchedulerAgentUser(userId, userName); + if (!userCanUseAdpanelAgent(user)) { + const error = new Error("scheduled user has no ADPanel Agent access"); + error.status = 403; + throw error; + } + if (!user.admin && !(await userHasAccessToServer(user.email, serverName))) { + const error = new Error("scheduled user no longer has access to this server"); + error.status = 403; + throw error; + } + + const plannerItem = await getNextActivePlannerItem(serverName); + if (!plannerItem) { + const error = new Error("no active planner prompt found"); + error.status = 404; + throw error; + } + + const payloadSelection = normalizeAiModelSelectionPayload(payload || {}); + let selection = null; + if (payloadSelection.provider && payloadSelection.model) { + selection = assertAiProviderReady(payloadSelection.provider, payloadSelection.model); + } else { + selection = await getSavedAiModelSelectionForUserId(user.id); + if (!selection) { + const error = new Error("scheduled user has no saved ADPanel Agent model"); + error.status = 400; + throw error; + } + } + + const prompt = buildPlannerAgentPrompt(plannerItem, serverName); + + return insertAiAgentChatJob({ + user, + serverName, + prompt, + provider: selection.provider, + model: selection.model, + source: "scheduler_planner_next", + sourceRef: plannerItem.id, + title: `Planner: ${plannerItem.title || deriveAiAgentChatTitle(plannerItem.prompt)}`, + }); +} + +async function queueSchedulerPromptToAgent({ serverName, payload, userId, userName }) { + const user = await resolveSchedulerAgentUser(userId, userName); + if (!userCanUseAdpanelAgent(user)) { + const error = new Error("scheduled user has no ADPanel Agent access"); + error.status = 403; + throw error; + } + if (!user.admin && !(await userHasAccessToServer(user.email, serverName))) { + const error = new Error("scheduled user no longer has access to this server"); + error.status = 403; + throw error; + } + + const { provider, model } = normalizeAiModelSelectionPayload(payload || {}); + const prompt = sanitizeAiAgentPrompt(payload?.prompt); + const ready = assertAiProviderReady(provider, model); + await saveAiModelSelectionForUserId(user.id, ready.provider, ready.model); + + return insertAiAgentChatJob({ + user, + serverName, + prompt, + provider: ready.provider, + model: ready.model, + source: "scheduler_prompt", + sourceRef: null, + title: deriveAiAgentChatTitle(prompt, "Scheduled Agent Prompt"), + }); +} + +function enqueueAiAgentJob(jobId) { + const id = Number(jobId); + if (!Number.isFinite(id) || id <= 0) return; + aiAgentQueuedJobIds.add(id); + scheduleAiAgentPump(); +} + +function scheduleAiAgentPump() { + if (aiAgentPumpScheduled) return; + aiAgentPumpScheduled = true; + setImmediate(() => { + aiAgentPumpScheduled = false; + pumpAiAgentJobs().catch((err) => { + console.error("[ai-agent-jobs] Pump error:", err?.message || err); + }); + }); +} + +async function resumeQueuedAiAgentJobs() { + if (!db?.query || !aiChatTablesReady) return; + try { + await db.query("UPDATE ai_agent_jobs SET status = 'queued', started_at = NULL WHERE status = 'running'"); + } catch (err) { + console.warn("[ai-agent-jobs] Could not requeue stale running jobs:", err?.message || err); + } + + const limit = Math.min(AI_AGENT_MAX_PENDING_JOBS, 1000); + const rows = await db.query( + `SELECT id FROM ai_agent_jobs WHERE status = 'queued' ORDER BY created_at ASC, id ASC LIMIT ${limit}` + ); + for (const row of rows || []) { + enqueueAiAgentJob(row.id); + } +} + +async function nextQueuedAiAgentJobId() { + const queued = aiAgentQueuedJobIds.values().next(); + if (!queued.done) { + aiAgentQueuedJobIds.delete(queued.value); + return Number(queued.value); + } + + if (!db?.query || !aiChatTablesReady) return null; + const rows = await db.query( + "SELECT id FROM ai_agent_jobs WHERE status = 'queued' ORDER BY created_at ASC, id ASC LIMIT 1" + ); + return rows?.[0]?.id ? Number(rows[0].id) : null; +} + +async function pumpAiAgentJobs() { + while (aiAgentActiveJobs < AI_AGENT_JOB_CONCURRENCY) { + const jobId = await nextQueuedAiAgentJobId(); + if (!jobId) break; + aiAgentActiveJobs += 1; + processAiAgentJob(jobId) + .catch((err) => { + console.error(`[ai-agent-jobs] Job ${jobId} crashed:`, err?.message || err); + }) + .finally(() => { + aiAgentActiveJobs = Math.max(0, aiAgentActiveJobs - 1); + scheduleAiAgentPump(); + }); + } +} + +async function claimAiAgentJob(jobId) { + const result = await db.query( + "UPDATE ai_agent_jobs SET status = 'running', started_at = NOW(), error = NULL WHERE id = ? AND status = 'queued'", + [jobId] + ); + if (!result?.affectedRows) return null; + const rows = await db.query("SELECT * FROM ai_agent_jobs WHERE id = ? LIMIT 1", [jobId]); + return rows?.[0] || null; +} + +function detectAiAgentTargetFile(prompt) { + const text = String(prompt || ""); + const filePatterns = [ + /(?:modify|change|edit|update|set|turn|enable|disable|fix|put|add|remove|optimize)\s+(?:in\s+)?(?:the\s+)?(?:file\s+)?([^\s]+\.(?:yml|yaml|json|properties|txt|conf|cfg|toml|ini|js|ts|css|html|xml|md|lua|py))/i, + /(?:in|at)\s+([^\s]+\.(?:yml|yaml|json|properties|txt|conf|cfg|toml|ini|js|ts|css|html|xml|md|lua|py))/i, + /([^\s]+\.(?:yml|yaml|json|properties|txt|conf|cfg|toml|ini|js|ts|css|html|xml|md|lua|py))\s+(?:and\s+)?(?:modify|change|edit|update|set|turn|enable|disable|fix|put|add|remove|optimize)/i, + ]; + for (const pattern of filePatterns) { + const match = text.match(pattern); + if (match?.[1]) return sanitizeAiAgentFilePath(match[1]); + } + return ""; +} + +function sanitizeAiAgentFilePath(value) { + let rel = String(value || "").replace(/\0/g, "").trim(); + rel = rel.replace(/^["'`]+|["'`]+$/g, "").replace(/[.,!?;:]+$/g, "").trim(); + while (rel.startsWith("/")) rel = rel.slice(1); + if (!rel || rel.length > 2048 || /[\r\n]/.test(rel)) return ""; + return rel; +} + +async function readAiAgentFileContent(serverName, relPath) { + const pathValue = sanitizeAiAgentFilePath(relPath); + if (!pathValue) return null; + const ctx = await resolveRemoteFsContext(serverName); + if (!ctx.remote) return null; + const full = safeJoinUnix(ctx.baseDir, pathValue); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/read", { path: full, encoding: "utf8" }, 120000); + if (status !== 200 || !json?.ok) return null; + return typeof json.content === "string" ? json.content : ""; +} + +function buildBrowserCompatibleAiAgentSystemPrompt({ serverName, perms, hasImage = false }) { + const currentServerName = String(serverName || "").trim(); + const canReadFiles = !!perms?.files_read; + const canWriteFiles = !!perms?.files_create; + const canDeleteFiles = !!perms?.files_delete; + const canReadConsole = !!perms?.console_read; + + const baseIdentity = `You are ADPanel Agent, an intelligent AI assistant integrated into ADPanel - an enterprise server management panel that lets users host and manage their Docker-based servers (FiveM, Minecraft, and more). + +CORE BEHAVIOR: +1. NEVER use diacritical marks, accents, or special unicode characters in ANY language. Write as if you only have a standard US English keyboard. +2. Reply naturally, like a fast voice assistant. +3. Default to one short sentence. Use two short sentences only when needed. +4. Prefer plain text. Use markdown only when it clearly helps. +5. For greetings, answer in 2-6 words. +6. For actions, say what you did or what you need next. +7. Prioritize the user's latest message and the live server context over older chat history if they conflict. +8. Never narrate internal planning, hidden reasoning, or which tool you are about to use. +9. Never say phrases like "The user wants", "I need to", "I should use", "Plan", or "Current page server".`; + + const nativeToolLines = [ + "Sensitive server actions, console actions, and backup actions are executed through native backend tools.", + `Current server: ${currentServerName || "current-server"}.`, + "Do not explain your internal planning or mention internal tool names in the visible reply.", + "Do not emit SERVER_START, SERVER_STOP, SERVER_RESTART, or SERVER_KILL lines.", + "If backend tools are needed, let the backend orchestrator handle them; never write planning text such as \"I need to use inspect_server\".", + "Use the current server when the user means this server or current server.", + "Backend permissions are re-checked on every native action, so do not claim success before the tool result confirms it.", + "For live console checks or crash diagnosis, prefer the native console inspection tool.", + "For real console execution, only use the native console command tool when the user explicitly asked to run a command.", + "For backup restore or delete, inspect the available backups first when the reference is unclear." + ].join("\n"); + + let systemPrompt; + if (canReadFiles) { + systemPrompt = `${baseIdentity} + +You have access to this server's file system. You can browse, read, create, edit, and manage files directly. + +${nativeToolLines} + +Use these commands (one per line, no extra formatting): + +FILE_LIST:. +FILE_LIST:config +FILE_READ:config/settings.yml +${canWriteFiles ? `FILE_MKDIR:plugins/myfolder` : ""} +${canDeleteFiles ? `FILE_DELETE:old-file.txt` : ""} + +${canWriteFiles ? `To create or modify a file: +FILE_CREATE:path/to/file.txt +---FILE_CONTENT_START--- +(file content here) +---FILE_CONTENT_END--- + +To modify an existing file: +FILE_WRITE:path/to/file.yml +---FILE_CONTENT_START--- +(complete modified file content) +---FILE_CONTENT_END---` : ""} + +IMPORTANT RULES: +1. Put each command on its own line +2. Path comes immediately after the colon (no spaces) +3. Use . for root directory listing +4. Use relative paths (no leading /) +5. Only list files or perform file operations when the user explicitly asks for it +6. When modifying a file, output the COMPLETE file content +7. After completing a task, briefly describe what you did +8. Do NOT automatically list files or show server files unless the user specifically asks to see them +9. When the user greets you or asks general questions, respond conversationally without performing file operations +10. When asked what ADPanel is, explain it is an enterprise Docker server management panel with file management, console, scheduling, backups, store, and AI agent features`; + } else { + systemPrompt = `${baseIdentity} + +You do NOT have file system access for this user. Do not attempt to list, read, or modify any server files. + +${nativeToolLines} + +Instead, provide helpful advice, explain concepts, troubleshoot issues, and guide users on configuring their servers. If the user asks you to manage files, let them know they need file management permissions and suggest contacting their server administrator.`; + } + + if (canReadConsole) { + systemPrompt += "\n\nWhen the user shares server logs or console output, analyze them carefully and provide helpful troubleshooting advice. Identify errors, warnings, and suggest specific fixes."; + } + + if (hasImage) { + systemPrompt += "\n\nYou also have vision capabilities. When the user provides an image, analyze it and describe what you see. If the image appears to be a screenshot or configuration, provide helpful insights about it."; + } + + return systemPrompt; +} + +async function buildBackgroundAiAgentMessages({ prompt, serverName, userEmail }) { + const safePrompt = sanitizeAiAgentPrompt(prompt); + const perms = await getEffectivePermsForUserOnServer(userEmail, serverName); + const canReadFiles = !!perms?.files_read; + + let userPrompt = safePrompt; + const targetFile = canReadFiles ? detectAiAgentTargetFile(safePrompt) : ""; + const modifyIntent = /(?:set|change|modify|edit|update|enable|disable|fix|optimize|turn|make|add|remove|replace)/i.test(safePrompt); + if (targetFile && modifyIntent) { + const fileContent = await readAiAgentFileContent(serverName, targetFile).catch(() => null); + if (typeof fileContent === "string") { + userPrompt = `User request: ${safePrompt} + +The file "${targetFile}" currently contains: +\`\`\` +${fileContent.slice(0, AI_AGENT_FILE_READ_MAX_CHARS)} +\`\`\` + +Apply the user's requested changes. You MUST output the complete modified file using this exact format: +FILE_WRITE:${targetFile} +---FILE_CONTENT_START--- +(paste the ENTIRE file with changes applied here) +---FILE_CONTENT_END---`; + } + } + + return [ + { + role: "system", + content: buildBrowserCompatibleAiAgentSystemPrompt({ serverName, perms }), + }, + { role: "user", content: userPrompt }, + ]; +} + +function extractAiAgentFileContent(fullContent, afterMarker) { + const afterIdx = String(fullContent || "").indexOf(afterMarker); + if (afterIdx === -1) return null; + const afterWrite = String(fullContent || "").slice(afterIdx + afterMarker.length); + const startMarker = "---FILE_CONTENT_START---"; + const endMarker = "---FILE_CONTENT_END---"; + const startIdx = afterWrite.indexOf(startMarker); + const endIdx = afterWrite.indexOf(endMarker); + if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) { + return afterWrite.slice(startIdx + startMarker.length, endIdx).trim(); + } + const codeBlockMatch = afterWrite.match(/```(?:\w*\n)?([\s\S]*?)```/); + if (codeBlockMatch) return codeBlockMatch[1].trim(); + + const lines = afterWrite.split("\n"); + const contentLines = []; + let foundContent = false; + for (const line of lines) { + const trimmed = line.trim(); + if (!foundContent && trimmed === "") continue; + if (trimmed.startsWith("FILE_") || trimmed.startsWith("---")) break; + foundContent = true; + contentLines.push(line); + } + const fallback = contentLines.join("\n").trim(); + if (fallback) return fallback; + return null; +} + +function parseAiAgentFileOperations(content) { + const raw = String(content || "").trim(); + if (!raw) return { operations: [], message: "" }; + const operations = []; + let message = raw; + + const pushOperation = (action, filePath, opContent = undefined) => { + const normalizedAction = String(action || "").trim().toLowerCase().replace(/^file_/, ""); + if (!["list", "read", "mkdir", "delete", "create", "write"].includes(normalizedAction)) return; + const safePath = sanitizeAiAgentFilePath(filePath); + if (!safePath) return; + if (operations.some((op) => op.action === normalizedAction && op.path === safePath)) return; + if (normalizedAction === "create" || normalizedAction === "write") { + if (opContent === undefined || opContent === null) return; + operations.push({ action: normalizedAction, path: safePath, content: String(opContent) }); + return; + } + operations.push({ action: normalizedAction, path: safePath }); + }; + + const parseXmlOperation = (action, innerContent) => { + const pathMatch = String(innerContent || "").match(/([^<]+)<\/path>/i); + const contentMatch = String(innerContent || "").match(/([\s\S]*?)<\/content>/i); + let filePath = pathMatch?.[1] ? pathMatch[1].trim() : ""; + if (!filePath) { + const plainPath = String(innerContent || "").trim().split(/\s+/)[0]; + if (plainPath && !plainPath.startsWith("<")) filePath = plainPath; + } + const normalizedAction = String(action || "").trim().toLowerCase().replace(/^file_/, ""); + if (normalizedAction === "create" || normalizedAction === "write") { + pushOperation(normalizedAction, filePath, contentMatch ? contentMatch[1].trim() : null); + } else { + pushOperation(normalizedAction, filePath); + } + }; + + const toolCallPattern = /\[TOOL_CALL\]\s*\{tool\s*=>\s*"([^"]+)",\s*args\s*=>\s*\{([^}]*)\}\s*\}\s*\[\/TOOL_CALL\]/gi; + let toolMatch; + while ((toolMatch = toolCallPattern.exec(raw)) !== null) { + const toolName = String(toolMatch[1] || "").toLowerCase().replace(/^file_/, ""); + const argsContent = String(toolMatch[2] || ""); + const pathMatch = argsContent.match(/--path\s+"([^"]+)"/i); + const contentArgMatch = argsContent.match(/--content\s+"([^"]*)"/i); + if (pathMatch?.[1]) { + pushOperation(toolName, pathMatch[1], contentArgMatch ? contentArgMatch[1] : undefined); + } + message = message.replace(toolMatch[0], ""); + } + + const invokePattern = /\s*<(FILE_\w+)>([\s\S]*?)<\/\1>\s*<\/invoke>/gi; + let invokeMatch; + while ((invokeMatch = invokePattern.exec(raw)) !== null) { + parseXmlOperation(invokeMatch[1], invokeMatch[2]); + message = message.replace(invokeMatch[0], ""); + } + + const directPattern = /<(FILE_\w+)>([\s\S]*?)<\/\1>/gi; + let directMatch; + while ((directMatch = directPattern.exec(raw)) !== null) { + parseXmlOperation(directMatch[1], directMatch[2]); + message = message.replace(directMatch[0], ""); + } + + const antmlPattern = /]*>([\s\S]*?)<\/antml:invoke>/gi; + let antmlMatch; + while ((antmlMatch = antmlPattern.exec(raw)) !== null) { + parseXmlOperation(antmlMatch[1], antmlMatch[2]); + message = message.replace(antmlMatch[0], ""); + } + + const pushSimple = (regex, action) => { + let match; + regex.lastIndex = 0; + while ((match = regex.exec(raw)) !== null) { + pushOperation(action, match[1]); + message = message.replace(match[0], ""); + } + }; + + pushSimple(/FILE_LIST:([^\s\n]+)/gi, "list"); + pushSimple(/FILE_READ:([^\s\n]+)/gi, "read"); + pushSimple(/FILE_MKDIR:([^\s\n]+)/gi, "mkdir"); + pushSimple(/FILE_DELETE:([^\s\n]+)/gi, "delete"); + + for (const action of ["CREATE", "WRITE"]) { + const regex = new RegExp(`FILE_${action}:([^\\s\\n]+)`, "i"); + const match = raw.match(regex); + if (!match) continue; + const filePath = sanitizeAiAgentFilePath(match[1]); + if (!filePath) continue; + const marker = match[0]; + const fileContent = extractAiAgentFileContent(raw, marker); + if (fileContent !== null) { + pushOperation(action.toLowerCase(), filePath, fileContent); + const removeRegex = new RegExp(`FILE_${action}:[^\\n]*[\\s\\S]*?---FILE_CONTENT_END---`, "i"); + message = message.replace(removeRegex, ""); + message = message.replace(new RegExp(`FILE_${action}:[^\\n]*[\\s\\S]*?\`\`\`[\\s\\S]*?\`\`\``, "i"), ""); + } + } + + message = message + .replace(/---FILE_CONTENT_START---|---FILE_CONTENT_END---/g, "") + .replace(/<\/?antml:[^>]+>/g, "") + .replace(/<\/?invoke>/g, "") + .replace(/<\/?FILE_\w+>/g, "") + .replace(/[^<]*<\/path>/g, "") + .replace(/[\s\S]*?<\/content>/g, "") + .replace(/\[TOOL_CALL\][\s\S]*?\[\/TOOL_CALL\]/g, "") + .replace(/FILE_(?:LIST|READ|MKDIR|DELETE|CREATE|WRITE):[^\s\n]+/gi, "") + .trim(); + + return { operations, message }; +} + +function summarizeAiAgentDirectory(entries) { + const list = Array.isArray(entries) ? entries.slice(0, AI_AGENT_FILE_LIST_MAX_ITEMS) : []; + if (!list.length) return "(empty)"; + return list.map((entry) => { + const name = String(entry?.name || "").trim(); + const isDir = entry?.isDirectory === true || entry?.type === "dir" || entry?.type === "directory"; + const size = !isDir && entry?.size ? ` (${entry.size} bytes)` : ""; + return `${isDir ? "[dir]" : "[file]"} ${name}${size}`; + }).join("\n"); +} + +async function executeAiAgentFileOperations({ operations, serverName, userEmail, req }) { + if (!operations.length) return []; + const perms = await getEffectivePermsForUserOnServer(userEmail, serverName); + const summaries = []; + + for (const op of operations.slice(0, 12)) { + const action = String(op.action || "").trim().toLowerCase(); + const relPath = sanitizeAiAgentFilePath(op.path); + if (!relPath) { + summaries.push("Skipped one file operation because the path was invalid."); + continue; + } + + const needsRead = action === "list" || action === "read"; + const needsWrite = action === "create" || action === "write" || action === "mkdir"; + const needsDelete = action === "delete"; + if (needsRead && !perms?.files_read) { + summaries.push(`No permission to read ${relPath}.`); + continue; + } + if (needsWrite && !perms?.files_create) { + summaries.push(`No permission to modify ${relPath}.`); + continue; + } + if (needsDelete && !perms?.files_delete) { + summaries.push(`No permission to delete ${relPath}.`); + continue; + } + + try { + const ctx = await resolveRemoteFsContext(serverName); + if (!ctx.remote) { + summaries.push(`Could not access node files for ${serverName}.`); + continue; + } + const full = safeJoinUnix(ctx.baseDir, relPath); + + if (action === "list") { + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/list", { path: full }, 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); + 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); + 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); + 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); + 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}.`); + } + } catch (err) { + summaries.push(`File operation failed for ${relPath}: ${String(err?.message || err).slice(0, 200)}.`); + } + } + + if (operations.length > 12) { + summaries.push(`Skipped ${operations.length - 12} extra file operation(s) to keep this job bounded.`); + } + + return summaries; +} + +async function postProcessAiAgentResponse({ content, serverName, userEmail, req }) { + const parsed = parseAiAgentFileOperations(content); + if (!parsed.operations.length) { + return String(content || "").trim(); + } + + const summaries = await executeAiAgentFileOperations({ + operations: parsed.operations, + serverName, + userEmail, + req, + }); + return [parsed.message, summaries.join("\n\n")].map((part) => String(part || "").trim()).filter(Boolean).join("\n\n") || "Done."; +} + +async function markPlannerItemDoneAfterAgentJob(row) { + if (String(row?.source || "") !== "scheduler_planner_next") return; + const itemId = parseInt(row?.source_ref, 10); + const serverName = String(row?.server_name || "").trim(); + if (!Number.isFinite(itemId) || !serverName) return; + const sortOrder = await getNextPlannerSortOrder(serverName, true).catch(() => 0); + await db.query( + "UPDATE server_planner_items SET is_done = 1, sort_order = ?, updated_by_email = ? WHERE id = ? AND server_name = ? AND is_done = 0", + [sortOrder, String(row.user_email || "scheduler").toLowerCase(), itemId, serverName] + ); +} + +async function processAiAgentJob(jobId) { + const row = await claimAiAgentJob(jobId); + if (!row) return; + + try { + const user = await findUserById(row.user_id) || await findUserByEmail(row.user_email); + if (!userCanUseAdpanelAgent(user)) { + const error = new Error("User no longer has ADPanel Agent access."); + error.status = 403; + throw error; + } + + const entry = await findServer(row.server_name); + const serverName = String(entry?.name || row.server_name || "").trim(); + if (!entry || !serverName) { + const error = new Error("Server not found."); + error.status = 404; + throw error; + } + if (!user.admin && !(await userHasAccessToServer(user.email, serverName))) { + const error = new Error("User no longer has access to this server."); + error.status = 403; + throw error; + } + + const ready = assertAiProviderReady(row.provider, row.model); + const req = buildBackgroundAgentRequest(user, row.source); + const messages = await buildBackgroundAiAgentMessages({ + prompt: row.prompt, + serverName, + userEmail: user.email, + }); + + const result = await completeAiChatConversation({ + req, + provider: ready.provider, + settings: ready.settings, + model: ready.model, + messages, + serverContext: { currentServer: serverName }, + }); + + let assistantContent = String(result?.content || "").trim() || "Done."; + assistantContent = await postProcessAiAgentResponse({ + content: assistantContent, + serverName, + userEmail: user.email, + req, + }); + + await db.query( + "INSERT INTO ai_messages (chat_id, role, content, image_data, thinking_time_ms, thinking_content, model) VALUES (?, 'assistant', ?, NULL, ?, ?, ?)", + [ + row.chat_id, + assistantContent, + Number.isFinite(Number(result?.thinking_time_ms)) ? Number(result.thinking_time_ms) : null, + String(result?.thinking_content || "").trim() || null, + formatAiMessageModelLabel(ready.provider, ready.model), + ] + ); + await db.query("UPDATE ai_chats SET updated_at = NOW() WHERE id = ?", [row.chat_id]); + await db.query( + "UPDATE ai_agent_jobs SET status = 'completed', completed_at = NOW(), error = NULL WHERE id = ?", + [row.id] + ); + await markPlannerItemDoneAfterAgentJob(row).catch((err) => { + console.warn(`[ai-agent-jobs] Could not mark planner item done for job ${row.id}:`, err?.message || err); + }); + } catch (err) { + const message = String(err?.message || "ADPanel Agent job failed.").slice(0, 1000); + console.error(`[ai-agent-jobs] Job ${row.id} failed:`, message); + try { + await db.query( + "INSERT INTO ai_messages (chat_id, role, content, image_data, thinking_time_ms, thinking_content, model) VALUES (?, 'assistant', ?, NULL, NULL, NULL, ?)", + [row.chat_id, `Error: ${message}`, formatAiMessageModelLabel(row.provider, row.model)] + ); + await db.query("UPDATE ai_chats SET updated_at = NOW() WHERE id = ?", [row.chat_id]); + } catch { } + await db.query( + "UPDATE ai_agent_jobs SET status = 'failed', completed_at = NOW(), error = ? WHERE id = ?", + [message, row.id] + ); + } +} + +app.get("/api/ai/selection", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + const user = await getLoggedInUser(req); + const selection = await getSavedAiModelSelectionForUserId(user?.id); + return res.json({ ok: true, selection: selection || null }); +}); + +app.post("/api/ai/selection", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + const user = await getLoggedInUser(req); + const { provider, model } = normalizeAiModelSelectionPayload(req.body || {}); + try { + const selection = await saveAiModelSelectionForUserId(user.id, provider, model); + return res.json({ ok: true, selection }); + } catch (err) { + return res.status(err.status || 400).json({ error: err.message || "failed to save model selection" }); + } +}); + +app.get("/api/ai/jobs/:id", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + await ensureAiChatTablesReady(); + const jobId = parseInt(req.params.id, 10); + if (!Number.isFinite(jobId)) return res.status(400).json({ error: "invalid job id" }); + const user = await getLoggedInUser(req); + const rows = await db.query( + "SELECT id, chat_id, status, error, created_at, started_at, completed_at FROM ai_agent_jobs WHERE id = ? AND user_id = ? LIMIT 1", + [jobId, user.id] + ); + const row = rows?.[0]; + if (!row) return res.status(404).json({ error: "job not found" }); + return res.json({ ok: true, job: row }); +}); + +app.post("/api/ai/chat", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + const { provider, model, messages, serverContext } = req.body || {}; + + if (!provider || !model || !Array.isArray(messages)) { + return res.status(400).json({ error: "provider, model, and messages are required" }); + } + + const providerLower = String(provider).toLowerCase(); + const providerConfig = getAiProviderConfig(providerLower); + + if (!providerConfig) { + return res.status(400).json({ error: "invalid provider" }); + } + + const env = readEnvFile(); + const settings = getStoredAiProviderSettings(providerLower, env); + + if (providerConfig.requiresKey !== false && !settings.apiKey) { + return res.status(400).json({ error: "API key not configured for this provider" }); + } + if (providerConfig.requiresBaseUrl && !settings.baseUrl) { + return res.status(400).json({ error: "Base URL not configured for this provider" }); + } + + try { + const currentUser = await getLoggedInUser(req); + if (currentUser?.id) { + await saveAiModelSelectionForUserId(currentUser.id, providerLower, model).catch((selectionErr) => { + console.warn("[ai-selection] Failed to persist selected model:", selectionErr?.message || selectionErr); + }); + } + const result = await completeAiChatConversation({ + req, + provider: providerLower, + settings, + model, + messages, + serverContext, + }); + return res.json({ ok: true, ...result }); + } catch (err) { + console.error(`[ai-chat] Error calling ${providerLower}:`, err.message); + return res.status(500).json({ error: err.message || "AI request failed" }); + } +}); + +async function proxyOpenAiCompatible(provider, settings, model, messages, options = {}) { + const providerConfig = getAiProviderConfig(provider); + const endpoint = provider === 'openai-compatible' + ? appendPathToBaseUrl(settings.baseUrl, 'chat/completions') + : providerConfig?.chatEndpoint; + if (!endpoint) throw new Error('Unknown provider'); + + const headers = { + 'Content-Type': 'application/json', + ...buildAiProviderAuthHeaders(provider, settings.apiKey) + }; + + const transformedMessages = messages.map(m => { + if (m.image && typeof m.image === 'string' && m.image.startsWith('data:image/')) { + return { + role: m.role, + content: [ + { type: 'text', text: m.content || '' }, + { type: 'image_url', image_url: { url: m.image } } + ] + }; + } + return { role: m.role, content: m.content }; + }); + + const body = JSON.stringify({ + model, + messages: transformedMessages, + max_tokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 2048, + temperature: Number.isFinite(options.temperature) ? options.temperature : 0.7 + }); + + const response = await proxyAiRequest(endpoint, { method: 'POST', headers, body }); + + if (response.status !== 200) { + throw new Error(extractAiErrorMessage(response)); + } + + const parsed = parseOpenAiCompatibleResponsePayload(response.data); + return { + content: parsed.content || response.data?.choices?.[0]?.message?.content || '', + thinking_content: parsed.thinking_content || '', + }; +} + +async function proxyAnthropicAi(apiKey, model, messages, options = {}) { + const endpoint = 'https://api.anthropic.com/v1/messages'; + const systemInstruction = buildAnthropicSystemMessage(messages); + const body = { + model, + max_tokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 2048, + messages: buildAnthropicInitialMessages(messages), + }; + + if (systemInstruction) { + body.system = systemInstruction; + } + if (Number.isFinite(options.temperature)) { + body.temperature = options.temperature; + } + + const response = await proxyAiRequest(endpoint, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + ...buildAiProviderAuthHeaders('anthropic', apiKey), + }, + body: JSON.stringify(body), + }); + + if (response.status !== 200) { + throw new Error(extractAiErrorMessage(response)); + } + + const parsed = parseAnthropicResponsePayload(response.data); + return { + content: parsed.content || normalizeAnthropicTextContent(response.data?.content), + thinking_content: parsed.thinking_content || '', + }; +} + +async function proxyGoogleAi(apiKey, model, messages, options = {}) { + const endpoint = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(model)}:generateContent?key=${encodeURIComponent(apiKey)}`; + + const systemMessage = messages.find(m => m.role === 'system'); + const contents = messages.filter(m => m.role !== 'system').map(m => { + const parts = [{ text: m.content || '' }]; + + if (m.image && typeof m.image === 'string' && m.image.startsWith('data:image/')) { + const match = m.image.match(/^data:(image\/[^;]+);base64,(.+)$/); + if (match) { + parts.push({ + inline_data: { + mime_type: match[1], + data: match[2] + } + }); + } + } + + return { + role: m.role === 'assistant' ? 'model' : 'user', + parts + }; + }); + + const requestBody = { + contents, + generationConfig: { + maxOutputTokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 2048, + temperature: Number.isFinite(options.temperature) ? options.temperature : 0.7 + } + }; + + if (systemMessage) { + requestBody.systemInstruction = { parts: [{ text: systemMessage.content }] }; + } + + const body = JSON.stringify(requestBody); + const headers = { 'Content-Type': 'application/json' }; + + const response = await proxyAiRequest(endpoint, { method: 'POST', headers, body }); + + if (response.status !== 200) { + const errMsg = response.data?.error?.message || `API error: ${response.status}`; + throw new Error(errMsg); + } + + const parsed = parseGoogleResponsePayload(response.data); + return { + content: parsed.content || response.data?.candidates?.[0]?.content?.parts?.[0]?.text || '', + thinking_content: parsed.thinking_content || '', + }; +} + +async function proxyCohereAiLegacyV1(apiKey, model, messages, options = {}) { + const endpoint = 'https://api.cohere.ai/v1/chat'; + const systemMessage = messages.find(m => m.role === 'system'); + const lastMessage = messages[messages.length - 1]; + const chatHistory = messages.slice(0, -1).filter(m => m.role !== 'system').map(m => ({ + role: m.role === 'assistant' ? 'CHATBOT' : 'USER', + message: m.content + })); + + const requestBody = { + model, + message: lastMessage?.content || '', + chat_history: chatHistory + }; + + if (systemMessage) { + requestBody.preamble = systemMessage.content; + } + if (Number.isFinite(options.temperature)) { + requestBody.temperature = options.temperature; + } + if (Number.isFinite(options.maxTokens)) { + requestBody.max_tokens = options.maxTokens; + } + + const body = JSON.stringify(requestBody); + const headers = { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${apiKey}` + }; + + const response = await proxyAiRequest(endpoint, { method: 'POST', headers, body }); + + if (response.status !== 200) { + const errMsg = response.data?.message || response.data?.error || `API error: ${response.status}`; + throw new Error(errMsg); + } + + const parsed = parseCohereResponsePayload(response.data); + return { + content: parsed.content || response.data?.text || '', + thinking_content: parsed.thinking_content || '', + }; +} + +function buildCohereStandardMessages(messages) { + return (Array.isArray(messages) ? messages : []) + .map((message) => { + const role = String(message?.role || '').trim().toLowerCase(); + if (!['system', 'user', 'assistant'].includes(role)) return null; + return { + role, + content: typeof message?.content === 'string' ? message.content : String(message?.content || ''), + }; + }) + .filter(Boolean); +} + +async function proxyCohereAi(apiKey, model, messages, options = {}) { + const endpoint = 'https://api.cohere.com/v2/chat'; + const body = JSON.stringify({ + stream: false, + model, + messages: buildCohereStandardMessages(messages), + max_tokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 2048, + temperature: Number.isFinite(options.temperature) ? options.temperature : 0.7, + }); + + const headers = { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${apiKey}` + }; + + const response = await proxyAiRequest(endpoint, { method: 'POST', headers, body }); + if (response.status === 200) { + const parsed = parseCohereResponsePayload(response.data); + return { + content: parsed.content || normalizeCohereNativeTextContent(response.data?.message?.content) || String(response.data?.text || '').trim(), + thinking_content: parsed.thinking_content || '', + }; + } + + if ([404, 405].includes(response.status)) { + return proxyCohereAiLegacyV1(apiKey, model, messages, options); + } + + const errMsg = response.data?.message || response.data?.error || `API error: ${response.status}`; + throw new Error(errMsg); +} + +async function proxyHuggingFaceAi(apiKey, model, messages, options = {}) { + const chatEndpoint = 'https://router.huggingface.co/v1/chat/completions'; + + const chatBody = JSON.stringify({ + model, + messages, + max_tokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 2048, + temperature: Number.isFinite(options.temperature) ? options.temperature : 0.7 + }); + + const headers = { + 'Content-Type': 'application/json', + 'Authorization': `Bearer ${apiKey}` + }; + + let response = await proxyAiRequest(chatEndpoint, { method: 'POST', headers, body: chatBody }); + + if (response.status !== 200) { + const errStr = JSON.stringify(response.data || {}).toLowerCase(); + const isUnsupported = errStr.includes('no endpoints') || errStr.includes('not supported') || errStr.includes('not found'); + + if (isUnsupported) { + console.log(`[ai-hf] Chat API not supported for ${model}, trying inference API`); + const inferenceEndpoint = `https://router.huggingface.co/hf-inference/models/${encodeURIComponent(model)}/v1/chat/completions`; + + response = await proxyAiRequest(inferenceEndpoint, { method: 'POST', headers, body: chatBody }); + + if (response.status !== 200) { + const textEndpoint = `https://router.huggingface.co/hf-inference/models/${encodeURIComponent(model)}`; + + const systemMsg = messages.find(m => m.role === 'system'); + let prompt = ''; + if (systemMsg) prompt += `System: ${systemMsg.content}\n\n`; + for (const msg of messages.filter(m => m.role !== 'system')) { + prompt += `${msg.role === 'user' ? 'User' : 'Assistant'}: ${msg.content}\n`; + } + prompt += 'Assistant:'; + + const textBody = JSON.stringify({ + inputs: prompt, + parameters: { + max_new_tokens: Number.isFinite(options.maxTokens) ? options.maxTokens : 2048, + temperature: Number.isFinite(options.temperature) ? options.temperature : 0.7, + return_full_text: false + } + }); + + response = await proxyAiRequest(textEndpoint, { method: 'POST', headers, body: textBody }); + + if (response.status === 200) { + let content = ''; + if (Array.isArray(response.data)) { + content = response.data[0]?.generated_text || ''; + } else if (response.data?.generated_text) { + content = response.data.generated_text; + } + const extracted = extractThinkingSectionsFromTaggedText(content); + return { + content: extracted.content || content, + thinking_content: extracted.thinking_content || '', + }; + } + } + } + + if (response.status !== 200) { + const errMsg = response.data?.error?.message || response.data?.error || response.data?.message || `API error: ${response.status}`; + throw new Error(errMsg); + } + } + + const parsed = parseOpenAiCompatibleResponsePayload(response.data); + return { + content: parsed.content || response.data?.choices?.[0]?.message?.content || '', + thinking_content: parsed.thinking_content || '', + }; +} + +app.get("/api/ai/models/:provider", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + const provider = String(req.params.provider || '').toLowerCase(); + const providerConfig = getAiProviderConfig(provider); + + if (!providerConfig) return res.status(400).json({ error: "invalid provider" }); + + const env = readEnvFile(); + const settings = getStoredAiProviderSettings(provider, env); + + if (providerConfig.requiresKey !== false && !settings.apiKey) { + return res.status(400).json({ error: "API key not configured" }); + } + if (providerConfig.requiresBaseUrl && !settings.baseUrl) { + return res.status(400).json({ error: "Base URL not configured" }); + } + + try { + const discovery = await fetchAvailableAiModels(provider, settings); + const finalSettings = { + ...settings, + ...(discovery?.resolvedBaseUrl ? { baseUrl: discovery.resolvedBaseUrl } : {}) + }; + + return res.json({ + ok: true, + models: discovery.models, + providerState: buildAiProviderState(provider, finalSettings, { includeBaseUrl: await isAdmin(req) }) + }); + } catch (err) { + console.error(`[ai-models] Error fetching models for ${provider}:`, err.message); + return res.status(502).json({ error: err.message || 'failed to load models' }); + } +}); + + +let aiChatTablesReady = false; +let aiChatTablesInitPromise = null; + +async function initAiChatTables() { + if (aiChatTablesReady) return; + if (aiChatTablesInitPromise) return aiChatTablesInitPromise; + aiChatTablesInitPromise = initAiChatTablesUnsafe().finally(() => { + aiChatTablesInitPromise = null; + }); + return aiChatTablesInitPromise; +} + +async function initAiChatTablesUnsafe() { + if (!db || !db.query) { + console.warn('[ai-chat] Database not available, skipping table initialization'); + return; + } + + try { + await db.query(` + CREATE TABLE IF NOT EXISTS ai_chats ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + user_email VARCHAR(255) NOT NULL, + title VARCHAR(255) NOT NULL DEFAULT 'New Chat', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY idx_ai_chats_user (user_email), + KEY idx_ai_chats_created (created_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + await db.query(` + CREATE TABLE IF NOT EXISTS ai_messages ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + chat_id BIGINT UNSIGNED NOT NULL, + role ENUM('user', 'assistant', 'system') NOT NULL, + content LONGTEXT NOT NULL, + image_data LONGTEXT NULL, + thinking_time_ms INT UNSIGNED NULL, + thinking_content LONGTEXT NULL, + model VARCHAR(255) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY idx_ai_messages_chat (chat_id) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + try { + await db.query(`ALTER TABLE ai_chats ADD COLUMN user_email VARCHAR(255) NOT NULL DEFAULT '' AFTER id`); + console.log('[ai-chat] Added user_email column to ai_chats'); + } catch (alterErr) { + if (!alterErr.message.includes('Duplicate column')) { + } + } + + try { + await db.query(`CREATE INDEX idx_ai_chats_user ON ai_chats(user_email)`); + } catch (idxErr) { + } + + try { + await db.query(`ALTER TABLE ai_messages ADD COLUMN image_data LONGTEXT NULL AFTER content`); + console.log('[ai-chat] Added image_data column to ai_messages'); + } catch (alterErr) { + if (!alterErr.message.includes('Duplicate column')) { + console.log('[ai-chat] image_data column already exists or error:', alterErr.message); + } + } + + try { + await db.query(`ALTER TABLE ai_messages ADD COLUMN thinking_content LONGTEXT NULL AFTER thinking_time_ms`); + console.log('[ai-chat] Added thinking_content column to ai_messages'); + } catch (alterErr) { + if (!alterErr.message.includes('Duplicate column')) { + console.log('[ai-chat] thinking_content column already exists or error:', alterErr.message); + } + } + + await db.query(` + CREATE TABLE IF NOT EXISTS user_ai_model_selections ( + user_id BIGINT UNSIGNED NOT NULL, + provider VARCHAR(64) NOT NULL, + model VARCHAR(255) NOT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (user_id), + KEY idx_user_ai_model_provider (provider), + CONSTRAINT fk_user_ai_model_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + await db.query(` + CREATE TABLE IF NOT EXISTS ai_agent_jobs ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + chat_id BIGINT UNSIGNED NOT NULL, + user_id BIGINT UNSIGNED NOT NULL, + user_email VARCHAR(255) NOT NULL, + server_name VARCHAR(120) NOT NULL, + provider VARCHAR(64) NOT NULL, + model VARCHAR(255) NOT NULL, + prompt LONGTEXT NOT NULL, + status ENUM('queued','running','completed','failed') NOT NULL DEFAULT 'queued', + source VARCHAR(64) NOT NULL DEFAULT 'manual', + source_ref VARCHAR(255) NULL, + error TEXT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + started_at TIMESTAMP NULL, + completed_at TIMESTAMP NULL, + PRIMARY KEY (id), + KEY idx_ai_agent_jobs_user (user_id, created_at), + KEY idx_ai_agent_jobs_status (status, created_at), + KEY idx_ai_agent_jobs_chat (chat_id), + CONSTRAINT fk_ai_agent_jobs_chat FOREIGN KEY (chat_id) REFERENCES ai_chats(id) ON DELETE CASCADE, + CONSTRAINT fk_ai_agent_jobs_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + aiChatTablesReady = true; + console.log('[ai-chat] Tables initialized successfully'); + resumeQueuedAiAgentJobs().catch((err) => { + console.warn('[ai-agent-jobs] Failed to resume queued jobs:', err?.message || err); + }); + } catch (err) { + console.error('[ai-chat] Failed to init tables:', err.message); + } +} + +async function ensureAiChatTablesReady() { + if (aiChatTablesReady) return; + await initAiChatTables(); +} + +let plannerTablesReady = false; + +async function initPlannerTables() { + if (!db || !db.query) { + console.warn('[planner] Database not available, skipping table initialization'); + return; + } + + try { + await db.query(` + CREATE TABLE IF NOT EXISTS server_planner_items ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + server_name VARCHAR(120) NOT NULL, + title VARCHAR(255) NOT NULL, + prompt LONGTEXT NOT NULL, + is_done TINYINT(1) NOT NULL DEFAULT 0, + sort_order INT NOT NULL DEFAULT 0, + created_by_email VARCHAR(255) NOT NULL, + updated_by_email VARCHAR(255) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY idx_server_planner_server (server_name), + KEY idx_server_planner_sort (server_name, is_done, sort_order, updated_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + plannerTablesReady = true; + console.log('[planner] Tables initialized successfully'); + } catch (err) { + console.error('[planner] Failed to init tables:', err.message); + } +} + +setTimeout(() => initAiChatTables(), 3000); +setTimeout(() => initPlannerTables(), 3200); + +app.get("/api/ai/chats", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + if (!db || !db.query) { + return res.json({ ok: true, chats: [] }); + } + + const userEmail = String(req.session.user || '').toLowerCase(); + if (!userEmail) return res.status(401).json({ error: 'not authenticated' }); + + try { + const chats = await db.query(` + SELECT c.id, c.title, c.created_at, c.updated_at, + (SELECT COUNT(*) FROM ai_messages WHERE chat_id = c.id) as message_count + FROM ai_chats c + WHERE c.user_email = ? + ORDER BY c.updated_at DESC + LIMIT 100 + `, [userEmail]); + return res.json({ ok: true, chats: chats || [] }); + } catch (err) { + console.error('[ai-chats] Error:', err.message); + return res.json({ ok: true, chats: [] }); + } +}); + +app.post("/api/ai/chats", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + if (!db || !db.query) { + return res.status(503).json({ error: 'Database not available' }); + } + + const userEmail = String(req.session.user || '').toLowerCase(); + if (!userEmail) return res.status(401).json({ error: 'not authenticated' }); + + const { title } = req.body || {}; + const chatTitle = String(title || 'New Chat').trim().slice(0, 255); + + try { + const result = await db.query( + 'INSERT INTO ai_chats (user_email, title) VALUES (?, ?)', + [userEmail, chatTitle] + ); + return res.json({ ok: true, chatId: result.insertId, title: chatTitle }); + } catch (err) { + console.error('[ai-chats] Create error:', err.message); + if (err.message.includes("doesn't exist")) { + await initAiChatTables(); + try { + const result = await db.query( + 'INSERT INTO ai_chats (user_email, title) VALUES (?, ?)', + [userEmail, chatTitle] + ); + return res.json({ ok: true, chatId: result.insertId, title: chatTitle }); + } catch (retryErr) { + console.error('[ai-chats] Retry failed:', retryErr.message); + } + } + return res.status(500).json({ error: 'Failed to create chat' }); + } +}); + +app.get("/api/ai/chats/:id", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + if (!db || !db.query) { + return res.status(503).json({ error: 'Database not available' }); + } + + const chatId = parseInt(req.params.id, 10); + if (!chatId || isNaN(chatId)) return res.status(400).json({ error: 'Invalid chat ID' }); + + const userEmail = String(req.session.user || '').toLowerCase(); + if (!userEmail) return res.status(401).json({ error: 'not authenticated' }); + + try { + const chatRows = await db.query('SELECT * FROM ai_chats WHERE id = ? AND user_email = ?', [chatId, userEmail]); + const chat = chatRows[0]; + if (!chat) return res.status(404).json({ error: 'Chat not found' }); + + const messages = await db.query( + 'SELECT id, role, content, image_data, thinking_time_ms, thinking_content, model, created_at FROM ai_messages WHERE chat_id = ? ORDER BY created_at ASC', + [chatId] + ); + + return res.json({ ok: true, chat, messages: messages || [] }); + } catch (err) { + console.error('[ai-chats] Get error:', err.message); + return res.status(500).json({ error: 'Failed to load chat' }); + } +}); + +app.put("/api/ai/chats/:id", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + if (!db || !db.query) { + return res.status(503).json({ error: 'Database not available' }); + } + + const chatId = parseInt(req.params.id, 10); + if (!chatId || isNaN(chatId)) return res.status(400).json({ error: 'Invalid chat ID' }); + + const userEmail = String(req.session.user || '').toLowerCase(); + if (!userEmail) return res.status(401).json({ error: 'not authenticated' }); + + const { title } = req.body || {}; + const chatTitle = String(title || 'New Chat').trim().slice(0, 255); + + try { + const result = await db.query('UPDATE ai_chats SET title = ? WHERE id = ? AND user_email = ?', [chatTitle, chatId, userEmail]); + if (result.affectedRows === 0) return res.status(404).json({ error: 'Chat not found' }); + return res.json({ ok: true }); + } catch (err) { + console.error('[ai-chats] Update error:', err.message); + return res.status(500).json({ error: 'Failed to update chat' }); + } +}); + +app.delete("/api/ai/chats/:id", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + if (!db || !db.query) { + return res.status(503).json({ error: 'Database not available' }); + } + + const chatId = parseInt(req.params.id, 10); + if (!chatId || isNaN(chatId)) return res.status(400).json({ error: 'Invalid chat ID' }); + + const userEmail = String(req.session.user || '').toLowerCase(); + if (!userEmail) return res.status(401).json({ error: 'not authenticated' }); + + try { + const result = await db.query('DELETE FROM ai_chats WHERE id = ? AND user_email = ?', [chatId, userEmail]); + if (result.affectedRows === 0) return res.status(404).json({ error: 'Chat not found' }); + await db.query('DELETE FROM ai_messages WHERE chat_id = ?', [chatId]); + return res.json({ ok: true }); + } catch (err) { + console.error('[ai-chats] Delete error:', err.message); + return res.status(500).json({ error: 'Failed to delete chat' }); + } +}); + +app.post("/api/ai/chats/:id/messages", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await hasAgentAccess(req))) return res.status(403).json({ error: "no agent access" }); + + if (!db || !db.query) { + return res.status(503).json({ error: 'Database not available' }); + } + + const chatId = parseInt(req.params.id, 10); + if (!chatId || isNaN(chatId)) return res.status(400).json({ error: 'Invalid chat ID' }); + + const userEmail = String(req.session.user || '').toLowerCase(); + if (!userEmail) return res.status(401).json({ error: 'not authenticated' }); + + try { + const chatRows = await db.query('SELECT id FROM ai_chats WHERE id = ? AND user_email = ?', [chatId, userEmail]); + if (!chatRows || !chatRows[0]) return res.status(404).json({ error: 'Chat not found' }); + } catch (err) { + console.error('[ai-chats] Ownership check error:', err.message); + return res.status(500).json({ error: 'Failed to verify chat ownership' }); + } + + const { role, content, thinking_time_ms, thinking_content, model, image_data } = req.body || {}; + + if (!role || !content) { + return res.status(400).json({ error: 'role and content are required' }); + } + + const validRoles = ['user', 'assistant', 'system']; + if (!validRoles.includes(role)) { + return res.status(400).json({ error: 'Invalid role' }); + } + + let sanitizedImageData = null; + if (image_data && typeof image_data === 'string') { + if (image_data.startsWith('data:image/')) { + if (image_data.length <= 10 * 1024 * 1024) { + sanitizedImageData = image_data; + } + } + } + + try { + const result = await db.query( + 'INSERT INTO ai_messages (chat_id, role, content, image_data, thinking_time_ms, thinking_content, model) VALUES (?, ?, ?, ?, ?, ?, ?)', + [chatId, role, content, sanitizedImageData, thinking_time_ms || null, String(thinking_content || '').trim() || null, model || null] + ); + + await db.query('UPDATE ai_chats SET updated_at = NOW() WHERE id = ?', [chatId]); + + if (role === 'user') { + const chatRows = await db.query('SELECT title FROM ai_chats WHERE id = ?', [chatId]); + const chat = chatRows[0]; + if (chat && chat.title === 'New Chat') { + const autoTitle = String(content).slice(0, 50).trim() + (content.length > 50 ? '...' : ''); + await db.query('UPDATE ai_chats SET title = ? WHERE id = ?', [autoTitle, chatId]); + } + } + + return res.json({ ok: true, messageId: result.insertId }); + } catch (err) { + console.error('[ai-messages] Add error:', err.message); + return res.status(500).json({ error: 'Failed to add message' }); + } +}); + +function derivePlannerTitleFromPrompt(prompt) { + const clean = String(prompt || '').trim().replace(/\s+/g, ' '); + if (!clean) return 'Untitled Prompt'; + return clean.length > 72 ? `${clean.slice(0, 69)}...` : clean; +} + +function sanitizePlannerTitle(value) { + return String(value || '').trim().replace(/\s+/g, ' ').slice(0, 255); +} + +function sanitizePlannerPrompt(value) { + return String(value || '').trim().slice(0, 4000); +} + +async function fetchPlannerItemsForServer(serverName) { + return db.query( + `SELECT id, server_name, title, prompt, is_done, sort_order, created_by_email, updated_by_email, created_at, updated_at + FROM server_planner_items + WHERE server_name = ? + ORDER BY is_done ASC, sort_order ASC, updated_at DESC, id ASC`, + [serverName] + ); +} + +async function getNextActivePlannerItem(serverName) { + const rows = await db.query( + `SELECT id, server_name, title, prompt, is_done, sort_order, created_by_email, updated_by_email, created_at, updated_at + FROM server_planner_items + WHERE server_name = ? AND is_done = 0 AND TRIM(prompt) <> '' + ORDER BY sort_order ASC, updated_at DESC, id ASC + LIMIT 1`, + [serverName] + ); + return rows?.[0] || null; +} + +async function getNextPlannerSortOrder(serverName, isDone) { + const rows = await db.query( + 'SELECT COALESCE(MAX(sort_order), -1) AS max_sort_order FROM server_planner_items WHERE server_name = ? AND is_done = ?', + [serverName, isDone ? 1 : 0] + ); + return Number(rows?.[0]?.max_sort_order ?? -1) + 1; +} + +async function resolvePlannerContext(req, res, rawServerName) { + if (!(await isAuthenticated(req))) { + res.status(401).json({ error: 'not authenticated' }); + return null; + } + if (!db || !db.query) { + res.status(503).json({ error: 'Database not available' }); + return null; + } + if (!plannerTablesReady) { + await initPlannerTables(); + } + + const requestedServerName = String(rawServerName || '').trim(); + if (!requestedServerName) { + res.status(400).json({ error: 'Server name is required' }); + return null; + } + + const entry = await findServer(requestedServerName); + if (!entry) { + res.status(404).json({ error: 'Server not found' }); + return null; + } + + const serverName = String(entry.name || requestedServerName).trim(); + const userEmail = String(req.session?.user || '').trim().toLowerCase(); + if (!userEmail) { + res.status(401).json({ error: 'not authenticated' }); + return null; + } + + if (!(await isAdmin(req)) && !(await userHasAccessToServer(userEmail, serverName))) { + res.status(403).json({ error: 'access denied' }); + return null; + } + + return { serverName, userEmail }; +} + +app.get("/api/servers/:name/planner", async (req, res) => { + const ctx = await resolvePlannerContext(req, res, req.params.name); + if (!ctx) return; + + try { + const items = await fetchPlannerItemsForServer(ctx.serverName); + return res.json({ ok: true, items }); + } catch (err) { + console.error('[planner] List error:', err.message); + return res.status(500).json({ error: 'Failed to load planner items' }); + } +}); + +app.post("/api/servers/:name/planner", async (req, res) => { + const ctx = await resolvePlannerContext(req, res, req.params.name); + if (!ctx) return; + + const prompt = sanitizePlannerPrompt(req.body?.prompt); + const title = sanitizePlannerTitle(req.body?.title) || derivePlannerTitleFromPrompt(prompt); + if (!prompt) { + return res.status(400).json({ error: 'Prompt is required' }); + } + + try { + const sortOrder = await getNextPlannerSortOrder(ctx.serverName, false); + const result = await db.query( + `INSERT INTO server_planner_items + (server_name, title, prompt, is_done, sort_order, created_by_email, updated_by_email) + VALUES (?, ?, ?, 0, ?, ?, ?)`, + [ctx.serverName, title, prompt, sortOrder, ctx.userEmail, ctx.userEmail] + ); + const items = await fetchPlannerItemsForServer(ctx.serverName); + return res.json({ ok: true, itemId: result.insertId, items }); + } catch (err) { + console.error('[planner] Create error:', err.message); + return res.status(500).json({ error: 'Failed to create planner item' }); + } +}); + +app.post("/api/servers/:name/planner/:id/send-agent", async (req, res) => { + const ctx = await resolvePlannerContext(req, res, req.params.name); + if (!ctx) return; + + if (!(await hasAgentAccess(req))) { + return res.status(403).json({ error: "no agent access" }); + } + + const itemId = parseInt(req.params.id, 10); + if (!Number.isFinite(itemId)) { + return res.status(400).json({ error: "Invalid planner item ID" }); + } + + try { + const rows = await db.query( + "SELECT id, title, prompt FROM server_planner_items WHERE id = ? AND server_name = ? LIMIT 1", + [itemId, ctx.serverName] + ); + const item = rows?.[0]; + if (!item) { + return res.status(404).json({ error: "Planner item not found" }); + } + + const user = await getLoggedInUser(req); + const selection = await getSavedAiModelSelectionForUserId(user?.id); + if (!selection) { + return res.status(400).json({ error: "Select an ADPanel Agent model first." }); + } + + const result = await insertAiAgentChatJob({ + user, + serverName: ctx.serverName, + prompt: item.prompt, + provider: selection.provider, + model: selection.model, + source: "planner_send", + sourceRef: item.id, + title: `Planner: ${item.title || deriveAiAgentChatTitle(item.prompt)}`, + }); + + return res.json({ ok: true, ...result }); + } catch (err) { + console.error("[planner] Send to agent error:", err?.message || err); + return res.status(err.status || 500).json({ error: err.message || "Failed to send planner prompt to ADPanel Agent" }); + } +}); + +app.post("/api/servers/:name/planner/reorder", async (req, res) => { + const ctx = await resolvePlannerContext(req, res, req.params.name); + if (!ctx) return; + + const requestedIds = Array.isArray(req.body?.itemIds) + ? req.body.itemIds.map((value) => parseInt(value, 10)).filter((value) => Number.isFinite(value)) + : []; + if (!requestedIds.length) { + return res.status(400).json({ error: 'itemIds are required' }); + } + + try { + const existingActive = await db.query( + 'SELECT id FROM server_planner_items WHERE server_name = ? AND is_done = 0 ORDER BY sort_order ASC, id ASC', + [ctx.serverName] + ); + const existingIds = existingActive.map((row) => Number(row.id)); + const normalizedRequested = requestedIds.filter((id) => existingIds.includes(id)); + const remainingIds = existingIds.filter((id) => !normalizedRequested.includes(id)); + const finalIds = [...normalizedRequested, ...remainingIds]; + + for (let index = 0; index < finalIds.length; index += 1) { + await db.query( + 'UPDATE server_planner_items SET sort_order = ?, updated_by_email = ? WHERE id = ? AND server_name = ?', + [index, ctx.userEmail, finalIds[index], ctx.serverName] + ); + } + + const items = await fetchPlannerItemsForServer(ctx.serverName); + return res.json({ ok: true, items }); + } catch (err) { + console.error('[planner] Reorder error:', err.message); + return res.status(500).json({ error: 'Failed to reorder planner items' }); + } +}); + +app.put("/api/servers/:name/planner/:id", async (req, res) => { + const ctx = await resolvePlannerContext(req, res, req.params.name); + if (!ctx) return; + + const itemId = parseInt(req.params.id, 10); + if (!Number.isFinite(itemId)) { + return res.status(400).json({ error: 'Invalid planner item ID' }); + } + + try { + const rows = await db.query( + 'SELECT id, title, prompt, is_done, sort_order FROM server_planner_items WHERE id = ? AND server_name = ? LIMIT 1', + [itemId, ctx.serverName] + ); + const current = rows?.[0]; + if (!current) { + return res.status(404).json({ error: 'Planner item not found' }); + } + + const body = req.body || {}; + const hasTitle = Object.prototype.hasOwnProperty.call(body, 'title'); + const hasPrompt = Object.prototype.hasOwnProperty.call(body, 'prompt'); + const hasDone = Object.prototype.hasOwnProperty.call(body, 'isDone'); + + const nextPrompt = hasPrompt ? sanitizePlannerPrompt(body.prompt) : String(current.prompt || ''); + if (!nextPrompt) { + return res.status(400).json({ error: 'Prompt is required' }); + } + + const nextTitle = (hasTitle ? sanitizePlannerTitle(body.title) : String(current.title || '').trim()) || derivePlannerTitleFromPrompt(nextPrompt); + const nextIsDone = hasDone ? !!body.isDone : !!current.is_done; + let nextSortOrder = Number(current.sort_order || 0); + + if (nextIsDone !== !!current.is_done) { + nextSortOrder = await getNextPlannerSortOrder(ctx.serverName, nextIsDone); + } + + await db.query( + `UPDATE server_planner_items + SET title = ?, prompt = ?, is_done = ?, sort_order = ?, updated_by_email = ? + WHERE id = ? AND server_name = ?`, + [nextTitle, nextPrompt, nextIsDone ? 1 : 0, nextSortOrder, ctx.userEmail, itemId, ctx.serverName] + ); + + const items = await fetchPlannerItemsForServer(ctx.serverName); + return res.json({ ok: true, items }); + } catch (err) { + console.error('[planner] Update error:', err.message); + return res.status(500).json({ error: 'Failed to update planner item' }); + } +}); + +app.delete("/api/servers/:name/planner/:id", async (req, res) => { + const ctx = await resolvePlannerContext(req, res, req.params.name); + if (!ctx) return; + + const itemId = parseInt(req.params.id, 10); + if (!Number.isFinite(itemId)) { + return res.status(400).json({ error: 'Invalid planner item ID' }); + } + + try { + const result = await db.query( + 'DELETE FROM server_planner_items WHERE id = ? AND server_name = ?', + [itemId, ctx.serverName] + ); + if (!result.affectedRows) { + return res.status(404).json({ error: 'Planner item not found' }); + } + const items = await fetchPlannerItemsForServer(ctx.serverName); + return res.json({ ok: true, items }); + } catch (err) { + console.error('[planner] Delete error:', err.message); + return res.status(500).json({ error: 'Failed to delete planner item' }); + } +}); + +const QUICK_ACTIONS_FILE = path.join(__dirname, "quick-actions.json"); + +const DEFAULT_ADMIN_ACTIONS = [ + { id: 'default-admin-1', title: 'Manage account', icon: 'fa-solid fa-list-check', link: '/settings?panel=account', animation: 'default', newTab: false }, + { id: 'default-admin-2', title: 'Manage servers', icon: 'fa-solid fa-bars-progress', link: '/settings?panel=servers', animation: 'default', newTab: false }, + { id: 'default-admin-3', title: 'ADPanel Site', icon: 'fa-solid fa-globe', link: 'https://ad-panel.com', animation: 'default', newTab: true }, +]; + +const DEFAULT_USER_ACTIONS = [ + { id: 'default-user-1', title: 'Manage account', icon: 'fa-solid fa-list-check', link: '/settings?panel=account', animation: 'default', newTab: false }, +]; + +let _quickActionsCache = null; +let _quickActionsCacheTs = 0; +const QUICK_ACTIONS_CACHE_TTL_MS = 30000; + +function loadQuickActions() { + const now = Date.now(); + if (_quickActionsCache && (now - _quickActionsCacheTs) < QUICK_ACTIONS_CACHE_TTL_MS) return _quickActionsCache; + try { + if (fs.existsSync(QUICK_ACTIONS_FILE)) { + const data = fs.readFileSync(QUICK_ACTIONS_FILE, "utf8"); + const parsed = JSON.parse(data); + + if (Array.isArray(parsed.actions) && !parsed.admin && !parsed.user) { + const result = { + admin: parsed.actions, + user: DEFAULT_USER_ACTIONS + }; + _quickActionsCache = result; + _quickActionsCacheTs = now; + return result; + } + + const result = { + admin: Array.isArray(parsed.admin) ? parsed.admin : DEFAULT_ADMIN_ACTIONS, + user: Array.isArray(parsed.user) ? parsed.user : DEFAULT_USER_ACTIONS + }; + _quickActionsCache = result; + _quickActionsCacheTs = now; + return result; + } + } catch (err) { + console.error("[quick-actions] Failed to load:", err); + } + const result = { + admin: DEFAULT_ADMIN_ACTIONS, + user: DEFAULT_USER_ACTIONS + }; + _quickActionsCache = result; + _quickActionsCacheTs = now; + return result; +} + +function saveQuickActions(actions) { + try { + safeWriteJson(QUICK_ACTIONS_FILE, { ...actions, updatedAt: Date.now() }); + _quickActionsCache = null; + _quickActionsCacheTs = 0; + return true; + } catch (err) { + console.error("[quick-actions] Failed to save:", err); + return false; + } +} + +app.get("/api/settings/quick-actions", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const actions = loadQuickActions(); + return res.json({ ok: true, actions }); +}); + +app.post("/api/settings/quick-actions", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const { admin, user } = req.body || {}; + + const validateList = (list, name) => { + if (!Array.isArray(list)) return { valid: false, error: `${name} actions must be an array` }; + if (list.length > 6) return { valid: false, error: `Maximum of 6 ${name} quick actions allowed` }; + + const validItems = []; + for (const action of list) { + const title = String(action.title || "").trim(); + const link = String(action.link || "").trim(); + const icon = String(action.icon || "fa-solid fa-star").trim(); + const animation = String(action.animation || "default").trim(); + const newTab = Boolean(action.newTab); + const id = String(action.id || `qa-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`).trim(); + + if (!title || title.length > 30) return { valid: false, error: `Invalid title for action: ${title || 'empty'}` }; + if (!link) return { valid: false, error: `Link is required for action: ${title}` }; + if (!link.startsWith('/') && !link.startsWith('http://') && !link.startsWith('https://')) { + return { valid: false, error: `Invalid link format for action: ${title}` }; + } + + const cleanIcon = icon.replace(/[^a-zA-Z0-9\-\s]/g, ''); + const validAnimations = ['default', 'pulse', 'shake', 'bounce', 'glow', 'scale', 'rotate', 'none']; + const cleanAnimation = validAnimations.includes(animation) ? animation : 'default'; + + let scaleValue = parseFloat(action.scaleValue); + if (isNaN(scaleValue) || scaleValue < 0.1 || scaleValue > 5) scaleValue = 1.05; + + validItems.push({ id, title, link, icon: cleanIcon, animation: cleanAnimation, newTab, scaleValue }); + } + return { valid: true, items: validItems }; + }; + + const adminResult = validateList(admin || [], 'admin'); + if (!adminResult.valid) return res.status(400).json({ error: adminResult.error }); + + const userResult = validateList(user || [], 'user'); + if (!userResult.valid) return res.status(400).json({ error: userResult.error }); + + const success = saveQuickActions({ + admin: adminResult.items, + user: userResult.items + }); + + if (success) { + return res.json({ ok: true }); + } else { + return res.status(500).json({ error: "Failed to save quick actions" }); + } +}); + +const DATABASE_CONFIG_FILE = path.join(__dirname, "database-config.json"); + +const _processIsRoot = (typeof process.getuid === 'function') ? process.getuid() === 0 : false; + +function _privBashSpawn(cmd, opts) { + if (_processIsRoot) return spawn("bash", ["-c", cmd], opts); + return spawn("sudo", ["-n", "bash", "-c", cmd], opts); +} + +function _privSpawn(command, args, opts) { + if (_processIsRoot) return spawn(command, args, opts); + return spawn("sudo", ["-n", command, ...args], opts); +} + +function _userSpawn(user, command, args, opts) { + if (_processIsRoot) return spawn("runuser", ["-u", user, "--", command, ...args], opts); + return spawn("sudo", ["-n", "-u", user, command, ...args], opts); +} + +function _privExecSync(cmd, opts) { + const { execSync } = require('child_process'); + if (_processIsRoot) return execSync(cmd, opts); + return execSync(`sudo -n bash -c ${JSON.stringify(cmd)}`, opts); +} + +let _dbConfigCache = null; +let _dbConfigCacheTs = 0; +const DB_CONFIG_CACHE_TTL_MS = 30000; + +function loadDatabaseConfig() { + const now = Date.now(); + if (_dbConfigCache && (now - _dbConfigCacheTs) < DB_CONFIG_CACHE_TTL_MS) return _dbConfigCache; + try { + if (!fs.existsSync(DATABASE_CONFIG_FILE)) { + const result = { enabled: false, config: null, users: [] }; + _dbConfigCache = result; + _dbConfigCacheTs = now; + return result; + } + const raw = fs.readFileSync(DATABASE_CONFIG_FILE, "utf8").trim(); + if (!raw) { + const result = { enabled: false, config: null, users: [] }; + _dbConfigCache = result; + _dbConfigCacheTs = now; + return result; + } + const data = JSON.parse(raw); + const result = { + enabled: !!data.enabled, + config: data.config || null, + users: Array.isArray(data.users) ? data.users : [] + }; + _dbConfigCache = result; + _dbConfigCacheTs = now; + return result; + } catch { + const result = { enabled: false, config: null, users: [] }; + _dbConfigCache = result; + _dbConfigCacheTs = now; + return result; + } +} + +function saveDatabaseConfig(data) { + try { + fs.writeFileSync(DATABASE_CONFIG_FILE, JSON.stringify(data, null, 2), { encoding: "utf8", mode: 0o600 }); + try { fs.chmodSync(DATABASE_CONFIG_FILE, 0o600); } catch (e) { } + _dbConfigCache = null; + _dbConfigCacheTs = 0; + return true; + } catch (err) { + console.error("[database] Failed to save config:", err); + return false; + } +} + +async function checkPackageInstalled(packageName) { + return new Promise((resolve) => { + const child = spawn("which", [packageName], { stdio: "ignore" }); + child.on("close", (code) => { + resolve(code === 0); + }); + child.on("error", () => resolve(false)); + }); +} + + +// ─── Nginx Cleanup Helpers for Secure DB Proxy ────────────────── +function removeDbSnippetIncludes(snippetName) { + const dirs = ['/etc/nginx/sites-enabled', '/etc/nginx/sites-available']; + for (const dir of dirs) { + try { + if (!fs.existsSync(dir)) continue; + for (const f of fs.readdirSync(dir)) { + const full = path.join(dir, f); + try { + const content = fs.readFileSync(full, 'utf8'); + if (content.includes(snippetName)) { + const cleaned = content.replace(new RegExp(`\\n?\\s*include\\s+/etc/nginx/snippets/${snippetName};`, 'g'), ''); + if (cleaned !== content) { + fs.writeFileSync(full, cleaned); + console.log(`[db-proxy] Removed ${snippetName} include from ${full}`); + } + } + } catch { } + } + } catch { } + } +} + +function migrateDbToolsNginxOnStartup() { + const { execSync } = require('child_process'); + let changed = false; + + try { + // phpMyAdmin: migrate from public snippet to internal-only server + const phpmyadminInstalled = fs.existsSync("/usr/share/phpmyadmin/index.php"); + const internalConf = '/etc/nginx/conf.d/adpanel-phpmyadmin-internal.conf'; + + if (phpmyadminInstalled && !fs.existsSync(internalConf)) { + console.log('[db-proxy] Migrating phpMyAdmin to internal-only nginx server...'); + configurePhpMyAdminWebServer(); + changed = true; + } else if (phpmyadminInstalled) { + // Still ensure public snippet is empty and includes are removed + const snippet = '/etc/nginx/snippets/phpmyadmin.conf'; + if (fs.existsSync(snippet)) { + const content = fs.readFileSync(snippet, 'utf8'); + if (content.includes('location /phpmyadmin') || content.includes('fastcgi_pass')) { + fs.writeFileSync(snippet, '# phpMyAdmin - served via secure token proxy only\n', { mode: 0o644 }); + removeDbSnippetIncludes('phpmyadmin.conf'); + changed = true; + console.log('[db-proxy] Replaced old public phpMyAdmin snippet with placeholder'); + } + } + } + + // pgAdmin: ensure public snippet is empty + const pgadminSnippet = '/etc/nginx/snippets/pgadmin4.conf'; + if (fs.existsSync(pgadminSnippet)) { + const content = fs.readFileSync(pgadminSnippet, 'utf8'); + if (content.includes('proxy_pass') || content.includes('location')) { + fs.writeFileSync(pgadminSnippet, '# pgAdmin4 - served via secure token proxy only\n', { mode: 0o644 }); + removeDbSnippetIncludes('pgadmin4.conf'); + changed = true; + console.log('[db-proxy] Replaced old public pgAdmin4 snippet with placeholder'); + } + } + + if (changed) { + try { + execSync('nginx -t && systemctl reload nginx', { stdio: 'pipe', timeout: 15000 }); + console.log('[db-proxy] Nginx reloaded after migration'); + } catch (e) { + console.warn('[db-proxy] Nginx reload failed:', e.message); + try { execSync('systemctl restart nginx', { stdio: 'pipe', timeout: 15000 }); } catch { } + } + } + } catch (e) { + console.warn('[db-proxy] Startup migration warning:', e.message); + } +} + +function detectPhpFpmSocket() { + try { + const files = fs.readdirSync('/run/php/'); + const versioned = files + .filter(f => /^php\d+\.\d+-fpm\.sock$/.test(f)) + .sort() + .reverse(); + if (versioned.length > 0) return `/run/php/${versioned[0]}`; + } catch { } + if (fs.existsSync('/run/php/php-fpm.sock')) return '/run/php/php-fpm.sock'; + for (const p of ['/var/run/php-fpm.sock', '/run/php-fpm/www.sock']) { + if (fs.existsSync(p)) return p; + } + return '/run/php/php-fpm.sock'; +} + +function writeSystemFileWithPrivilegeFallback(filePath, content, mode = 0o644) { + try { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, content, { mode }); + return true; + } catch (err) { + try { + const encoded = Buffer.from(String(content), 'utf8').toString('base64'); + const modeStr = Number(mode).toString(8).padStart(4, '0'); + _privExecSync( + `mkdir -p ${JSON.stringify(path.dirname(filePath))} && printf %s ${JSON.stringify(encoded)} | base64 -d > ${JSON.stringify(filePath)} && chmod ${modeStr} ${JSON.stringify(filePath)}`, + { stdio: 'pipe', timeout: 20000 } + ); + return true; + } catch (privErr) { + console.error(`[file-write] Failed to write ${filePath}:`, privErr?.message || err?.message || String(err)); + return false; + } + } +} + +async function installPhpMyAdmin() { + return new Promise((resolve) => { + console.log("[database] Checking phpMyAdmin installation..."); + + const phpmyadminInstalled = fs.existsSync("/usr/share/phpmyadmin/index.php"); + const phpFpmAvailable = fs.existsSync(detectPhpFpmSocket()); + if (phpmyadminInstalled && phpFpmAvailable) { + console.log("[database] phpMyAdmin and PHP-FPM are already installed"); + resolve(true); + return; + } + + console.log("[database] Installing PHP-FPM and phpMyAdmin..."); + + const installCmd = ` + set -e + export DEBIAN_FRONTEND=noninteractive + + apt-get update -qq + + # Install PHP-FPM and required extensions first + apt-get install -y --no-install-recommends \\ + php-fpm php-mysql php-mbstring php-zip php-gd php-curl php-xml php-cli + + # Install phpMyAdmin — skip Apache recommends + apt-get install -y --no-install-recommends phpmyadmin + + # If Apache was pulled in anyway, stop and disable it — Nginx handles web traffic + if systemctl is-active apache2 >/dev/null 2>&1; then + systemctl stop apache2 2>/dev/null || true + fi + systemctl disable apache2 2>/dev/null || true + + # Ensure PHP-FPM is running + PHP_FPM_SVC=$(systemctl list-units --type=service --state=running,exited --no-legend | grep -oP 'php[\\d.]+-fpm\\.service' | sort -rV | head -1) + if [ -z "$PHP_FPM_SVC" ]; then + # Not running yet — find the newest installed version + PHP_FPM_SVC=$(systemctl list-unit-files --type=service --no-legend | grep -oP 'php[\\d.]+-fpm\\.service' | sort -rV | head -1) + fi + if [ -n "$PHP_FPM_SVC" ]; then + systemctl enable "$PHP_FPM_SVC" 2>/dev/null || true + systemctl restart "$PHP_FPM_SVC" 2>/dev/null || true + fi + `.trim(); + + const installChild = _privBashSpawn(installCmd, { + shell: false, + env: { ...process.env, DEBIAN_FRONTEND: "noninteractive" } + }); + + installChild.stdout.on("data", (data) => { + const line = data.toString().trim(); + if (line) console.log("[database] " + line); + }); + + installChild.stderr.on("data", (data) => { + const line = data.toString().trim(); + if (line && !line.includes("debconf")) console.error("[database] " + line); + }); + + installChild.on("close", async (installCode) => { + if (installCode === 0 || fs.existsSync("/usr/share/phpmyadmin/index.php")) { + console.log("[database] phpMyAdmin and PHP-FPM installed successfully"); + await ensureMySqlRunning(); + resolve(true); + } else { + console.error("[database] Installation failed with code:", installCode); + resolve(false); + } + }); + + installChild.on("error", (err) => { + console.error("[database] Installation error:", err); + resolve(false); + }); + }); +} + +function configurePhpMyAdminWebServer() { + try { + try { + _privExecSync('systemctl stop apache2 2>/dev/null; systemctl disable apache2 2>/dev/null', { stdio: 'pipe', timeout: 10000 }); + } catch { } + + const fpmSocket = detectPhpFpmSocket(); + console.log(`[phpmyadmin] Using PHP-FPM socket: ${fpmSocket}`); + + const internalPort = dbProxy.PHPMYADMIN_INTERNAL_PORT; + + // Internal-only nginx server — only reachable from Node.js proxy on 127.0.0.1 + const internalConf = `# phpMyAdmin internal server - ADPanel managed +# Only accessible from the Node.js token-based proxy on 127.0.0.1:${internalPort} +server { + listen 127.0.0.1:${internalPort}; + server_name _; + + location /phpmyadmin { + root /usr/share/; + index index.php index.html index.htm; + + location ~ ^/phpmyadmin/(.+\\.php)$ { + try_files $uri =404; + root /usr/share/; + fastcgi_pass unix:${fpmSocket}; + fastcgi_index index.php; + fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; + include /etc/nginx/fastcgi_params; + fastcgi_read_timeout 300; + fastcgi_buffers 16 16k; + fastcgi_buffer_size 32k; + } + + location ~* ^/phpmyadmin/(.+\\.(jpg|jpeg|gif|css|png|js|ico|html|xml|txt|svg|woff|woff2|ttf))$ { + root /usr/share/; + expires 30d; + access_log off; + } + } +} +`; + + // Write internal server config + if (!writeSystemFileWithPrivilegeFallback('/etc/nginx/conf.d/adpanel-phpmyadmin-internal.conf', internalConf, 0o644)) { + throw new Error('Could not write internal phpMyAdmin nginx server config'); + } + console.log('[phpmyadmin] Internal nginx server written to /etc/nginx/conf.d/adpanel-phpmyadmin-internal.conf'); + + // Replace public snippet with empty placeholder (keeps include lines valid but serves nothing) + if (!writeSystemFileWithPrivilegeFallback('/etc/nginx/snippets/phpmyadmin.conf', '# phpMyAdmin - served via secure token proxy only\n', 0o644)) { + throw new Error('Could not write phpMyAdmin placeholder snippet'); + } + console.log('[phpmyadmin] Public snippet replaced with placeholder'); + + // Remove old /phpmyadmin include lines from site configs to keep them clean + removeDbSnippetIncludes('phpmyadmin.conf'); + + const snippetsDir = '/etc/nginx/snippets'; + if (!fs.existsSync(path.join(snippetsDir, 'pgadmin4.conf'))) { + writeSystemFileWithPrivilegeFallback(path.join(snippetsDir, 'pgadmin4.conf'), '# pgAdmin4 - served via secure token proxy only\n', 0o644); + } + if (!fs.existsSync(path.join(snippetsDir, 'mongodb.conf'))) { + writeSystemFileWithPrivilegeFallback(path.join(snippetsDir, 'mongodb.conf'), '# Placeholder - MongoDB not installed\n', 0o644); + } + + try { + _privExecSync('nginx -t && systemctl reload nginx', { stdio: 'pipe', timeout: 15000 }); + } catch (e) { + console.error('[phpmyadmin] Nginx reload error:', e.message); + try { _privExecSync('systemctl restart nginx', { stdio: 'pipe', timeout: 15000 }); } catch { } + } + + console.log('[phpmyadmin] Web server configuration complete (internal proxy only)'); + return true; + } catch (e) { + console.error('[phpmyadmin] Web server config error:', e.message); + return false; + } +} + +function disablePhpMyAdminWebServer() { + try { + const placeholderContent = '# phpMyAdmin disabled - placeholder\n'; + writeSystemFileWithPrivilegeFallback('/etc/nginx/snippets/phpmyadmin.conf', placeholderContent, 0o644); + + // Remove internal server config + try { + const internalConf = '/etc/nginx/conf.d/adpanel-phpmyadmin-internal.conf'; + _privExecSync(`rm -f ${JSON.stringify(internalConf)}`, { stdio: 'pipe', timeout: 10000 }); + } catch { } + + // Remove old include lines from site configs + removeDbSnippetIncludes('phpmyadmin.conf'); + + try { + _privExecSync('nginx -t && systemctl reload nginx', { stdio: 'pipe', timeout: 15000 }); + } catch (e) { console.error('[phpmyadmin] Nginx reload error:', e.message); } + + console.log('[phpmyadmin] Web server configuration disabled'); + return true; + } catch (e) { + console.error('[phpmyadmin] Web server disable error:', e.message); + return false; + } +} + +function configurePhpMyAdmin(dbConfig) { + if (!dbConfig) return false; + + const validatedHost = validateDbHost(dbConfig.host); + if (!validatedHost) { + console.error("[database] Invalid host for phpMyAdmin config:", dbConfig.host); + return false; + } + + const validatedPort = validatePort(dbConfig.port); + if (!validatedPort) { + console.error("[database] Invalid port for phpMyAdmin config:", dbConfig.port); + return false; + } + + const blowfishSecret = crypto.randomBytes(32).toString("hex"); + + const safeHost = escapePhpSingleQuote(validatedHost); + const safePort = String(validatedPort); + + // Protect the panel database from phpMyAdmin access + const panelDbName = String(process.env.MYSQL_DATABASE || process.env.MYSQL_DB || "adpanel").trim(); + const safeDbRegex = escapePhpSingleQuote(panelDbName.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')); + + const configContent = ``; + + const configPaths = [ + "/etc/phpmyadmin/config.inc.php", + "/usr/share/phpmyadmin/config.inc.php" + ]; + + for (const configPath of configPaths) { + if (writeSystemFileWithPrivilegeFallback(configPath, configContent, 0o644)) { + console.log("[database] phpMyAdmin config written to", configPath); + return true; + } else { + console.warn("[database] Could not write to", configPath); + } + } + + console.error("[database] Failed to write phpMyAdmin config to any location"); + return false; +} + +const PGADMIN_CONFIG_FILE = path.join(__dirname, "pgadmin-config.json"); + +function loadPgAdminConfig() { + try { + if (fs.existsSync(PGADMIN_CONFIG_FILE)) { + return JSON.parse(fs.readFileSync(PGADMIN_CONFIG_FILE, "utf8")); + } + } catch { } + return { enabled: false, users: [] }; +} + +function savePgAdminConfig(data) { + try { + fs.writeFileSync(PGADMIN_CONFIG_FILE, JSON.stringify(data, null, 2), { mode: 0o600 }); + return true; + } catch (err) { + console.error("[pgadmin] Failed to save config:", err); + return false; + } +} + +const installationJobs = new Map(); + +function createInstallJob(type) { + const jobId = `${type}-${Date.now()}`; + installationJobs.set(jobId, { + type, + status: 'starting', + progress: 0, + message: 'Starting installation...', + startedAt: Date.now(), + completedAt: null, + error: null, + result: null + }); + return jobId; +} + +function updateInstallJob(jobId, updates) { + const job = installationJobs.get(jobId); + if (job) { + Object.assign(job, updates); + } +} + +function getInstallJob(jobId) { + return installationJobs.get(jobId) || null; +} + +setInterval(() => { + try { + const now = Date.now(); + for (const [id, job] of installationJobs.entries()) { + if (job.completedAt) { + if (now - job.completedAt > 30 * 60 * 1000) installationJobs.delete(id); + } else if (job.startedAt && (now - job.startedAt > 60 * 60 * 1000)) { + installationJobs.delete(id); + } + } + } catch (err) { console.debug("[installJobs] sweep error:", err.message); } +}, 300_000).unref(); + +app.get("/api/settings/database/install-progress/:jobId", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const job = getInstallJob(req.params.jobId); + if (!job) { + const jobId = req.params.jobId; + if (jobId.startsWith('mongodb-')) { + const config = loadMongoDBConfig(); + if (config.enabled) { + return res.json({ status: 'completed', progress: 100, message: 'Installation complete!' }); + } + } else if (jobId.startsWith('pgadmin-')) { + const config = loadPgAdminConfig(); + if (config.enabled) { + return res.json({ status: 'completed', progress: 100, message: 'Installation complete!' }); + } + } + return res.status(404).json({ error: "Job not found" }); + } + return res.json(job); +}); + +async function installPostgreSQLAndPgAdmin(email, password, jobId, listenHost = '127.0.0.1', listenPort = '5432') { + const runCmd = (cmd, timeoutMs = 120000) => new Promise((resolve) => { + console.log("[pgadmin] Running install step..."); + const child = _privBashSpawn(cmd, { + shell: false, + env: { ...process.env, DEBIAN_FRONTEND: "noninteractive" } + }); + let stdout = "", stderr = ""; + child.stdout.on("data", (d) => { stdout += d.toString(); }); + child.stderr.on("data", (d) => { stderr += d.toString(); }); + const timeout = setTimeout(() => { + console.log(`[pgadmin] Command timed out after ${timeoutMs}ms`); + child.kill(); + resolve({ code: -1, stdout, stderr: "Command timed out" }); + }, timeoutMs); + child.on("close", (code) => { + clearTimeout(timeout); + if (code !== 0) console.log(`[pgadmin] Command exited with code ${code}`); + resolve({ code, stdout, stderr }); + }); + child.on("error", (err) => { clearTimeout(timeout); resolve({ code: 1, stdout, stderr: err.message }); }); + }); + + const validatedHost = validateDbHost(listenHost); + if (!validatedHost) { + if (jobId) updateInstallJob(jobId, { status: 'failed', error: 'Invalid listen host address', completedAt: Date.now() }); + return; + } + const validatedPort = validatePort(listenPort); + if (!validatedPort) { + if (jobId) updateInstallJob(jobId, { status: 'failed', error: 'Invalid listen port', completedAt: Date.now() }); + return; + } + listenHost = validatedHost; + listenPort = String(validatedPort); + const postgresListenHost = isLocalOnlyDbHost(listenHost) ? 'localhost' : listenHost; + + try { + console.log("[pgadmin] Starting pgAdmin4 installation (handles fresh install and reinstall)..."); + + if (jobId) updateInstallJob(jobId, { status: 'running', progress: 5, message: 'Preparing installation environment...' }); + console.log("[pgadmin] Step 0: Pre-installation cleanup..."); + await runCmd(` + # Stop any existing services to avoid conflicts during reinstall + systemctl stop apache2 2>/dev/null || true + + # Clean up any stale Apache pgAdmin configs from previous installs + rm -f /etc/apache2/sites-enabled/pgadmin4.conf 2>/dev/null || true + rm -f /etc/apache2/sites-available/pgadmin4.conf 2>/dev/null || true + rm -f /etc/apache2/conf-enabled/pgadmin4.conf 2>/dev/null || true + + # Clean up stale pgAdmin data directories that might cause issues + rm -rf /var/lib/pgadmin/sessions/* 2>/dev/null || true + + # Remove stale GPG keys and sources to ensure fresh fetch + rm -f /usr/share/keyrings/packages-pgadmin-org.gpg 2>/dev/null || true + rm -f /etc/apt/sources.list.d/pgadmin4.list 2>/dev/null || true + + true + `, 30000); + + if (jobId) updateInstallJob(jobId, { status: 'running', progress: 10, message: 'Adding PostgreSQL repository...' }); + await runCmd(` + if [ ! -f /etc/apt/sources.list.d/pgdg.list ]; then + echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list + wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | apt-key add - 2>/dev/null + fi + `); + + if (jobId) updateInstallJob(jobId, { progress: 20, message: 'Adding pgAdmin4 repository...' }); + console.log("[pgadmin] Step 2: Adding pgAdmin4 repository..."); + await runCmd(` + # Always download fresh GPG key and create sources list + curl -fsS https://www.pgadmin.org/static/packages_pgadmin_org.pub | gpg --batch --yes --dearmor -o /usr/share/keyrings/packages-pgadmin-org.gpg 2>/dev/null || true + echo "deb [signed-by=/usr/share/keyrings/packages-pgadmin-org.gpg] https://ftp.postgresql.org/pub/pgadmin/pgadmin4/apt/$(lsb_release -cs) pgadmin4 main" > /etc/apt/sources.list.d/pgadmin4.list + `); + + if (jobId) updateInstallJob(jobId, { progress: 30, message: 'Updating package lists...' }); + console.log("[pgadmin] Step 3: Updating package lists..."); + const updateRes = await runCmd("DEBIAN_FRONTEND=noninteractive apt-get update -qq", 120000); + if (updateRes.code !== 0) throw new Error("Failed to update packages: " + updateRes.stderr); + + if (jobId) updateInstallJob(jobId, { progress: 40, message: 'Installing PostgreSQL...' }); + console.log("[pgadmin] Step 4: Installing PostgreSQL..."); + const pgRes = await runCmd("DEBIAN_FRONTEND=noninteractive apt-get install -y postgresql postgresql-contrib", 300000); + if (pgRes.code !== 0) throw new Error("Failed to install PostgreSQL: " + pgRes.stderr); + + if (jobId) updateInstallJob(jobId, { progress: 55, message: 'Installing pgAdmin4 web interface...' }); + console.log("[pgadmin] Step 5: Installing pgAdmin4 and Apache..."); + + await runCmd("DEBIAN_FRONTEND=noninteractive apt-get install -y apache2 libapache2-mod-wsgi-py3", 300000); + + const pgaRes = await runCmd("DEBIAN_FRONTEND=noninteractive apt-get install -y pgadmin4-web", 300000); + if (pgaRes.code !== 0) throw new Error("Failed to install pgAdmin4: " + pgaRes.stderr); + + if (jobId) updateInstallJob(jobId, { progress: 62, message: 'Configuring Apache for pgAdmin4...' }); + console.log("[pgadmin] Step 5b: Configuring Apache..."); + + const apachePortsConf = `# Apache ports configuration - managed by ADPanel +# Only listen on localhost:5050 for pgAdmin4 (accessed via secure token proxy only) +Listen 127.0.0.1:5050 +`; + try { + fs.writeFileSync('/etc/apache2/ports.conf', apachePortsConf, { mode: 0o644 }); + console.log("[pgadmin] Apache ports.conf configured for port 5050 only"); + } catch (e) { + console.warn("[pgadmin] Could not write ports.conf:", e.message); + await runCmd("sed -i '/^Listen/d' /etc/apache2/ports.conf 2>/dev/null || true", 10000); + await runCmd("echo 'Listen 127.0.0.1:5050' >> /etc/apache2/ports.conf", 10000); + } + + await runCmd("a2enmod wsgi /dev/null || true", 15000); + await runCmd("a2enmod headers /dev/null || true", 15000); + console.log("[pgadmin] Apache modules configured"); + + const pgadminApacheConf = ` +ServerTokens Prod +ServerSignature Off +Header always unset "X-Powered-By" +Header always set "Server" "webserver" + + + ServerAdmin webmaster@localhost + DocumentRoot /usr/pgadmin4/web + + WSGIDaemonProcess pgadmin processes=1 threads=25 python-home=/usr/pgadmin4/venv + WSGIScriptAlias / /usr/pgadmin4/web/pgAdmin4.wsgi + + + WSGIProcessGroup pgadmin + WSGIApplicationGroup %{GLOBAL} + Require all granted + + + ErrorLog \${APACHE_LOG_DIR}/pgadmin4_error.log + CustomLog \${APACHE_LOG_DIR}/pgadmin4_access.log combined + +`.trim(); + + try { + fs.mkdirSync('/etc/apache2/sites-available', { recursive: true }); + fs.mkdirSync('/etc/apache2/sites-enabled', { recursive: true }); + fs.writeFileSync('/etc/apache2/sites-available/pgadmin4.conf', pgadminApacheConf, { mode: 0o644 }); + + const symlinkTarget = '/etc/apache2/sites-enabled/pgadmin4.conf'; + const symlinkSource = '/etc/apache2/sites-available/pgadmin4.conf'; + try { + if (fs.existsSync(symlinkTarget)) { + fs.unlinkSync(symlinkTarget); + } + fs.symlinkSync(symlinkSource, symlinkTarget); + console.log("[pgadmin] Created pgadmin4 site symlink"); + } catch (symErr) { + await runCmd(`ln -sf ${symlinkSource} ${symlinkTarget} ' /etc/apache2/sites-enabled/*.conf 2>/dev/null | xargs -r rm -f /dev/null | xargs -r rm -f > "\\$1"' _ {} \\;`, 30000); + await runCmd(`find /etc/postgresql -name pg_hba.conf -exec sh -c 'grep -q "host all all ::0/0" "\\$1" || echo "host all all ::0/0 scram-sha-256" >> "\\$1"' _ {} \\;`, 30000); + } + + if (jobId) updateInstallJob(jobId, { progress: 68, message: 'Starting PostgreSQL service...' }); + await runCmd("systemctl enable postgresql 2>/dev/null; systemctl restart postgresql 2>/dev/null || systemctl reload postgresql 2>/dev/null || pg_ctlcluster --skip-systemctl-redirect $(pg_lsclusters -h | head -1 | awk '{print $1, $2}') restart 2>/dev/null || true", 60000); + + if (jobId) updateInstallJob(jobId, { progress: 72, message: 'Checking firewall policy...' }); + await maybeOpenFirewallPort(runCmd, listenPort, listenHost, 'pgadmin'); + + if (jobId) updateInstallJob(jobId, { progress: 80, message: 'Configuring pgAdmin4 web setup...' }); + + const setupScriptPath = '/usr/pgadmin4/bin/setup-web.sh'; + const altSetupPath = '/usr/share/pgadmin4/bin/setup-web.sh'; + let setupPath = fs.existsSync(setupScriptPath) ? setupScriptPath : (fs.existsSync(altSetupPath) ? altSetupPath : null); + + await runCmd(` + mkdir -p /var/lib/pgadmin /var/lib/pgadmin/sessions /var/lib/pgadmin/storage /var/log/pgadmin /etc/pgadmin + chown -R www-data:www-data /var/lib/pgadmin /var/log/pgadmin 2>/dev/null || true + chmod 750 /var/lib/pgadmin + `, 15000); + + if (setupPath) { + const setupCmd = [ + `export PGADMIN_SETUP_EMAIL=${JSON.stringify(email)}`, + `export PGADMIN_SETUP_PASSWORD=${JSON.stringify(password)}`, + `${setupPath} --yes` + ].join('\n'); + + const setupResult = await runCmd(setupCmd, 120000); + console.log("[pgadmin] Setup script result:", setupResult.code, (setupResult.stdout || '').substring(0, 300), (setupResult.stderr || '').substring(0, 200)); + + if (setupResult.code !== 0) { + console.warn("[pgadmin] setup-web.sh did not complete successfully. pgAdmin may require additional setup."); + } + } else { + console.warn("[pgadmin] setup-web.sh not found, skipping initial setup. You may need to configure pgAdmin manually."); + } + + if (jobId) updateInstallJob(jobId, { progress: 88, message: 'Applying performance optimizations...' }); + const pgadminConfigPath = "/etc/pgadmin/config_local.py"; + const perfConfig = ` +# Performance optimizations +SESSION_DB_PATH = '/var/lib/pgadmin/sessions' +STORAGE_DIR = '/var/lib/pgadmin/storage' +LOG_FILE = '/var/log/pgadmin/pgadmin.log' +MAX_SESSION_IDLE_TIME = 3600 +ALLOW_SAVE_PASSWORD = True +SERVER_MODE = True +`.trim(); + try { + fs.mkdirSync(path.dirname(pgadminConfigPath), { recursive: true }); + fs.appendFileSync(pgadminConfigPath, "\n" + perfConfig); + } catch { } + + if (jobId) updateInstallJob(jobId, { progress: 92, message: 'Configuring nginx proxy...' }); + console.log("[pgadmin] Step 10: Configuring nginx (secure token proxy mode)..."); + + try { + // pgAdmin is accessed ONLY through Node.js token proxy → Apache:5050 + // Write empty placeholder snippet to avoid nginx include errors + const snippetPath = "/etc/nginx/snippets/pgadmin4.conf"; + fs.mkdirSync("/etc/nginx/snippets", { recursive: true }); + fs.writeFileSync(snippetPath, "# pgAdmin4 - served via secure token proxy only\n", { mode: 0o644 }); + console.log("[pgadmin] Nginx snippet set to placeholder (proxy-only mode)"); + + // Remove any old public includes from site configs + removeDbSnippetIncludes('pgadmin4.conf'); + console.log("[pgadmin] Site config check complete"); + } catch (err) { + console.warn("[pgadmin] Could not write nginx config:", err.message); + } + + console.log("[pgadmin] Nginx config section done, proceeding to Step 11..."); + + if (jobId) updateInstallJob(jobId, { progress: 95, message: 'Reloading web server...' }); + console.log("[pgadmin] Step 11: Reloading web servers..."); + + const { execSync } = require('child_process'); + + try { + const conflictingConfigs = [ + '/etc/apache2/sites-enabled/000-default.conf', + '/etc/apache2/sites-enabled/default-ssl.conf', + '/etc/apache2/conf-enabled/phpmyadmin.conf', + '/etc/apache2/conf-enabled/serve-cgi-bin.conf', + '/etc/apache2/conf-enabled/pgadmin4.conf' + ]; + for (const conf of conflictingConfigs) { + try { if (fs.existsSync(conf)) fs.unlinkSync(conf); } catch (e) { } + } + console.log("[pgadmin] Removed conflicting Apache configs"); + } catch (e) { console.log("[pgadmin] Conflicting configs cleanup done"); } + + try { + execSync("a2enmod wsgi /dev/null || true", { stdio: 'pipe', timeout: 10000, input: '' }); + execSync("a2enmod headers /dev/null || true", { stdio: 'pipe', timeout: 10000, input: '' }); + console.log("[pgadmin] Enabled wsgi and headers modules"); + } catch (e) { console.log("[pgadmin] wsgi module enable:", e.message); } + + try { + const symlinkTarget = '/etc/apache2/sites-enabled/pgadmin4.conf'; + const symlinkSource = '/etc/apache2/sites-available/pgadmin4.conf'; + if (!fs.existsSync(symlinkTarget) && fs.existsSync(symlinkSource)) { + try { fs.unlinkSync(symlinkTarget); } catch (e) { } + fs.symlinkSync(symlinkSource, symlinkTarget); + } + console.log("[pgadmin] Enabled pgadmin4 site"); + } catch (e) { + try { + execSync("ln -sf /etc/apache2/sites-available/pgadmin4.conf /etc/apache2/sites-enabled/pgadmin4.conf &1", { stdio: 'pipe', timeout: 15000 }); + console.log("[pgadmin] Apache config test passed"); + } catch (e) { + console.warn("[pgadmin] Apache config test failed:", e.message); + try { + try { fs.unlinkSync('/etc/apache2/conf-enabled/pgadmin4.conf'); } catch (e) { } + if (!fs.existsSync('/etc/apache2/sites-enabled/pgadmin4.conf')) { + fs.symlinkSync('/etc/apache2/sites-available/pgadmin4.conf', '/etc/apache2/sites-enabled/pgadmin4.conf'); + } + } catch (fixErr) { } + } + + try { + execSync("systemctl restart apache2 2>&1 || service apache2 restart 2>&1", { stdio: 'pipe', timeout: 60000 }); + console.log("[pgadmin] Apache restarted"); + + try { + const verifyResult = execSync("curl -sI http://127.0.0.1:5050/ 2>&1 | head -5", { stdio: 'pipe', timeout: 10000 }); + const verifyStr = verifyResult.toString(); + if (verifyStr.includes('302') || verifyStr.includes('200')) { + console.log("[pgadmin] Apache pgAdmin verification passed - service responding on port 5050"); + } else if (verifyStr.includes('It works') || verifyStr.includes('Apache')) { + console.warn("[pgadmin] Apache is serving default page instead of pgAdmin - retrying site enable"); + execSync("ln -sf /etc/apache2/sites-available/pgadmin4.conf /etc/apache2/sites-enabled/pgadmin4.conf && systemctl reload apache2", { stdio: 'pipe', timeout: 15000 }); + } + } catch (verifyErr) { + console.debug("[pgadmin] Verification check:", verifyErr.message); + } + } catch (e) { + console.error("[pgadmin] Apache restart error:", e.message); + try { + const status = execSync("systemctl status apache2 2>&1 | tail -20", { stdio: 'pipe', timeout: 10000 }); + console.error("[pgadmin] Apache status:", status.toString()); + } catch { } + } + + try { + const snippetsDir = "/etc/nginx/snippets"; + fs.mkdirSync(snippetsDir, { recursive: true }); + if (!fs.existsSync(path.join(snippetsDir, "phpmyadmin.conf"))) { + fs.writeFileSync(path.join(snippetsDir, "phpmyadmin.conf"), "# Placeholder - phpMyAdmin not installed\n", { mode: 0o644 }); + } + if (!fs.existsSync(path.join(snippetsDir, "mongodb.conf"))) { + fs.writeFileSync(path.join(snippetsDir, "mongodb.conf"), "# Placeholder - MongoDB not installed\n", { mode: 0o644 }); + } + } catch (e) { console.debug("[pgadmin] Could not create placeholder snippets:", e.message); } + + try { + execSync("nginx -t && systemctl restart nginx", { stdio: 'pipe', timeout: 15000 }); + execSync("sleep 2", { stdio: 'pipe' }); + console.log("[pgadmin] Nginx restarted"); + } catch (e) { console.error("[pgadmin] Nginx restart error:", e.message); } + + try { + const finalCheck = execSync("curl -sI http://127.0.0.1:5050/login 2>&1 | head -3", { stdio: 'pipe', timeout: 10000 }); + if (finalCheck.toString().includes('200') || finalCheck.toString().includes('302')) { + console.log("[pgadmin] Final verification passed - pgAdmin4 is ready"); + } + } catch { } + + if (jobId) updateInstallJob(jobId, { status: 'completed', progress: 100, message: 'Installation complete!', completedAt: Date.now() }); + + console.log("[pgadmin] pgAdmin4 installed successfully"); + return { ok: true }; + + } catch (err) { + console.error("[pgadmin] Installation error:", err); + if (jobId) updateInstallJob(jobId, { status: 'failed', error: err.message, completedAt: Date.now() }); + return { ok: false, error: err.message }; + } +} + +async function createPostgresDbUser(username, password, host = '127.0.0.1', port = '5432') { + + const safeUser = username.replace(/[^a-zA-Z0-9_]/g, '').slice(0, 63); + if (!safeUser || safeUser.length < 1) { + console.error("[pgadmin] Invalid username after sanitization"); + return { ok: false, error: "Invalid username" }; + } + + if (/^[0-9]/.test(safeUser)) { + console.error("[pgadmin] Username cannot start with a number"); + return { ok: false, error: "Username cannot start with a number" }; + } + + const reservedNames = ['postgres', 'pg_', 'admin', 'root', 'public']; + if (reservedNames.some(r => safeUser.toLowerCase().startsWith(r))) { + console.error("[pgadmin] Reserved username attempted:", safeUser); + return { ok: false, error: "Reserved username not allowed" }; + } + + const safePass = password.replace(/'/g, "''").slice(0, 128); + + console.log("[pgadmin] Creating PostgreSQL user:", safeUser); + + const runPsqlCommand = (sql) => new Promise((resolve) => { + const child = _userSpawn("postgres", "psql", [], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + let stdout = "", stderr = ""; + child.stdout.on("data", (d) => { stdout += d.toString(); }); + child.stderr.on("data", (d) => { stderr += d.toString(); }); + child.on("close", (code) => resolve({ code, stdout, stderr })); + child.on("error", (err) => resolve({ code: 1, stdout, stderr: err.message })); + const timeout = setTimeout(() => { child.kill(); resolve({ code: -1, stdout, stderr: "timeout" }); }, 10000); + child.on("close", () => clearTimeout(timeout)); + child.stdin.write(sql); + child.stdin.end(); + }); + + try { + await runPsqlCommand(`DROP ROLE IF EXISTS ${safeUser};`); + + const createResult = await runPsqlCommand(`CREATE ROLE ${safeUser} LOGIN PASSWORD '${safePass}' SUPERUSER CREATEDB CREATEROLE;`); + if (createResult.code !== 0 && !createResult.stderr.includes('already exists')) { + throw new Error(createResult.stderr || "Failed to create role"); + } + console.log(`[pgadmin] PostgreSQL user '${safeUser}' created`); + if (isLocalOnlyDbHost(host)) { + console.log("[pgadmin] PostgreSQL user is scoped to the local-only server configuration"); + } + + await new Promise((resolve) => { + const child = _privSpawn("systemctl", ["reload", "postgresql"], { shell: false, stdio: 'pipe' }); + child.on("close", resolve); + child.on("error", resolve); + setTimeout(() => { child.kill(); resolve(); }, 10000); + }); + console.log(`[pgadmin] PostgreSQL user '${safeUser}' configured`); + + return { ok: true }; + } catch (err) { + console.error(`[pgadmin] Failed to create user:`, err.message); + return { ok: false, error: err.message }; + } +} + +const MONGODB_CONFIG_FILE = path.join(__dirname, "mongodb-config.json"); + +function loadMongoDBConfig() { + try { + if (fs.existsSync(MONGODB_CONFIG_FILE)) { + const config = JSON.parse(fs.readFileSync(MONGODB_CONFIG_FILE, "utf8")); + + let migrated = false; + if (Array.isArray(config.users)) { + for (const u of config.users) { + if (u.password && !u.passwordHash) { + u.passwordHash = require('bcrypt').hashSync(u.password, BCRYPT_ROUNDS); + delete u.password; + migrated = true; + } + } + } + if (migrated) { + try { + fs.writeFileSync(MONGODB_CONFIG_FILE, JSON.stringify(config, null, 2), { mode: 0o600 }); + console.log("[mongodb] Migrated legacy plaintext passwords to bcrypt hashes"); + } catch (e) { + console.error("[mongodb] Failed to save migrated config:", e.message); + } + } + + return config; + } + } catch { } + return { enabled: false, users: [] }; +} + +function saveMongoDBConfig(data) { + try { + fs.writeFileSync(MONGODB_CONFIG_FILE, JSON.stringify(data, null, 2), { mode: 0o600 }); + return true; + } catch (err) { + console.error("[mongodb] Failed to save config:", err); + return false; + } +} + +async function installMongoDB(adminUser, adminPassword, jobId, listenHost = '127.0.0.1', listenPort = '27017') { + const runCmd = (cmd, timeoutMs = 120000) => new Promise((resolve) => { + console.log("[mongodb] Running install step..."); + const child = _privBashSpawn(cmd, { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'], + env: { ...process.env, DEBIAN_FRONTEND: "noninteractive" } + }); + let stdout = "", stderr = ""; + child.stdout.on("data", (d) => { stdout += d.toString(); }); + child.stderr.on("data", (d) => { stderr += d.toString(); }); + const timeout = setTimeout(() => { child.kill('SIGKILL'); resolve({ code: -1, stdout, stderr: "Command timed out" }); }, timeoutMs); + child.on("close", (code) => { clearTimeout(timeout); resolve({ code, stdout, stderr }); }); + child.on("error", (err) => { clearTimeout(timeout); resolve({ code: 1, stdout, stderr: err.message }); }); + }); + + const waitFor = async (checkFn, maxAttempts = 30, delayMs = 2000) => { + for (let i = 0; i < maxAttempts; i++) { + if (await checkFn()) return true; + await new Promise(r => setTimeout(r, delayMs)); + } + return false; + }; + + const validatedHost = validateDbHost(listenHost); + if (!validatedHost) { + if (jobId) updateInstallJob(jobId, { status: 'failed', error: 'Invalid listen host address', completedAt: Date.now() }); + return; + } + const validatedPort = validatePort(listenPort); + if (!validatedPort) { + if (jobId) updateInstallJob(jobId, { status: 'failed', error: 'Invalid listen port', completedAt: Date.now() }); + return; + } + listenHost = validatedHost; + listenPort = String(validatedPort); + const mongoBindHost = isLocalOnlyDbHost(listenHost) ? '127.0.0.1' : listenHost; + + try { + console.log(`[mongodb] Starting MongoDB installation (host: ${listenHost}, port: ${listenPort})...`); + + if (jobId) updateInstallJob(jobId, { status: 'running', progress: 5, message: 'Installing prerequisites...' }); + await runCmd("apt-get install -y gnupg curl 2>&1", 60000); + + if (jobId) updateInstallJob(jobId, { progress: 10, message: 'Adding MongoDB repository...' }); + + const lsbRes = await runCmd("lsb_release -cs 2>/dev/null || cat /etc/os-release | grep VERSION_CODENAME | cut -d= -f2", 5000); + let codename = (lsbRes.stdout || '').trim().split('\n')[0] || 'jammy'; + + const supportedCodenames = ['focal', 'jammy', 'noble']; + if (!supportedCodenames.includes(codename)) { + console.log(`[mongodb] Codename '${codename}' not directly supported, using 'jammy'`); + codename = 'jammy'; + } + console.log(`[mongodb] Using codename: ${codename}`); + + await runCmd("rm -f /etc/apt/sources.list.d/mongodb*.list /usr/share/keyrings/mongodb*.gpg 2>/dev/null || true", 10000); + + let gpgRes = { code: -1, stderr: 'Not attempted' }; + for (let attempt = 1; attempt <= 3; attempt++) { + console.log(`[mongodb] Importing GPG key (attempt ${attempt}/3)...`); + gpgRes = await runCmd("curl -fsSL --retry 3 --retry-delay 5 https://www.mongodb.org/static/pgp/server-8.0.asc | gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg 2>&1", 120000); + if (gpgRes.code === 0) break; + console.warn(`[mongodb] GPG key import attempt ${attempt} failed:`, gpgRes.stderr); + if (attempt < 3) await new Promise(r => setTimeout(r, 5000)); + } + if (gpgRes.code !== 0) { + console.error("[mongodb] Failed to import GPG key after 3 attempts:", gpgRes.stderr); + throw new Error("Failed to import MongoDB GPG key"); + } + + const repoLine = `deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu ${codename}/mongodb-org/8.0 multiverse`; + fs.writeFileSync('/etc/apt/sources.list.d/mongodb-org-8.0.list', repoLine + '\n', { mode: 0o644 }); + console.log("[mongodb] Repository configured:", repoLine); + + if (jobId) updateInstallJob(jobId, { progress: 20, message: 'Updating package lists...' }); + const updateRes = await runCmd("apt-get update 2>&1", 120000); + if (updateRes.code !== 0) { + console.error("[mongodb] apt-get update failed:", updateRes.stderr); + throw new Error("Failed to update packages: " + (updateRes.stderr || updateRes.stdout).substring(0, 200)); + } + console.log("[mongodb] Package lists updated"); + + if (jobId) updateInstallJob(jobId, { progress: 35, message: 'Installing MongoDB packages...' }); + console.log("[mongodb] Installing mongodb-org package..."); + + const installRes = await runCmd("DEBIAN_FRONTEND=noninteractive apt-get install -y mongodb-org 2>&1", 300000); + if (installRes.code !== 0) { + console.error("[mongodb] Installation failed:", installRes.stdout, installRes.stderr); + throw new Error("MongoDB installation failed: " + (installRes.stderr || installRes.stdout).substring(0, 200)); + } + console.log("[mongodb] MongoDB packages installed"); + + const mongodCheck = await runCmd("which mongod && mongod --version | head -1", 5000); + if (mongodCheck.code !== 0) { + throw new Error("MongoDB installation failed - mongod binary not found"); + } + console.log("[mongodb] MongoDB version:", mongodCheck.stdout.trim()); + + const mongoshCheck = await runCmd("which mongosh", 5000); + const mongoShell = mongoshCheck.code === 0 ? mongoshCheck.stdout.trim() : null; + if (!mongoShell) { + console.warn("[mongodb] mongosh not found, will try to install separately"); + await runCmd("DEBIAN_FRONTEND=noninteractive apt-get install -y mongodb-mongosh 2>&1", 60000); + } + const finalShellCheck = await runCmd("which mongosh", 5000); + const finalMongoShell = finalShellCheck.code === 0 ? finalShellCheck.stdout.trim() : null; + console.log(`[mongodb] Using shell: ${finalMongoShell || 'none'}`); + + if (jobId) updateInstallJob(jobId, { progress: 50, message: 'Configuring MongoDB...' }); + const mongoConfPath = "/etc/mongod.conf"; + + await runCmd("mkdir -p /var/lib/mongodb /var/log/mongodb"); + await runCmd("chown -R mongodb:mongodb /var/lib/mongodb /var/log/mongodb"); + await runCmd("chmod 755 /var/lib/mongodb /var/log/mongodb"); + + const mongoConfig = `# MongoDB 8.0 configuration file +storage: + dbPath: /var/lib/mongodb + +systemLog: + destination: file + logAppend: true + path: /var/log/mongodb/mongod.log + +net: + port: ${listenPort} + bindIp: 127.0.0.1 + +processManagement: + timeZoneInfo: /usr/share/zoneinfo +`; + fs.writeFileSync(mongoConfPath, mongoConfig, { mode: 0o644 }); + console.log("[mongodb] Configuration written (auth disabled for user creation)"); + + if (jobId) updateInstallJob(jobId, { progress: 60, message: 'Starting MongoDB service...' }); + + await runCmd("systemctl stop mongod 2>/dev/null || true"); + await runCmd("rm -f /tmp/mongodb-*.sock /var/lib/mongodb/mongod.lock 2>/dev/null || true"); + await new Promise(r => setTimeout(r, 1000)); + + await runCmd("systemctl daemon-reload"); + await runCmd("systemctl enable mongod 2>/dev/null || true"); + + const startRes = await runCmd("systemctl start mongod 2>&1", 30000); + if (startRes.code !== 0) { + const journalRes = await runCmd("journalctl -u mongod --no-pager -n 20 2>&1", 10000); + console.error("[mongodb] Failed to start service:", journalRes.stdout); + throw new Error("Failed to start MongoDB service"); + } + + if (jobId) updateInstallJob(jobId, { progress: 65, message: 'Waiting for MongoDB to be ready...' }); + console.log("[mongodb] Waiting for MongoDB to accept connections..."); + + const mongoReady = await waitFor(async () => { + const statusRes = await runCmd("systemctl is-active mongod 2>/dev/null", 5000); + if (statusRes.stdout.trim() !== 'active') return false; + + if (finalMongoShell) { + const pingRes = await runCmd(`${finalMongoShell} --host 127.0.0.1 --port ${listenPort} --quiet --eval 'db.runCommand({ping:1}).ok' 2>&1`, 10000); + return pingRes.stdout.trim() === '1'; + } else { + const portRes = await runCmd(`ss -tlnp | grep -q ':${listenPort}' && echo ok`, 5000); + return portRes.stdout.includes('ok'); + } + }, 30, 2000); + + if (!mongoReady) { + const journalRes = await runCmd("journalctl -u mongod --no-pager -n 30 2>&1", 10000); + console.error("[mongodb] Service did not become ready. Logs:", journalRes.stdout); + throw new Error("MongoDB service failed to start properly. Check system logs."); + } + console.log("[mongodb] MongoDB is running and accepting connections"); + + if (jobId) updateInstallJob(jobId, { progress: 75, message: 'Creating admin user...' }); + + if (!finalMongoShell) { + throw new Error("MongoDB shell (mongosh) not available - cannot create admin user"); + } + + const safeUser = JSON.stringify(adminUser); + const safePass = JSON.stringify(adminPassword); + + const createUserScript = ` + db = db.getSiblingDB('admin'); + try { db.dropAllUsers(); } catch(e) {} + db.createUser({ + user: ${safeUser}, + pwd: ${safePass}, + roles: [{ role: 'root', db: 'admin' }] + }); + print('USER_CREATED_OK'); + `; + + let userCreated = false; + for (let attempt = 1; attempt <= 3; attempt++) { + console.log(`[mongodb] Creating admin user, attempt ${attempt}/3...`); + const createRes = await new Promise((resolve) => { + const child = spawn(finalMongoShell, [ + '--host', '127.0.0.1', '--port', String(listenPort), + '--quiet', '--eval', createUserScript.replace(/\n/g, ' ') + ], { shell: false, stdio: ['pipe', 'pipe', 'pipe'] }); + let stdout = '', stderr = ''; + child.stdout.on('data', d => { stdout += d.toString(); }); + child.stderr.on('data', d => { stderr += d.toString(); }); + child.on('close', code => resolve({ stdout, stderr, code })); + child.on('error', err => resolve({ stdout: '', stderr: err.message, code: 1 })); + }); + + if (createRes.stdout.includes('USER_CREATED_OK') || createRes.stdout.includes('already exists')) { + console.log("[mongodb] Admin user created successfully"); + userCreated = true; + break; + } + + console.warn(`[mongodb] Attempt ${attempt} failed:`, createRes.stdout, createRes.stderr); + await new Promise(r => setTimeout(r, 2000)); + } + + if (!userCreated) { + throw new Error("Failed to create MongoDB admin user after 3 attempts"); + } + + if (jobId) updateInstallJob(jobId, { progress: 85, message: 'Enabling authentication...' }); + + const secureConfig = `# MongoDB 8.0 configuration file +storage: + dbPath: /var/lib/mongodb + +systemLog: + destination: file + logAppend: true + path: /var/log/mongodb/mongod.log + quiet: true + +net: + port: ${listenPort} + bindIp: ${mongoBindHost} + +processManagement: + timeZoneInfo: /usr/share/zoneinfo + +security: + authorization: enabled +`; + fs.writeFileSync(mongoConfPath, secureConfig, { mode: 0o644 }); + console.log("[mongodb] Configuration updated with authentication enabled"); + + await runCmd("systemctl restart mongod 2>&1", 30000); + await new Promise(r => setTimeout(r, 3000)); + + const authReady = await waitFor(async () => { + const statusRes = await runCmd("systemctl is-active mongod 2>/dev/null", 5000); + return statusRes.stdout.trim() === 'active'; + }, 15, 2000); + + if (!authReady) { + console.error("[mongodb] Service failed to restart with authentication"); + throw new Error("MongoDB failed to restart after enabling authentication"); + } + + if (jobId) updateInstallJob(jobId, { progress: 95, message: 'Verifying installation...' }); + + let verified = false; + for (let attempt = 1; attempt <= 5; attempt++) { + const verifyRes = await new Promise((resolve) => { + const child = spawn(finalMongoShell, [ + '--host', '127.0.0.1', '--port', String(listenPort), + '-u', adminUser, '-p', adminPassword, + '--authenticationDatabase', 'admin', + '--quiet', '--eval', 'db.runCommand({ping:1}).ok' + ], { shell: false, stdio: ['pipe', 'pipe', 'pipe'] }); + let stdout = '', stderr = ''; + child.stdout.on('data', d => { stdout += d.toString(); }); + child.stderr.on('data', d => { stderr += d.toString(); }); + child.on('close', code => resolve({ stdout, stderr, code })); + child.on('error', err => resolve({ stdout: '', stderr: err.message, code: 1 })); + }); + + if (verifyRes.stdout.trim() === '1') { + console.log("[mongodb] Authentication verified successfully"); + verified = true; + break; + } + + console.log(`[mongodb] Verification attempt ${attempt}/5 failed:`, verifyRes.stdout.substring(0, 100)); + await new Promise(r => setTimeout(r, 2000)); + } + + if (!verified) { + throw new Error("MongoDB authentication verification failed"); + } + + await maybeOpenFirewallPort(runCmd, listenPort, listenHost, 'mongodb'); + + if (jobId) updateInstallJob(jobId, { status: 'completed', progress: 100, message: 'Installation complete!', completedAt: Date.now() }); + console.log("[mongodb] MongoDB installation completed successfully"); + + return { ok: true }; + + } catch (err) { + console.error("[mongodb] Installation failed:", err.message); + if (jobId) updateInstallJob(jobId, { status: 'failed', error: err.message, completedAt: Date.now() }); + return { ok: false, error: err.message }; + } +} + +async function checkServiceRunning(serviceName) { + return new Promise((resolve) => { + const child = spawn("systemctl", ["is-active", serviceName]); + let output = ""; + child.stdout.on("data", (d) => { output += d.toString(); }); + child.on("close", (code) => { + resolve(output.trim() === "active"); + }); + child.on("error", () => resolve(false)); + }); +} + +async function checkDatabaseConnection(type, host, port, username, password) { + if (type !== 'mysql') { + console.log(`[database] Skipping connection check for ${type} (only mysql supported for now)`); + return true; + } + + console.log(`[database] Testing ${type} connection to ${host}:${port} as ${username}`); + let connection; + try { + connection = await mysql.createConnection({ + host: host, + port: port, + user: username, + password: password, + connectTimeout: 5000 + }); + console.log(`[database] Connection successful!`); + return true; + } catch (err) { + console.error(`[database] Connection failed: ${err.message}`); + return false; + } finally { + if (connection) await connection.end(); + } +} + +let _cachedMySqlAdminCmd = null; + +function _detectMySqlServiceName() { + const { execSync } = require('child_process'); + for (const svc of ['mariadb', 'mysql', 'mysqld']) { + try { + const out = execSync(`systemctl list-unit-files ${svc}.service 2>/dev/null | grep -c ${svc}`, { encoding: 'utf8', timeout: 5000 }).trim(); + if (parseInt(out, 10) > 0) return svc; + } catch { } + } + return null; +} + +async function ensureMySqlRunning() { + const { execSync } = require('child_process'); + const svc = _detectMySqlServiceName(); + if (!svc) { + console.warn('[database] No MySQL/MariaDB service detected on this system'); + return false; + } + + try { + const status = execSync(`systemctl is-active ${svc} 2>/dev/null`, { encoding: 'utf8', timeout: 5000 }).trim(); + if (status === 'active') return true; + } catch { } + + console.log(`[database] MySQL/MariaDB service '${svc}' is not running. Starting it...`); + try { + try { execSync('pkill -9 mariadbd 2>/dev/null; pkill -9 mysqld 2>/dev/null', { timeout: 5000 }); } catch { } + await new Promise(r => setTimeout(r, 1000)); + execSync(`systemctl start ${svc}`, { timeout: 30000 }); + } catch (e) { + console.error(`[database] Failed to start ${svc}:`, e.message); + return false; + } + + for (let i = 0; i < 20; i++) { + await new Promise(r => setTimeout(r, 500)); + try { + const status = execSync(`systemctl is-active ${svc} 2>/dev/null`, { encoding: 'utf8', timeout: 3000 }).trim(); + if (status === 'active') { + console.log(`[database] Service '${svc}' is now running`); + return true; + } + } catch { } + } + console.error(`[database] Service '${svc}' did not start in time`); + return false; +} + +function _probeMySqlCmd(command, args, timeoutMs = 5000) { + return new Promise((resolve) => { + try { + const child = spawn(command, args, { + shell: false, + stdio: ['ignore', 'pipe', 'pipe'] + }); + let stderr = ''; + child.stderr.on('data', d => { stderr += d.toString(); }); + const timer = setTimeout(() => { child.kill('SIGKILL'); resolve(false); }, timeoutMs); + child.on('close', (code) => { + clearTimeout(timer); + resolve(code === 0 && !stderr.includes('Access denied')); + }); + child.on('error', () => { clearTimeout(timer); resolve(false); }); + } catch { resolve(false); } + }); +} + +async function getMySqlAdminCommand() { + if (_cachedMySqlAdminCmd) return _cachedMySqlAdminCmd; + + const running = await ensureMySqlRunning(); + if (!running) { + console.error('[database] MySQL/MariaDB is not running and could not be started. Cannot probe auth.'); + return null; + } + + console.log('[database] Probing MySQL/MariaDB admin auth methods...'); + + const envPassword = (process.env.MYSQL_PASSWORD || '').trim(); + if (envPassword) { + if (await _probeMySqlCmd('mysql', ['-u', 'root', `--password=${envPassword}`, '--connect-timeout=3', '-e', 'SELECT 1'])) { + console.log('[database] Auth method: mysql -u root with MYSQL_PASSWORD from env'); + _cachedMySqlAdminCmd = { command: 'mysql', args: ['-u', 'root', `--password=${envPassword}`] }; + return _cachedMySqlAdminCmd; + } + } + + if (await _probeMySqlCmd('mysql', ['--connect-timeout=3', '-e', 'SELECT 1'])) { + console.log('[database] Auth method: mysql (unix_socket)'); + _cachedMySqlAdminCmd = { command: 'mysql', args: [] }; + return _cachedMySqlAdminCmd; + } + + if (await _probeMySqlCmd('mariadb', ['--connect-timeout=3', '-e', 'SELECT 1'])) { + console.log('[database] Auth method: mariadb (unix_socket)'); + _cachedMySqlAdminCmd = { command: 'mariadb', args: [] }; + return _cachedMySqlAdminCmd; + } + + if (!_processIsRoot) { + if (await _probeMySqlCmd('sudo', ['-n', 'mysql', '--connect-timeout=3', '-e', 'SELECT 1'])) { + console.log('[database] Auth method: sudo mysql (unix_socket)'); + _cachedMySqlAdminCmd = { command: 'sudo', args: ['-n', 'mysql'] }; + return _cachedMySqlAdminCmd; + } + + if (await _probeMySqlCmd('sudo', ['-n', 'mariadb', '--connect-timeout=3', '-e', 'SELECT 1'])) { + console.log('[database] Auth method: sudo mariadb (unix_socket)'); + _cachedMySqlAdminCmd = { command: 'sudo', args: ['-n', 'mariadb'] }; + return _cachedMySqlAdminCmd; + } + } + + if (fs.existsSync('/etc/mysql/debian.cnf')) { + if (await _probeMySqlCmd('mysql', ['--defaults-file=/etc/mysql/debian.cnf', '--connect-timeout=3', '-e', 'SELECT 1'])) { + console.log('[database] Auth method: mysql --defaults-file=/etc/mysql/debian.cnf'); + _cachedMySqlAdminCmd = { command: 'mysql', args: ['--defaults-file=/etc/mysql/debian.cnf'] }; + return _cachedMySqlAdminCmd; + } + } + + if (await _probeMySqlCmd('mysql', ['-u', 'root', '--skip-password', '--connect-timeout=3', '-e', 'SELECT 1'])) { + console.log('[database] Auth method: mysql -u root --skip-password'); + _cachedMySqlAdminCmd = { command: 'mysql', args: ['-u', 'root', '--skip-password'] }; + return _cachedMySqlAdminCmd; + } + + console.warn('[database] No standard MySQL admin auth method worked. Will use skip-grant-tables fallback.'); + return null; +} + +async function runMySqlAdmin(sqlCommands) { + const adminCmd = await getMySqlAdminCommand(); + + if (adminCmd) { + return new Promise((resolve) => { + const child = spawn(adminCmd.command, adminCmd.args, { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + let stderr = '', stdout = ''; + child.stdout.on('data', d => { stdout += d.toString(); }); + child.stderr.on('data', d => { stderr += d.toString(); }); + child.on('close', (code) => { + if (code === 0) { + resolve({ ok: true }); + } else { + if (stderr.includes('Access denied') || stderr.includes('1045')) { + console.warn('[database] Cached auth method failed, clearing cache for next attempt'); + _cachedMySqlAdminCmd = null; + } + resolve({ ok: false, error: stderr || 'Unknown error' }); + } + }); + child.on('error', (err) => { + _cachedMySqlAdminCmd = null; + resolve({ ok: false, error: err.message }); + }); + child.stdin.write(sqlCommands); + child.stdin.end(); + }); + } + + console.log('[database] Using skip-grant-tables fallback...'); + return new Promise((resolve) => { + const heredocDelim = `___ADPANEL_SQL_${crypto.randomBytes(8).toString('hex')}___`; + const script = ` +set -e + +SOCK_DIR="/var/run/mysqld" +SOCK_PATH="$SOCK_DIR/mysqld.sock" + +# Detect service name (mysql or mariadb) +SVC="" +for s in mariadb mysql mysqld; do + if systemctl list-unit-files "$s.service" >/dev/null 2>&1; then + SVC="$s" + break + fi +done + +if [ -z "$SVC" ]; then + echo "ERROR: Could not detect MySQL/MariaDB service name" >&2 + exit 1 +fi + +# Detect the server binary (mariadbd or mysqld) +SERVER_BIN="" +for bin in mariadbd mysqld; do + if command -v "$bin" >/dev/null 2>&1; then + SERVER_BIN="$bin" + break + fi + # Check common paths + for p in /usr/sbin /usr/bin /usr/libexec; do + if [ -x "$p/$bin" ]; then + SERVER_BIN="$p/$bin" + break 2 + fi + done +done + +if [ -z "$SERVER_BIN" ]; then + echo "ERROR: Could not find mariadbd or mysqld binary" >&2 + exit 1 +fi + +# Stop the service and any stale processes +systemctl stop "$SVC" 2>/dev/null || true +pkill -9 mariadbd 2>/dev/null || true +pkill -9 mysqld 2>/dev/null || true +sleep 2 + +# Ensure socket directory exists with correct perms +mkdir -p "$SOCK_DIR" +chown mysql:mysql "$SOCK_DIR" +chmod 755 "$SOCK_DIR" +rm -f "$SOCK_PATH" 2>/dev/null || true + +# Start server in skip-grant-tables mode (no TCP, socket only) +"$SERVER_BIN" --skip-grant-tables --skip-networking --user=mysql --socket="$SOCK_PATH" & +SAFE_PID=$! + +# Wait for the socket to appear (max 20 seconds) +READY=0 +for i in $(seq 1 40); do + if [ -S "$SOCK_PATH" ]; then + # Also verify we can actually connect + if mysql --socket="$SOCK_PATH" -u root -e "SELECT 1" >/dev/null 2>&1; then + READY=1 + break + fi + fi + sleep 0.5 +done + +if [ "$READY" -ne 1 ]; then + echo "ERROR: skip-grant-tables server did not become ready" >&2 + kill $SAFE_PID 2>/dev/null || true + pkill -9 mariadbd 2>/dev/null || true + pkill -9 mysqld 2>/dev/null || true + systemctl start "$SVC" 2>/dev/null || true + exit 1 +fi + +# Execute the SQL commands via socket +mysql --socket="$SOCK_PATH" -u root <<'${heredocDelim}' +FLUSH PRIVILEGES; +${sqlCommands} +${heredocDelim} +SQL_EXIT=$? + +# Kill the safe-mode instance +kill $SAFE_PID 2>/dev/null || true +pkill -9 mariadbd 2>/dev/null || true +pkill -9 mysqld 2>/dev/null || true +sleep 2 + +# Restart the service normally +systemctl start "$SVC" 2>/dev/null || true + +# Wait for normal restart (max 15 seconds) +for i in $(seq 1 30); do + if systemctl is-active "$SVC" >/dev/null 2>&1; then + break + fi + sleep 0.5 +done + +exit $SQL_EXIT +`; + + const child = _privBashSpawn(script, { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'], + env: { ...process.env, DEBIAN_FRONTEND: 'noninteractive' } + }); + let stderr = '', stdout = ''; + child.stdout.on('data', d => { stdout += d.toString(); }); + child.stderr.on('data', d => { stderr += d.toString(); }); + const timer = setTimeout(() => { + child.kill('SIGKILL'); + _privBashSpawn('killall -9 mysqld mariadbd 2>/dev/null; sleep 1; systemctl start mariadb 2>/dev/null || systemctl start mysql 2>/dev/null || systemctl start mysqld 2>/dev/null', { stdio: 'ignore' }); + resolve({ ok: false, error: 'skip-grant-tables fallback timed out' }); + }, 45000); + child.on('close', (code) => { + clearTimeout(timer); + if (code === 0) { + console.log('[database] skip-grant-tables fallback succeeded'); + _cachedMySqlAdminCmd = null; + resolve({ ok: true }); + } else { + console.error('[database] skip-grant-tables fallback failed:', stderr); + resolve({ ok: false, error: stderr || 'skip-grant-tables fallback failed' }); + } + }); + child.on('error', (err) => { + clearTimeout(timer); + resolve({ ok: false, error: err.message }); + }); + }); +} + +async function createMySqlUser(username, password, host = '%', forceRecreate = false) { + const safeUser = username.replace(/\\/g, '\\\\').replace(/'/g, "''"); + const safeHost = host.replace(/\\/g, '\\\\').replace(/'/g, "''"); + const safePass = password.replace(/\\/g, '\\\\').replace(/'/g, "''"); + + // Grant DML/DDL privileges only — no SUPER, FILE, PROCESS, GRANT OPTION, or other admin privileges. + // Panel DB isolation is enforced at the phpMyAdmin config level (hide_db + AllowDeny rules) + // because MariaDB does not support partial revokes on global grants. + const sqlCommands = ` +${forceRecreate ? `DROP USER IF EXISTS '${safeUser}'@'${safeHost}';` : ''} +CREATE USER IF NOT EXISTS '${safeUser}'@'${safeHost}' IDENTIFIED BY '${safePass}'; +ALTER USER '${safeUser}'@'${safeHost}' IDENTIFIED BY '${safePass}'; +GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, ALTER, INDEX, CREATE TEMPORARY TABLES, LOCK TABLES, EXECUTE, CREATE VIEW, SHOW VIEW, CREATE ROUTINE, ALTER ROUTINE, EVENT, TRIGGER ON *.* TO '${safeUser}'@'${safeHost}'; +FLUSH PRIVILEGES; +`; + + const result = await runMySqlAdmin(sqlCommands); + if (result.ok) { + console.log(`[database] MySQL user '${username}' created successfully`); + } else { + console.error(`[database] Failed to create MySQL user: ${result.error}`); + } + return result; +} + +async function updateMySqlUserPassword(username, password, host = '%') { + const tryUpdate = async (h) => { + const safeUser = username.replace(/\\/g, '\\\\').replace(/'/g, "''"); + const safeHost = h.replace(/\\/g, '\\\\').replace(/'/g, "''"); + const safePass = password.replace(/\\/g, '\\\\').replace(/'/g, "''"); + const sqlCommands = ` +ALTER USER '${safeUser}'@'${safeHost}' IDENTIFIED BY '${safePass}'; +FLUSH PRIVILEGES; +`; + const result = await runMySqlAdmin(sqlCommands); + if (result.ok) { + console.log(`[database] MySQL password updated for '${username}'@'${h}'`); + } + return result; + }; + + let result = await tryUpdate(host); + + if (!result.ok && (result.error.includes("1396") || result.error.includes("Operation ALTER USER failed")) && host === '%') { + console.log(`[database] Failed to update password for '${username}'@'%', retrying with '${username}'@'localhost'...`); + const retryResult = await tryUpdate('localhost'); + if (retryResult.ok) return retryResult; + } + + if (!result.ok) { + console.error(`[database] Failed to update MySQL password: ${result.error}`); + } + return result; +} + +async function deleteMySqlUser(username, host = '%') { + const safeUser = username.replace(/\\/g, '\\\\').replace(/'/g, "''"); + const safeHost = host.replace(/\\/g, '\\\\').replace(/'/g, "''"); + + const sqlCommands = ` +DROP USER IF EXISTS '${safeUser}'@'${safeHost}'; +FLUSH PRIVILEGES; +`; + + const result = await runMySqlAdmin(sqlCommands); + if (result.ok) { + console.log(`[database] MySQL user '${username}' deleted`); + } else { + console.error(`[database] Failed to delete MySQL user: ${result.error}`); + } + return result; +} + +async function createPostgresUser(username, password) { + return new Promise((resolve) => { + const safeUsername = username.replace(/'/g, "''"); + const safePassword = password.replace(/'/g, "''"); + const dqTag = `$adp_${crypto.randomBytes(4).toString('hex')}$`; + + const sqlCommands = ` +DO ${dqTag} +BEGIN + IF NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '${safeUsername}') THEN + CREATE ROLE "${username.replace(/"/g, '""')}" WITH LOGIN PASSWORD '${safePassword}' SUPERUSER CREATEDB CREATEROLE; + ELSE + ALTER ROLE "${username.replace(/"/g, '""')}" WITH PASSWORD '${safePassword}'; + END IF; +END +${dqTag}; +`; + + const child = _userSpawn("postgres", "psql", [], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0) { + console.log(`[database] PostgreSQL user '${username}' created successfully`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to create PostgreSQL user: ${stderr}`); + resolve({ ok: false, error: stderr || "Unknown error" }); + } + }); + + child.on("error", (err) => { + console.error("[database] PostgreSQL command error:", err); + resolve({ ok: false, error: err.message }); + }); + + child.stdin.write(sqlCommands); + child.stdin.end(); + }); +} + +async function updatePostgresUserPassword(username, password) { + return new Promise((resolve) => { + const safePassword = password.replace(/'/g, "''"); + const sqlCommands = `ALTER ROLE "${username.replace(/"/g, '""')}" WITH PASSWORD '${safePassword}';`; + + const child = _userSpawn("postgres", "psql", [], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0) { + console.log(`[database] PostgreSQL password updated for '${username}'`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to update PostgreSQL password: ${stderr}`); + resolve({ ok: false, error: stderr || "Unknown error" }); + } + }); + + child.on("error", (err) => { + console.error("[database] PostgreSQL command error:", err); + resolve({ ok: false, error: err.message }); + }); + + child.stdin.write(sqlCommands); + child.stdin.end(); + }); +} + +async function deletePostgresUser(username) { + return new Promise((resolve) => { + const sqlCommands = `DROP ROLE IF EXISTS "${username.replace(/"/g, '""')}";`; + + const child = _userSpawn("postgres", "psql", [], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0) { + console.log(`[database] PostgreSQL user '${username}' deleted`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to delete PostgreSQL user: ${stderr}`); + resolve({ ok: false, error: stderr || "Unknown error" }); + } + }); + + child.on("error", (err) => { + console.error("[database] PostgreSQL command error:", err); + resolve({ ok: false, error: err.message }); + }); + + child.stdin.write(sqlCommands); + child.stdin.end(); + }); +} + +async function createMongoUser(username, password) { + return new Promise((resolve) => { + const safeUsername = JSON.stringify(username); + const safePassword = JSON.stringify(password); + + const mongoCommands = ` +use admin +db.createUser({ + user: ${safeUsername}, + pwd: ${safePassword}, + roles: [ + { role: "root", db: "admin" }, + { role: "userAdminAnyDatabase", db: "admin" }, + { role: "dbAdminAnyDatabase", db: "admin" }, + { role: "readWriteAnyDatabase", db: "admin" } + ] +}) +`; + + const child = spawn("mongosh", ["--quiet", "--eval", mongoCommands], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + let stdout = ""; + + child.stdout.on("data", (data) => { + stdout += data.toString(); + }); + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0 || stdout.includes("already exists")) { + console.log(`[database] MongoDB user '${username}' created successfully`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to create MongoDB user: ${stderr || stdout}`); + resolve({ ok: false, error: stderr || stdout || "Unknown error" }); + } + }); + + child.on("error", (err) => { + if (err.code === 'ENOENT') { + createMongoUserLegacy(username, password).then(resolve); + } else { + console.error("[database] MongoDB command error:", err); + resolve({ ok: false, error: err.message }); + } + }); + }); +} + +async function createMongoUserLegacy(username, password) { + return new Promise((resolve) => { + const safeUsername = JSON.stringify(username); + const safePassword = JSON.stringify(password); + const mongoCommands = `db.getSiblingDB('admin').createUser({user:${safeUsername},pwd:${safePassword},roles:[{role:"root",db:"admin"}]})`; + + const child = spawn("mongo", ["admin", "--eval", mongoCommands], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + let stdout = ""; + + child.stdout.on("data", (data) => { + stdout += data.toString(); + }); + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0 || stdout.includes("already exists")) { + console.log(`[database] MongoDB user '${username}' created (legacy)`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to create MongoDB user (legacy): ${stderr || stdout}`); + resolve({ ok: false, error: stderr || stdout || "Unknown error" }); + } + }); + + child.on("error", (err) => { + console.error("[database] MongoDB legacy command error:", err); + resolve({ ok: false, error: "MongoDB not installed or not accessible" }); + }); + }); +} + +async function updateMongoUserPassword(username, password) { + return new Promise((resolve) => { + const safeUsername = JSON.stringify(username); + const safePassword = JSON.stringify(password); + const mongoCommands = `db.getSiblingDB('admin').changeUserPassword(${safeUsername}, ${safePassword})`; + + const child = spawn("mongosh", ["--quiet", "--eval", mongoCommands], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0) { + console.log(`[database] MongoDB password updated for '${username}'`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to update MongoDB password: ${stderr}`); + resolve({ ok: false, error: stderr || "Unknown error" }); + } + }); + + child.on("error", (err) => { + if (err.code === 'ENOENT') { + updateMongoUserPasswordLegacy(username, password).then(resolve); + } else { + console.error("[database] MongoDB command error:", err); + resolve({ ok: false, error: err.message }); + } + }); + }); +} + +async function updateMongoUserPasswordLegacy(username, password) { + return new Promise((resolve) => { + const safeUsername = JSON.stringify(username); + const safePassword = JSON.stringify(password); + const mongoCommands = `db.getSiblingDB('admin').changeUserPassword(${safeUsername}, ${safePassword})`; + + const child = spawn("mongo", ["admin", "--eval", mongoCommands], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0) { + console.log(`[database] MongoDB password updated (legacy) for '${username}'`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to update MongoDB password (legacy): ${stderr}`); + resolve({ ok: false, error: stderr || "Unknown error" }); + } + }); + + child.on("error", (err) => { + console.error("[database] MongoDB legacy command error:", err); + resolve({ ok: false, error: "MongoDB not installed or not accessible" }); + }); + }); +} + +async function deleteMongoUser(username) { + return new Promise((resolve) => { + const safeUsername = JSON.stringify(username); + const mongoCommands = `db.getSiblingDB('admin').dropUser(${safeUsername})`; + + const child = spawn("mongosh", ["--quiet", "--eval", mongoCommands], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0) { + console.log(`[database] MongoDB user '${username}' deleted`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to delete MongoDB user: ${stderr}`); + resolve({ ok: false, error: stderr || "Unknown error" }); + } + }); + + child.on("error", (err) => { + if (err.code === 'ENOENT') { + deleteMongoUserLegacy(username).then(resolve); + } else { + console.error("[database] MongoDB command error:", err); + resolve({ ok: false, error: err.message }); + } + }); + }); +} + +async function deleteMongoUserLegacy(username) { + return new Promise((resolve) => { + const safeUsername = JSON.stringify(username); + const mongoCommands = `db.getSiblingDB('admin').dropUser(${safeUsername})`; + + const child = spawn("mongo", ["admin", "--eval", mongoCommands], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + + let stderr = ""; + + child.stderr.on("data", (data) => { + stderr += data.toString(); + }); + + child.on("close", (code) => { + if (code === 0) { + console.log(`[database] MongoDB user '${username}' deleted (legacy)`); + resolve({ ok: true }); + } else { + console.error(`[database] Failed to delete MongoDB user (legacy): ${stderr}`); + resolve({ ok: false, error: stderr || "Unknown error" }); + } + }); + + child.on("error", (err) => { + console.error("[database] MongoDB legacy command error:", err); + resolve({ ok: false, error: "MongoDB not installed or not accessible" }); + }); + }); +} + +function hashDbPassword(password) { + const secret = process.env.SESSION_SECRET; + return crypto.createHash("sha256").update(String(password) + secret).digest("hex"); +} + +function runPrivilegedBash(cmd, timeoutMs = 30000) { + return new Promise((resolve) => { + const child = _privBashSpawn(cmd, { + shell: false, + env: { ...process.env, DEBIAN_FRONTEND: "noninteractive" } + }); + let stdout = ""; + let stderr = ""; + const timeout = setTimeout(() => { + child.kill("SIGKILL"); + resolve({ code: -1, stdout, stderr: "Command timed out" }); + }, timeoutMs); + child.stdout.on("data", (d) => { stdout += d.toString(); }); + child.stderr.on("data", (d) => { stderr += d.toString(); }); + child.on("close", (code) => { + clearTimeout(timeout); + resolve({ code, stdout, stderr }); + }); + child.on("error", (err) => { + clearTimeout(timeout); + resolve({ code: 1, stdout, stderr: err.message }); + }); + }); +} + +function isLocalPortOpen(port, host = "127.0.0.1", timeoutMs = 1500) { + return new Promise((resolve) => { + const socket = net.createConnection({ host, port: Number(port) }); + let finished = false; + + const done = (ok) => { + if (finished) return; + finished = true; + try { socket.destroy(); } catch { } + resolve(ok); + }; + + socket.setTimeout(timeoutMs); + socket.once("connect", () => done(true)); + socket.once("timeout", () => done(false)); + socket.once("error", () => done(false)); + }); +} + +async function waitForLocalPort(port, host = "127.0.0.1", attempts = 12, delayMs = 500) { + for (let i = 0; i < attempts; i++) { + if (await isLocalPortOpen(port, host)) return true; + await new Promise((r) => setTimeout(r, delayMs)); + } + return false; +} + +async function ensureDbToolBackendReady(service, opts = {}) { + const autoInstall = !!opts.autoInstall; + try { + if (service === "pgadmin") { + const pgConfig = loadPgAdminConfig(); + if (!pgConfig.enabled) { + return { ok: false, error: "pgAdmin4 is not enabled. Install it from Settings first." }; + } + + const pgadminApacheConf = ` +ServerTokens Prod +ServerSignature Off +Header always unset "X-Powered-By" +Header always set "Server" "webserver" + + + ServerAdmin webmaster@localhost + DocumentRoot /usr/pgadmin4/web + + WSGIDaemonProcess pgadmin processes=1 threads=25 python-home=/usr/pgadmin4/venv + WSGIScriptAlias /pgadmin4 /usr/pgadmin4/web/pgAdmin4.wsgi + + + WSGIProcessGroup pgadmin + WSGIApplicationGroup %{GLOBAL} + Require all granted + + + ErrorLog \${APACHE_LOG_DIR}/pgadmin4_error.log + CustomLog \${APACHE_LOG_DIR}/pgadmin4_access.log combined + +`.trim(); + const pgadminApacheConfB64 = Buffer.from(pgadminApacheConf, 'utf8').toString('base64'); + + const prepRes = await runPrivilegedBash(` + set -e + systemctl daemon-reload 2>/dev/null || true + systemctl start postgresql 2>/dev/null || true + + mkdir -p /etc/apache2/sites-available /etc/apache2/sites-enabled + printf %s ${JSON.stringify(pgadminApacheConfB64)} | base64 -d > /etc/apache2/sites-available/pgadmin4.conf + chmod 0644 /etc/apache2/sites-available/pgadmin4.conf + ln -sf /etc/apache2/sites-available/pgadmin4.conf /etc/apache2/sites-enabled/pgadmin4.conf + + rm -f /etc/apache2/sites-enabled/000-default.conf 2>/dev/null || true + rm -f /etc/apache2/sites-enabled/default-ssl.conf 2>/dev/null || true + rm -f /etc/apache2/conf-enabled/phpmyadmin.conf 2>/dev/null || true + rm -f /etc/apache2/conf-enabled/pgadmin4.conf 2>/dev/null || true + + cat > /etc/apache2/ports.conf <<'EOF' +# Apache ports configuration - managed by ADPanel +Listen 127.0.0.1:5050 +EOF + + a2enmod wsgi >/dev/null 2>&1 || true + a2enmod headers >/dev/null 2>&1 || true + apache2ctl -t >/dev/null 2>&1 || true + systemctl restart apache2 2>/dev/null || systemctl start apache2 2>/dev/null || true + `, 45000); + + if (prepRes.code !== 0) { + return { ok: false, error: "Failed to prepare pgAdmin backend" }; + } + + const pgReady = await waitForLocalPort(5050, "127.0.0.1", 20, 500); + if (!pgReady) { + const logs = await runPrivilegedBash("journalctl -u apache2 --no-pager -n 20 2>/dev/null || true", 8000); + return { + ok: false, + error: "pgAdmin backend is unreachable on 127.0.0.1:5050" + (logs.stdout ? ` | apache2: ${logs.stdout.split("\n").slice(-3).join(" | ")}` : "") + }; + } + + const pgProbe = await runPrivilegedBash("curl -fsS http://127.0.0.1:5050/pgadmin4/ 2>/dev/null | head -c 6000 || true", 10000); + let pgProbeText = (pgProbe.stdout || '').toLowerCase(); + if (!pgProbeText.includes('pgadmin')) { + const recoveryEmail = String(pgConfig?.users?.[0]?.email || process.env.PGADMIN_SETUP_EMAIL || 'admin@localhost').trim(); + const recoveryPassword = String( + process.env.PGADMIN_SETUP_PASSWORD || + process.env.MYSQL_PASSWORD || + (`AdPanel-${crypto.createHash('sha256').update(String(process.env.SESSION_SECRET || recoveryEmail)).digest('hex').slice(0, 20)}!`) + ); + + const setupRecoverRes = await runPrivilegedBash(` + SETUP_SCRIPT="" + if [ -x /usr/pgadmin4/bin/setup-web.sh ]; then + SETUP_SCRIPT="/usr/pgadmin4/bin/setup-web.sh" + elif [ -x /usr/share/pgadmin4/bin/setup-web.sh ]; then + SETUP_SCRIPT="/usr/share/pgadmin4/bin/setup-web.sh" + fi + + if [ -n "$SETUP_SCRIPT" ]; then + export PGADMIN_SETUP_EMAIL=${JSON.stringify(recoveryEmail)} + export PGADMIN_SETUP_PASSWORD=${JSON.stringify(recoveryPassword)} + "$SETUP_SCRIPT" --yes >/dev/null 2>&1 || true + rm -f /etc/apache2/conf-enabled/pgadmin4.conf 2>/dev/null || true + systemctl restart apache2 2>/dev/null || systemctl start apache2 2>/dev/null || true + fi + `, 120000); + + if (setupRecoverRes.code === 0) { + const probeAfterRecover = await runPrivilegedBash("curl -fsS http://127.0.0.1:5050/pgadmin4/ 2>/dev/null | head -c 6000 || true", 10000); + pgProbeText = (probeAfterRecover.stdout || '').toLowerCase(); + } + } + + if (!pgProbeText.includes('pgadmin')) { + return { + ok: false, + error: "pgAdmin backend responded, but pgAdmin content was not detected on /pgadmin4/." + }; + } + + return { ok: true }; + } + + if (service === "phpmyadmin") { + const dbConfig = loadDatabaseConfig(); + if (!dbConfig.enabled || !dbConfig.config) { + return { ok: false, error: "phpMyAdmin is not enabled. Configure it from Settings first." }; + } + + if (!fs.existsSync("/usr/share/phpmyadmin/index.php")) { + if (!autoInstall) { + return { ok: false, error: "phpMyAdmin is not installed." }; + } + const installed = await installPhpMyAdmin(); + if (!installed) { + return { ok: false, error: "phpMyAdmin is not installed and auto-install failed." }; + } + } + + if (!configurePhpMyAdminWebServer()) { + return { ok: false, error: "Failed to configure phpMyAdmin internal web server." }; + } + + const prepRes = await runPrivilegedBash(` + PHP_FPM_SVC=$(systemctl list-unit-files --type=service --no-legend | awk '{print $1}' | grep -E '^php[0-9.]+-fpm\\.service$' | sort -rV | head -1) + if [ -n "$PHP_FPM_SVC" ]; then + systemctl enable "$PHP_FPM_SVC" 2>/dev/null || true + systemctl restart "$PHP_FPM_SVC" 2>/dev/null || true + fi + + systemctl start nginx 2>/dev/null || true + nginx -t >/dev/null 2>&1 && systemctl reload nginx 2>/dev/null || systemctl restart nginx 2>/dev/null || true + `, 45000); + + if (prepRes.code !== 0) { + return { ok: false, error: "Failed to prepare phpMyAdmin backend" }; + } + + const phpReady = await waitForLocalPort(dbProxy.PHPMYADMIN_INTERNAL_PORT, "127.0.0.1", 20, 500); + if (!phpReady) { + return { ok: false, error: `phpMyAdmin backend is unreachable on 127.0.0.1:${dbProxy.PHPMYADMIN_INTERNAL_PORT}` }; + } + + const phpProbe = await runPrivilegedBash(`curl -fsS http://127.0.0.1:${dbProxy.PHPMYADMIN_INTERNAL_PORT}/phpmyadmin/ 2>/dev/null | head -c 6000 || true`, 10000); + const phpProbeText = (phpProbe.stdout || '').toLowerCase(); + if (!phpProbeText.includes('phpmyadmin')) { + return { + ok: false, + error: "phpMyAdmin backend responded, but phpMyAdmin content was not detected on /phpmyadmin/." + }; + } + + return { ok: true }; + } + + return { ok: false, error: "Unsupported database service" }; + } catch (err) { + return { ok: false, error: err?.message || "Database backend readiness check failed" }; + } +} + +// ── Database Access Token API ──────────────────────────────────── +app.post("/api/settings/database/access-token", async (req, res) => { + if (!(await isAdmin(req))) return res.status(404).end(); + const { service } = req.body || {}; + const validServices = ["phpmyadmin", "pgadmin"]; + if (!validServices.includes(service)) { + return res.status(400).json({ error: "Invalid service" }); + } + + const readiness = await ensureDbToolBackendReady(service, { autoInstall: true }); + if (!readiness.ok) { + return res.status(503).json({ error: readiness.error || "Database tool backend is not ready" }); + } + + const userIp = getRequestIp(req) || req.ip || req.connection?.remoteAddress || ""; + const username = req.session?.user || "unknown"; + const result = dbProxy.generateToken(service, userIp, username, req.sessionID || null); + if (!result) return res.status(500).json({ error: "Failed to generate token" }); + return res.json({ + url: `/db-access/${result.token}/`, + token: result.token, + expiresAt: result.expiresAt, + ttl: dbProxy.TOKEN_TTL_MS + }); +}); + +// Open DB tools in a real browser tab (non-popup flow) via normal navigation. +app.get("/db-open/:service", async (req, res) => { + if (!(await isAdmin(req))) { + return res.status(403).send("Access denied"); + } + + const service = String(req.params.service || "").toLowerCase(); + const validServices = ["phpmyadmin", "pgadmin"]; + if (!validServices.includes(service)) { + return res.status(404).send("Not found"); + } + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); + return res.render("db-open", { + service, + serviceLabel: service === "pgadmin" ? "pgAdmin4" : "phpMyAdmin" + }); +}); + +app.get("/api/settings/database", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const data = loadDatabaseConfig(); + const safeUsers = (data.users || []).map(u => ({ + username: u.username, + createdAt: u.createdAt + })); + + const actionTokens = { + setup: issueActionToken(req, "POST /api/settings/database/setup", {}, { ttlSeconds: 120, oneTime: true }), + 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 }), + 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 }), + mongodbDisable: issueActionToken(req, "POST /api/settings/database/mongodb/disable", {}, { ttlSeconds: 120, oneTime: true }), + }; + for (const u of safeUsers) { + actionTokens[`deleteUser_${u.username}`] = issueActionToken(req, "DELETE /api/settings/database/users/:username", { username: u.username }, { ttlSeconds: 120, oneTime: true }); + actionTokens[`changePassword_${u.username}`] = issueActionToken(req, "POST /api/settings/database/users/:username/password", { username: u.username }, { ttlSeconds: 120, oneTime: true }); + } + + return res.json({ + enabled: data.enabled, + config: data.config ? { + type: data.config.type, + host: data.config.host, + port: data.config.port + } : null, + users: safeUsers, + actionTokens + }); +}); + +app.post("/api/settings/database/setup", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/setup")) return; + + const { type, host, port, username, password } = req.body || {}; + + const validTypes = ["mysql", "postgresql", "mongodb"]; + const cleanType = String(type || "mysql").toLowerCase(); + if (!validTypes.includes(cleanType)) { + return res.status(400).json({ error: "Invalid database type" }); + } + + const rawHost = String(host || "localhost").trim(); + const cleanHost = validateDbHost(rawHost); + if (!cleanHost) { + return res.status(400).json({ error: "Invalid host. Must be localhost, a valid IPv4/IPv6 address, or a valid hostname (a-z, 0-9, dots, hyphens only)" }); + } + + const cleanPort = validatePort(port); + if (!cleanPort) { + return res.status(400).json({ error: "Invalid port. Must be a number between 1 and 65535" }); + } + + const cleanUsername = String(username || "").trim(); + if (!cleanUsername || cleanUsername.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(cleanUsername)) { + return res.status(400).json({ error: "Invalid username (alphanumeric, _, - only)" }); + } + + if (!password || password.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + try { + const isInstalled = await checkPackageInstalled("phpmyadmin"); + if (!isInstalled) { + console.log("[database] phpMyAdmin not installed, attempting installation..."); + const installed = await installPhpMyAdmin(); + if (!installed) { + return res.status(500).json({ error: "Failed to install phpMyAdmin. Please install it manually." }); + } + } + + const isLocal = ['localhost', '127.0.0.1', '%', '0.0.0.0'].includes(cleanHost); + const connectionHost = (cleanHost === '%' || cleanHost === 'localhost' || cleanHost === '0.0.0.0') ? '127.0.0.1' : cleanHost; + + if (cleanType === 'mysql' && isLocal) { + const mysqlRunning = await ensureMySqlRunning(); + if (!mysqlRunning) { + return res.status(500).json({ error: "MySQL/MariaDB service is not running and could not be started. Please start it manually and try again." }); + } + + console.log(`[database] Ensuring MySQL user '${cleanUsername}' exists (Local Setup)...`); + + const resPerc = await createMySqlUser(cleanUsername, password, '%', true); + if (!resPerc.ok) { + console.error(`[database] Failed to create user@%: ${resPerc.error}`); + return res.status(500).json({ error: "Failed to create MySQL user: " + resPerc.error }); + } + + console.log(`[database] Ensuring '${cleanUsername}'@'localhost' also exists...`); + const resLocal = await createMySqlUser(cleanUsername, password, 'localhost', true); + if (!resLocal.ok) { + console.warn(`[database] Warning: Failed to create user@localhost: ${resLocal.error}`); + } + } else if (cleanType === 'mysql') { + console.log(`[database] Skipping local user creation for remote host: ${cleanHost}`); + } + + let connectionOk = await checkDatabaseConnection(cleanType, connectionHost, cleanPort, cleanUsername, password); + + if (!connectionOk) { + return res.status(400).json({ error: `Connection failed: Access denied for user '${cleanUsername}'@'${connectionHost}' (or user does not exist on target server).` }); + } + + const data = { + enabled: true, + config: { + type: cleanType, + host: connectionHost, + port: cleanPort + }, + users: [{ + username: cleanUsername, + passwordHash: hashDbPassword(password), + createdAt: Date.now() + }], + setupAt: Date.now() + }; + + if (!saveDatabaseConfig(data)) { + return res.status(500).json({ error: "Failed to save configuration" }); + } + + configurePhpMyAdmin(data.config); + + setTimeout(() => { + configurePhpMyAdminWebServer(); + }, 500); + + console.log(`[phpmyadmin] phpMyAdmin setup complete for ${cleanType} at ${cleanHost}:${cleanPort}`); + + return res.json({ ok: true, message: "phpMyAdmin setup complete" }); + + } catch (err) { + console.error("[database] Setup error:", err); + return res.status(500).json({ error: "Setup failed: " + (err.message || "unknown error") }); + } +}); + +app.post("/api/settings/database/disable", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/disable")) return; + + try { + console.log("[phpmyadmin] Disabling phpMyAdmin..."); + + disablePhpMyAdminWebServer(); + + const data = { enabled: false, config: null, users: [], disabledAt: Date.now() }; + + if (!saveDatabaseConfig(data)) { + return res.status(500).json({ error: "Failed to save configuration" }); + } + + console.log("[phpmyadmin] phpMyAdmin disabled - web access blocked"); + + return res.json({ ok: true, message: "phpMyAdmin disabled" }); + + } catch (err) { + console.error("[phpmyadmin] Disable error:", err); + return res.status(500).json({ error: "Failed to disable" }); + } +}); + +app.post("/api/settings/database/users", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/users")) return; + + const { username, password, host } = req.body || {}; + + const cleanUsername = String(username || "").trim(); + if (!cleanUsername || cleanUsername.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(cleanUsername)) { + return res.status(400).json({ error: "Invalid username (alphanumeric, _, - only)" }); + } + + if (!password || password.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + const cleanHost = String(host || "%").trim(); + if (cleanHost.length > 255 || /[;'"\\]/.test(cleanHost)) { + return res.status(400).json({ error: "Invalid host" }); + } + + try { + const data = loadDatabaseConfig(); + + if (!data.enabled) { + return res.status(400).json({ error: "Database management is not enabled" }); + } + + const exists = data.users.find(u => u.username.toLowerCase() === cleanUsername.toLowerCase() && u.host === cleanHost); + if (exists) { + return res.status(400).json({ error: "User already exists" }); + } + + const dbType = data.config?.type || 'mysql'; + let result; + let dbName = 'MySQL'; + + if (dbType === 'mysql') { + result = await createMySqlUser(cleanUsername, password, cleanHost); + dbName = 'MySQL'; + } else if (dbType === 'postgresql') { + result = await createPostgresUser(cleanUsername, password); + dbName = 'PostgreSQL'; + } else if (dbType === 'mongodb') { + result = await createMongoUser(cleanUsername, password); + dbName = 'MongoDB'; + } else { + return res.status(400).json({ error: `Unsupported database type: ${dbType}` }); + } + + if (!result.ok) { + return res.status(500).json({ error: `Failed to create ${dbName} user: ${result.error || 'Unknown error'}` }); + } + + data.users.push({ + username: cleanUsername, + host: cleanHost, + passwordHash: hashDbPassword(password), + createdAt: Date.now() + }); + + if (!saveDatabaseConfig(data)) { + return res.status(500).json({ error: "Failed to save user" }); + } + + console.log(`[database] Created ${dbType} user: ${cleanUsername}@${cleanHost}`); + + return res.json({ ok: true, message: `User created successfully in ${dbName}` }); + + } catch (err) { + console.error("[database] Create user error:", err); + return res.status(500).json({ error: "Failed to create user" }); + } +}); + +app.post("/api/settings/database/users/:username/password", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/users/:username/password", { username: String(req.params.username || "").trim() })) return; + + const { username } = req.params; + const { password, host } = req.body || {}; + + const cleanUsername = String(username || "").trim(); + + if (!password || password.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + const cleanHost = String(host || "%").trim(); + if (cleanHost.length > 255 || /[;'"\\]/.test(cleanHost)) { + return res.status(400).json({ error: "Invalid host" }); + } + + try { + const data = loadDatabaseConfig(); + + if (!data.enabled) { + return res.status(400).json({ error: "Database management is not enabled" }); + } + + const userIndex = data.users.findIndex(u => u.username.toLowerCase() === cleanUsername.toLowerCase()); + if (userIndex === -1) { + return res.status(404).json({ error: "User not found" }); + } + + const userHost = data.users[userIndex].host || cleanHost; + + const dbType = data.config?.type || 'mysql'; + let result; + let dbName = 'MySQL'; + + if (dbType === 'mysql') { + result = await updateMySqlUserPassword(cleanUsername, password, userHost); + dbName = 'MySQL'; + } else if (dbType === 'postgresql') { + result = await updatePostgresUserPassword(cleanUsername, password); + dbName = 'PostgreSQL'; + } else if (dbType === 'mongodb') { + result = await updateMongoUserPassword(cleanUsername, password); + dbName = 'MongoDB'; + } else { + return res.status(400).json({ error: `Unsupported database type: ${dbType}` }); + } + + if (!result.ok) { + return res.status(500).json({ error: `Failed to update ${dbName} password: ${result.error || 'Unknown error'}` }); + } + + data.users[userIndex].passwordHash = hashDbPassword(password); + data.users[userIndex].updatedAt = Date.now(); + + if (!saveDatabaseConfig(data)) { + return res.status(500).json({ error: "Failed to update password" }); + } + + console.log(`[database] Password updated for ${dbType} user: ${cleanUsername}`); + + return res.json({ ok: true, message: `Password updated successfully in ${dbName}` }); + + } catch (err) { + console.error("[database] Update password error:", err); + return res.status(500).json({ error: "Failed to update password" }); + } +}); + +app.delete("/api/settings/database/users/:username", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "DELETE /api/settings/database/users/:username", { username: String(req.params.username || "").trim() })) return; + + const { username } = req.params; + const { host } = req.query || {}; + const cleanUsername = String(username || "").trim(); + + const cleanHost = String(host || "%").trim(); + if (cleanHost.length > 255 || /[;'"\\]/.test(cleanHost)) { + return res.status(400).json({ error: "Invalid host" }); + } + + try { + const data = loadDatabaseConfig(); + + if (!data.enabled) { + return res.status(400).json({ error: "Database management is not enabled" }); + } + + const userIndex = data.users.findIndex(u => u.username.toLowerCase() === cleanUsername.toLowerCase()); + if (userIndex === -1) { + return res.status(404).json({ error: "User not found" }); + } + + const userHost = data.users[userIndex].host || cleanHost; + + const dbType = data.config?.type || 'mysql'; + let result; + let dbName = 'MySQL'; + + if (dbType === 'mysql') { + result = await deleteMySqlUser(cleanUsername, userHost); + dbName = 'MySQL'; + } else if (dbType === 'postgresql') { + result = await deletePostgresUser(cleanUsername); + dbName = 'PostgreSQL'; + } else if (dbType === 'mongodb') { + result = await deleteMongoUser(cleanUsername); + dbName = 'MongoDB'; + } else { + result = { ok: true }; + dbName = dbType; + } + + if (!result.ok) { + console.warn(`[database] Could not delete ${dbType} user (may not exist): ${result.error}`); + } + + data.users.splice(userIndex, 1); + + if (!saveDatabaseConfig(data)) { + return res.status(500).json({ error: "Failed to delete user" }); + } + + console.log(`[database] Deleted ${dbType} user: ${cleanUsername}`); + + return res.json({ ok: true, message: `User deleted from ${dbName}` }); + + } catch (err) { + console.error("[database] Delete user error:", err); + return res.status(500).json({ error: "Failed to delete user" }); + } +}); + +app.post("/api/settings/database/change-type", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/change-type")) return; + + const { type, host, port, username, password } = req.body || {}; + + const validTypes = ["mysql", "postgresql", "mongodb"]; + const cleanType = String(type || "").toLowerCase(); + if (!validTypes.includes(cleanType)) { + return res.status(400).json({ error: "Invalid database type" }); + } + + const cleanHost = validateDbHost(String(host || "localhost").trim()); + if (!cleanHost) { + return res.status(400).json({ error: "Invalid host. Must be localhost, a valid IPv4/IPv6 address, or a valid hostname." }); + } + + const cleanPort = parseInt(port, 10); + if (isNaN(cleanPort) || cleanPort < 1 || cleanPort > 65535) { + return res.status(400).json({ error: "Invalid port" }); + } + + const cleanUsername = String(username || "").trim(); + if (!cleanUsername || cleanUsername.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(cleanUsername)) { + return res.status(400).json({ error: "Invalid username (alphanumeric, _, - only)" }); + } + + if (!password || password.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + try { + const connectionOk = await checkDatabaseConnection(cleanType, cleanHost, cleanPort, cleanUsername, password); + if (!connectionOk) { + return res.status(400).json({ error: "Failed to connect to database. Check credentials." }); + } + + const data = { + enabled: true, + config: { + type: cleanType, + host: cleanHost, + port: cleanPort + }, + users: [{ + username: cleanUsername, + passwordHash: hashDbPassword(password), + createdAt: Date.now() + }], + changedAt: Date.now() + }; + + if (!saveDatabaseConfig(data)) { + return res.status(500).json({ error: "Failed to save configuration" }); + } + + console.log(`[database] Database type changed to ${cleanType} at ${cleanHost}:${cleanPort}`); + + return res.json({ ok: true, message: "Database type changed successfully" }); + + } catch (err) { + console.error("[database] Change type error:", err); + return res.status(500).json({ error: "Failed to change database type: " + (err.message || "unknown error") }); + } +}); + + +app.use(['/pgadmin4', '/pgadmin'], async (req, res, next) => { + if (!(await isAdmin(req))) { + return res.status(403).send('Access denied - Admin authentication required'); + } + + const proxyReq = httpMod.request({ + hostname: '127.0.0.1', + port: 5050, + path: req.originalUrl.replace(/^\/(pgadmin4?)\/?/, '/') || '/', + method: req.method, + headers: { + ...req.headers, + host: '127.0.0.1:5050', + 'X-Script-Name': req.originalUrl.startsWith('/pgadmin4') ? '/pgadmin4' : '/pgadmin', + 'X-Forwarded-For': req.ip, + 'X-Forwarded-Proto': req.protocol, + 'X-Real-IP': req.ip + } + }, (proxyRes) => { + if (proxyRes.headers.location) { + let location = proxyRes.headers.location; + if (location.startsWith('/') && !location.startsWith('/pgadmin')) { + const prefix = req.originalUrl.startsWith('/pgadmin4') ? '/pgadmin4' : '/pgadmin'; + proxyRes.headers.location = prefix + location; + } + } + res.writeHead(proxyRes.statusCode, proxyRes.headers); + proxyRes.pipe(res); + }); + + proxyReq.on('error', (err) => { + console.error('[pgadmin-proxy] Error:', err.message); + res.status(502).send(` + + pgAdmin4 Unavailable + +

pgAdmin4 is not running

+

The pgAdmin4 service (Apache on port 5050) is not available.

+

Please install PostgreSQL & pgAdmin4 from the panel settings first.

+

Error: ${escapeHtml(err.message)}

+ Go to Settings + + + `); + }); + + if (['POST', 'PUT', 'PATCH'].includes(req.method)) { + req.pipe(proxyReq); + } else { + proxyReq.end(); + } +}); + +app.use('/phpmyadmin', async (req, res, next) => { + if (!(await isAdmin(req))) { + return res.status(403).send('Access denied - Admin authentication required'); + } + + if (!fs.existsSync('/usr/share/phpmyadmin/index.php')) { + return res.status(503).send(` + + phpMyAdmin Not Installed + +

phpMyAdmin is not installed

+

Please enable and configure a database from the panel settings first.

+ Go to Settings + + + `); + } + + return res.status(503).send(` + + phpMyAdmin Configuration Required + +

phpMyAdmin nginx configuration needed

+

phpMyAdmin is installed but nginx is not configured to serve it.

+

Please re-enable the database from settings to configure nginx, or add this to your nginx server block:

+
include /etc/nginx/snippets/phpmyadmin.conf;
+

Go to Settings

+ + + `); +}); + +app.get("/api/settings/database/pgadmin/status", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const config = loadPgAdminConfig(); + const postgresRunning = await checkServiceRunning("postgresql"); + + return res.json({ + enabled: config.enabled, + installed: postgresRunning, + postgresRunning, + users: (config.users || []).map(u => ({ email: u.email, createdAt: u.createdAt })) + }); +}); + +app.post("/api/settings/database/pgadmin/setup", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/pgadmin/setup")) return; + + const { email, password, dbUser, dbHost, dbPort } = req.body || {}; + + const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/; + if (!email || !emailRegex.test(email) || email.length > 255) { + return res.status(400).json({ error: "Valid email required for pgAdmin login" }); + } + + if (!password || password.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + const postgresUser = dbUser || email.split("@")[0].replace(/[^a-zA-Z0-9_]/g, "") || "admin"; + + const rawHost = dbHost || "127.0.0.1"; + const rawPort = dbPort || "5432"; + + const postgresHost = validateDbHost(rawHost); + if (!postgresHost) { + return res.status(400).json({ error: "Invalid host. Must be localhost, a valid IPv4/IPv6 address, or a valid hostname (a-z, 0-9, dots, hyphens only)" }); + } + + const postgresPortNum = validatePort(rawPort); + if (!postgresPortNum) { + return res.status(400).json({ error: "Invalid port. Must be a number between 1 and 65535" }); + } + const postgresPort = String(postgresPortNum); + + const jobId = createInstallJob('pgadmin'); + const host = req.headers.host || "localhost"; + const protocol = req.protocol || "http"; + const accessUrl = `${protocol}://${host} (via secure token access)`; + + res.json({ ok: true, jobId, message: "Installation started", accessUrl }); + + (async () => { + try { + console.log("[pgadmin] Starting pgAdmin4 setup..."); + + const result = await installPostgreSQLAndPgAdmin(email, password, jobId, postgresHost, postgresPort); + if (!result.ok) { + updateInstallJob(jobId, { status: 'failed', error: result.error || "Installation failed", completedAt: Date.now() }); + return; + } + + updateInstallJob(jobId, { progress: 92, message: 'Creating PostgreSQL user...' }); + await createPostgresDbUser(postgresUser, password, postgresHost, postgresPort); + + const config = { + enabled: true, + host: postgresHost, + port: postgresPort, + users: [{ + email, + pgUser: postgresUser, + createdAt: Date.now() + }], + setupAt: Date.now() + }; + + if (!savePgAdminConfig(config)) { + updateInstallJob(jobId, { status: 'failed', error: "Failed to save configuration", completedAt: Date.now() }); + return; + } + + updateInstallJob(jobId, { + status: 'completed', + progress: 100, + message: 'Installation complete!', + completedAt: Date.now(), + result: { accessUrl, pgUser: postgresUser } + }); + + console.log("[pgadmin] Setup complete"); + + } catch (err) { + console.error("[pgadmin] Setup error:", err); + updateInstallJob(jobId, { status: 'failed', error: err.message || "unknown error", completedAt: Date.now() }); + } + })(); +}); + +app.post("/api/settings/database/pgadmin/disable", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/pgadmin/disable")) return; + + try { + console.log("[pgadmin] Disabling pgAdmin4 and PostgreSQL - full cleanup for clean reinstall..."); + + const runCmd = (cmd, timeoutMs = 60000) => new Promise((resolve) => { + const child = _privBashSpawn(cmd, { shell: false }); + let output = ""; + child.stdout.on("data", (d) => { output += d.toString(); }); + child.stderr.on("data", (d) => { output += d.toString(); }); + child.on("close", (code) => resolve({ code, output })); + child.on("error", () => resolve({ code: 1, output: "spawn error" })); + setTimeout(() => { child.kill(); resolve({ code: -1, output: "timeout" }); }, timeoutMs); + }); + + await runCmd("systemctl stop postgresql 2>/dev/null; systemctl disable postgresql 2>/dev/null; killall -9 postgres 2>/dev/null; true"); + console.log("[pgadmin] PostgreSQL stopped and disabled"); + + await runCmd("systemctl stop apache2 2>/dev/null; systemctl disable apache2 2>/dev/null; killall -9 apache2 2>/dev/null; true"); + console.log("[pgadmin] Apache stopped and disabled"); + + console.log("[pgadmin] Removing Apache pgAdmin4 configuration..."); + try { + const configsToRemove = [ + '/etc/apache2/sites-enabled/pgadmin4.conf', + '/etc/apache2/sites-available/pgadmin4.conf', + '/etc/apache2/conf-enabled/pgadmin4.conf', + '/etc/apache2/conf-available/pgadmin4.conf' + ]; + for (const conf of configsToRemove) { + try { if (fs.existsSync(conf)) fs.unlinkSync(conf); } catch (e) { } + } + } catch (e) { } + + await runCmd(` + # Remove Listen 5050 from ports.conf (clean slate for reinstall) + sed -i '/Listen 5050/d' /etc/apache2/ports.conf 2>/dev/null || true + + # If ports.conf is empty or only has comments, add a placeholder + # Don't add Listen 80 as nginx owns that port + if ! grep -q '^Listen' /etc/apache2/ports.conf 2>/dev/null; then + echo '# Apache ports - no active listeners (nginx handles web traffic)' > /etc/apache2/ports.conf + fi + + true + `); + console.log("[pgadmin] Apache pgAdmin4 config completely removed"); + + await runCmd(` + # Write placeholder to prevent nginx include errors (don't delete, just empty it) + echo '# pgAdmin4 disabled - placeholder to prevent nginx include errors' > /etc/nginx/snippets/pgadmin4.conf 2>/dev/null || true + + # Remove any include lines for pgadmin from nginx configs + for conf in /etc/nginx/sites-available/*.conf /etc/nginx/sites-enabled/*.conf /etc/nginx/conf.d/*.conf; do + if [ -f "\$conf" ]; then + sed -i '/include.*pgadmin4.conf/d' "\$conf" 2>/dev/null || true + fi + done + + # Test and reload nginx + nginx -t 2>/dev/null && systemctl reload nginx 2>/dev/null || true + + true + `); + console.log("[pgadmin] Nginx pgAdmin config removed"); + + await runCmd(` + DEBIAN_FRONTEND=noninteractive apt-get remove --purge -y pgadmin4-web pgadmin4-desktop pgadmin4 2>/dev/null || true + DEBIAN_FRONTEND=noninteractive apt-get autoremove -y 2>/dev/null || true + `, 120000); + console.log("[pgadmin] pgAdmin4 packages removed"); + + await runCmd(` + rm -rf /var/lib/pgadmin 2>/dev/null || true + rm -rf /var/log/pgadmin 2>/dev/null || true + rm -rf /etc/pgadmin 2>/dev/null || true + rm -f /usr/pgadmin4 2>/dev/null || true + + true + `); + console.log("[pgadmin] pgAdmin4 data directories cleaned"); + + await runCmd(` + rm -f /etc/apt/sources.list.d/pgadmin4.list 2>/dev/null || true + rm -f /usr/share/keyrings/packages-pgadmin-org.gpg 2>/dev/null || true + + # Update apt to remove stale references + apt-get update -qq 2>/dev/null || true + + true + `); + console.log("[pgadmin] pgAdmin4 apt sources removed for clean reinstall"); + + await runCmd(` + true + `); + const existingConfig = loadPgAdminConfig(); + const savedPgPort = validatePort(existingConfig.port || '5432'); + await maybeRemoveFirewallPort(runCmd, String(savedPgPort || 5432), 'pgadmin'); + console.log("[pgadmin] Firewall cleanup check completed"); + + const config = { enabled: false, users: [], disabledAt: Date.now() }; + if (!savePgAdminConfig(config)) { + return res.status(500).json({ error: "Failed to save configuration" }); + } + + console.log("[pgadmin] pgAdmin4 fully disabled and uninstalled - ready for clean reinstall"); + return res.json({ ok: true, message: "pgAdmin4 disabled and uninstalled. You can reinstall fresh at any time." }); + } catch (err) { + console.error("[pgadmin] Disable error:", err); + return res.status(500).json({ error: "Failed to disable: " + err.message }); + } +}); + +app.get("/api/settings/database/mongodb/status", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const config = loadMongoDBConfig(); + const mongoRunning = await checkServiceRunning("mongod"); + + return res.json({ + enabled: config.enabled, + installed: mongoRunning, + mongoRunning, + host: config.host || '127.0.0.1', + port: config.port || '27017', + users: (config.users || []).map(u => ({ username: u.username, createdAt: u.createdAt })) + }); +}); + +app.post("/api/settings/database/mongodb/setup", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/mongodb/setup")) return; + + const { username, password, host, port } = req.body || {}; + + const cleanUsername = String(username || "admin").trim(); + if (!cleanUsername || cleanUsername.length > 64 || !/^[a-zA-Z0-9_-]+$/.test(cleanUsername)) { + return res.status(400).json({ error: "Invalid username (alphanumeric, _, - only)" }); + } + + if (!password || password.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + const rawHost = String(host || "127.0.0.1").trim(); + const rawPort = String(port || "27017").trim(); + + const cleanHost = validateDbHost(rawHost); + if (!cleanHost) { + return res.status(400).json({ error: "Invalid host. Must be localhost, a valid IPv4/IPv6 address, or a valid hostname" }); + } + + const cleanPortNum = validatePort(rawPort); + if (!cleanPortNum) { + return res.status(400).json({ error: "Invalid port. Must be a number between 1 and 65535" }); + } + const cleanPort = String(cleanPortNum); + + const jobId = createInstallJob('mongodb'); + const connectionString = `mongodb://${cleanUsername}:****@localhost:${cleanPort}/admin?authSource=admin`; + + res.json({ ok: true, jobId, message: "Installation started", connectionString }); + + (async () => { + try { + console.log("[mongodb] Starting MongoDB setup..."); + + const result = await installMongoDB(cleanUsername, password, jobId, cleanHost, cleanPort); + if (!result.ok) { + updateInstallJob(jobId, { status: 'failed', error: result.error || "Installation failed", completedAt: Date.now() }); + return; + } + + updateInstallJob(jobId, { progress: 95, message: 'Saving configuration...' }); + const passwordHash = await bcrypt.hash(password, BCRYPT_ROUNDS); + const config = { + enabled: true, + host: cleanHost, + port: cleanPort, + users: [{ + username: cleanUsername, + passwordHash, + createdAt: Date.now() + }], + setupAt: Date.now() + }; + + if (!saveMongoDBConfig(config)) { + updateInstallJob(jobId, { status: 'failed', error: "Failed to save configuration", completedAt: Date.now() }); + return; + } + + updateInstallJob(jobId, { + status: 'completed', + progress: 100, + message: 'Installation complete!', + completedAt: Date.now(), + result: { connectionString } + }); + + console.log("[mongodb] Setup complete"); + + } catch (err) { + console.error("[mongodb] Setup error:", err); + updateInstallJob(jobId, { status: 'failed', error: err.message || "unknown error", completedAt: Date.now() }); + } + })(); +}); + +app.post("/api/settings/database/mongodb/disable", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/mongodb/disable")) return; + + try { + console.log("[mongodb] Disabling MongoDB - full cleanup..."); + + const runCmd = (cmd, timeoutMs = 60000) => new Promise((resolve) => { + const child = _privBashSpawn(cmd, { + shell: false, + env: { ...process.env, DEBIAN_FRONTEND: "noninteractive" } + }); + let output = ""; + child.stdout.on("data", (d) => { output += d.toString(); }); + child.stderr.on("data", (d) => { output += d.toString(); }); + child.on("close", (code) => resolve({ code, output })); + child.on("error", () => resolve({ code: 1, output: "spawn error" })); + setTimeout(() => { child.kill(); resolve({ code: -1, output: "timeout" }); }, timeoutMs); + }); + + console.log("[mongodb] Stopping MongoDB service..."); + await runCmd("systemctl stop mongod 2>/dev/null || true"); + await runCmd("systemctl disable mongod 2>/dev/null || true"); + await runCmd("pkill -9 mongod 2>/dev/null || true"); + console.log("[mongodb] MongoDB service stopped and disabled"); + + console.log("[mongodb] Removing MongoDB packages..."); + await runCmd("DEBIAN_FRONTEND=noninteractive apt-get purge -y mongodb-org mongodb-org-server mongodb-org-mongos mongodb-org-shell mongodb-org-tools mongodb-mongosh 2>/dev/null || true", 120000); + await runCmd("DEBIAN_FRONTEND=noninteractive apt-get autoremove -y 2>/dev/null || true", 60000); + console.log("[mongodb] MongoDB packages removed"); + + console.log("[mongodb] Removing MongoDB data and configuration..."); + await runCmd(` + # Remove data directories + rm -rf /var/lib/mongodb 2>/dev/null || true + rm -rf /var/log/mongodb 2>/dev/null || true + + # Remove config files + rm -f /etc/mongod.conf 2>/dev/null || true + + # Remove lock files + rm -f /tmp/mongodb-*.sock 2>/dev/null || true + + true + `); + const existingConfig = loadMongoDBConfig(); + const savedMongoPort = validatePort(existingConfig.port || '27017'); + await maybeRemoveFirewallPort(runCmd, String(savedMongoPort || 27017), 'mongodb'); + console.log("[mongodb] MongoDB data and config removed"); + + console.log("[mongodb] Removing MongoDB apt sources..."); + await runCmd(` + rm -f /etc/apt/sources.list.d/mongodb*.list 2>/dev/null || true + rm -f /usr/share/keyrings/mongodb*.gpg 2>/dev/null || true + apt-get update 2>/dev/null || true + `, 60000); + console.log("[mongodb] MongoDB apt sources removed"); + + + await runCmd("systemctl daemon-reload"); + + const config = { enabled: false, users: [], disabledAt: Date.now() }; + if (!saveMongoDBConfig(config)) { + return res.status(500).json({ error: "Failed to save configuration" }); + } + + console.log("[mongodb] MongoDB fully disabled and removed - ready for clean reinstall"); + return res.json({ ok: true, message: "MongoDB disabled and fully removed" }); + } catch (err) { + console.error("[mongodb] Disable error:", err); + return res.status(500).json({ error: "Failed to disable: " + err.message }); + } +}); + +app.post("/api/settings/database/mongodb/users", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/mongodb/users")) return; + + if (mongodbOperationLock) { + return res.status(429).json({ error: "Another MongoDB operation is in progress. Please wait." }); + } + mongodbOperationLock = true; + + try { + const { username, password } = req.body || {}; + const cleanUsername = String(username || "").trim(); + + if (!cleanUsername || !/^[a-zA-Z0-9_-]+$/.test(cleanUsername) || cleanUsername.length > 64) { + return res.status(400).json({ error: "Invalid username" }); + } + if (!password || password.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + try { + const config = loadMongoDBConfig(); + if (!config.enabled) { + return res.status(400).json({ error: "MongoDB is not enabled" }); + } + + if (config.users?.some(u => u.username === cleanUsername)) { + return res.status(400).json({ error: "User already exists" }); + } + + const portNum = validatePort(config.port || '27017'); + if (!portNum) { + return res.status(500).json({ error: "Invalid MongoDB port in config" }); + } + const port = String(portNum); + const mongoConfPath = '/etc/mongod.conf'; + + let originalBindIp = null; + + const runMongosh = (evalScript) => new Promise((resolve) => { + const child = spawn("mongosh", ["--port", port, "admin", "--quiet", "--eval", evalScript], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + let stdout = "", stderr = ""; + child.stdout.on("data", (d) => { stdout += d.toString(); }); + child.stderr.on("data", (d) => { stderr += d.toString(); }); + child.on("close", (code) => resolve({ code, stdout, stderr })); + child.on("error", (err) => resolve({ code: 1, stdout, stderr: err.message })); + setTimeout(() => { child.kill(); resolve({ code: -1, stdout, stderr: "timeout" }); }, 15000); + }); + + const runSystemctl = (action) => new Promise((resolve) => { + const child = spawn("systemctl", [action, "mongod"], { shell: false, stdio: 'pipe' }); + child.on("close", (code) => resolve(code === 0)); + child.on("error", () => resolve(false)); + setTimeout(() => { child.kill(); resolve(false); }, 30000); + }); + + try { + let conf = fs.readFileSync(mongoConfPath, 'utf8'); + const hadAuth = conf.includes('authorization: enabled'); + + if (hadAuth) { + const bindMatch = conf.match(/bindIp:\s*([\d.,]+)/); + originalBindIp = bindMatch ? bindMatch[1] : '127.0.0.1'; + + conf = conf.replace(/bindIp:\s*[\d.,]+/g, 'bindIp: 127.0.0.1'); + conf = conf.replace(/security:\s*\n\s*authorization:\s*enabled\s*/g, ''); + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + await new Promise(r => setTimeout(r, 2000)); + } + + const safePassword = JSON.stringify(password); + const safeUsername = JSON.stringify(cleanUsername); + const createScript = `db.createUser({user: ${safeUsername}, pwd: ${safePassword}, roles: [{role: "readWriteAnyDatabase", db: "admin"}]})`; + const result = await runMongosh(createScript); + + if (result.code !== 0 && !result.stderr.includes('already exists')) { + throw new Error(result.stderr || result.stdout || "Failed to create user"); + } + + if (hadAuth) { + conf = fs.readFileSync(mongoConfPath, 'utf8'); + if (originalBindIp) { + conf = conf.replace(/bindIp:\s*[\d.,]+/g, `bindIp: ${originalBindIp}`); + } + if (!conf.includes('authorization: enabled')) { + conf += '\nsecurity:\n authorization: enabled\n'; + } + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + } + + config.users = config.users || []; + const passwordHash = await bcrypt.hash(password, BCRYPT_ROUNDS); + config.users.push({ username: cleanUsername, passwordHash, createdAt: Date.now() }); + saveMongoDBConfig(config); + + console.log(`[mongodb] User '${cleanUsername}' created`); + return res.json({ ok: true, message: "User created" }); + } catch (cmdErr) { + try { + let conf = fs.readFileSync(mongoConfPath, 'utf8'); + if (originalBindIp) { + conf = conf.replace(/bindIp:\s*[\d.,]+/g, `bindIp: ${originalBindIp}`); + } + if (!conf.includes('authorization: enabled')) { + conf += '\nsecurity:\n authorization: enabled\n'; + } + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + } catch (e) { console.error("[mongodb] Failed to restore config:", e.message); } + throw cmdErr; + } + } catch (err) { + console.error("[mongodb] Create user error:", err.message); + return res.status(500).json({ error: "Failed to create user: " + err.message }); + } + } finally { + mongodbOperationLock = false; + } +}); + +app.delete("/api/settings/database/mongodb/users/:username", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "DELETE /api/settings/database/mongodb/users/:username", { username: String(req.params.username || "").trim() })) return; + + if (mongodbOperationLock) { + return res.status(429).json({ error: "Another MongoDB operation is in progress. Please wait." }); + } + mongodbOperationLock = true; + + try { + const { username } = req.params; + const cleanUsername = String(username || "").trim(); + + if (!cleanUsername || !/^[a-zA-Z0-9_-]+$/.test(cleanUsername)) { + return res.status(400).json({ error: "Invalid username" }); + } + + try { + const config = loadMongoDBConfig(); + if (!config.enabled) { + return res.status(400).json({ error: "MongoDB is not enabled" }); + } + + if (config.users?.[0]?.username === cleanUsername) { + return res.status(400).json({ error: "Cannot delete the admin user" }); + } + + const portNum = validatePort(config.port || '27017'); + if (!portNum) { + return res.status(500).json({ error: "Invalid MongoDB port in config" }); + } + const port = String(portNum); + const mongoConfPath = '/etc/mongod.conf'; + let originalBindIp = null; + + const runMongosh = (evalScript) => new Promise((resolve) => { + const child = spawn("mongosh", ["--port", port, "admin", "--quiet", "--eval", evalScript], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + let stdout = "", stderr = ""; + child.stdout.on("data", (d) => { stdout += d.toString(); }); + child.stderr.on("data", (d) => { stderr += d.toString(); }); + child.on("close", (code) => resolve({ code, stdout, stderr })); + child.on("error", (err) => resolve({ code: 1, stdout, stderr: err.message })); + setTimeout(() => { child.kill(); resolve({ code: -1, stdout, stderr: "timeout" }); }, 15000); + }); + + const runSystemctl = (action) => new Promise((resolve) => { + const child = spawn("systemctl", [action, "mongod"], { shell: false, stdio: 'pipe' }); + child.on("close", (code) => resolve(code === 0)); + child.on("error", () => resolve(false)); + setTimeout(() => { child.kill(); resolve(false); }, 30000); + }); + + try { + let conf = fs.readFileSync(mongoConfPath, 'utf8'); + const hadAuth = conf.includes('authorization: enabled'); + if (hadAuth) { + const bindMatch = conf.match(/bindIp:\s*([\d.,]+)/); + originalBindIp = bindMatch ? bindMatch[1] : '127.0.0.1'; + + conf = conf.replace(/bindIp:\s*[\d.,]+/g, 'bindIp: 127.0.0.1'); + conf = conf.replace(/security:\s*\n\s*authorization:\s*enabled\s*/g, ''); + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + await new Promise(r => setTimeout(r, 2000)); + } + + const safeUsername = JSON.stringify(cleanUsername); + const deleteScript = `db.dropUser(${safeUsername})`; + await runMongosh(deleteScript); + + if (hadAuth) { + conf = fs.readFileSync(mongoConfPath, 'utf8'); + if (originalBindIp) { + conf = conf.replace(/bindIp:\s*[\d.,]+/g, `bindIp: ${originalBindIp}`); + } + if (!conf.includes('authorization: enabled')) { + conf += '\nsecurity:\n authorization: enabled\n'; + } + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + } + } catch (cmdErr) { + try { + let conf = fs.readFileSync(mongoConfPath, 'utf8'); + if (originalBindIp) { + conf = conf.replace(/bindIp:\s*[\d.,]+/g, `bindIp: ${originalBindIp}`); + } + if (!conf.includes('authorization: enabled')) { + conf += '\nsecurity:\n authorization: enabled\n'; + } + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + } catch (e) { console.error("[mongodb] Failed to restore config:", e.message); } + } + + config.users = (config.users || []).filter(u => u.username !== cleanUsername); + saveMongoDBConfig(config); + + console.log(`[mongodb] User '${cleanUsername}' deleted`); + return res.json({ ok: true, message: "User deleted" }); + } catch (err) { + console.error("[mongodb] Delete user error:", err.message); + return res.status(500).json({ error: "Failed to delete user" }); + } + } finally { + mongodbOperationLock = false; + } +}); + +app.post("/api/settings/database/mongodb/users/:username/password", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/database/mongodb/users/:username/password", { username: String(req.params.username || "").trim() })) return; + + if (mongodbOperationLock) { + return res.status(429).json({ error: "Another MongoDB operation is in progress. Please wait." }); + } + mongodbOperationLock = true; + + try { + const { username } = req.params; + const { password } = req.body || {}; + const cleanUsername = String(username || "").trim(); + + if (!cleanUsername) { + return res.status(400).json({ error: "Invalid username" }); + } + if (!password || password.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + try { + const config = loadMongoDBConfig(); + if (!config.enabled) { + return res.status(400).json({ error: "MongoDB is not enabled" }); + } + + const portNum = validatePort(config.port || '27017'); + if (!portNum) { + return res.status(500).json({ error: "Invalid MongoDB port in config" }); + } + const port = String(portNum); + const mongoConfPath = '/etc/mongod.conf'; + let originalBindIp = null; + + const runMongosh = (evalScript) => new Promise((resolve) => { + const child = spawn("mongosh", ["--port", port, "admin", "--quiet", "--eval", evalScript], { + shell: false, + stdio: ['pipe', 'pipe', 'pipe'] + }); + let stdout = "", stderr = ""; + child.stdout.on("data", (d) => { stdout += d.toString(); }); + child.stderr.on("data", (d) => { stderr += d.toString(); }); + child.on("close", (code) => resolve({ code, stdout, stderr })); + child.on("error", (err) => resolve({ code: 1, stdout, stderr: err.message })); + setTimeout(() => { child.kill(); resolve({ code: -1, stdout, stderr: "timeout" }); }, 15000); + }); + + const runSystemctl = (action) => new Promise((resolve) => { + const child = spawn("systemctl", [action, "mongod"], { shell: false, stdio: 'pipe' }); + child.on("close", (code) => resolve(code === 0)); + child.on("error", () => resolve(false)); + setTimeout(() => { child.kill(); resolve(false); }, 30000); + }); + + try { + let conf = fs.readFileSync(mongoConfPath, 'utf8'); + const hadAuth = conf.includes('authorization: enabled'); + if (hadAuth) { + const bindMatch = conf.match(/bindIp:\s*([\d.,]+)/); + originalBindIp = bindMatch ? bindMatch[1] : '127.0.0.1'; + + conf = conf.replace(/bindIp:\s*[\d.,]+/g, 'bindIp: 127.0.0.1'); + conf = conf.replace(/security:\s*\n\s*authorization:\s*enabled\s*/g, ''); + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + await new Promise(r => setTimeout(r, 2000)); + } + + const safeUsername = JSON.stringify(cleanUsername); + const safePassword = JSON.stringify(password); + const changeScript = `db.changeUserPassword(${safeUsername}, ${safePassword})`; + const result = await runMongosh(changeScript); + + if (result.code !== 0) { + throw new Error(result.stderr || result.stdout || "Failed to change password"); + } + + if (hadAuth) { + conf = fs.readFileSync(mongoConfPath, 'utf8'); + if (originalBindIp) { + conf = conf.replace(/bindIp:\s*[\d.,]+/g, `bindIp: ${originalBindIp}`); + } + if (!conf.includes('authorization: enabled')) { + conf += '\nsecurity:\n authorization: enabled\n'; + } + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + } + + const userEntry = config.users?.find(u => u.username === cleanUsername); + if (userEntry) { + userEntry.passwordHash = await bcrypt.hash(password, BCRYPT_ROUNDS); + delete userEntry.password; + saveMongoDBConfig(config); + } + + console.log(`[mongodb] Password changed for '${cleanUsername}'`); + return res.json({ ok: true, message: "Password changed" }); + } catch (cmdErr) { + try { + let conf = fs.readFileSync(mongoConfPath, 'utf8'); + if (originalBindIp) { + conf = conf.replace(/bindIp:\s*[\d.,]+/g, `bindIp: ${originalBindIp}`); + } + if (!conf.includes('authorization: enabled')) { + conf += '\nsecurity:\n authorization: enabled\n'; + } + fs.writeFileSync(mongoConfPath, conf); + await runSystemctl('restart'); + } catch (e) { console.error("[mongodb] Failed to restore config:", e.message); } + throw cmdErr; + } + } catch (err) { + console.error("[mongodb] Change password error:", err.message); + return res.status(500).json({ error: "Failed to change password" }); + } + } finally { + mongodbOperationLock = false; + } +}); + +app.get("/api/settings/database/mongodb/users", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + try { + const config = loadMongoDBConfig(); + + const safeUsers = (config.users || []).map(u => ({ username: u.username, createdAt: u.createdAt })); + + const actionTokens = { + createUser: issueActionToken(req, "POST /api/settings/database/mongodb/users", {}, { ttlSeconds: 120, oneTime: true }), + }; + for (const u of safeUsers) { + actionTokens[`deleteUser_${u.username}`] = issueActionToken(req, "DELETE /api/settings/database/mongodb/users/:username", { username: u.username }, { ttlSeconds: 120, oneTime: true }); + actionTokens[`changePassword_${u.username}`] = issueActionToken(req, "POST /api/settings/database/mongodb/users/:username/password", { username: u.username }, { ttlSeconds: 120, oneTime: true }); + } + + return res.json({ + ok: true, + enabled: config.enabled || false, + host: config.host || '127.0.0.1', + port: config.port || '27017', + users: safeUsers, + actionTokens + }); + } catch (err) { + return res.status(500).json({ error: "Failed to load users" }); + } +}); + +app.get("/api/templates", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + return res.json({ templates: loadTemplatesFile() }); +}); + +app.post("/api/templates/startup-command", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const templateId = normalizeTemplateId(req.body?.templateId || ""); + if (!templateId) return res.status(400).json({ error: "missing templateId" }); + + const targetNodeId = String(req.body?.nodeId || "").trim(); + + const template = findTemplateById(templateId); + if (!template) return res.status(404).json({ error: "template not found" }); + + const startFile = String(template.start || defaultStartFileForTemplate(templateId) || "").trim(); + const docker = normalizeTemplateDockerForRuntime(templateId, template.docker, startFile); + const adpanelStartup = sanitizeADPanelStartupInput(docker?.adpanelStartup); + const fallback = normalizeLegacyRuntimeProcessCommandInput( + templateId, + docker?.command || defaultRuntimeCommandForTemplate(templateId, docker, startFile) + ); + const fallbackError = validateRuntimeProcessCommandInput(fallback); + const fallbackCommand = fallbackError ? "" : fallback; + + const image = String(docker?.image || "").trim(); + const tag = String(docker?.tag || "latest").trim() || "latest"; + if (adpanelStartup) { + return res.json({ + ok: true, + command: adpanelStartup, + source: "adpanel-startup", + imageRef: image ? `${image}:${tag}` : "", + templateManaged: true, + warning: "Startup is managed by the template installer/runtime environment.", + }); + } + if (!image) { + if (fallbackCommand) { + return res.json({ ok: true, command: fallbackCommand, source: "template-default", imageRef: "" }); + } + return res.status(400).json({ error: "template has no docker image" }); + } + + let node = null; + if (targetNodeId && targetNodeId.toLowerCase() !== "local") { + node = await findNodeByIdOrName(targetNodeId); + } + if (!node) { + const allNodes = await loadNodes(); + node = allNodes.find(n => n && n.online) || allNodes[0] || null; + } + if (!node) { + if (fallbackCommand) { + return res.json({ ok: true, command: fallbackCommand, source: "template-default", imageRef: `${image}:${tag}`, warning: "no node available for image inspect" }); + } + return res.status(503).json({ error: "no node available for image inspect" }); + } + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) { + if (fallbackCommand) { + return res.json({ ok: true, command: fallbackCommand, source: "template-default", imageRef: `${image}:${tag}`, warning: "invalid node address for image inspect" }); + } + return res.status(400).json({ error: "invalid node address" }); + } + + const payload = { + templateId, + image, + tag, + startFile, + dataDir: runtimeDataDirForTemplate(templateId, docker), + fallbackCommand, + }; + + const headers = nodeAuthHeadersFor(node, true); + const upstream = await httpRequestJson(`${baseUrl}/v1/runtime/startup-command`, "POST", headers, payload, 45_000); + + let command = ""; + let source = "template-default"; + let warning = null; + let inspectEntrypoint = []; + let inspectCmd = []; + let inspectWorkingDir = ""; + let inspectEnv = {}; + + if (upstream.status === 200 && upstream.json && upstream.json.ok) { + command = normalizeLegacyRuntimeProcessCommandInput(templateId, upstream.json.command); + source = String(upstream.json.source || "image-inspect").trim() || "image-inspect"; + inspectEntrypoint = Array.isArray(upstream.json.entrypoint) ? upstream.json.entrypoint : []; + inspectCmd = Array.isArray(upstream.json.cmd) ? upstream.json.cmd : []; + inspectWorkingDir = String(upstream.json.workingDir || "").trim(); + inspectEnv = (upstream.json.env && typeof upstream.json.env === 'object' && !Array.isArray(upstream.json.env)) + ? upstream.json.env + : {}; + } else { + const detail = String(upstream.json?.detail || upstream.json?.error || `inspect failed (${upstream.status})`).trim(); + warning = detail || null; + } + + if ( + source === 'image-inspect' && + command && + (looksLikeWrapperEntrypointOnlyCommand(command, inspectEntrypoint, inspectCmd) || looksLikePathOnlyScriptCommand(command)) + ) { + if (fallbackCommand) { + command = fallbackCommand; + source = 'template-default'; + warning = warning + ? `${warning}; inspect returned wrapper/path-only command` + : 'inspect returned wrapper/path-only command'; + } + } + + if (!command) { + command = fallbackCommand; + if (command) source = "template-default"; + } + + const commandError = validateRuntimeProcessCommandInput(command); + if (!command || commandError) { + return res.status(502).json({ + error: commandError || "failed to infer startup command", + detail: warning || "Image inspection did not produce a valid process command.", + }); + } + + return res.json({ + ok: true, + command, + source, + imageRef: `${image}:${tag}`, + warning, + inspect: { + entrypoint: inspectEntrypoint, + cmd: inspectCmd, + workingDir: inspectWorkingDir || '/', + env: inspectEnv, + }, + }); +}); + +app.get("/api/settings/templates", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + let templates = loadTemplatesFile() || []; + + const search = String(req.query.search || '').trim().toLowerCase(); + if (search) { + templates = templates.filter(t => t && ((t.name && t.name.toLowerCase().includes(search)) || (t.id && t.id.toLowerCase().includes(search)))); + } + + const total = templates.length; + const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 50, 1), 200); + 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; + templates = templates.slice(offset, offset + limit); + + return res.json({ templates, total, page, totalPages }); +}); + +app.post("/api/settings/templates", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const { + id, + name, + description, + dockerImage, + dockerTag, + templateImage, + defaultPort, + ports, + volumes, + env, + command, + startup, + startupCommand, + adpanelStartup, + install, + installation, + dockerWorkdir, + workdir, + } = req.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 cleanStartupCommand = String(startupCommand || "").trim(); + const cleanADPanelStartup = sanitizeADPanelStartupInput(adpanelStartup); + const cleanInstall = sanitizeDockerInstallPayload(install || installation); + const rawWorkdir = String(dockerWorkdir ?? workdir ?? "").trim(); + const cleanWorkdir = normalizeRuntimeWorkdirInput(rawWorkdir); + + 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 (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." }); + } + const commandError = validateRuntimeProcessCommandInput(cleanCommand); + if (commandError) return res.status(400).json({ error: commandError }); + + const list = loadTemplatesFile(); + const exists = list.find(t => String(t?.id || "").toLowerCase() === cleanId); + if (exists) return res.status(400).json({ error: "template id already exists" }); + + const cleanPorts = validatePortListInput(ports); + if (cleanPorts === null) return res.status(400).json({ error: "invalid ports" }); + + let cleanVolumes = cleanWorkdir ? [defaultTemplateBotDirVolumeForWorkdir(cleanWorkdir)] : []; + if (Array.isArray(volumes) && volumes.length > 0) { + cleanVolumes = volumes.map(v => String(v).trim()).filter(Boolean); + } else if (typeof volumes === "string" && volumes.trim()) { + cleanVolumes = [volumes.trim()]; + } + + const cleanEnv = sanitizeEnvPayload(env) || {}; + + const cleanDefaultPort = validatePort(defaultPort) || (cleanPorts.length > 0 ? cleanPorts[0] : 8080); + const tpl = { + id: cleanId, + name: cleanName, + description: cleanDesc, + defaultPort: cleanDefaultPort, + ...(cleanTemplateImage ? { templateImage: cleanTemplateImage } : {}), + docker: { + image: cleanImage, + tag: cleanTag, + ports: cleanPorts, + volumes: cleanVolumes, + ...(cleanWorkdir ? { workdir: cleanWorkdir } : {}), + env: cleanEnv, + ...(cleanCommand ? { command: cleanCommand } : {}), + ...(cleanADPanelStartup ? { adpanelStartup: cleanADPanelStartup } : {}), + ...(cleanInstall ? { install: cleanInstall } : {}), + restart: "unless-stopped", + console: { type: "stdin" }, + }, + }; + + list.push(tpl); + if (!saveTemplatesFile(list)) return res.status(500).json({ error: "failed to save templates" }); + return res.json({ ok: true, template: tpl }); +}); + +app.put("/api/settings/templates/:id", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const targetId = normalizeTemplateId(req.params.id || ""); + if (!targetId) return res.status(400).json({ error: "invalid template id" }); + + const list = loadTemplatesFile(); + const idx = list.findIndex(t => normalizeTemplateId(t?.id) === targetId); + if (idx < 0) return res.status(404).json({ error: "template not found" }); + + const current = list[idx] || {}; + const currentDocker = (current && typeof current.docker === "object" && !Array.isArray(current.docker)) ? current.docker : {}; + const body = req.body && typeof req.body === "object" ? req.body : {}; + + const { + id, + name, + description, + dockerImage, + dockerTag, + templateImage, + defaultPort, + ports, + volumes, + env, + command, + startup, + startupCommand, + adpanelStartup, + install, + installation, + dockerWorkdir, + workdir, + } = body; + + const cleanId = String(id || current.id || "").trim().toLowerCase(); + if (!cleanId || !/^[a-z0-9_-]{2,60}$/.test(cleanId)) return res.status(400).json({ error: "invalid id" }); + if (normalizeTemplateId(cleanId) !== targetId) return res.status(400).json({ error: "template id cannot be changed" }); + + const cleanName = String(name || "").trim(); + const cleanDesc = String(description || "").trim(); + const cleanImage = String(dockerImage || "").trim(); + const cleanTag = String(dockerTag || currentDocker.tag || "latest").trim() || "latest"; + + const hasTemplateImage = Object.prototype.hasOwnProperty.call(body, "templateImage"); + const cleanTemplateImage = hasTemplateImage + ? String(templateImage || "").trim() + : String(current.templateImage || "").trim(); + + const hasCommandInput = Object.prototype.hasOwnProperty.call(body, "command") + || Object.prototype.hasOwnProperty.call(body, "startup"); + const rawCommandInput = hasCommandInput + ? (Object.prototype.hasOwnProperty.call(body, "command") ? command : startup) + : (currentDocker.command || ""); + const cleanCommand = normalizeLegacyRuntimeProcessCommandInput(cleanId, rawCommandInput || ""); + const cleanStartupCommand = String(startupCommand || "").trim(); + const hasADPanelStartupInput = Object.prototype.hasOwnProperty.call(body, "adpanelStartup") + || Object.prototype.hasOwnProperty.call(body, "adpanel_startup") + || Object.prototype.hasOwnProperty.call(body, "pterodactylStartup") + || Object.prototype.hasOwnProperty.call(body, "pterodactyl_startup"); + const cleanADPanelStartup = sanitizeADPanelStartupInput( + hasADPanelStartupInput + ? (body.adpanelStartup ?? body.adpanel_startup ?? body.pterodactylStartup ?? body.pterodactyl_startup) + : (currentDocker.adpanelStartup || "") + ); + const hasInstallInput = Object.prototype.hasOwnProperty.call(body, "install") + || Object.prototype.hasOwnProperty.call(body, "installation"); + const cleanInstall = sanitizeDockerInstallPayload( + hasInstallInput + ? (install || installation) + : (currentDocker.install || currentDocker.installation) + ); + const rawWorkdir = String(dockerWorkdir ?? workdir ?? currentDocker.workdir ?? "").trim(); + const cleanWorkdir = normalizeRuntimeWorkdirInput(rawWorkdir); + + if (!cleanName) return res.status(400).json({ error: "missing name" }); + if (!cleanImage) return res.status(400).json({ error: "missing docker image" }); + 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." }); + } + const commandError = validateRuntimeProcessCommandInput(cleanCommand); + if (commandError) return res.status(400).json({ error: commandError }); + + const hasPortsInput = Object.prototype.hasOwnProperty.call(body, "ports"); + const cleanPorts = validatePortListInput(hasPortsInput ? ports : currentDocker.ports); + if (cleanPorts === null) return res.status(400).json({ error: "invalid ports" }); + + let cleanVolumes = cleanWorkdir ? [defaultTemplateBotDirVolumeForWorkdir(cleanWorkdir)] : []; + const workdirChanged = normalizeRuntimeWorkdirInput(currentDocker.workdir || "") !== cleanWorkdir; + const autoAlignCurrentBotDirVolume = shouldAutoAlignBotDirVolume(currentDocker.volumes); + if (Object.prototype.hasOwnProperty.call(body, "volumes")) { + if (Array.isArray(volumes) && volumes.length > 0) { + cleanVolumes = volumes.map(v => String(v).trim()).filter(Boolean); + } else if (typeof volumes === "string" && volumes.trim()) { + cleanVolumes = [volumes.trim()]; + } + } else if (Array.isArray(currentDocker.volumes) && currentDocker.volumes.length > 0) { + cleanVolumes = currentDocker.volumes.map(v => String(v || "").trim()).filter(Boolean); + if (!cleanVolumes.length && cleanWorkdir) { + cleanVolumes = [defaultTemplateBotDirVolumeForWorkdir(cleanWorkdir)]; + } else if (workdirChanged && autoAlignCurrentBotDirVolume) { + cleanVolumes = cleanWorkdir ? [defaultTemplateBotDirVolumeForWorkdir(cleanWorkdir)] : []; + } + } + + let cleanEnv = {}; + if (Object.prototype.hasOwnProperty.call(body, "env")) { + 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 ?? ""); + } + } + } + } 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 existingDefaultPort = validatePort(current.defaultPort); + const cleanDefaultPort = validatePort(defaultPort) + || existingDefaultPort + || (cleanPorts.length > 0 ? cleanPorts[0] : 8080); + + const tpl = { + id: cleanId, + name: cleanName, + description: cleanDesc, + defaultPort: cleanDefaultPort, + ...(cleanTemplateImage ? { templateImage: cleanTemplateImage } : {}), + docker: { + image: cleanImage, + tag: cleanTag, + ports: cleanPorts, + volumes: cleanVolumes, + ...(cleanWorkdir ? { workdir: cleanWorkdir } : {}), + env: cleanEnv, + ...(cleanCommand ? { command: cleanCommand } : {}), + ...(cleanADPanelStartup ? { adpanelStartup: cleanADPanelStartup } : {}), + ...(cleanInstall ? { install: cleanInstall } : {}), + restart: "unless-stopped", + console: { type: "stdin" }, + }, + }; + + list[idx] = tpl; + if (!saveTemplatesFile(list)) return res.status(500).json({ error: "failed to save templates" }); + return res.json({ ok: true, template: tpl }); +}); + +app.delete("/api/settings/templates/:id", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const cleanId = normalizeTemplateId(req.params.id || ""); + if (!cleanId) return res.status(400).json({ error: "invalid template id" }); + + const list = loadTemplatesFile(); + const idx = list.findIndex(t => normalizeTemplateId(t?.id) === cleanId); + if (idx < 0) return res.status(404).json({ error: "template not found" }); + + const used = (await loadServersIndex()) + .filter(s => normalizeTemplateId(s?.template) === cleanId) + .map(s => s.name) + .filter(Boolean); + if (used.length) return res.status(400).json({ error: "template in use", servers: used }); + + list.splice(idx, 1); + if (!saveTemplatesFile(list)) return res.status(500).json({ error: "failed to save templates" }); + return res.json({ ok: true, removed: cleanId }); +}); + +const DASH_STATUS_TTL_MS = parseInt(process.env.DASH_STATUS_TTL_MS || "5000", 10); +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; + + const allNames = serverIndex.map(e => e && e.name).filter(Boolean); + + let botsToShow; + if (safeUser && safeUser.admin) { + botsToShow = allNames; + } else { + const access = email ? await getAccessListForEmail(email) : []; + botsToShow = access.includes("all") ? allNames : allNames.filter(n => access.includes(n)); + } + + const dashSearch = String(req.query.search || '').trim().toLowerCase(); + if (dashSearch) { + const sMap = new Map(serverIndex.filter(e => e && e.name).map(e => [e.name, e])); + botsToShow = botsToShow.filter(name => { + if (name.toLowerCase().includes(dashSearch)) return true; + const e = sMap.get(name); + return e && e.displayName && e.displayName.toLowerCase().includes(dashSearch); + }); + } + const totalServers = botsToShow.length; + const dashLimit = Math.min(Math.max(parseInt(req.query.limit, 10) || 50, 1), 200); + const dashTotalPages = Math.max(1, Math.ceil(totalServers / dashLimit)); + 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 templates = loadTemplatesFile() || []; + const templateMap = new Map(templates.filter(Boolean).map(t => [normalizeTemplateId(t.id), t])); + const nodes = await loadNodes(); + 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])); + + const botCards = botsToShow.map((name) => { + const entry = serverMap.get(name) || {}; + const cached = cachedStatuses.get(name); + const template = templateMap.get(normalizeTemplateId(entry.template)) || null; + const node = entry.nodeId ? nodeMap.get(entry.nodeId) : null; + + const status = cached?.status || normalizeStatusLabel(entry.status) || 'unknown'; + const nodeOnline = cached?.nodeOnline !== false; + + const cpuPercent = cached?.cpu ?? null; + const memoryUsed = cached?.memory ?? null; + const diskUsed = cached?.disk ?? null; + + const docker = entry.docker || {}; + const res = entry.resources || {}; + const memory = formatResource(memoryUsed ?? docker.memoryUsedMb ?? docker.memoryMbUsed, res.ramMb ?? docker.memoryMb); + const disk = formatResource(diskUsed ?? docker.storageUsedMb ?? docker.storageMbUsed, res.storageMb ?? docker.storageMb); + return { + name, + displayName: entry.displayName || null, + templateId: entry.template || null, + templateName: template?.name || entry.template || "Custom template", + templateImage: template?.templateImage || null, + description: template?.description || "Manage configuration, logs and deployments.", + nodeName: node?.name || (entry.nodeId ? entry.nodeId : "Node"), + nodeId: entry.nodeId || null, + ip: entry.ip || null, + port: entry.port || null, + cpu: cpuPercent != null ? `${Number(cpuPercent).toFixed(1)}%` : null, + cpuPercent, + cpuLimit: cached?.cpuLimit ?? null, + memory, + disk, + status, + nodeOnline, + statusUpdatedAt: cached?.updatedAt || null + }; + }); + + return res.render("index", { + bots: botCards, + pagination: { page: dashPage, totalPages: dashTotalPages, total: totalServers, limit: dashLimit, search: dashSearch }, + isAdmin: safeUser ? safeUser.admin : false, + showDashboardAssistant: canUserAccessDashboardAssistant(safeUser), + user: safeUser, + serverStartTime: SERVER_START, + globalAlert: getActiveGlobalAlert(), + quickActions: (function () { + const all = loadQuickActions(); + return (safeUser && safeUser.admin) ? all.admin : all.user; + })(), + avatarUrl: resolveUserAvatarUrl(safeUser), + cacheInfo: { + lastRefresh: statusCache.lastFullRefresh, + ttlMs: STATUS_CACHE_TTL_MS + } + }); + } catch (err) { + console.error("Error in GET /", err); + return res.status(500).send("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 }); +}); + +app.get("/account", async (req, res) => { + if (!req.session || !req.session.user) { + return res.redirect("/login"); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.redirect("/login"); + } + + const adminCheck = await isAdmin(req); + + res.render("account", { + username: user.username || user.email.split('@')[0], + email: user.email, + isAdmin: adminCheck, + odbc_id: user.id || 'N/A', + cspNonce: res.locals.cspNonce + }); +}); + +app.get("/api/account", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const adminCheck = await isAdmin(req); + + let statusText = "Available"; + let statusExpiresAt = null; + try { + const rows = await db.query( + "SELECT status_text, expires_at FROM user_status WHERE user_id = ?", + [user.id] + ); + if (rows && rows[0]) { + const now = Date.now(); + if (!rows[0].expires_at || Number(rows[0].expires_at) > now) { + statusText = rows[0].status_text || "Available"; + statusExpiresAt = rows[0].expires_at ? Number(rows[0].expires_at) : null; + } + } + } catch { + } + + let usernameChangeCooldown = null; + if (!adminCheck && user.username_changed_at) { + const lastChange = Number(user.username_changed_at); + const sevenDaysMs = 7 * 24 * 60 * 60 * 1000; + const timeSinceChange = Date.now() - lastChange; + if (timeSinceChange < sevenDaysMs) { + usernameChangeCooldown = sevenDaysMs - timeSinceChange; + } + } + + return res.json({ + ok: true, + username: user.username || user.email.split('@')[0], + email: user.email, + isAdmin: adminCheck, + userId: user.id || null, + createdAt: user.created_at || null, + avatarUrl: resolveUserAvatarUrl({ ...user, admin: adminCheck }), + status: statusText, + statusExpiresAt, + usernameChangeCooldown + }); +}); + +app.post("/api/account/avatar", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { avatarUrl } = req.body || {}; + + if (!avatarUrl || typeof avatarUrl !== 'string') { + return res.status(400).json({ error: "Avatar URL is required" }); + } + + const cleanUrl = avatarUrl.trim(); + if (cleanUrl.length > 2048) { + return res.status(400).json({ error: "URL too long" }); + } + + try { + new URL(cleanUrl); + } catch { + return res.status(400).json({ error: "Invalid URL format" }); + } + + if (!cleanUrl.startsWith('http://') && !cleanUrl.startsWith('https://')) { + return res.status(400).json({ error: "URL must use http or https protocol" }); + } + + try { + await db.query( + "UPDATE users SET avatar_url = ? WHERE LOWER(email) = LOWER(?)", + [cleanUrl, req.session.user] + ); + + return res.json({ ok: true, avatarUrl: cleanUrl }); + } catch (err) { + console.error("[account] Avatar update error:", err); + return res.status(500).json({ error: "Failed to update avatar" }); + } +}); + +app.post("/api/account/username", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { username } = req.body || {}; + + if (!username || typeof username !== 'string') { + return res.status(400).json({ error: "Username is required" }); + } + + const cleanUsername = username.trim(); + if (cleanUsername.length < 3 || cleanUsername.length > 30) { + return res.status(400).json({ error: "Username must be 3-30 characters" }); + } + + if (!/^[a-zA-Z0-9_-]+$/.test(cleanUsername)) { + return res.status(400).json({ error: "Username can only contain letters, numbers, underscore and hyphen" }); + } + + const isUserAdmin = !!user.admin; + if (!isUserAdmin && user.username_changed_at) { + const lastChange = Number(user.username_changed_at); + const sevenDaysMs = 7 * 24 * 60 * 60 * 1000; + const now = Date.now(); + const timeSinceChange = now - lastChange; + + if (timeSinceChange < sevenDaysMs) { + const remainingMs = sevenDaysMs - timeSinceChange; + const remainingDays = Math.ceil(remainingMs / (24 * 60 * 60 * 1000)); + return res.status(429).json({ + error: `You can change your username again in ${remainingDays} day${remainingDays !== 1 ? 's' : ''}`, + cooldownRemaining: remainingMs + }); + } + } + + try { + await db.query( + "UPDATE users SET username = ?, username_changed_at = ? WHERE LOWER(email) = LOWER(?)", + [cleanUsername, Date.now(), req.session.user] + ); + + return res.json({ ok: true, username: cleanUsername }); + } catch (err) { + console.error("[account] Username update error:", err); + return res.status(500).json({ error: "Failed to update username" }); + } +}); + +let _avatarUpload; +function getAvatarUpload() { + if (!_avatarUpload) { + const multer = getLazyMulter(); + const avatarStorage = multer.diskStorage({ + destination: function (req, file, cb) { + const uploadDir = path.join(__dirname, 'public', 'uploads', 'avatars'); + fs.mkdirSync(uploadDir, { recursive: true }); + cb(null, uploadDir); + }, + filename: function (req, file, cb) { + const mimeToExt = { + "image/jpeg": ".jpg", + "image/png": ".png", + "image/gif": ".gif", + "image/webp": ".webp" + }; + const ext = mimeToExt[file.mimetype] || ".jpg"; + const uniqueName = `${Date.now()}-${crypto.randomBytes(8).toString('hex')}${ext}`; + cb(null, uniqueName); + } + }); + _avatarUpload = multer({ + storage: avatarStorage, + limits: { fileSize: 5 * 1024 * 1024 }, + fileFilter: function (req, file, cb) { + const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']; + if (allowedTypes.includes(file.mimetype)) { + cb(null, true); + } else { + cb(new Error('Only image files are allowed (JPEG, PNG, GIF, WebP)')); + } + } + }); + } + return _avatarUpload; +} + +app.post("/api/account/avatar/upload", (req, res, next) => getAvatarUpload().single('avatar')(req, res, next), async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + if (!req.file) { + return res.status(400).json({ error: "No file uploaded" }); + } + + try { + const fileBuffer = await fsp.readFile(req.file.path); + + if (!validateFileMagicBytes(fileBuffer, req.file.mimetype)) { + await fsp.unlink(req.file.path).catch(() => { }); + console.warn(`[security] Rejected file upload: magic bytes don't match declared type ${req.file.mimetype}`); + return res.status(400).json({ error: "Invalid file format: file content doesn't match declared type" }); + } + + if (!checkFileForDangerousContent(fileBuffer)) { + await fsp.unlink(req.file.path).catch(() => { }); + console.warn(`[security] Rejected file upload: potentially dangerous content detected`); + return res.status(400).json({ error: "File rejected: potentially dangerous content detected" }); + } + } catch (err) { + await fsp.unlink(req.file.path).catch(() => { }); + console.error("[security] File validation error:", err); + return res.status(500).json({ error: "Failed to validate uploaded file" }); + } + + const avatarUrl = `/uploads/avatars/${req.file.filename}`; + + try { + if (user.avatar_url && user.avatar_url.startsWith('/uploads/avatars/')) { + try { + const oldFile = path.basename(user.avatar_url); + const oldPath = path.join(__dirname, 'public', 'uploads', 'avatars', oldFile); + await fsp.unlink(oldPath); + } catch { + } + } + + await db.query( + "UPDATE users SET avatar_url = ? WHERE LOWER(email) = LOWER(?)", + [avatarUrl, req.session.user] + ); + + return res.json({ ok: true, avatarUrl }); + } catch (err) { + console.error("[account] Avatar upload error:", err); + return res.status(500).json({ error: "Failed to update avatar" }); + } +}); + +app.post("/api/account/2fa/generate", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { currentCode } = 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" }); + } + + const newSecret = speakeasy.generateSecret({ length: 20 }); + const appName = process.env.APP_NAME || "ADPanel"; + const otpauthUrl = speakeasy.otpauthURL({ + secret: newSecret.base32, + label: user.email, + issuer: appName, + encoding: "base32", + }); + + const qrcode = require("qrcode"); + try { + const qrCodeUrl = await qrcode.toDataURL(otpauthUrl); + req.session.pending2faSecret = newSecret.base32; + req.session.pending2faFrom = 'standard'; + return res.json({ + ok: true, + newSecret: newSecret.base32, + qrCodeUrl: qrCodeUrl + }); + } catch (err) { + console.error("[account] QR code generation error:", err); + return res.status(500).json({ error: "Failed to generate QR code" }); + } +}); + +app.post("/api/account/2fa/confirm", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { newCode, newSecret } = req.body || {}; + + if (!newCode || typeof newCode !== 'string') { + return res.status(400).json({ error: "New 2FA code is required" }); + } + + if (!newSecret || typeof newSecret !== 'string') { + return res.status(400).json({ error: "New secret is required" }); + } + + const codeStr = newCode.replace(/\s+/g, ""); + if (!/^\d{6}$/.test(codeStr)) { + return res.status(400).json({ error: "Invalid 2FA code format" }); + } + + if (!/^[A-Z2-7]+=*$/i.test(newSecret) || newSecret.length < 16) { + return res.status(400).json({ error: "Invalid secret format" }); + } + + const pendingFlow = req.session.pending2faFrom || 'none'; + if (!req.session.pending2faSecret || req.session.pending2faSecret !== newSecret) { + delete req.session.pending2faSecret; + delete req.session.pending2faFrom; + console.log(`[SECURITY] 2FA confirm denied - secret mismatch | User: ${req.session.user} | IP: ${getRequestIp(req)} | Flow: ${pendingFlow}`); + return res.status(403).json({ error: "Invalid or tampered secret. Please generate a new 2FA secret first." }); + } + + const verified = speakeasy.totp.verify({ + secret: newSecret, + encoding: "base32", + token: codeStr, + window: 1, + }); + + if (!verified) { + return res.status(403).json({ error: "Incorrect code from new authenticator" }); + } + + try { + await db.query( + "UPDATE users SET secret = ? WHERE LOWER(email) = LOWER(?)", + [newSecret, req.session.user] + ); + + const wasRecoveryFlow = req.session.pending2faFrom === 'recovery'; + delete req.session.pending2faSecret; + delete req.session.pending2faFrom; + + console.log(`[SECURITY] 2FA secret updated | User: ${req.session.user} | IP: ${getRequestIp(req)} | Flow: ${wasRecoveryFlow ? 'recovery' : 'standard'}`); + + setRememberLoginCookie(req, res, { ...user, secret: newSecret }); + return res.json({ ok: true }); + } catch (err) { + console.error("[account] 2FA update error:", err); + return res.status(500).json({ error: "Failed to update 2FA" }); + } +}); + + +app.post("/api/admin/user/reset-2fa", async (req, res) => { + if (!(await isAdmin(req))) { + return res.status(403).json({ error: "Admin access required" }); + } + if (!requireActionTokenOr403(req, res, "POST /api/admin/user/reset-2fa")) return; + + const { email } = req.body || {}; + if (!email || typeof email !== "string") { + return res.status(400).json({ error: "Target email required" }); + } + + 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 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", + }); + + const qrcode = require("qrcode"); + try { + const qrCodeUrl = await qrcode.toDataURL(otpauthUrl); + return res.json({ + ok: true, + email: targetUser.email, + newSecret: newSecret.base32, + qrCodeUrl: qrCodeUrl + }); + } catch (err) { + console.error("[admin] 2FA reset QR generation error:", err); + return res.status(500).json({ error: "Failed to generate QR code" }); + } +}); + +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 || {}; + + 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" }); + } + + try { + await db.query( + "UPDATE users SET secret = ? WHERE LOWER(email) = LOWER(?)", + [newSecret, email] + ); + + console.log(`[admin] 2FA reset for user ${email} by admin ${req.session.user}`); + return res.json({ ok: true }); + } catch (err) { + console.error("[admin] 2FA reset save error:", err); + return res.status(500).json({ error: "Failed to update 2FA secret" }); + } +}); + +app.post("/api/admin/user/reset-recovery-codes", async (req, res) => { + 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 access required" }); + } + if (!requireActionTokenOr403(req, res, "POST /api/admin/user/reset-recovery-codes")) return; + + const { email } = req.body || {}; + if (!email || typeof email !== "string") { + return res.status(400).json({ error: "Target email required" }); + } + + const targetUser = await findUserByEmail(email); + if (!targetUser) { + return res.status(404).json({ error: "User not found" }); + } + + const RECOVERY_CODE_COUNT = 7; + const RECOVERY_CODE_LENGTH = 8; + const RECOVERY_CODE_CHARS = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + + const RECOVERY_REJECT_THRESHOLD = RECOVERY_CODE_CHARS.length * Math.floor(256 / RECOVERY_CODE_CHARS.length); + function generateRecoveryCode() { + let code = ''; + for (let i = 0; i < RECOVERY_CODE_LENGTH; i++) { + let byte; + do { byte = crypto.randomBytes(1)[0]; } while (byte >= RECOVERY_REJECT_THRESHOLD); + code += RECOVERY_CODE_CHARS.charAt(byte % RECOVERY_CODE_CHARS.length); + } + return code; + } + + let bcrypt; + try { + bcrypt = require("bcrypt"); + } catch { + bcrypt = require("bcryptjs"); + } + + const plainRecoveryCodes = []; + const hashedRecoveryCodes = []; + for (let i = 0; i < RECOVERY_CODE_COUNT; i++) { + const code = generateRecoveryCode(); + plainRecoveryCodes.push(code); + hashedRecoveryCodes.push(await bcrypt.hash(code, BCRYPT_ROUNDS)); + } + + const recoveryCodesJson = JSON.stringify(hashedRecoveryCodes); + + try { + await db.query( + "UPDATE users SET recovery_codes = ? WHERE LOWER(email) = LOWER(?)", + [recoveryCodesJson, email] + ); + + console.log(`[admin] Recovery codes reset for user ${email} by admin ${req.session.user}`); + return res.json({ + ok: true, + email: targetUser.email, + recoveryCodes: plainRecoveryCodes + }); + } catch (err) { + console.error("[admin] Recovery codes reset error:", err); + return res.status(500).json({ error: "Failed to reset recovery codes" }); + } +}); + +function normalizeProvisionedAccountRole(raw) { + const value = String(raw || "").trim().toLowerCase(); + if (value === "admin" || value === "administrator") return "admin"; + if (value === "user" || value === "normal" || value === "normal-user") return "user"; + return ""; +} + +function normalizeProvisionedEmail(raw) { + if (typeof raw !== "string") return ""; + const email = raw.trim().toLowerCase(); + if (!email || email.length > 254 || /[\x00-\x1f\x7f]/.test(email)) return ""; + const parts = email.split("@"); + if (parts.length !== 2) return ""; + const [local, domain] = parts; + if (!local || local.length > 64 || !domain || domain.length > 253) return ""; + if (domain.split(".").some(part => !part || part.length > 63)) return ""; + const emailRegex = /^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/i; + return emailRegex.test(email) ? email : ""; +} + +function getProvisionedPasswordError(password, email) { + if (typeof password !== "string") return "Password required"; + if (password.length < 12) return "Password must be at least 12 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"; + + const lower = password.toLowerCase(); + const common = new Set([ + "password", "password1", "password12", "password123", "adminadmin", "administrator", + "changeme", "qwerty123", "qwerty12345", "letmein123", "welcome123", "adpanel123" + ]); + if (common.has(lower) || common.has(lower.replace(/[^a-z0-9]/g, ""))) { + return "Use a stronger password"; + } + + const emailLocal = String(email || "").split("@")[0]?.toLowerCase() || ""; + if (emailLocal.length >= 4 && lower.includes(emailLocal)) return "Password cannot contain the email name"; + if (/^(.)\1{11,}$/.test(password)) return "Use a stronger password"; + if ("abcdefghijklmnopqrstuvwxyz0123456789".includes(lower.replace(/[^a-z0-9]/g, ""))) { + 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"; + } + + return ""; +} + +function normalizeTotpCode(raw) { + const code = String(raw || "").replace(/\s+/g, ""); + return /^\d{6}$/.test(code) ? code : ""; +} + +async function verifyAdminProvisioningStepUp(req, adminUser, adminPassword, adminTwoFactorCode) { + if (!adminUser || !adminUser.password) return "Admin re-authentication failed"; + if (typeof adminPassword !== "string" || !adminPassword) return "Your password is required"; + + const passwordOk = await withTimeout( + bcrypt.compare(String(adminPassword), String(adminUser.password || "")), + 8000, + "bcrypt-compare-timeout" + ).catch(() => false); + if (!passwordOk) { + securityLog("Admin creation password step-up failed", req); + 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"; + + const twoFactorOk = speakeasy.totp.verify({ + secret: adminUser.secret, + encoding: "base32", + token: code, + window: 1, + }); + if (!twoFactorOk) { + securityLog("Admin creation 2FA step-up failed", req); + return "Admin re-authentication failed"; + } + + return ""; +} + +async function generateHashedRecoveryCodes() { + const RECOVERY_CODE_COUNT = 7; + const RECOVERY_CODE_LENGTH = 8; + const RECOVERY_CODE_CHARS = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"; + const threshold = RECOVERY_CODE_CHARS.length * Math.floor(256 / RECOVERY_CODE_CHARS.length); + + function generateRecoveryCode() { + let code = ""; + for (let i = 0; i < RECOVERY_CODE_LENGTH; i++) { + let byte; + do { byte = crypto.randomBytes(1)[0]; } while (byte >= threshold); + code += RECOVERY_CODE_CHARS.charAt(byte % RECOVERY_CODE_CHARS.length); + } + return code; + } + + const plainRecoveryCodes = []; + const hashedRecoveryCodes = []; + for (let i = 0; i < RECOVERY_CODE_COUNT; i++) { + const code = generateRecoveryCode(); + plainRecoveryCodes.push(code); + hashedRecoveryCodes.push(await bcrypt.hash(code, BCRYPT_ROUNDS)); + } + + return { plainRecoveryCodes, hashedRecoveryCodes }; +} + +app.post("/api/admin/user/create", adminUserCreateRateLimiter, async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const currentAdmin = await getLoggedInUser(req); + if (!(currentAdmin && currentAdmin.admin)) { + return res.status(403).json({ error: "Admin access required" }); + } + + if (!req.is("application/json")) { + return res.status(415).json({ error: "JSON body required" }); + } + + if (!requireActionTokenOr403(req, res, "POST /api/admin/user/create")) return; + + const { email, password, confirmPassword, role: rawRole, adminPassword, adminTwoFactorCode } = req.body || {}; + const role = normalizeProvisionedAccountRole(rawRole || "user"); + if (!role) { + return res.status(400).json({ error: "Invalid account type" }); + } + + const emailLower = normalizeProvisionedEmail(email); + if (!emailLower) { + return res.status(400).json({ error: "Invalid email format" }); + } + + const passwordError = getProvisionedPasswordError(password, emailLower); + if (passwordError) { + return res.status(400).json({ error: passwordError }); + } + + if (typeof confirmPassword === "string" && password !== confirmPassword) { + return res.status(400).json({ error: "Passwords do not match" }); + } + + if (role === "admin") { + const stepUpError = await verifyAdminProvisioningStepUp(req, currentAdmin, adminPassword, adminTwoFactorCode); + if (stepUpError) { + return res.status(403).json({ error: stepUpError }); + } + } + + const existingUser = await findUserByEmail(emailLower); + if (existingUser) { + return res.status(409).json({ error: "User already exists" }); + } + + const passwordHash = await withTimeout( + bcrypt.hash(password, BCRYPT_ROUNDS), + 10000, + "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", + }); + + 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 { 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] + ); + + console.log(`[admin] ${isAdminAccount ? "Admin user" : "User"} created: ${emailLower} by admin ${req.session.user} from ${getRequestIp(req)}`); + + return res.json({ + ok: true, + email: emailLower, + role, + admin: isAdminAccount, + secret: secret.base32, + qrCodeUrl: qrCodeUrl, + recoveryCodes: plainRecoveryCodes + }); + } catch (err) { + console.error("[admin] User creation error:", err); + if (err.code === 'ER_DUP_ENTRY') { + return res.status(409).json({ error: "User already exists" }); + } + return res.status(500).json({ error: "Failed to create user" }); + } +}); + +app.post("/api/admin/branding/update", async (req, res) => { + 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 access required" }); + } + + const { appName, logoUrl, logoBase64, logoFilename } = req.body || {}; + + const sanitizedAppName = sanitizeAppName(appName); + if (!sanitizedAppName) { + return res.status(400).json({ + error: "Invalid app name. Must be 1-50 characters, alphanumeric with basic punctuation only." + }); + } + + const currentAppName = loadBrandingConfig().appName; + + try { + let localLogoPath = null; + let finalLogoUrl = null; + + if (logoBase64 && logoFilename) { + const validation = validateBase64Image(logoBase64); + if (!validation.valid) { + return res.status(400).json({ error: validation.error || "Invalid image data" }); + } + + const ext = getValidatedExtension(logoFilename); + if (!ext) { + return res.status(400).json({ + error: "Invalid file type. Allowed: png, jpg, jpeg, webp, ico, svg" + }); + } + + const safeFilename = generateSafeLogoFilename(ext); + const logoPath = path.join(__dirname, "public", "images", safeFilename); + + fs.writeFileSync(logoPath, validation.data); + + const faviconPath = path.join(__dirname, "public", "images", "favicon.ico"); + try { + fs.copyFileSync(logoPath, faviconPath); + } catch (e) { + console.log("[branding] Could not update favicon:", e.message); + } + + localLogoPath = safeFilename; + console.log(`[branding] Logo saved securely as: ${safeFilename}`); + } else if (logoUrl) { + const sanitizedUrl = sanitizeLogoUrl(logoUrl); + if (!sanitizedUrl) { + return res.status(400).json({ + error: "Invalid logo URL. Must be a valid HTTP/HTTPS URL." + }); + } + finalLogoUrl = sanitizedUrl; + } + + const saved = saveBrandingConfig({ + appName: sanitizedAppName, + logoUrl: finalLogoUrl, + localLogoPath: localLogoPath + }); + + if (!saved) { + return res.status(500).json({ error: "Failed to save branding configuration" }); + } + + invalidateBrandingCache(); + + console.log(`[admin] Branding updated securely: "${currentAppName}" -> "${sanitizedAppName}" by ${req.session.user}`); + + return res.json({ + ok: true, + message: "Branding updated successfully. Refresh the page to see changes.", + newAppName: sanitizedAppName + }); + } catch (err) { + console.error("[admin] Branding update error:", err); + return res.status(500).json({ error: "Failed to update branding" }); + } +}); + +app.get("/api/admin/branding", async (req, res) => { + 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 access required" }); + } + + const branding = loadBrandingConfig(); + + return res.json({ + appName: branding.appName, + logoUrl: branding.logoUrl + }); +}); + +app.get("/api/admin/login-watermark", async (req, res) => { + 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 access required" }); + } + + const branding = loadBrandingConfig(); + const watermarkUrl = resolveLoginWatermarkAssetUrl(branding); + const watermarkMode = branding.loginWatermarkUrl ? "url" : "upload"; + + return res.json({ + watermarkUrl, + externalUrl: branding.loginWatermarkUrl || "", + mode: watermarkMode + }); +}); + +app.post("/api/admin/login-watermark", async (req, res) => { + 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 access required" }); + } + + const { watermarkUrl, watermarkBase64, watermarkFilename } = req.body || {}; + const currentBranding = loadBrandingConfig(); + + try { + let localLoginWatermarkPath = currentBranding.localLoginWatermarkPath || null; + let finalLoginWatermarkUrl = currentBranding.loginWatermarkUrl || null; + + if (watermarkBase64 && watermarkFilename) { + const validation = validateBase64Image(watermarkBase64); + if (!validation.valid) { + return res.status(400).json({ error: validation.error || "Invalid image data" }); + } + + const ext = getValidatedExtension(watermarkFilename); + if (!ext) { + return res.status(400).json({ + error: "Invalid file type. Allowed: png, jpg, jpeg, webp, ico, svg" + }); + } + + const safeFilename = `login-watermark-${crypto.randomBytes(8).toString("hex")}.${ext}`; + const targetPath = path.join(__dirname, "public", "images", safeFilename); + fs.writeFileSync(targetPath, validation.data); + + localLoginWatermarkPath = safeFilename; + finalLoginWatermarkUrl = null; + } else if (watermarkUrl) { + const sanitizedUrl = sanitizeLogoUrl(watermarkUrl); + if (!sanitizedUrl) { + return res.status(400).json({ + error: "Invalid image URL. Must be a valid HTTP/HTTPS URL." + }); + } + + finalLoginWatermarkUrl = sanitizedUrl; + localLoginWatermarkPath = null; + } + + const saved = saveBrandingConfig({ + loginWatermarkUrl: finalLoginWatermarkUrl, + localLoginWatermarkPath + }); + + if (!saved) { + return res.status(500).json({ error: "Failed to save login watermark" }); + } + + invalidateBrandingCache(); + clearBrandingRemoteAssetCache("login-watermark"); + + const updatedBranding = loadBrandingConfig(); + const resolvedWatermarkUrl = resolveLoginWatermarkAssetUrl(updatedBranding); + const watermarkMode = updatedBranding.loginWatermarkUrl ? "url" : "upload"; + + console.log(`[admin] Login watermark updated by ${req.session.user}`); + + return res.json({ + ok: true, + message: "Login watermark updated successfully.", + watermarkUrl: resolvedWatermarkUrl, + externalUrl: updatedBranding.loginWatermarkUrl || "", + mode: watermarkMode + }); + } catch (err) { + console.error("[admin] Login watermark update error:", err); + return res.status(500).json({ error: "Failed to update login watermark" }); + } +}); + +function removeOldLoginBackgroundFile(filenameToRemove, replacementFilename = null) { + if (!filenameToRemove || filenameToRemove === replacementFilename) { + return; + } + + const safeFilename = path.basename(String(filenameToRemove)); + if (!safeFilename || safeFilename === "." || safeFilename === "..") return; + const targetPath = path.join(__dirname, "public", "images", safeFilename); + try { + if (fs.existsSync(targetPath)) { + fs.unlinkSync(targetPath); + } + } catch (err) { + console.log("[branding] Could not remove previous login background:", err.message); + } +} + +function getLoginBackgroundStoragePath(filename) { + const safeFilename = path.basename(String(filename || "")); + if (!safeFilename || safeFilename === "." || safeFilename === "..") { + return null; + } + return path.join(__dirname, "public", "images", safeFilename); +} + +function getMirroredLoginBackgroundFilename(sourceUrl, extension) { + const hash = crypto + .createHash("sha256") + .update(String(sourceUrl || "").trim()) + .digest("hex") + .slice(0, 16); + return `login-background-remote-${hash}.${extension}`; +} + +function hasStoredLoginBackground(filename) { + const targetPath = getLoginBackgroundStoragePath(filename); + return !!(targetPath && fs.existsSync(targetPath)); +} + +function validateLoginBackgroundBuffer(rawBuffer, mediaType, extension) { + const base64 = rawBuffer.toString("base64"); + return mediaType === "video" + ? validateBase64Video(base64, extension) + : validateBase64Image(base64); +} + +async function downloadLoginBackgroundToLocal(sourceUrl, mediaType, extension, preferredFilename = null) { + const maxBytes = mediaType === "video" ? LOGIN_BACKGROUND_VIDEO_MAX_BYTES : LOGIN_BACKGROUND_IMAGE_MAX_BYTES; + const rawBuffer = await httpGetRaw(sourceUrl, { maxBytes }); + const validation = validateLoginBackgroundBuffer(rawBuffer, mediaType, extension); + if (!validation?.valid) { + throw new Error(validation?.error || "Invalid media data"); + } + + const filename = preferredFilename || `login-background-${crypto.randomBytes(8).toString("hex")}.${extension}`; + const targetPath = getLoginBackgroundStoragePath(filename); + if (!targetPath) { + throw new Error("Invalid local background filename"); + } + + fs.writeFileSync(targetPath, validation.data || rawBuffer); + return filename; +} + +async function ensureLocalLoginBackgroundMirror() { + const branding = loadBrandingConfig(); + const sourceUrl = String(branding.loginBackgroundExternalUrl || "").trim(); + if (!sourceUrl) { + return null; + } + + const mediaType = branding.loginBackgroundType || getMediaTypeFromUrl(sourceUrl); + const extension = getExtensionFromUrl(sourceUrl); + if (!mediaType || !extension) { + return null; + } + + const nextFilename = getMirroredLoginBackgroundFilename(sourceUrl, extension); + const currentFilename = branding.localLoginBackgroundPath ? path.basename(String(branding.localLoginBackgroundPath)) : null; + + if (currentFilename === nextFilename && hasStoredLoginBackground(nextFilename)) { + return nextFilename; + } + + if (hasStoredLoginBackground(nextFilename)) { + const saved = saveBrandingConfig({ + loginBackgroundExternalUrl: sourceUrl, + localLoginBackgroundPath: nextFilename, + loginBackgroundType: mediaType, + loginBackgroundMimeType: getMimeTypeForExtension(extension) || (mediaType === "video" ? "video/webm" : "image/webp") + }); + + if (!saved) { + throw new Error("Failed to update local login background mirror"); + } + + removeOldLoginBackgroundFile(currentFilename, nextFilename); + invalidateBrandingCache(); + clearBrandingRemoteAssetCache("login-background"); + return nextFilename; + } + + const mirroredFilename = await downloadLoginBackgroundToLocal(sourceUrl, mediaType, extension, nextFilename); + const saved = saveBrandingConfig({ + loginBackgroundExternalUrl: sourceUrl, + localLoginBackgroundPath: mirroredFilename, + loginBackgroundType: mediaType, + loginBackgroundMimeType: getMimeTypeForExtension(extension) || (mediaType === "video" ? "video/webm" : "image/webp") + }); + + if (!saved) { + removeOldLoginBackgroundFile(mirroredFilename); + throw new Error("Failed to persist local login background mirror"); + } + + removeOldLoginBackgroundFile(currentFilename, mirroredFilename); + invalidateBrandingCache(); + clearBrandingRemoteAssetCache("login-background"); + return mirroredFilename; +} + +function maybeScheduleLoginBackgroundMirror() { + const branding = loadBrandingConfig(); + const sourceUrl = String(branding.loginBackgroundExternalUrl || "").trim(); + if (!sourceUrl) { + return; + } + + const extension = getExtensionFromUrl(sourceUrl); + const mediaType = branding.loginBackgroundType || getMediaTypeFromUrl(sourceUrl); + if (!extension || !mediaType) { + return; + } + + const expectedFilename = getMirroredLoginBackgroundFilename(sourceUrl, extension); + if (branding.localLoginBackgroundPath === expectedFilename && hasStoredLoginBackground(expectedFilename)) { + return; + } + + if (loginBackgroundMirrorPromise) { + return; + } + + loginBackgroundMirrorPromise = ensureLocalLoginBackgroundMirror() + .catch((err) => { + console.error("[branding] Failed to mirror login background locally:", err.message); + return null; + }) + .finally(() => { + loginBackgroundMirrorPromise = null; + }); +} + +setImmediate(() => { + maybeScheduleLoginBackgroundMirror(); +}); + +app.get("/api/admin/login-background", async (req, res) => { + 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 access required" }); + } + + const branding = loadBrandingConfig(); + const backgroundUrl = resolveLoginBackgroundAssetUrl(branding); + const backgroundMode = branding.loginBackgroundExternalUrl ? "url" : (branding.localLoginBackgroundPath ? "upload" : "upload"); + + return res.json({ + backgroundUrl, + externalUrl: branding.loginBackgroundExternalUrl || "", + mediaType: branding.loginBackgroundType || "video", + mimeType: branding.loginBackgroundMimeType || "video/webm", + mode: backgroundMode + }); +}); + +app.post("/api/admin/login-background", async (req, res) => { + 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 access required" }); + } + + const { backgroundUrl, backgroundBase64, backgroundFilename } = req.body || {}; + const currentBranding = loadBrandingConfig(); + + try { + let localLoginBackgroundPath = currentBranding.localLoginBackgroundPath || null; + let loginBackgroundExternalUrl = currentBranding.loginBackgroundExternalUrl || null; + let loginBackgroundType = currentBranding.loginBackgroundType || "video"; + let loginBackgroundMimeType = currentBranding.loginBackgroundMimeType || "video/webm"; + const previousLocalPath = currentBranding.localLoginBackgroundPath || null; + let cleanupReplacementFilename = null; + + if (backgroundBase64 && backgroundFilename) { + const mediaType = getMediaTypeFromFilename(backgroundFilename); + if (!mediaType) { + return res.status(400).json({ + error: "Invalid file type. Allowed images: png, jpg, jpeg, webp, ico, svg. Allowed videos: webm, mp4, ogg" + }); + } + + let ext = null; + let validation = null; + if (mediaType === "image") { + ext = getValidatedExtension(backgroundFilename); + validation = validateBase64Image(backgroundBase64); + } else { + ext = getValidatedVideoExtension(backgroundFilename); + validation = validateBase64Video(backgroundBase64, ext); + } + + if (!ext) { + return res.status(400).json({ error: "Could not detect the selected media type" }); + } + if (!validation?.valid) { + return res.status(400).json({ error: validation?.error || "Invalid media data" }); + } + + const safeFilename = `login-background-${crypto.randomBytes(8).toString("hex")}.${ext}`; + const targetPath = path.join(__dirname, "public", "images", safeFilename); + fs.writeFileSync(targetPath, validation.data); + + localLoginBackgroundPath = safeFilename; + loginBackgroundExternalUrl = null; + loginBackgroundType = mediaType; + loginBackgroundMimeType = getMimeTypeForExtension(ext) || (mediaType === "video" ? "video/webm" : "image/webp"); + cleanupReplacementFilename = safeFilename; + } else if (backgroundUrl) { + const sanitizedUrl = sanitizeLogoUrl(backgroundUrl); + if (!sanitizedUrl) { + return res.status(400).json({ + error: "Invalid media URL. Must be a valid HTTP/HTTPS URL." + }); + } + + const mediaType = getMediaTypeFromUrl(sanitizedUrl); + const ext = getExtensionFromUrl(sanitizedUrl); + if (!mediaType || !ext) { + return res.status(400).json({ + error: "URL must point directly to an image or video file." + }); + } + + try { + cleanupReplacementFilename = await downloadLoginBackgroundToLocal( + sanitizedUrl, + mediaType, + ext, + getMirroredLoginBackgroundFilename(sanitizedUrl, ext) + ); + } catch (err) { + return res.status(400).json({ + error: `Could not download that media URL: ${err.message}` + }); + } + + loginBackgroundExternalUrl = sanitizedUrl; + localLoginBackgroundPath = cleanupReplacementFilename; + loginBackgroundType = mediaType; + loginBackgroundMimeType = getMimeTypeForExtension(ext) || (mediaType === "video" ? "video/webm" : "image/webp"); + } else { + return res.status(400).json({ error: "Choose an image or video first" }); + } + + const saved = saveBrandingConfig({ + loginBackgroundType, + loginBackgroundExternalUrl, + localLoginBackgroundPath, + loginBackgroundMimeType + }); + + if (!saved) { + removeOldLoginBackgroundFile(cleanupReplacementFilename, previousLocalPath); + return res.status(500).json({ error: "Failed to save login background" }); + } + + removeOldLoginBackgroundFile(previousLocalPath, cleanupReplacementFilename); + invalidateBrandingCache(); + clearBrandingRemoteAssetCache("login-background"); + + const updatedBranding = loadBrandingConfig(); + const resolvedBackgroundUrl = resolveLoginBackgroundAssetUrl(updatedBranding); + const backgroundMode = updatedBranding.loginBackgroundExternalUrl ? "url" : (updatedBranding.localLoginBackgroundPath ? "upload" : "upload"); + + console.log(`[admin] Login background updated by ${req.session.user}`); + + return res.json({ + ok: true, + message: "Login background updated successfully.", + backgroundUrl: resolvedBackgroundUrl, + externalUrl: updatedBranding.loginBackgroundExternalUrl || "", + mediaType: updatedBranding.loginBackgroundType || loginBackgroundType, + mimeType: updatedBranding.loginBackgroundMimeType || loginBackgroundMimeType, + mode: backgroundMode + }); + } catch (err) { + console.error("[admin] Login background update error:", err); + return res.status(500).json({ error: "Failed to update login background" }); + } +}); + +app.post("/api/account/recovery/verify", recoveryRateLimiter, async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { recoveryCode } = req.body || {}; + + if (!recoveryCode || typeof recoveryCode !== 'string') { + return res.status(400).json({ error: "Recovery code is required" }); + } + + const codeStr = recoveryCode.trim().toUpperCase(); + if (!/^[A-Z0-9]{8}$/.test(codeStr)) { + return res.status(400).json({ error: "Invalid recovery code format" }); + } + + let recoveryCodes = []; + try { + const rows = await db.query( + "SELECT id, recovery_codes FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", + [req.session.user] + ); + const row = rows[0]; + if (row && row.recovery_codes) { + recoveryCodes = JSON.parse(row.recovery_codes); + } + } catch (err) { + console.error("[account] Failed to get recovery codes:", err); + return res.status(500).json({ error: "Failed to verify recovery code" }); + } + + if (!Array.isArray(recoveryCodes) || recoveryCodes.length === 0) { + return res.status(403).json({ error: "No recovery codes available" }); + } + + let matchedIndex = -1; + for (let i = 0; i < recoveryCodes.length; i++) { + try { + const isMatch = await bcrypt.compare(codeStr, recoveryCodes[i]); + if (isMatch && matchedIndex === -1) { + matchedIndex = i; + } + } catch (err) { + } + } + + if (matchedIndex === -1) { + console.log(`[SECURITY] Recovery code verification failed | User: ${req.session.user} | IP: ${getRequestIp(req)}`); + return res.status(403).json({ error: "Invalid recovery code" }); + } + + try { + recoveryCodes.splice(matchedIndex, 1); + await db.query( + "UPDATE users SET recovery_codes = ? WHERE LOWER(email) = LOWER(?)", + [JSON.stringify(recoveryCodes), req.session.user] + ); + } catch (err) { + console.error("[account] Failed to remove used recovery code:", err); + } + + req.session.recoveryVerified = { + userId: user.id, + email: req.session.user, + nonce: crypto.randomBytes(16).toString('hex'), + verifiedAt: Date.now() + }; + + console.log(`[SECURITY] Recovery code verified successfully | User: ${req.session.user} | IP: ${getRequestIp(req)} | RemainingCodes: ${recoveryCodes.length}`); + + return res.json({ ok: true, verified: true, remainingCodes: recoveryCodes.length }); +}); + +app.post("/api/account/2fa/generate-recovery", recoveryRateLimiter, async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const RECOVERY_EXPIRY_MS = 5 * 60 * 1000; + const rv = req.session.recoveryVerified; + + if (!rv) { + console.log(`[SECURITY] Recovery 2FA generation denied - no verification | User: ${req.session.user} | IP: ${getRequestIp(req)}`); + return res.status(403).json({ error: "Recovery verification required" }); + } + + if (rv.email !== req.session.user) { + delete req.session.recoveryVerified; + console.log(`[SECURITY] Recovery 2FA generation denied - user mismatch | User: ${req.session.user} | IP: ${getRequestIp(req)}`); + return res.status(403).json({ error: "Recovery verification required" }); + } + + if (Date.now() - rv.verifiedAt > RECOVERY_EXPIRY_MS) { + delete req.session.recoveryVerified; + console.log(`[SECURITY] Recovery 2FA generation denied - expired | User: ${req.session.user} | IP: ${getRequestIp(req)}`); + return res.status(403).json({ error: "Recovery verification expired. Please verify a recovery code again." }); + } + + try { + const newSecret = speakeasy.generateSecret({ length: 20 }); + const appName = process.env.APP_NAME || "ADPanel"; + const otpauthUrl = speakeasy.otpauthURL({ + secret: newSecret.base32, + label: user.email, + issuer: appName, + encoding: "base32", + }); + + const qrcode = require("qrcode"); + const qrCodeUrl = await qrcode.toDataURL(otpauthUrl); + + req.session.pending2faSecret = newSecret.base32; + req.session.pending2faFrom = 'recovery'; + + delete req.session.recoveryVerified; + + console.log(`[SECURITY] Recovery 2FA secret generated | User: ${req.session.user} | IP: ${getRequestIp(req)}`); + + return res.json({ + ok: true, + newSecret: newSecret.base32, + qrCodeUrl: qrCodeUrl, + }); + } catch (err) { + console.error("[account] 2FA generation error:", err); + return res.status(500).json({ error: "Failed to generate new 2FA" }); + } +}); + +app.post("/api/account/password/verify", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { currentPassword, twoFactorCode } = req.body || {}; + + if (!currentPassword || typeof currentPassword !== 'string') { + return res.status(400).json({ error: "Current password is required" }); + } + + try { + if (process.env.DEBUG_AUTH === "true") { + console.log("[account] Password verify attempt for:", req.session.user); + } + + if (!user.password) { + console.error("[account] User has no password hash in database"); + return res.status(500).json({ error: "Account configuration error" }); + } + + const isValid = await withTimeout(bcrypt.compare(currentPassword, user.password), 8000, "bcrypt-timeout"); + + if (!isValid) { + return res.status(403).json({ error: "Incorrect current password" }); + } + } catch (err) { + console.error("[account] Password verify error:", err); + 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)) { + 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" }); + } + } + + return res.json({ ok: true, verified: true }); +}); + +app.post("/api/account/password/change", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { currentPassword, twoFactorCode, newPassword } = req.body || {}; + + if (!currentPassword || typeof currentPassword !== 'string') { + return res.status(400).json({ error: "Current password is required" }); + } + if (!newPassword || typeof newPassword !== 'string') { + return res.status(400).json({ error: "New password is required" }); + } + if (newPassword.length < 8) { + return res.status(400).json({ error: "Password must be at least 8 characters" }); + } + + try { + const isValid = await withTimeout(bcrypt.compare(currentPassword, user.password), 8000, "bcrypt-timeout"); + if (!isValid) { + return res.status(403).json({ error: "Incorrect current password" }); + } + } catch (err) { + console.error("[account] Password change verify error:", err); + 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)) { + 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" }); + } + } + + try { + const hashedPassword = await bcrypt.hash(newPassword, BCRYPT_ROUNDS); + + await db.query( + "UPDATE users SET password = ? WHERE LOWER(email) = LOWER(?)", + [hashedPassword, req.session.user] + ); + + setRememberLoginCookie(req, res, { ...user, password: hashedPassword }); + return res.json({ ok: true }); + } catch (err) { + console.error("[account] Password update error:", err); + return res.status(500).json({ error: "Failed to update password" }); + } +}); + +app.post("/api/account/email/verify", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { currentPassword, twoFactorCode } = req.body || {}; + + if (!currentPassword || typeof currentPassword !== 'string') { + return res.status(400).json({ error: "Password is required" }); + } + + try { + if (!user.password) { + return res.status(500).json({ error: "Account configuration error" }); + } + + const isValid = await withTimeout(bcrypt.compare(currentPassword, user.password), 8000, "bcrypt-timeout"); + if (!isValid) { + return res.status(403).json({ error: "Incorrect password" }); + } + } catch (err) { + console.error("[account] Email verify error:", err); + 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)) { + 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" }); + } + } + + return res.json({ ok: true, verified: true }); +}); + +app.post("/api/account/email/change", async (req, res) => { + if (!req.session || !req.session.user) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const user = await findUserByEmail(req.session.user); + if (!user) { + return res.status(401).json({ error: "User not found" }); + } + + const { currentPassword, twoFactorCode, newEmail } = req.body || {}; + + if (!currentPassword || typeof currentPassword !== 'string') { + return res.status(400).json({ error: "Password is required" }); + } + if (!newEmail || typeof newEmail !== 'string') { + return res.status(400).json({ error: "New email is required" }); + } + + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(newEmail)) { + return res.status(400).json({ error: "Invalid email format" }); + } + + const existingUser = await findUserByEmail(newEmail); + if (existingUser && existingUser.id !== user.id) { + return res.status(400).json({ error: "Email already in use" }); + } + + try { + if (!user.password) { + return res.status(500).json({ error: "Account configuration error" }); + } + + const isValid = await withTimeout(bcrypt.compare(currentPassword, user.password), 8000, "bcrypt-timeout"); + if (!isValid) { + return res.status(403).json({ error: "Incorrect password" }); + } + } catch (err) { + console.error("[account] Email change verify error:", err); + 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)) { + 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" }); + } + } + + try { + await db.query( + "UPDATE users SET email = ? WHERE LOWER(email) = LOWER(?)", + [newEmail.toLowerCase(), req.session.user] + ); + + req.session.user = newEmail.toLowerCase(); + setRememberLoginCookie(req, res, { ...user, email: newEmail.toLowerCase() }); + + return res.json({ ok: true }); + } catch (err) { + console.error("[account] Email update error:", err); + return res.status(500).json({ error: "Failed to update email" }); + } +}); + +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 }); +}); + +let USER_COUNT_CACHE = 0; +async function loadUserCount() { + try { + const rows = await db.query("SELECT COUNT(*) AS count FROM users"); + const count = rows && rows[0] ? Number(rows[0].count) : 0; + return Number.isFinite(count) ? count : 0; + } catch { + return USER_COUNT_CACHE; + } +} +async function refreshUserCount() { + USER_COUNT_CACHE = await loadUserCount(); +} +refreshUserCount().catch(() => { }); +setInterval(() => { + refreshUserCount().catch(() => { }); +}, 10_000); +app.get("/api/usercount", (req, res) => res.json({ userCount: USER_COUNT_CACHE })); + +app.get("/api/me", async (req, res, next) => { + try { + const email = req.session?.user; + if (!email) return res.status(401).json({ ok: false, user: null }); + const user = await findUserByEmail(email); + if (!user) return res.status(401).json({ ok: false, user: null }); + return res.json({ + ok: true, + user: { + email: user.email, + admin: !!user.admin, + has2FA: !!user.secret, + preferences: user.preferences || {} + } + }); + } catch (err) { + return next(err); + } +}); + +app.post("/api/me/preferences", async (req, res, next) => { + try { + const email = req.session?.user; + if (!email) return res.status(401).json({ error: "Unauthorized" }); + const { preferences } = req.body; + if (!preferences || typeof preferences !== 'object') { + return res.status(400).json({ error: "Invalid preferences" }); + } + + const user = await findUserByEmail(email); + if (!user) return res.status(404).json({ error: "User not found" }); + + const currentPrefs = user.preferences || {}; + const newPrefs = { ...currentPrefs, ...preferences }; + + await db.query("UPDATE users SET preferences = ? WHERE id = ?", [JSON.stringify(newPrefs), user.id]); + + return res.json({ ok: true, preferences: newPrefs }); + } catch (err) { + next(err); + } +}); + + +app.get("/api/me/status", async (req, res, next) => { + try { + const email = req.session?.user; + if (!email) return res.status(401).json({ ok: false, error: "not authenticated" }); + const user = await findUserByEmail(email); + if (!user) return res.status(401).json({ ok: false, error: "user not found" }); + + const rows = await db.query( + "SELECT status_text, expires_at FROM user_status WHERE user_id = ?", + [user.id] + ); + + if (!rows || rows.length === 0) { + return res.json({ ok: true, status: { text: "Available", expiresAt: null } }); + } + + const row = rows[0]; + const now = Date.now(); + + if (row.expires_at && Number(row.expires_at) <= now) { + await db.query("DELETE FROM user_status WHERE user_id = ?", [user.id]); + return res.json({ ok: true, status: { text: "Available", expiresAt: null } }); + } + + return res.json({ + ok: true, + status: { + text: row.status_text || "Available", + expiresAt: row.expires_at ? Number(row.expires_at) : null + } + }); + } catch (err) { + return next(err); + } +}); + +app.post("/api/me/status", async (req, res, next) => { + try { + const email = req.session?.user; + if (!email) return res.status(401).json({ ok: false, error: "not authenticated" }); + const user = await findUserByEmail(email); + if (!user) return res.status(401).json({ ok: false, error: "user not found" }); + + const { text, expiresAt } = req.body || {}; + const statusText = String(text || "Available").slice(0, 80); + const expiresAtNum = expiresAt ? Number(expiresAt) : null; + + await db.query( + `INSERT INTO user_status (user_id, status_text, expires_at) + VALUES (?, ?, ?) + ON DUPLICATE KEY UPDATE status_text = VALUES(status_text), expires_at = VALUES(expires_at)`, + [user.id, statusText, expiresAtNum] + ); + + return res.json({ ok: true }); + } catch (err) { + return next(err); + } +}); + + +async function deleteServerSchedules(serverName) { + if (!schedulerQueue) return; + + try { + const [waiting, active, delayed] = await Promise.all([ + schedulerQueue.getJobs(["waiting"], 0, 1000), + schedulerQueue.getJobs(["active"], 0, 1000), + schedulerQueue.getJobs(["delayed"], 0, 1000) + ]); + + const allJobs = [...waiting, ...active, ...delayed]; + let deletedCount = 0; + + for (const job of allJobs) { + if (job?.data?.serverName === serverName) { + try { + await job.remove(); + deletedCount++; + } catch (e) { + console.log(`[deleteServerSchedules] Could not remove job ${job.id}: ${e.message}`); + } + } + } + + const repeatableJobs = await schedulerQueue.getRepeatableJobs(); + for (const job of repeatableJobs) { + try { + const nameData = JSON.parse(job.name || "{}"); + if (nameData.serverName === serverName) { + await schedulerQueue.removeRepeatableByKey(job.key); + deletedCount++; + } + } catch (e) { + console.log(`[deleteServerSchedules] Could not parse/remove repeatable job: ${e.message}`); + } + } + + if (deletedCount > 0) { + console.log(`[deleteServerSchedules] Deleted ${deletedCount} schedules for server ${serverName}`); + } + } catch (err) { + console.error(`[deleteServerSchedules] Error deleting schedules for ${serverName}:`, err); + } +} + +app.get("/api/scheduler/:serverName/tasks", async (req, res) => { + try { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ ok: false, error: "not authenticated" }); + } + + const serverName = sanitizeServerName(req.params.serverName); + if (!serverName) { + return res.status(400).json({ ok: false, error: "invalid server name" }); + } + + const email = req.session?.user; + if (!email) return res.status(401).json({ ok: false, error: "not authenticated" }); + + const hasAccess = await userHasAccessToServer(email, serverName); + if (!hasAccess) { + return res.status(403).json({ ok: false, error: "access denied" }); + } + + const perms = await getEffectivePermsForUserOnServer(email, serverName); + if (!perms.scheduler_access) { + return res.status(403).json({ ok: false, error: "no scheduler access permission" }); + } + + if (!schedulerQueue) { + return res.status(503).json({ ok: false, error: "scheduler not available", detail: "Redis not configured" }); + } + + const [waiting, active, delayed, completed, failed] = await Promise.all([ + schedulerQueue.getJobs(["waiting"], 0, 100), + schedulerQueue.getJobs(["active"], 0, 50), + schedulerQueue.getJobs(["delayed"], 0, 100), + schedulerQueue.getJobs(["completed"], 0, 50), + schedulerQueue.getJobs(["failed"], 0, 50) + ]); + + const allJobs = [...waiting, ...active, ...delayed, ...completed, ...failed]; + const serverJobs = allJobs.filter(job => job?.data?.serverName === serverName); + + const repeatableJobs = await schedulerQueue.getRepeatableJobs(); + const serverRepeatables = repeatableJobs.filter(job => { + try { + const nameData = JSON.parse(job.name || "{}"); + return nameData.serverName === serverName; + } catch { + return false; + } + }); + + const tasks = serverJobs.map(job => ({ + id: job.id, + name: job.data?.name || "Unnamed Task", + actionType: job.data?.actionType, + payload: job.data?.payload, + scheduleType: job.data?.scheduleType, + scheduledFor: job.timestamp + (job.delay || 0), + status: job.finishedOn ? (job.failedReason ? "failed" : "completed") : (job.processedOn ? "running" : "pending"), + createdAt: job.timestamp, + failedReason: job.failedReason || null, + returnValue: job.returnvalue || null + })); + + const recurring = serverRepeatables.map(job => { + try { + const nameData = JSON.parse(job.name || "{}"); + return { + id: job.key, + name: nameData.name || "Recurring Task", + actionType: nameData.actionType, + payload: nameData.payload, + scheduleType: nameData.scheduleType, + cron: job.pattern, + next: job.next, + status: "recurring" + }; + } catch { + return null; + } + }).filter(Boolean); + + return res.json({ ok: true, tasks, recurring }); + } catch (err) { + console.error("[scheduler] List tasks error:", err); + return res.status(500).json({ ok: false, error: "internal error" }); + } +}); + +app.post("/api/scheduler/:serverName/tasks", async (req, res) => { + try { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ ok: false, error: "not authenticated" }); + } + + const serverName = sanitizeServerName(req.params.serverName); + if (!serverName) { + return res.status(400).json({ ok: false, error: "invalid server name" }); + } + + const email = req.session?.user; + if (!email) return res.status(401).json({ ok: false, error: "not authenticated" }); + + const hasAccess = await userHasAccessToServer(email, serverName); + if (!hasAccess) { + return res.status(403).json({ ok: false, error: "access denied" }); + } + + const perms = await getEffectivePermsForUserOnServer(email, serverName); + if (!perms.scheduler_create) { + return res.status(403).json({ ok: false, error: "no permission to create schedules" }); + } + + if (!schedulerQueue) { + return res.status(503).json({ ok: false, error: "scheduler not available", detail: "Redis not configured" }); + } + + const serverEntry = await findServer(serverName); + const maxSchedules = serverEntry?.resources?.maxSchedules || serverEntry?.docker?.maxSchedules; + if (maxSchedules && maxSchedules > 0) { + const [waiting, active, delayed] = await Promise.all([ + schedulerQueue.getJobs(["waiting"], 0, 1000), + schedulerQueue.getJobs(["active"], 0, 1000), + schedulerQueue.getJobs(["delayed"], 0, 1000) + ]); + const allActiveJobs = [...waiting, ...active, ...delayed]; + const serverSchedules = allActiveJobs.filter(job => job?.data?.serverName === serverName).length; + + const repeatableJobs = await schedulerQueue.getRepeatableJobs(); + const serverRecurring = repeatableJobs.filter(job => { + try { + const nameData = JSON.parse(job.name || "{}"); + return nameData.serverName === serverName; + } catch { + return false; + } + }).length; + + const totalSchedules = serverSchedules + serverRecurring; + if (totalSchedules >= maxSchedules) { + return res.status(400).json({ + ok: false, + error: `Maximum schedule limit reached (${maxSchedules})`, + current: totalSchedules, + max: maxSchedules + }); + } + } + + const { name, actionType, payload: rawPayload, scheduleType, scheduleValue, scheduleTime, scheduledTimestamp } = req.body || {}; + const payload = rawPayload && typeof rawPayload === "object" && !Array.isArray(rawPayload) ? rawPayload : {}; + + if (!actionType) { + return res.status(400).json({ ok: false, error: "actionType is required" }); + } + + if (!scheduleType) { + return res.status(400).json({ ok: false, error: "scheduleType is required" }); + } + + const validActions = ["console_command", "server_start", "server_stop", "create_file", "modify_file", "backup", "planner_next_to_agent", "agent_prompt"]; + if (!validActions.includes(actionType)) { + return res.status(400).json({ ok: false, error: "invalid actionType" }); + } + + const validScheduleTypes = ["once", "seconds", "minutes", "hourly", "daily", "weekly"]; + if (!validScheduleTypes.includes(scheduleType)) { + return res.status(400).json({ ok: false, error: "invalid scheduleType" }); + } + + if (actionType === "console_command" && !payload?.command) { + return res.status(400).json({ ok: false, error: "command is required for console_command action" }); + } + if ((actionType === "create_file" || actionType === "modify_file") && !payload?.filePath) { + return res.status(400).json({ ok: false, error: "filePath is required for file operations" }); + } + + const user = await findUserByEmail(email); + if ((actionType === "planner_next_to_agent" || actionType === "agent_prompt") && !userCanUseAdpanelAgent(user)) { + return res.status(403).json({ ok: false, error: "no ADPanel Agent access" }); + } + if (actionType === "planner_next_to_agent") { + const selection = await getSavedAiModelSelectionForUserId(user?.id); + if (!selection) { + return res.status(400).json({ ok: false, error: "Select an ADPanel Agent model before scheduling planner prompts" }); + } + payload.provider = selection.provider; + payload.model = selection.model; + } + if (actionType === "agent_prompt") { + const prompt = sanitizeAiAgentPrompt(payload?.prompt); + if (!prompt) { + return res.status(400).json({ ok: false, error: "prompt is required for Send prompt to ADPanel Agent" }); + } + try { + const { provider, model } = normalizeAiModelSelectionPayload(payload || {}); + const ready = assertAiProviderReady(provider, model); + payload.prompt = prompt; + payload.provider = ready.provider; + payload.model = ready.model; + await saveAiModelSelectionForUserId(user.id, ready.provider, ready.model); + } catch (selectionErr) { + return res.status(selectionErr.status || 400).json({ ok: false, error: selectionErr.message || "invalid ADPanel Agent model" }); + } + } + const jobData = { + name: name || `${actionType} task`, + serverName, + actionType, + payload: payload || {}, + scheduleType, + scheduleValue, + scheduleTime, + userId: user?.id, + userName: email + }; + + let job; + + if (scheduleType === "once") { + const runAt = scheduledTimestamp ? new Date(scheduledTimestamp).getTime() : Date.now(); + const delay = Math.max(0, runAt - Date.now()); + + job = await schedulerQueue.add("scheduled-task", jobData, { + delay, + removeOnComplete: { count: 50 }, + removeOnFail: { count: 25 } + }); + + console.log(`[scheduler] Created one-time task ${job.id} for ${serverName}, runs in ${delay}ms`); + } else { + const schedule = scheduleToCron(scheduleType, scheduleValue, scheduleTime); + + const repeatJobName = JSON.stringify({ + serverName, + name: name || `${actionType} task`, + actionType, + payload, + scheduleType + }); + + if (schedule && typeof schedule === "object" && schedule.type === "interval") { + job = await schedulerQueue.add(repeatJobName, jobData, { + repeat: { every: schedule.ms }, + removeOnComplete: { count: 20 }, + removeOnFail: { count: 10 } + }); + console.log(`[scheduler] Created interval task for ${serverName}, every ${schedule.ms}ms`); + } else if (schedule) { + job = await schedulerQueue.add(repeatJobName, jobData, { + repeat: { pattern: schedule }, + removeOnComplete: { count: 20 }, + removeOnFail: { count: 10 } + }); + console.log(`[scheduler] Created recurring task for ${serverName}, cron: ${schedule}`); + } else { + return res.status(400).json({ ok: false, error: "invalid schedule configuration" }); + } + } + + const userIp = getRequestIp(req); + recordActivity(serverName, "scheduler_create", { + taskId: job.id, + taskName: jobData.name, + actionType, + scheduleType, + scheduleValue, + scheduleTime + }, email, userIp); + + return res.json({ + ok: true, + task: { + id: job.id, + name: jobData.name, + actionType, + scheduleType, + createdAt: Date.now() + } + }); + } catch (err) { + console.error("[scheduler] Create task error:", err); + return res.status(500).json({ ok: false, error: "internal error", detail: err?.message }); + } +}); + +app.delete("/api/scheduler/:serverName/tasks/:taskId", async (req, res) => { + try { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ ok: false, error: "not authenticated" }); + } + + const serverName = sanitizeServerName(req.params.serverName); + if (!serverName) { + return res.status(400).json({ ok: false, error: "invalid server name" }); + } + + const email = req.session?.user; + if (!email) return res.status(401).json({ ok: false, error: "not authenticated" }); + + const hasAccess = await userHasAccessToServer(email, serverName); + if (!hasAccess) { + return res.status(403).json({ ok: false, error: "access denied" }); + } + + const perms = await getEffectivePermsForUserOnServer(email, serverName); + if (!perms.scheduler_delete) { + return res.status(403).json({ ok: false, error: "no permission to delete schedules" }); + } + + if (!schedulerQueue) { + return res.status(503).json({ ok: false, error: "scheduler not available" }); + } + + const taskId = req.params.taskId; + const userIp = getRequestIp(req); + + const job = await schedulerQueue.getJob(taskId); + if (job && job.data?.serverName === serverName) { + const taskName = job.data?.name || "Unknown task"; + const actionType = job.data?.actionType || "unknown"; + await job.remove(); + console.log(`[scheduler] Removed task ${taskId}`); + + recordActivity(serverName, "scheduler_delete", { + taskId, + taskName, + actionType + }, email, userIp); + + return res.json({ ok: true }); + } + + const repeatables = await schedulerQueue.getRepeatableJobs(); + const repeatable = repeatables.find(r => r.key === taskId); + if (repeatable) { + try { + const nameData = JSON.parse(repeatable.name || "{}"); + if (nameData.serverName === serverName) { + await schedulerQueue.removeRepeatableByKey(taskId); + console.log(`[scheduler] Removed recurring task ${taskId}`); + + recordActivity(serverName, "scheduler_delete", { + taskId, + taskName: nameData.name || "Recurring task", + actionType: nameData.actionType || "unknown", + recurring: true + }, email, userIp); + + return res.json({ ok: true }); + } + } catch { } + } + + return res.status(404).json({ ok: false, error: "task not found" }); + } catch (err) { + console.error("[scheduler] Delete task error:", err); + return res.status(500).json({ ok: false, error: "internal error" }); + } +}); + +app.get("/api/scheduler/status", async (req, res) => { + try { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ ok: false, error: "not authenticated" }); + } + + const available = !!schedulerQueue; + let queueInfo = null; + + if (available) { + try { + const [waiting, active, delayed, completed, failed] = await Promise.all([ + schedulerQueue.getWaitingCount(), + schedulerQueue.getActiveCount(), + schedulerQueue.getDelayedCount(), + schedulerQueue.getCompletedCount(), + schedulerQueue.getFailedCount() + ]); + + queueInfo = { waiting, active, delayed, completed, failed }; + } catch (qErr) { + console.error("[scheduler] Queue info error:", qErr?.message); + } + } + + return res.json({ + ok: true, + available, + redisConfigured: !!SCHEDULER_REDIS_URL, + queue: queueInfo + }); + } catch (err) { + console.error("[scheduler] Status error:", err); + return res.status(500).json({ ok: false, error: "internal error" }); + } +}); + +app.get("/api/server/:name/node-status", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ error: "not authenticated" }); + } + const serverName = sanitizeServerName(req.params.name); + if (!serverName) { + return res.status(400).json({ error: "invalid server name" }); + } + + const email = req.session?.user; + if (!email) return res.status(401).json({ error: "not authenticated" }); + + const hasAccess = await userHasAccessToServer(email, serverName); + if (!hasAccess) { + return res.status(403).json({ error: "access denied" }); + } + + const serverIndex = await loadServersIndex(); + const entry = serverIndex.find(e => e && e.name && e.name.toLowerCase() === serverName.toLowerCase()); + if (!entry) { + return res.json({ ok: false, nodeOnline: false, status: "unknown" }); + } + + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); + + const cachedStatus = await getCachedServerStatusLenient(entry.name); + + let nodeStats = null; + if (isRemoteEntry(entry)) { + const node = await findNodeByIdOrName(entry.nodeId); + if (node) { + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (baseUrl) { + const headers = nodeAuthHeadersFor(node, true); + try { + const { status, json } = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(serverName)}`, + "GET", + headers, + null, + 5000 + ); + if (status === 200 && json && json.ok) { + nodeStats = json; + } + } catch { } + } + } + } + + let result; + if (nodeStats) { + const nodeStatusLabel = + normalizeStatusLabel(nodeStats.status || nodeStats.state) || + normalizeStatusLabel(cachedStatus?.status) || + 'unknown'; + + if (nodeStats.stats) { + const stats = nodeStats.stats; + result = normalizeServerStatusRecord({ + ok: true, + status: nodeStatusLabel, + nodeOnline: true, + cpu: stats.cpu?.percent ?? cachedStatus?.cpu ?? null, + cpuLimit: stats.cpu?.limit ?? cachedStatus?.cpuLimit ?? null, + memory: { + used: stats.memory?.usedMb ?? 0, + total: stats.memory?.limitMb ?? 1, + percent: stats.memory?.percent ?? 0 + }, + disk: { + used: (stats.disk?.usedMb ?? 0) / 1024, + total: (stats.disk?.limitMb ?? 0) / 1024, + percent: stats.disk?.percent ?? 0 + }, + uptime: nodeStats.uptime ?? cachedStatus?.uptime ?? null + }); + } else { + result = normalizeServerStatusRecord({ + ok: true, + status: nodeStatusLabel, + nodeOnline: true, + cpu: cachedStatus?.cpu ?? null, + cpuLimit: cachedStatus?.cpuLimit ?? null, + memory: cachedStatus?.memory ?? null, + disk: cachedStatus?.disk ?? null, + uptime: nodeStats.uptime ?? cachedStatus?.uptime ?? null + }); + } + } else { + let nodeOnline = false; + let serverStatus = normalizeStatusLabel(cachedStatus?.status) || 'unknown'; + + if (isRemoteEntry(entry)) { + const node = await findNodeByIdOrName(entry.nodeId); + if (node) { + const cachedNode = await getCachedNodeStatus(node.uuid || node.id || node.name); + nodeOnline = cachedNode?.online ?? false; + } + } else { + nodeOnline = true; + } + + result = normalizeServerStatusRecord({ + ok: true, + status: serverStatus, + nodeOnline: nodeOnline, + cpu: cachedStatus?.cpu ?? null, + cpuLimit: cachedStatus?.cpuLimit ?? null, + memory: cachedStatus?.memory ?? null, + disk: cachedStatus?.disk ?? null, + uptime: cachedStatus?.uptime ?? null + }); + } + + return res.json(result); + } catch (err) { + console.error("[node-status] Error:", err); + return res.status(500).json({ error: "internal error" }); + } +}); + +const ACTIVITY_LOGS_DIR = path.join(__dirname, ".activity-logs"); + +app.get("/api/server/:name/activity", async (req, res) => { + try { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ error: "not authenticated" }); + } + + const serverName = sanitizeServerName(req.params.name); + if (!serverName) { + return res.status(400).json({ error: "invalid server name" }); + } + + const email = req.session?.user; + if (!email) return res.status(401).json({ error: "not authenticated" }); + + const isAdminUser = await isAdmin(req); + if (!isAdminUser) { + const hasAccess = await userHasAccessToServer(email, serverName); + if (!hasAccess) { + return res.status(403).json({ error: "access denied" }); + } + const perms = await getEffectivePermsForUserOnServer(email, serverName); + if (!perms || !perms.activity_logs) { + return res.status(403).json({ error: "access denied" }); + } + } + + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); + + 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)); + + const safeName = String(serverName).replace(/[^a-zA-Z0-9_-]/g, "_"); + const logPath = path.join(ACTIVITY_LOGS_DIR, `${safeName}.log`); + + let entries = []; + try { + const st = await fsp.stat(logPath).catch(() => null); + if (st && st.size > 10 * 1024 * 1024) { + return res.status(413).json({ error: "activity log too large; rotate logs" }); + } + const content = await fsp.readFile(logPath, "utf8"); + const lines = content.trim().split("\n").filter(Boolean); + + for (let i = lines.length - 1; i >= 0; i--) { + try { + const entry = JSON.parse(lines[i]); + entries.push(entry); + } catch { } + } + } catch (err) { + if (err.code !== "ENOENT") { + console.error("[activity] Error reading log:", err); + } + } + + const paginated = entries.slice(offset, offset + limit); + + return res.json({ + ok: true, + entries: paginated, + total: entries.length, + offset, + limit + }); + } catch (err) { + console.error("[activity] Error:", err); + return res.status(500).json({ error: "failed to load activity logs" }); + } +}); + + +app.post("/api/servers/statuses", async (req, res) => { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ error: "not authenticated" }); + } + + const email = req.session?.user; + const rawNames = Array.isArray(req.body?.names) ? req.body.names : []; + const requestedNames = [...new Set(rawNames.slice(0, 200))]; + + const safeNames = requestedNames.map(n => String(n || '').trim()).filter(Boolean); + const user = email ? await findUserByEmail(email) : null; + let accessibleNames; + if (user && user.admin) { + accessibleNames = safeNames; + } else { + const access = email ? await getAccessListForEmail(email) : []; + const accessLower = new Set(access.map(a => String(a).toLowerCase())); + const hasAll = accessLower.has('all'); + accessibleNames = hasAll ? safeNames : safeNames.filter(n => accessLower.has(n.toLowerCase())); + } + + const statuses = {}; + const BATCH = 200; + for (let i = 0; i < accessibleNames.length; i += BATCH) { + const batch = accessibleNames.slice(i, i + BATCH); + const entries = await Promise.all(batch.map(async (name) => { + const cached = await getCachedServerStatus(name); + return [name, cached]; + })); + for (const [name, cached] of entries) { + if (cached) { + statuses[name] = { + status: cached.status, + cpu: cached.cpu, + memory: cached.memory, + disk: cached.disk, + nodeOnline: cached.nodeOnline, + updatedAt: cached.updatedAt + }; + } else { + statuses[name] = { + status: 'unknown', + nodeOnline: true, + updatedAt: null + }; + } + } + } + + return res.json({ + ok: true, + statuses, + cacheAge: Date.now() - statusCache.lastFullRefresh + }); +}); + +app.get("/api/server/:name/status", async (req, res) => { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ error: "not authenticated" }); + } + + const name = sanitizeServerName(req.params.name); + const email = req.session?.user; + + if (!name || !email || !(await userHasAccessToServer(email, name))) { + return res.status(403).json({ error: "access denied" }); + } + + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); + + const cached = await getCachedServerStatus(name); + + if (cached) { + const normalizedCached = normalizeServerStatusRecord(cached); + return res.json({ + ok: true, + name, + status: normalizedCached.status, + cpu: normalizedCached.cpu, + cpuLimit: normalizedCached.cpuLimit ?? null, + memory: normalizedCached.memory, + disk: normalizedCached.disk, + nodeOnline: normalizedCached.nodeOnline, + updatedAt: normalizedCached.updatedAt, + fresh: Date.now() - normalizedCached.updatedAt < STATUS_CACHE_TTL_MS + }); + } + + return res.json({ + ok: true, + name, + status: 'unknown', + cpuLimit: null, + nodeOnline: true, + updatedAt: null, + fresh: false + }); +}); + +app.get("/api/nodes/statuses", async (req, res) => { + if (!(await isAdmin(req))) { + return res.status(403).json({ error: "not authorized" }); + } + + const nodes = await loadNodes(); + const statuses = {}; + + for (const node of nodes) { + const id = node.uuid || node.id || node.name; + const cached = await getCachedNodeStatus(id); + + statuses[id] = cached ? { + online: cached.online, + latency: cached.latency, + lastSeen: cached.lastSeen, + serverCount: cached.serverCount, + updatedAt: cached.updatedAt + } : { + online: null, + lastSeen: null, + updatedAt: null + }; + } + + return res.json({ + ok: true, + nodes: statuses, + lastRefresh: statusCache.lastFullRefresh + }); +}); + +app.get("/api/admin/nodes/:id/stats", async (req, res) => { + if (!(await isAdmin(req))) { + return res.status(403).json({ error: "Admin access required" }); + } + + const nodeId = req.params.id; + if (!nodeId) { + return res.status(400).json({ error: "Node ID required" }); + } + + const node = await findNodeByIdOrName(nodeId); + if (!node) { + return res.status(404).json({ error: "Node not found" }); + } + + const isLocal = isLocalHost(node.address); + const baseUrl = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); + + if (!baseUrl) { + return res.json({ + ok: false, + online: false, + error: "Node address not configured" + }); + } + + const headers = nodeAuthHeadersFor(node, !isLocal); + + try { + const statsUrl = `${baseUrl}/api/system/stats`; + const result = await httpRequestJson(statsUrl, "GET", headers, null, 8000); + + if (!result || result.status !== 200 || !result.json || !result.json.ok) { + return res.json({ + ok: false, + online: false, + nodeId: node.id || node.uuid, + nodeName: node.name, + error: result?.json?.error || "Failed to reach node" + }); + } + + const data = result.json; + + const ramUsedMb = Number(data.ram_used_mb || data.memory_used_mb || 0); + const ramTotalMb = Number(data.ram_total_mb || data.memory_total_mb || 1); + const ramFreeMb = ramTotalMb - ramUsedMb; + const ramPercent = ramTotalMb > 0 ? Math.round((ramUsedMb / ramTotalMb) * 100) : 0; + + const diskUsedGb = Number(data.disk_used_gb || 0); + const diskTotalGb = Number(data.disk_total_gb || 1); + const diskFreeGb = diskTotalGb - diskUsedGb; + const diskPercent = diskTotalGb > 0 ? Math.round((diskUsedGb / diskTotalGb) * 100) : 0; + + const cpuPercent = Number(data.cpu_percent || data.cpu_usage || 0); + + const warnings = []; + if (ramFreeMb < 100) warnings.push({ type: "ram", level: "critical", message: `Only ${Math.round(ramFreeMb)} MB RAM remaining` }); + else if (ramPercent > 90) warnings.push({ type: "ram", level: "warning", message: "RAM usage above 90%" }); + + if (cpuPercent > 90) warnings.push({ type: "cpu", level: "warning", message: "CPU usage above 90%" }); + + if (diskPercent > 90) warnings.push({ type: "disk", level: "warning", message: "Disk usage above 90%" }); + else if (diskFreeGb < 1) warnings.push({ type: "disk", level: "critical", message: `Only ${(diskFreeGb * 1024).toFixed(0)} MB disk space remaining` }); + + return res.json({ + ok: true, + online: true, + nodeId: node.id || node.uuid, + nodeName: node.name, + stats: { + cpu: { + percent: Math.round(cpuPercent), + cores: Number(data.cpu_cores || data.cores || 0) + }, + ram: { + usedMb: Math.round(ramUsedMb), + totalMb: Math.round(ramTotalMb), + freeMb: Math.round(ramFreeMb), + percent: ramPercent + }, + disk: { + usedGb: Math.round(diskUsedGb * 10) / 10, + totalGb: Math.round(diskTotalGb * 10) / 10, + freeGb: Math.round(diskFreeGb * 10) / 10, + percent: diskPercent + }, + uptime: data.uptime || data.uptime_seconds || 0, + hostname: data.hostname || node.name, + os: data.os || data.platform || "Unknown" + }, + warnings, + timestamp: Date.now() + }); + } catch (err) { + console.error(`[stats] Error fetching stats from node ${nodeId}:`, err.message); + return res.json({ + ok: false, + online: false, + nodeId: node.id || node.uuid, + nodeName: node.name, + error: "Failed to connect to node" + }); + } +}); + +app.post("/api/admin/refresh-statuses", async (req, res) => { + if (!(await isAdmin(req))) { + return res.status(403).json({ error: "not authorized" }); + } + + if (statusCache.refreshing) { + return res.json({ ok: true, message: "Refresh already in progress" }); + } + + pollAllNodes().catch(console.error); + + return res.json({ ok: true, message: "Refresh started" }); +}); + +function fileInfo(p) { + const exists = fs.existsSync(p); + let writable = false; + if (exists) { + try { fs.accessSync(p, fs.constants.W_OK); writable = true; } catch { } + } + return { p, exists, writable }; +} + +app.post("/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" }); + + const { type, value } = req.body || {}; + if (!type || typeof value === "undefined") return res.status(400).json({ error: "missing type/value" }); + + const cssVal = makeCssBackground(type, 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) { + req.app.locals.themeVersion = Date.now(); + return res.json({ ok: true }); + } + return res.status(500).json({ error: "failed", details: { ok1, ok2 } }); + } catch (e) { + console.error("[bg] 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"]); + +const DISCORD_WEBHOOK_REGEX = /^https:\/\/discord\.com\/api\/webhooks\/\d+\/[\w-]+$/; + +function validateDiscordWebhookUrl(url) { + if (!url || typeof url !== "string") return false; + const trimmed = url.trim(); + if (trimmed.length > 200) return false; + return DISCORD_WEBHOOK_REGEX.test(trimmed); +} + +function maskWebhookUrlServer(url) { + if (!url || typeof url !== "string") return null; + try { + const parts = url.split("/"); + if (parts.length >= 7) return parts.slice(0, 6).join("/") + "/••••••"; + } catch (_) { } + return "https://discord.com/api/webhooks/••••••/••••••"; +} + +function sanitizeWebhooksConfig(raw) { + const safe = Object.create(null); + safe.mode = (raw && (raw.mode === "single" || raw.mode === "multiple")) ? raw.mode : "single"; + safe.single = (raw && typeof raw.single === "string" && validateDiscordWebhookUrl(raw.single)) ? raw.single.trim() : null; + const safeMultiple = Object.create(null); + if (raw && raw.multiple && typeof raw.multiple === "object" && !Array.isArray(raw.multiple)) { + const validCatIds = new Set(WEBHOOK_CATEGORIES.map(c => c.id)); + for (const [k, v] of Object.entries(raw.multiple)) { + if (DANGEROUS_KEYS.has(k)) continue; + if (!validCatIds.has(k)) continue; + if (typeof v === "string" && validateDiscordWebhookUrl(v)) { + safeMultiple[k] = v.trim(); + } + } + } + safe.multiple = safeMultiple; + return safe; +} + +let _webhooksConfigCache = null; +let _webhooksConfigCacheTs = 0; +const WEBHOOKS_CONFIG_CACHE_TTL_MS = 30000; + +function loadWebhooksConfig() { + const now = Date.now(); + if (_webhooksConfigCache && (now - _webhooksConfigCacheTs) < WEBHOOKS_CONFIG_CACHE_TTL_MS) return _webhooksConfigCache; + try { + if (fs.existsSync(WEBHOOKS_CONFIG_PATH)) { + const raw = JSON.parse(fs.readFileSync(WEBHOOKS_CONFIG_PATH, "utf8")); + const result = sanitizeWebhooksConfig(raw); + _webhooksConfigCache = result; + _webhooksConfigCacheTs = now; + return result; + } + } catch (e) { + console.error("[webhooks] Failed to load config:", e.message); + } + const result = sanitizeWebhooksConfig(null); + _webhooksConfigCache = result; + _webhooksConfigCacheTs = now; + return result; +} + +function saveWebhooksConfig(config) { + const safe = sanitizeWebhooksConfig(config); + try { + fs.writeFileSync(WEBHOOKS_CONFIG_PATH, JSON.stringify(safe, null, 2), { encoding: "utf8", mode: 0o600 }); + _webhooksConfigCache = null; + _webhooksConfigCacheTs = 0; + return true; + } catch (e) { + console.error("[webhooks] Failed to save config:", e.message); + return false; + } +} + +function maskConfigForResponse(config) { + const masked = Object.create(null); + masked.mode = config.mode; + masked.single = config.single ? maskWebhookUrlServer(config.single) : null; + masked.singleConfigured = !!config.single; + const maskedMultiple = Object.create(null); + if (config.multiple) { + for (const [k, v] of Object.entries(config.multiple)) { + maskedMultiple[k] = maskWebhookUrlServer(v); + } + } + masked.multiple = maskedMultiple; + const configured = Object.create(null); + if (config.multiple) { + for (const k of Object.keys(config.multiple)) { + configured[k] = true; + } + } + masked.multipleConfigured = configured; + return masked; +} + +const WEBHOOK_CATEGORIES = [ + { id: "server_start", label: "Server Start", icon: "fa-solid fa-play", color: "#34d399" }, + { id: "server_stop", label: "Server Stop", icon: "fa-solid fa-stop", color: "#f87171" }, + { id: "server_restart", label: "Server Restart", icon: "fa-solid fa-rotate", color: "#fbbf24" }, + { id: "server_kill", label: "Server Kill", icon: "fa-solid fa-skull", color: "#f87171" }, + { id: "console_command", label: "Console Command", icon: "fa-solid fa-terminal", color: "#60a5fa" }, + { id: "file_edit", label: "File Edit", icon: "fa-solid fa-pen", color: "#a78bfa" }, + { id: "file_create", label: "File Create", icon: "fa-solid fa-file-circle-plus", color: "#34d399" }, + { id: "file_delete", label: "File Delete", icon: "fa-solid fa-trash", color: "#f87171" }, + { id: "file_rename", label: "File Rename", icon: "fa-solid fa-i-cursor", color: "#fbbf24" }, + { id: "file_upload", label: "File Upload", icon: "fa-solid fa-upload", color: "#60a5fa" }, + { id: "file_extract", label: "File Extract", icon: "fa-solid fa-file-zipper", color: "#a78bfa" }, + { id: "file_archive", label: "File Archive", icon: "fa-solid fa-box-archive", color: "#a78bfa" }, + { id: "file_delete_batch", label: "Batch File Delete", icon: "fa-solid fa-trash-can", color: "#f87171" }, + { id: "scheduler_create", label: "Scheduler Create", icon: "fa-solid fa-clock", color: "#34d399" }, + { id: "scheduler_delete", label: "Scheduler Delete", icon: "fa-solid fa-clock", color: "#f87171" }, + + { id: "password_change", label: "Password Change", icon: "fa-solid fa-lock", color: "#fbbf24" }, + { id: "user_create", label: "User Create", icon: "fa-solid fa-user-plus", color: "#34d399" }, + { id: "user_delete", label: "User Delete", icon: "fa-solid fa-user-minus", color: "#f87171" }, +]; + +const VALID_CATEGORY_IDS = new Set(WEBHOOK_CATEGORIES.map(c => c.id)); + +const webhookRateLimit = new Map(); +const WEBHOOK_RATE_LIMIT_MS = 2000; +const WEBHOOK_RATE_LIMIT_MAX_ENTRIES = 500; + +setInterval(() => { + try { + const now = Date.now(); + for (const [key, ts] of webhookRateLimit.entries()) { + if (now - ts > 60000) webhookRateLimit.delete(key); + } + } catch (err) { console.debug("[webhookRateLimit] sweep error:", err.message); } +}, 60000).unref(); + +function stripDiscordMentions(str) { + if (!str || typeof str !== "string") return str; + return str + .replace(/@(everyone|here)/gi, "@\u200B$1") + .replace(/<@[!&]?\d+>/g, "[mention removed]") + .replace(/<#\d+>/g, "[channel removed]"); +} + +function sanitizeFieldValue(val) { + if (val === null || val === undefined) return null; + let s = String(val); + s = s.slice(0, 256); + s = stripDiscordMentions(s); + s = s.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g, ""); + return s; +} + +function sanitizeFieldName(name) { + if (!name || typeof name !== "string") return "field"; + let s = name.slice(0, 64); + s = s.replace(/[\x00-\x1f\x7f]/g, ""); + return s || "field"; +} + +async function dispatchDiscordWebhook(webhookUrl, action, details, user, serverName) { + if (!webhookUrl) return; + + if (!validateDiscordWebhookUrl(webhookUrl)) { + console.warn("[SECURITY][webhooks] Blocked dispatch to invalid webhook URL (possible config tampering)"); + return; + } + + const now = Date.now(); + const key = `${action}:${webhookUrl.slice(-12)}`; + const lastSent = webhookRateLimit.get(key) || 0; + if (now - lastSent < WEBHOOK_RATE_LIMIT_MS) return; + + if (webhookRateLimit.size >= WEBHOOK_RATE_LIMIT_MAX_ENTRIES) { + const entries = [...webhookRateLimit.entries()].sort((a, b) => a[1] - b[1]); + const toEvict = Math.max(1, Math.floor(entries.length / 4)); + for (let i = 0; i < toEvict; i++) webhookRateLimit.delete(entries[i][0]); + } + webhookRateLimit.set(key, now); + + const cat = WEBHOOK_CATEGORIES.find(c => c.id === action); + const colorInt = cat ? parseInt(cat.color.replace("#", ""), 16) : 0x5865f2; + const title = cat ? cat.label : String(action || "unknown").slice(0, 64); + + const fields = []; + if (serverName) fields.push({ name: "Server", value: sanitizeFieldValue(serverName), inline: true }); + if (user) fields.push({ name: "User", value: sanitizeFieldValue(user), inline: true }); + fields.push({ name: "Time", value: new Date().toISOString(), inline: true }); + + if (details && typeof details === "object" && !Array.isArray(details)) { + let fieldCount = 0; + const MAX_DETAIL_FIELDS = 10; + for (const [k, v] of Object.entries(details)) { + if (fieldCount >= MAX_DETAIL_FIELDS) break; + if (v === null || v === undefined) continue; + if (DANGEROUS_KEYS.has(k)) continue; + fields.push({ name: sanitizeFieldName(k), value: sanitizeFieldValue(v), inline: true }); + fieldCount++; + } + } + + const payload = { + embeds: [{ + title: stripDiscordMentions(`\u{1F4CB} ${title}`), + color: colorInt, + fields, + footer: { text: "ADPanel Webhook" }, + timestamp: new Date().toISOString() + }], + allowed_mentions: { parse: [] } + }; + + try { + const body = JSON.stringify(payload); + if (Buffer.byteLength(body) > 8192) { + console.warn("[webhooks] Payload too large, skipping dispatch"); + return; + } + const urlObj = new URL(webhookUrl); + const options = { + hostname: urlObj.hostname, + path: urlObj.pathname, + method: "POST", + headers: { "Content-Type": "application/json", "Content-Length": Buffer.byteLength(body) }, + timeout: 5000 + }; + const req = https.request(options, (res) => { res.resume(); }); + req.on("error", () => { }); + req.on("timeout", () => { req.destroy(); }); + req.end(body); + } catch (e) { + console.error("[webhooks] Dispatch error:", e.message); + } +} + +function dispatchWebhookForActivity(action, details, user, serverName) { + const config = loadWebhooksConfig(); + if (!config) return; + + if (config.mode === "single" && config.single) { + dispatchDiscordWebhook(config.single, action, details, user, serverName); + } else if (config.mode === "multiple" && config.multiple) { + const url = config.multiple[action]; + if (url) { + dispatchDiscordWebhook(url, action, details, user, serverName); + } + } +} + +nodesRouter.setWebhookDispatcher(dispatchWebhookForActivity); + +app.get("/api/settings/webhooks", async (req, res) => { + const config = loadWebhooksConfig(); + res.json({ ok: true, config: maskConfigForResponse(config), categories: WEBHOOK_CATEGORIES }); +}); + +app.post("/api/settings/webhooks", async (req, res) => { + const { mode, url, category } = req.body || {}; + const hasMode = mode === "single" || mode === "multiple"; + const hasUrl = typeof url === "string" && !!url.trim(); + + if (typeof mode !== "undefined" && !hasMode) { + return res.status(400).json({ error: "Invalid mode. Must be 'single' or 'multiple'" }); + } + if (!hasMode && !hasUrl) { + return res.status(400).json({ error: "Missing mode or webhook URL" }); + } + const config = loadWebhooksConfig(); + + if (hasMode) { + config.mode = mode; + } + + if (hasUrl) { + if (!validateDiscordWebhookUrl(url)) { + return res.status(400).json({ error: "Invalid Discord webhook URL. Must be: https://discord.com/api/webhooks/..." }); + } + + if (category) { + if (!VALID_CATEGORY_IDS.has(category)) { + return res.status(400).json({ error: "Invalid category" }); + } + if (DANGEROUS_KEYS.has(category)) { + return res.status(400).json({ error: "Invalid category" }); + } + if (!config.multiple) config.multiple = Object.create(null); + config.multiple[category] = url.trim(); + } else { + config.single = url.trim(); + config.mode = "single"; + } + } + + const userEmail = req.session?.user || "unknown"; + recordActivity("_system", "webhook_config_change", { + change: hasUrl ? (category ? `set_category:${category}` : "set_single") : `mode:${mode}`, + }, userEmail, getRequestIp(req)); + + if (saveWebhooksConfig(config)) return res.json({ ok: true, config: maskConfigForResponse(config) }); + res.status(500).json({ error: "Failed to save" }); +}); + +app.delete("/api/settings/webhooks", async (req, res) => { + const { category } = req.body || {}; + const config = loadWebhooksConfig(); + + if (category) { + if (!VALID_CATEGORY_IDS.has(category)) { + return res.status(400).json({ error: "Invalid category" }); + } + if (DANGEROUS_KEYS.has(category)) { + return res.status(400).json({ error: "Invalid category" }); + } + if (config.multiple) delete config.multiple[category]; + } else { + config.single = null; + } + + const userEmail = req.session?.user || "unknown"; + recordActivity("_system", "webhook_config_delete", { + target: category || "single", + }, userEmail, getRequestIp(req)); + + if (saveWebhooksConfig(config)) return res.json({ ok: true }); + res.status(500).json({ error: "Failed to save" }); +}); + +app.post("/api/settings/webhooks/test", async (req, res) => { + const { category } = req.body || {}; + const config = loadWebhooksConfig(); + let webhookUrl = null; + + if (category) { + if (!VALID_CATEGORY_IDS.has(category)) { + return res.status(400).json({ error: "Invalid category" }); + } + webhookUrl = config.multiple ? config.multiple[category] : null; + } else { + webhookUrl = config.single; + } + + if (!webhookUrl || !validateDiscordWebhookUrl(webhookUrl)) { + return res.status(400).json({ error: "No valid webhook URL configured" }); + } + + try { + await dispatchDiscordWebhook(webhookUrl, "test", { message: "Webhook test from ADPanel" }, req.session?.user || "admin", "test"); + res.json({ ok: true }); + } catch (e) { + res.status(500).json({ error: "Failed to send test" }); + } +}); + +app.get("/api/settings/alert", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "Unauthorized" }); + res.json(getGlobalAlerts() || []); +}); + +app.post("/api/settings/alert", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "Unauthorized" }); + + const user = await findUserByEmail(req.session.user); + if (!user || !user.admin) return res.status(403).json({ error: "Admin only" }); + + const { message, date, endDate, neverEnds } = req.body || {}; + const trimmedMessage = String(message || "").trim(); + if (!trimmedMessage) return res.status(400).json({ error: "Message required" }); + + const startAt = date ? new Date(date).getTime() : NaN; + if (!Number.isFinite(startAt)) { + return res.status(400).json({ error: "Valid start date required" }); + } + + const isInfinite = neverEnds === true || String(neverEnds).toLowerCase() === "true"; + let normalizedEndDate = null; + + if (!isInfinite) { + const endAt = endDate ? new Date(endDate).getTime() : NaN; + if (!Number.isFinite(endAt)) { + return res.status(400).json({ error: "Valid end date required" }); + } + if (endAt <= startAt) { + return res.status(400).json({ error: "End date must be after start date" }); + } + normalizedEndDate = new Date(endAt).toISOString(); + } + + if (addGlobalAlert(trimmedMessage, new Date(startAt).toISOString(), normalizedEndDate, isInfinite)) { + return res.json({ ok: true }); + } + res.status(500).json({ error: "Failed to save alert" }); +}); + +app.delete("/api/settings/alert/:id", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "Unauthorized" }); + + const user = await findUserByEmail(req.session.user); + if (!user || !user.admin) return res.status(403).json({ error: "Admin only" }); + + const { id } = req.params; + if (deleteGlobalAlert(id)) return res.json({ ok: true }); + res.status(500).json({ error: "Failed to delete alert" }); +}); + +app.post("/api/settings/change-password", async (req, res) => { + try { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ error: "not authenticated" }); + } + + const email = req.session?.user; + if (!email) return res.status(401).json({ error: "not authenticated" }); + + const { current, newPassword, confirm, twoFactorCode } = req.body || {}; + + if (!current || !newPassword || !confirm) { + return res.status(400).json({ error: "missing required fields" }); + } + + if (newPassword.length < 8) { + return res.status(400).json({ error: "new password must be at least 8 characters" }); + } + + if (newPassword !== confirm) { + return res.status(400).json({ error: "passwords do not match" }); + } + + const user = await findUserByEmail(email); + if (!user) { + return res.status(404).json({ error: "user not found" }); + } + + const isValid = await withTimeout(bcrypt.compare(current, user.password), 8000, "bcrypt-timeout"); + if (!isValid) { + return res.status(403).json({ error: "current password is incorrect" }); + } + + if (user.secret) { + if (!twoFactorCode) { + 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" }); + } + } + + const hashedPassword = await withTimeout(bcrypt.hash(newPassword, BCRYPT_ROUNDS), 10000, "bcrypt-hash-timeout"); + + await db.query( + "UPDATE users SET password = ? WHERE LOWER(email) = LOWER(?)", + [hashedPassword, email] + ); + + console.log(`[auth] Password changed for user: ${email}`); + setRememberLoginCookie(req, res, { ...user, password: hashedPassword }); + return res.json({ ok: true, message: "password changed successfully" }); + } catch (err) { + console.error("[change-password] Error:", err); + return res.status(500).json({ error: "failed to change password" }); + } +}); + +app.get("/api/settings/servers", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + const index = await loadServersIndex(); + let items = (index || []) + .filter(e => e && e.name) + .map(e => ({ + name: e.name, + displayName: e.displayName || null, + nodeId: e.nodeId || null, + template: e.template || null, + })) + .sort((a, b) => a.name.localeCompare(b.name)); + + const search = String(req.query.search || '').trim().toLowerCase(); + if (search) { + items = items.filter(e => (e.name && e.name.toLowerCase().includes(search)) || (e.displayName && e.displayName.toLowerCase().includes(search))); + } + + const total = items.length; + const limit = Math.min(Math.max(parseInt(req.query.limit, 10) || 50, 1), 200); + 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); + + return res.json({ items, total, page, totalPages }); + } catch (err) { + return next(err); + } +}); + +app.get("/api/my-servers", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + const idx = (await loadServersIndex()) || []; + const entries = (Array.isArray(idx) ? idx : []).filter((entry) => entry && entry.name); + + const userEmail = req.session.user; + const u = await findUserByEmail(userEmail); + if (u && u.admin) { + return res.json({ + names: entries.map((entry) => entry.name), + servers: entries.map((entry) => ({ + name: entry.name, + displayName: entry.displayName || entry.name, + status: entry.status || "unknown", + template: entry.template || "custom", + nodeId: entry.nodeId || null, + })), + }); + } + + const access = (await getAccessListForEmail(userEmail)) || []; + const loweredAccess = new Set(access.map((name) => String(name || "").trim().toLowerCase())); + const filteredEntries = loweredAccess.has("all") + ? entries + : entries.filter((entry) => loweredAccess.has(String(entry.name || "").trim().toLowerCase())); + return res.json({ + names: filteredEntries.map((entry) => entry.name), + servers: filteredEntries.map((entry) => ({ + name: entry.name, + displayName: entry.displayName || entry.name, + status: entry.status || "unknown", + template: entry.template || "custom", + nodeId: entry.nodeId || null, + })), + }); + } catch (err) { + return next(err); + } +}); + +app.get("/api/servers/:name/permissions", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const serverName = 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, serverName))) { + return res.status(403).json({ error: "no access to server" }); + } + + const basePerms = await getEffectivePermsForUserOnServer(email, serverName); + const perms = isAdminUser + ? ALLOWED_PERM_KEYS.reduce((accumulator, key) => { + accumulator[key] = true; + return accumulator; + }, {}) + : { ...(basePerms || {}) }; + + const actionTokens = {}; + if (perms.files_create) { + actionTokens.fileWrite = issueActionToken(req, "PUT /api/servers/:name/files/write", { serverName }, { ttlSeconds: 300 }); + actionTokens.fileMkdir = issueActionToken(req, "POST /api/servers/:name/files/mkdir", { serverName }, { ttlSeconds: 300 }); + } + if (perms.files_delete) { + actionTokens.fileDelete = issueActionToken(req, "DELETE /api/servers/:name/files/delete", { serverName }, { ttlSeconds: 120, oneTime: true }); + actionTokens.fileRename = issueActionToken(req, "POST /api/servers/:name/files/rename", { serverName }, { ttlSeconds: 120, oneTime: true }); + } + if (perms.files_upload) { + actionTokens.fileUpload = issueActionToken(req, "POST /upload", { serverName }, { ttlSeconds: 300 }); + actionTokens.fileExtract = issueActionToken(req, "POST /extract", { serverName }, { ttlSeconds: 300 }); + actionTokens.fileArchive = issueActionToken(req, "POST /archive", { serverName }, { ttlSeconds: 300 }); + } + if (perms.store_access) { + actionTokens.changeTemplate = issueActionToken(req, "POST /api/servers/:bot/template", { serverName }, { ttlSeconds: 120, oneTime: true }); + actionTokens.applyVersion = issueActionToken(req, "POST /api/servers/:bot/versions/apply", { serverName }, { ttlSeconds: 120, oneTime: true }); + } + + return res.json({ + isAdmin: isAdminUser, + perms, + email, + user: user ? { email: user.email, admin: isAdminUser } : null, + agent_access: !!(user && (isAdminUser || user.agent_access)), + actionTokens, + }); + } catch (err) { + return next(err); + } +}); + + +app.get("/api/settings/accounts", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const users = await loadUsers(); + + const accessRaw = await loadUserAccess(); + const accessMap = new Map(); + for (const a of (Array.isArray(accessRaw) ? accessRaw : [])) { + const emailLower = String(a.email || "").toLowerCase(); + if (emailLower) { + accessMap.set(emailLower, Array.isArray(a.servers) ? a.servers : []); + } + } + + 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 + }; + }) + .sort((a, b) => { + if (a.admin !== b.admin) return a.admin ? -1 : 1; + return String(a.email || "").localeCompare(String(b.email || "")); + }); + + 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 }), + }, + }); + } catch (e) { + console.error("Failed to read accounts:", e); + return res.status(500).json({ error: "failed to read accounts" }); + } +}); + +app.post("/api/settings/accounts/:email/add", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/add")) return; + + let email; + try { email = decodeURIComponent(req.params.email || ""); } catch { email = req.params.email || ""; } + email = String(email).trim(); + + const server = String(req.body?.server || "").trim(); + if (!email || !server) return res.status(400).json({ error: "missing email or server" }); + + const targetUser = await findUserByEmail(email); + if (!targetUser) return res.status(404).json({ error: "user not found" }); + if (targetUser.admin) return res.status(403).json({ error: "cannot change server access for admin users" }); + + const allBots = (await loadServersIndex() || []).map(e => e?.name).filter(Boolean); + if (!allBots.includes(server) && server !== "all") return res.status(400).json({ error: "server not found" }); + + const ok = await addAccessForEmail(email, server); + if (!ok) return res.status(500).json({ error: "failed to save access" }); + return res.json({ ok: true }); + } catch (err) { + return next(err); + } +}); + +app.post("/api/settings/accounts/:email/remove", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/remove")) return; + + let email; + try { email = decodeURIComponent(req.params.email || ""); } catch { email = req.params.email || ""; } + email = String(email).trim(); + + const server = String(req.body?.server || "").trim(); + if (!email || !server) return res.status(400).json({ error: "missing email or server" }); + + const targetUser = await findUserByEmail(email); + if (!targetUser) return res.status(404).json({ error: "user not found" }); + if (targetUser.admin) return res.status(403).json({ error: "cannot change server access for admin users" }); + + const ok = await removeAccessForEmail(email, server); + if (!ok) return res.status(500).json({ error: "failed to save access" }); + return res.json({ ok: true }); + } catch (err) { + return next(err); + } +}); + +app.post("/api/settings/accounts/:email/agent-access", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/agent-access")) return; + + let email; + try { email = decodeURIComponent(req.params.email || ""); } catch { email = req.params.email || ""; } + email = String(email).trim().toLowerCase(); + + if (!email) return res.status(400).json({ error: "missing email" }); + + const targetUser = await findUserByEmail(email); + if (!targetUser) return res.status(404).json({ error: "user not found" }); + if (targetUser.admin) return res.status(403).json({ error: "cannot change agent access for admin users" }); + + const enabled = !!req.body?.enabled; + + try { + await db.query("ALTER TABLE users ADD COLUMN agent_access TINYINT(1) NOT NULL DEFAULT 0"); + } catch (e) { + } + + await db.query("UPDATE users SET agent_access = ? WHERE LOWER(email) = LOWER(?)", [enabled ? 1 : 0, email]); + + return res.json({ ok: true }); + } catch (err) { + return next(err); + } +}); + +app.get("/api/settings/accounts/:email/perms", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + let email; + try { email = decodeURIComponent(req.params.email || ""); } catch { email = req.params.email || ""; } + email = String(email).trim().toLowerCase(); + + const server = String(req.query?.server || "").trim(); + if (!email) return res.status(400).json({ error: "missing email" }); + if (!server) return res.status(400).json({ error: "missing server" }); + + const targetUser = await findUserByEmail(email); + if (!targetUser) return res.status(404).json({ error: "user not found" }); + if (targetUser.admin) return res.status(403).json({ error: "cannot query server permissions for admin users" }); + + const list = await loadServersIndex(); + const entry = list.find(e => e && e.name === server); + if (!entry) return res.status(404).json({ error: "server not found" }); + + const acl = entry.acl && typeof entry.acl === "object" ? entry.acl : {}; + const rec = acl[email] || null; + + const permissions = {}; + for (const k of ALLOWED_PERM_KEYS) { + permissions[k] = !!(rec && rec[k]); + } + if (rec && rec.console_write && !Object.prototype.hasOwnProperty.call(rec, "console_read")) { + permissions.console_read = true; + } + if (rec && rec.backups_manage) { + permissions.backups_view = true; + permissions.backups_create = true; + permissions.backups_delete = true; + } + + return res.json({ ok: true, permissions }); + } catch (err) { + return next(err); + } +}); + +app.post("/api/settings/accounts/:email/grant-perms", async (req, res, next) => { + try { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + if (!requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/grant-perms")) return; + + let email; + try { email = decodeURIComponent(req.params.email || ""); } catch { email = req.params.email || ""; } + email = String(email).trim().toLowerCase(); + + const server = String(req.body?.server || "").trim(); + const permsIn = (req.body && typeof req.body.permissions === "object") ? req.body.permissions : null; + + if (!email) return res.status(400).json({ error: "missing email" }); + if (!server) return res.status(400).json({ error: "missing server" }); + + const targetUser = await findUserByEmail(email); + if (!targetUser) return res.status(404).json({ error: "user not found" }); + if (targetUser.admin) return res.status(403).json({ error: "cannot change server permissions for admin users" }); + + const exists = !!(await findServer(server)); + if (!exists) return res.status(404).json({ error: "server not found" }); + + const cleanPerms = {}; + for (const k of ALLOWED_PERM_KEYS) cleanPerms[k] = !!(permsIn && typeof permsIn[k] === "boolean" ? permsIn[k] : false); + + const list = await loadServersIndex(); + const idx = list.findIndex(e => e && e.name === server); + if (idx === -1) { + list.push({ name: server, acl: { [email]: cleanPerms } }); + } else { + const entry = list[idx] || {}; + const acl = (entry.acl && typeof entry.acl === "object") ? entry.acl : {}; + acl[email] = cleanPerms; + entry.acl = acl; + list[idx] = entry; + } + + if (!(await saveServersIndex(list))) return res.status(500).json({ error: "failed to write servers.json" }); + try { await addAccessForEmail(email, server); } catch { } + return res.json({ ok: true }); + } catch (err) { + return next(err); + } +}); + +app.delete("/api/settings/accounts/:email", 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" }); + } + if (!requireActionTokenOr403(req, res, "DELETE /api/settings/accounts/:email")) return; + + 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" }); + } + + if (targetEmail.toLowerCase() === req.session.user.toLowerCase()) { + return res.status(400).json({ error: "cannot delete yourself" }); + } + + const targetUser = await findUserByEmail(targetEmail); + if (!targetUser) { + return res.status(404).json({ error: "user not found" }); + } + + await db.query("DELETE FROM user_access WHERE user_id = ?", [targetUser.id]); + + try { + const servers = await loadServersIndex(); + let aclsModified = false; + for (const srv of servers) { + if (srv.acl && typeof srv.acl === "object") { + const lowerEmail = targetEmail.toLowerCase(); + if (srv.acl[lowerEmail]) { + delete srv.acl[lowerEmail]; + aclsModified = true; + } + } + } + if (aclsModified) { + await saveServersIndex(servers); + } + } catch (aclErr) { + console.warn("[delete-user] Failed to clean ACLs:", aclErr); + } + + await db.query("DELETE FROM users WHERE id = ?", [targetUser.id]); + + console.log(`[delete-user] Admin ${req.session.user} deleted user ${targetEmail}`); + return res.json({ ok: true, message: "User deleted successfully" }); + } catch (err) { + console.error("[delete-user] Error:", err); + return next(err); + } +}); + +app.post("/api/settings/accounts/:email/change-password", 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" }); + } + if (!requireActionTokenOr403(req, res, "POST /api/settings/accounts/:email/change-password")) return; + + 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" }); + } + + if (targetEmail.toLowerCase() === req.session.user.toLowerCase()) { + return res.status(400).json({ error: "use the regular password change for your own account" }); + } + + const targetUser = await findUserByEmail(targetEmail); + if (!targetUser) { + return res.status(404).json({ error: "user not found" }); + } + + const { newPassword, confirm } = req.body || {}; + if (!newPassword || !confirm) { + return res.status(400).json({ error: "missing required fields" }); + } + + if (newPassword.length < 8) { + return res.status(400).json({ error: "password must be at least 8 characters" }); + } + + if (newPassword !== confirm) { + return res.status(400).json({ error: "passwords do not match" }); + } + + const hashedPassword = await withTimeout(bcrypt.hash(newPassword, BCRYPT_ROUNDS), 10000, "bcrypt-hash-timeout"); + + await db.query( + "UPDATE users SET password = ? WHERE id = ?", + [hashedPassword, targetUser.id] + ); + + console.log(`[admin-change-password] Admin ${req.session.user} changed password for user ${targetEmail}`); + return res.json({ ok: true, message: "Password changed successfully" }); + } catch (err) { + console.error("[admin-change-password] Error:", err); + return next(err); + } +}); + + + +app.get("/api/servers/:name/files/list", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const name = String(req.params.name || "").trim(); + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, name))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, name); + if (!perms.files_read) return res.status(403).json({ error: "not authorized" }); + + const rel = String(req.query.path || ""); + + const ctx = await resolveRemoteFsContext(name); + if (!ctx.remote) return res.status(404).json({ error: "server not found on node" }); + + try { + const dir = safeJoinUnix(ctx.baseDir, rel || ""); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/list", { path: dir }, 60_000); + + if (status === 0) { + console.error(`[files/list] Node connection failed for ${name} - node may be offline`); + return res.status(502).json({ error: "node_offline", message: "Cannot connect to server node. The node may be offline." }); + } + if (status !== 200 || !json || !json.ok) { + console.error(`[files/list] Node returned error for ${name}: status=${status}, json=${JSON.stringify(json)}`); + return res.status(502).json({ error: "node_list_failed", detail: json?.error || `status ${status}` }); + } + return res.json({ ok: true, path: rel, entries: Array.isArray(json.entries) ? json.entries : [] }); + } catch (e) { + console.error(`[files/list] Error for ${name}:`, e.message); + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } +}); + +app.get("/api/servers/:name/files/read", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const name = String(req.params.name || "").trim(); + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, name))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, name); + if (!perms.files_read) return res.status(403).json({ error: "not authorized" }); + + const rel = String(req.query.path || ""); + + const ctx = await resolveRemoteFsContext(name); + if (!ctx.remote) return res.status(404).json({ 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); + 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" }); + + const content = typeof json.content === "string" ? json.content : ""; + return res.json({ ok: true, path: rel, content }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } +}); + +app.get("/api/servers/:name/files/stream", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).end("not authenticated"); + + const name = String(req.params.name || "").trim(); + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, name))) { + return res.status(403).end("no access to server"); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, name); + if (!perms.files_read) return res.status(403).end("not authorized"); + + const rel = String(req.query.path || ""); + + const ctx = await resolveRemoteFsContext(name); + if (!ctx.remote) return res.status(404).end("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); + 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"); + + const content = typeof json.content === "string" ? json.content : ""; + res.setHeader("Content-Type", "text/plain; charset=utf-8"); + return res.end(content); + } catch (e) { + return res.status(400).end(maskPathErrorMessage(e, "invalid path", "invalid path")); + } +}); + +app.get("/api/servers/:name/files/download", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).end("not authenticated"); + + const name = String(req.params.name || "").trim(); + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, name))) { + return res.status(403).end("no access to server"); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, name); + if (!perms.files_read) return res.status(403).end("not authorized"); + + const rel = String(req.query.path || ""); + + const ctx = await resolveRemoteFsContext(name); + if (!ctx.remote) return res.status(404).end("server not found on node"); + + try { + 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 lib = nodeBase.startsWith("https:") ? require("https") : require("http"); + const url = new URL(`${nodeBase}/v1/fs/download`); + const hdrs = nodeAuthHeadersFor(ctx.node, true); + const reqOpts = { + hostname: url.hostname, + port: url.port, + path: url.pathname, + method: "POST", + headers: Object.assign({ "Content-Type": "application/json", "Content-Length": Buffer.byteLength(postData) }, hdrs), + timeout: 300000 + }; + const proxyReq = lib.request(reqOpts, (proxyRes) => { + if (proxyRes.statusCode !== 200) { + return res.status(proxyRes.statusCode || 502).end("download failed"); + } + if (proxyRes.headers["content-type"]) res.setHeader("Content-Type", proxyRes.headers["content-type"]); + if (proxyRes.headers["content-disposition"]) res.setHeader("Content-Disposition", proxyRes.headers["content-disposition"]); + if (proxyRes.headers["content-length"]) res.setHeader("Content-Length", proxyRes.headers["content-length"]); + proxyRes.pipe(res); + }); + proxyReq.on("error", () => res.status(502).end("node connection failed")); + proxyReq.on("timeout", () => { proxyReq.destroy(); res.status(504).end("download timeout"); }); + proxyReq.write(postData); + proxyReq.end(); + } catch (e) { + return res.status(400).end(maskPathErrorMessage(e, "invalid path", "invalid path")); + } +}); + +app.put("/api/servers/:name/files/write", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const name = String(req.params.name || "").trim(); + if (!requireActionTokenOr403(req, res, "PUT /api/servers/:name/files/write", { serverName: name })) return; + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, name))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, name); + if (!perms.files_create) return res.status(403).json({ error: "not authorized" }); + + const rel = String(req.body?.path || ""); + const content = String(req.body?.content ?? ""); + + const ctx = await resolveRemoteFsContext(name); + if (!ctx.remote) return res.status(404).json({ error: "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, encoding: "utf8" }, 120000); + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_write_failed" }); + return res.json({ ok: true }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } +}); + +app.post("/api/servers/:name/files/mkdir", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const name = String(req.params.name || "").trim(); + if (!requireActionTokenOr403(req, res, "POST /api/servers/:name/files/mkdir", { serverName: name })) return; + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, name))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, name); + if (!perms.files_create) return res.status(403).json({ error: "not authorized" }); + + const rel = String(req.body?.path || ""); + + const ctx = await resolveRemoteFsContext(name); + if (!ctx.remote) return res.status(404).json({ error: "server not found on node" }); + + try { + const full = safeJoinUnix(ctx.baseDir, rel || ""); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/mkdir", { path: full }, 120000); + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_mkdir_failed" }); + return res.json({ ok: true }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } +}); + +app.delete("/api/servers/:name/files/delete", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const name = String(req.params.name || "").trim(); + if (!requireActionTokenOr403(req, res, "DELETE /api/servers/:name/files/delete", { serverName: name })) return; + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, name))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, name); + if (!perms.files_delete) return res.status(403).json({ error: "not authorized" }); + + const rel = String(req.query.path || req.body?.path || ""); + + const ctx = await resolveRemoteFsContext(name); + if (!ctx.remote) return res.status(404).json({ error: "server not found on node" }); + + 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); + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_delete_failed" }); + return res.json({ ok: true }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } +}); + +app.post("/api/servers/:name/files/rename", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const name = String(req.params.name || "").trim(); + if (!requireActionTokenOr403(req, res, "POST /api/servers/:name/files/rename", { serverName: name })) return; + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, name))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, name); + if (!perms.files_rename) return res.status(403).json({ error: "not authorized" }); + + const srcRel = String(req.body?.src || ""); + const destRel = String(req.body?.dest || ""); + + const ctx = await resolveRemoteFsContext(name); + if (!ctx.remote) return res.status(404).json({ error: "server not found on node" }); + + 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); + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_rename_failed" }); + return res.json({ ok: true }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } +}); + +function streamPanelUploadToNode(node, sourceStream, originalName, targetDir, maxBytes, maxMb) { + return new Promise((resolve) => { + let settled = false; + let nodeReq = null; + const done = (result) => { + if (settled) return; + settled = true; + resolve(result); + }; + + try { + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + const uploadUrl = `${baseUrl}/v1/fs/upload`; + const lib = uploadUrl.startsWith("https:") ? https : httpMod; + const parsedUrl = new URL(uploadUrl); + const boundary = `----ADPanelUpload${crypto.randomBytes(16).toString("hex")}`; + const safeOriginalName = String(originalName || "upload.bin").replace(/[\r\n"]/g, "_"); + const preamble = Buffer.from( + `--${boundary}\r\n` + + `Content-Disposition: form-data; name="dir"\r\n\r\n` + + `${targetDir}\r\n` + + `--${boundary}\r\n` + + `Content-Disposition: form-data; name="file"; filename="${safeOriginalName}"\r\n` + + `Content-Type: application/octet-stream\r\n\r\n`, + "utf8" + ); + const epilogue = Buffer.from(`\r\n--${boundary}--\r\n`, "utf8"); + + const headers = nodeAuthHeadersFor(node, true); + headers["Content-Type"] = `multipart/form-data; boundary=${boundary}`; + + nodeReq = lib.request({ + method: "POST", + hostname: parsedUrl.hostname, + port: parsedUrl.port || (uploadUrl.startsWith("https:") ? 443 : 80), + path: parsedUrl.pathname + parsedUrl.search, + headers, + timeout: 3600000 + }, (response) => { + const chunks = []; + let total = 0; + response.on("data", (d) => { + if (total < 64 * 1024) { + chunks.push(d); + total += d.length; + } + }); + response.on("end", () => { + if (settled) return; + const body = Buffer.concat(chunks).toString().slice(0, 2000); + let json = null; + try { json = body ? JSON.parse(body) : null; } catch { } + done({ status: response.statusCode, json, body }); + }); + }); + + nodeReq.on("error", (err) => done({ status: 0, json: { error: "upload_network_error", detail: err.message } })); + nodeReq.on("timeout", () => { + try { nodeReq.destroy(); } catch { } + done({ status: 0, json: { error: "upload_timeout" } }); + }); + + nodeReq.write(preamble); + let written = 0; + sourceStream.on("data", (chunk) => { + if (settled) return; + written += chunk.length; + if (maxBytes > 0 && written > maxBytes) { + try { sourceStream.destroy(); } catch { } + try { nodeReq.destroy(); } catch { } + done({ + status: 413, + json: { + error: "file_too_large", + message: `File exceeds this node's upload limit of ${maxMb || Math.round(maxBytes / 1024 / 1024)} MB`, + limit_mb: maxMb || Math.round(maxBytes / 1024 / 1024), + }, + }); + return; + } + if (!nodeReq.write(chunk)) { + sourceStream.pause(); + nodeReq.once("drain", () => { + if (!settled) sourceStream.resume(); + }); + } + }); + sourceStream.on("end", () => { + if (settled) return; + nodeReq.write(epilogue); + nodeReq.end(); + }); + sourceStream.on("error", (err) => { + if (settled) return; + try { nodeReq.destroy(); } catch { } + done({ status: 0, json: { error: "upload_stream_error", detail: err.message } }); + }); + } catch (e) { + try { if (nodeReq) nodeReq.destroy(); } catch { } + done({ status: 0, json: { error: "stream_error", detail: e.message } }); + } + }); +} + +app.post("/upload", async (req, res) => { + if (!(await isAuthenticated(req))) { + if (req.headers?.accept?.includes("text/html")) return res.redirect("/login"); + return res.status(401).json({ error: "Not authenticated" }); + } + + let bot = ""; + let relPath = ""; + let fileSeen = false; + let responded = false; + const incomingLength = Number(req.headers["content-length"] || 0) || 0; + + const respond = (status, payload) => { + if (responded || res.headersSent) return; + responded = true; + res.status(status).json(payload); + }; + + const bb = getLazyBusboy()({ + headers: req.headers, + limits: { files: 1, fields: 8, fieldSize: 64 * 1024 }, + }); + + bb.on("field", (name, value) => { + if (name === "bot") bot = String(value || "").trim(); + if (name === "path") relPath = String(value || "").trim(); + }); + + bb.on("file", (name, fileStream, info) => { + if (responded) { + fileStream.resume(); + return; + } + if (name !== "file") { + fileStream.resume(); + return; + } + if (fileSeen) { + fileStream.resume(); + respond(400, { error: "too_many_files" }); + return; + } + fileSeen = true; + + (async () => { + if (!bot) { + fileStream.resume(); + respond(400, { error: "missing bot" }); + return; + } + + if (!requireActionTokenOr403(req, res, "POST /upload", { serverName: bot })) { + responded = true; + fileStream.resume(); + return; + } + + const currentEmail = req.session.user; + if (!(await isAdmin(req)) && !(await userHasAccessToServer(currentEmail, bot))) { + fileStream.resume(); + respond(403, { error: "no access to server" }); + return; + } + + const perms = await getEffectivePermsForUserOnServer(currentEmail, bot); + if (!perms.files_upload && !(await isAdmin(req))) { + fileStream.resume(); + respond(403, { error: "no upload permission" }); + return; + } + + const ctx = await resolveRemoteFsContext(bot); + if (!ctx.remote) { + fileStream.resume(); + respond(404, { error: "server not found on node" }); + return; + } + + const nodeMaxUploadMb = ctx.node?.max_upload_mb || 10240; + const nodeMaxUploadBytes = nodeMaxUploadMb * 1024 * 1024; + const filename = sanitizeUploadFilename(info?.filename || "upload"); + if (!filename) { + fileStream.resume(); + respond(400, { error: "Invalid filename" }); + return; + } + if (!isUploadExtensionAllowed(filename)) { + fileStream.resume(); + respond(400, { error: "file-type-not-allowed" }); + return; + } + + const targetDir = safeJoinUnix(ctx.baseDir, relPath || ""); + const diskSnapshot = await fetchNodeDiskSnapshot(ctx.node, bot, 5000).catch(() => null); + const replacedBytes = await fetchNodeReplacementBytes(ctx.node, targetDir, filename, 5000).catch(() => null); + const diskLimitError = replacedBytes == null ? null : buildDiskLimitUploadError(diskSnapshot, incomingLength, replacedBytes); + if (diskLimitError) { + fileStream.resume(); + respond(507, diskLimitError); + return; + } + + const result = await streamPanelUploadToNode(ctx.node, fileStream, filename, targetDir, nodeMaxUploadBytes, nodeMaxUploadMb); + if (result.status === 507 && result.json?.error === "disk_limit_exceeded") { + respond(507, result.json); + return; + } + if (result.status === 413) { + respond(413, result.json || { + error: "file_too_large", + message: `File exceeds this node's upload limit of ${nodeMaxUploadMb} MB`, + limit_mb: nodeMaxUploadMb, + }); + return; + } + if (result.status !== 200 || !result.json || !result.json.ok) { + console.error("[upload->node] failed:", result.status, result.body || result.json?.error || ""); + respond(502, { error: "Failed to upload to node" }); + return; + } + + respond(200, { ok: true, msg: "Uploaded to node", path: path.posix.join(relPath || "", filename) }); + })().catch((e) => { + console.error("[upload->node] failed:", e); + fileStream.resume(); + respond(400, { error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + }); + }); + + bb.on("error", (err) => { + respond(400, { error: "bad_multipart", detail: err.message }); + }); + + bb.on("finish", () => { + if (!responded && !fileSeen) { + respond(400, { error: "No file uploaded" }); + } + }); + + req.pipe(bb); +}); + +app.post("/upload-url", express.json({ limit: "16kb" }), async (req, res) => { + if (!(await isAuthenticated(req))) { + return res.status(401).json({ error: "Not authenticated" }); + } + + const bot = String(req.body?.bot || "").trim(); + const rawUrl = String(req.body?.url || "").trim(); + const relPath = String(req.body?.path || "").trim(); + + if (!bot) return res.status(400).json({ error: "missing bot" }); + if (!rawUrl) return res.status(400).json({ error: "missing url" }); + if (rawUrl.length > 2048) return res.status(400).json({ error: "url too long" }); + + if (!requireActionTokenOr403(req, res, "POST /upload", { serverName: bot })) return; + + const currentEmail = req.session.user; + if (!(await isAdmin(req)) && !(await userHasAccessToServer(currentEmail, bot))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(currentEmail, bot); + if (!perms.files_upload && !(await isAdmin(req))) { + return res.status(403).json({ error: "no upload permission" }); + } + + let validatedUrl; + try { + const normalizedUrl = /^[a-zA-Z][a-zA-Z0-9+.\-]*:\/\//.test(rawUrl) ? rawUrl : `https://${rawUrl}`; + validatedUrl = await assertSafeRemoteUrl(normalizedUrl); + } catch (err) { + return res.status(400).json({ error: "invalid_url", message: (err && err.message) ? err.message : "Invalid URL" }); + } + + const ctx = await resolveRemoteFsContext(bot); + if (!ctx.remote) return res.status(404).json({ error: "server not found on node" }); + + try { + const targetDir = safeJoinUnix(ctx.baseDir, relPath || ""); + const baseUrl = buildNodeBaseUrl(ctx.node.address, ctx.node.api_port || 8080, ctx.node.ssl_enabled, nodeUnderCloudflare(ctx.node)); + if (!baseUrl) return res.status(502).json({ error: "node_offline" }); + + const { status, json } = await nodeFsPost( + ctx.node, + "/v1/fs/uploadUrl", + { dir: targetDir, url: validatedUrl.toString() }, + 30 * 60 * 1000 + ); + + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status === 413 && json) { + return res.status(413).json(json); + } + if (status !== 200 || !json || json.ok !== true) { + const msg = (json && (json.error || json.message)) || `node_upload_url_failed (HTTP ${status})`; + return res.status(502).json({ error: "node_upload_url_failed", message: msg }); + } + + return res.json({ + ok: true, + msg: "Uploaded from URL", + filename: json.filename || null, + bytes: json.bytes || null + }); + } catch (e) { + console.error("[upload-url->node] failed:", e); + return res.status(400).json({ error: "upload_url_failed", message: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } +}); + +app.post("/extract", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const bot = String(req.body?.bot || "").trim(); + const relPath = String(req.body?.path || "").trim(); + if (!bot || !relPath) return res.status(400).json({ error: "missing bot or path" }); + + if (!requireActionTokenOr403(req, res, "POST /extract", { serverName: bot })) return; + + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, bot))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, bot); + if (!perms.files_create && !(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + const ctx = await resolveRemoteFsContext(bot); + if (!ctx.remote) return res.status(404).json({ error: "server not found on node" }); + + try { + const full = safeJoinUnix(ctx.baseDir, relPath); + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/extract", { path: full }, 300_000); + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_extract_failed" }); + return res.json({ ok: true, msg: "Extracted successfully" }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "invalid path") }); + } +}); + +app.post("/archive", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const bot = String(req.body?.bot || "").trim(); + const paths = req.body?.paths; + const destDir = String(req.body?.destDir || "").trim(); + + if (!bot || !Array.isArray(paths) || paths.length === 0) { + return res.status(400).json({ error: "missing bot or paths" }); + } + + if (!requireActionTokenOr403(req, res, "POST /archive", { serverName: bot })) return; + + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, bot))) { + return res.status(403).json({ error: "no access to server" }); + } + + 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" }); + } + + const ctx = await resolveRemoteFsContext(bot); + if (!ctx.remote) return res.status(404).json({ error: "server not found on node" }); + + try { + const botSeg = encodeURIComponent(bot); + const { status, json } = await nodeFsPost(ctx.node, `/v1/servers/${botSeg}/files/archive`, { paths, destDir }, 300_000); + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status !== 200 || !json || !json.ok) { + return res.status(502).json({ error: json?.error || "archive failed" }); + } + return res.json({ ok: true, path: json.path, name: json.name }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e, "invalid path", "archive failed") }); + } +}); + +app.post("/create", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).send("Not authenticated"); + + const bot = String(req.body?.bot || "").trim(); + const type = String(req.body?.type || "").trim().toLowerCase(); + const name = String(req.body?.name || "").trim(); + const relPath = String(req.body?.path || "").trim(); + + if (!bot || !type || !name) return res.status(400).send("Missing fields"); + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, bot))) { + return res.status(403).send("Not authorized"); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, bot); + if (!perms.files_create && !(await isAdmin(req))) return res.status(403).send("Not authorized"); + + if (!["file", "folder"].includes(type)) return res.status(400).send("Invalid type"); + if (name.includes("..") || /[\\/]/.test(name)) return res.status(400).send("Invalid name"); + + const ctx = await resolveRemoteFsContext(bot); + if (!ctx.remote) return res.status(404).send("Server not found on node"); + + try { + const relativePosix = path.posix.join(relPath || "", name); + const target = safeJoinUnix(ctx.baseDir, relativePosix); + + const payload = type === "folder" + ? { path: safeJoinUnix(target, ".keep"), content: "", encoding: "utf8" } + : { path: target, content: "", encoding: "utf8" }; + + const { status, json } = await nodeFsPost(ctx.node, "/v1/fs/write", payload, 120000); + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status !== 200 || !json || !json.ok) throw new Error("node-create-failed"); + return res.json({ ok: true, path: relativePosix }); + } catch (e) { + return res.status(400).send(maskPathErrorMessage(e, "Invalid path", "Create failed")); + } +}); + +app.post("/rename", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).send("Not authenticated"); + + const bot = String(req.body?.bot || "").trim(); + const oldPath = String(req.body?.oldPath || "").trim(); + const newName = String(req.body?.newName || "").trim(); + + if (!bot || !oldPath || !newName) return res.status(400).send("Missing fields"); + if (!(await isAdmin(req)) && !(await userHasAccessToServer(req.session.user, bot))) { + return res.status(403).send("Not authorized"); + } + + const perms = await getEffectivePermsForUserOnServer(req.session.user, bot); + if (!perms.files_rename) return res.status(403).send("Not authorized"); + + if (newName.includes("..") || /[\\/]/.test(newName)) return res.status(400).send("Invalid new name"); + + const ctx = await resolveRemoteFsContext(bot); + if (!ctx.remote) return res.status(404).send("Server not found on node"); + + try { + const relative = path.posix.join(path.posix.dirname(path.posix.join(oldPath)), newName); + 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); + if (status !== 200 || !json || !json.ok) return res.status(500).send("Rename failed"); + return res.json({ ok: true, path: relative }); + } catch (e) { + return res.status(400).send(maskPathErrorMessage(e, "Invalid path", "Invalid path")); + } +}); + +const nodeVersions = ["14", "16", "18", "20"]; + +app.get("/server/:server/resources", async (req, res) => { + try { + if (!(await isAuthenticated(req))) return res.redirect("/login"); + + const requested = String(req.params.server || ""); + const botName = sanitizeServerName(requested) || requested; + const entry = await findServer(botName); + + if (!entry) return res.status(404).send("Server not found"); + + const hasAccess = (await isAdmin(req)) || (await userHasAccessToServer(req.session.user, botName)); + if (!hasAccess) return res.status(403).send("Unauthorized"); + + return res.render("resource-popup", { bot: botName, cspNonce: res.locals.cspNonce }); + } catch (err) { + console.error(err); + return res.status(500).send("Internal Server Error"); + } +}); + +app.get("/server/:server", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.redirect("/login"); + + const requested = String(req.params.server || ""); + const botName = sanitizeServerName(requested) || requested; + const entry = await findServer(botName); + + if (!entry) { + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); + return res.status(404).render("404", { cspNonce: res.locals.cspNonce }); + } + + const hasAccess = (await isAdmin(req)) || (await userHasAccessToServer(req.session.user, botName)); + if (!hasAccess) { + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); + return res.status(404).render("404", { cspNonce: res.locals.cspNonce }); + } + + const activeTransfer = getTransferJob(botName); + const isTransferring = (entry && String(entry.status || "").toLowerCase() === "transferring") || (activeTransfer && !activeTransfer.finishedAt); + if (isTransferring) { + const botNameHtml = escapeHtml(botName); + const html = `ADPanel - Transferring
Server is transferring
${botNameHtml} is being moved to another node. Please wait…
Refresh in a moment. This page will be available once the transfer finishes.
`; + return res.status(200).send(html); + } + + const email = req.session.user; + const userObj = email ? await findUserByEmail(email) : null; + const avatarUrl = resolveUserAvatarUrl(userObj); + + return res.render("bot", { bot: botName, displayName: entry.displayName || botName, nodeVersions, avatarUrl, user: userObj }); + } catch (err) { + return next(err); + } +}); + +app.get("/bot/:bot", (req, res) => { + res.redirect(301, "/server/" + encodeURIComponent(req.params.bot)); +}); + +async function resolveTemplateForBot(bot) { + const entry = await findServer(bot); + const explicit = normalizeTemplateId(entry?.template); + if (explicit) return { entry, template: explicit }; + const start = String(entry?.start || "").toLowerCase(); + if (start.endsWith(".jar")) return { entry, template: "minecraft" }; + if (start.endsWith(".js") || start.endsWith(".ts")) return { entry, template: "nodejs" }; + if (start.endsWith(".py")) return { entry, template: "python" }; + return { entry, template: "" }; +} + +function setBodyBackgroundInFile(filePath, cssVal) { + try { + let css = fs.readFileSync(filePath, "utf8"); + + const varRe = /(--ui-bg\s*:\s*)([^;]*)(;)/; + if (varRe.test(css)) { + css = css.replace(varRe, `$1${cssVal}$3`); + } else { + if (/:root\s*\{/.test(css)) { + css = css.replace(/:root\s*\{/, `:root{\n --ui-bg: ${cssVal};`); + } else { + css += `\n:root{ --ui-bg: ${cssVal}; }\n`; + } + } + + if (!/body\s*\{[^}]*background\s*:/.test(css)) { + css += `\nbody{ background: var(--ui-bg) center/cover no-repeat fixed !important; }\n`; + } + + fs.writeFileSync(filePath, css, "utf8"); + return true; + } catch (e) { + console.error("[setBodyBackgroundInFile] failed:", filePath, e); + return false; + } +} + +app.get("/api/servers/:bot/versions", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const bot = String(req.params.bot || "").trim(); + const safeBotName = sanitizeServerName(bot) || bot; + const { entry, template } = await resolveTemplateForBot(safeBotName); + const preferredTemplate = normalizeTemplateId(req.query.template || req.query.tpl || ""); + const isAdminUser = await isAdmin(req); + + if (!entry) return res.status(404).json({ error: "server-not-found" }); + + const serverName = entry.name || safeBotName; + if (!isAdminUser && !(await userHasAccessToServer(req.session.user, serverName))) { + return res.status(403).json({ error: "no-access-to-server" }); + } + if (!isAdminUser) { + const perms = await getEffectivePermsForUserOnServer(req.session.user, serverName); + if (!perms.store_access) return res.status(403).json({ error: "not-authorized", permission: "store_access" }); + } + + const effectiveTemplate = preferredTemplate || template; + + const providers = providersForTemplate(effectiveTemplate).map(p => ({ + id: p.id, + name: p.name, + description: p.description, + logo: p.logo, + })); + + return res.json({ providers }); + } catch (err) { + return next(err); + } +}); + +app.get("/api/servers/:bot/versions/:providerId", async (req, res, next) => { + try { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + + const bot = String(req.params.bot || "").trim(); + const safeBotName = sanitizeServerName(bot) || bot; + const providerId = String(req.params.providerId || "").trim(); + const isAdminUser = await isAdmin(req); + + const { entry, template } = await resolveTemplateForBot(safeBotName); + const preferredTemplate = normalizeTemplateId(req.query.template || req.query.tpl || ""); + if (!entry) return res.status(404).json({ error: "server-not-found" }); + + const serverName = entry.name || safeBotName; + if (!isAdminUser && !(await userHasAccessToServer(req.session.user, serverName))) { + return res.status(403).json({ error: "no-access-to-server" }); + } + if (!isAdminUser) { + const perms = await getEffectivePermsForUserOnServer(req.session.user, serverName); + if (!perms.store_access) return res.status(403).json({ error: "not-authorized", permission: "store_access" }); + } + + const effectiveTemplate = preferredTemplate || template; + + const provider = providersForTemplate(effectiveTemplate).find(p => p.id === providerId); + if (!provider) return res.status(404).json({ error: "provider-not-found" }); + + if (provider.id === "python") { + try { + const tags = await fetchPythonDockerTags(); + const versions = mapPythonTagsToVersions(tags); + return res.json({ provider: provider.id, displayName: provider.name, description: provider.description, versions }); + } catch { + return res.status(502).json({ error: "python-versions-unavailable" }); + } + } + + if (provider.id === "nodejs") { + try { + const tags = await fetchNodeDockerTags(); + const versions = mapNodeVersionsToList(tags); + return res.json({ provider: provider.id, displayName: provider.name, description: provider.description, versions }); + } catch { + return res.status(502).json({ error: "node-versions-unavailable" }); + } + } + + if (provider.id === "fivem") { + try { + const versions = await getFivemArtifactChannelVersions(); + return res.json({ provider: provider.id, displayName: provider.name, description: provider.description, versions }); + } catch { + return res.status(502).json({ error: "fivem-artifacts-unavailable" }); + } + } + + return res.json({ + provider: provider.id, + displayName: provider.name, + description: provider.description, + versions: provider.versions || [], + }); + } catch (err) { + return next(err); + } +}); + +app.get("/api/papermc/*", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not-authenticated" }); + const subPath = req.params[0] || ""; + if (subPath.includes("..") || subPath.length > 300) return res.status(400).json({ error: "invalid-path" }); + const upstream = `https://api.papermc.io/v2/${subPath}`; + try { + const r = await httpRequestJson(upstream, "GET", { "Accept": "application/json" }, null, 15000); + if (!r.json) return res.status(502).json({ error: "upstream-error" }); + return res.status(r.status || 200).json(r.json); + } catch { + return res.status(502).json({ error: "proxy-failed" }); + } +}); + +app.get("/api/purpurmc/*", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not-authenticated" }); + const subPath = req.params[0] || ""; + if (subPath.includes("..") || subPath.length > 300) return res.status(400).json({ error: "invalid-path" }); + const upstream = `https://api.purpurmc.org/v2/${subPath}`; + try { + const r = await httpRequestJson(upstream, "GET", { "Accept": "application/json" }, null, 15000); + if (!r.json) return res.status(502).json({ error: "upstream-error" }); + return res.status(r.status || 200).json(r.json); + } catch { + return res.status(502).json({ error: "proxy-failed" }); + } +}); + +app.post("/api/servers/:bot/versions/apply", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ ok: false, error: "not-authenticated" }); + + const bot = String(req.params.bot || "").trim(); + if (!bot) return res.status(400).json({ ok: false, error: "missing-bot" }); + + if (!requireActionTokenOr403(req, res, "POST /api/servers/:bot/versions/apply", { serverName: bot })) return; + const isAdminUser = await isAdmin(req); + + if (!isAdminUser && !(await userHasAccessToServer(req.session.user, bot))) { + return res.status(403).json({ ok: false, error: "no-access-to-server" }); + } + if (!isAdminUser) { + const perms = await getEffectivePermsForUserOnServer(req.session.user, bot); + if (!perms.store_access) return res.status(403).json({ ok: false, error: "not-authorized", permission: "store_access" }); + } + + const entry = await findServer(bot); + if (!entry) return res.status(404).json({ ok: false, error: "server-not-found" }); + if (!isRemoteEntry(entry)) return res.status(400).json({ ok: false, error: "server-not-on-node" }); + + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) return res.status(400).json({ ok: false, error: "node-not-found" }); + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || NODE_AGENT_PORT, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return res.status(400).json({ ok: false, error: "invalid-node-address" }); + + const { providerId, versionId, url: bodyUrl, destPath: rawDestPath } = req.body || {}; + + const serverTemplate = normalizeTemplateId(entry.template); + const preferredTemplate = normalizeTemplateId(req.body?.template || req.body?.tpl || ""); + const runtimeTemplate = preferredTemplate || serverTemplate || ((providerId === "nodejs" || providerId === "python") ? "discord-bot" : ""); + const headers = nodeAuthHeadersFor(node, true); + + try { + const providerKey = String(providerId || "").trim().toLowerCase(); + if (providerKey === "fivem" || runtimeTemplate === "fivem") { + const providerCfg = findProviderConfig("fivem"); + if (!providerCfg || !providerSupportsTemplate(providerCfg, "fivem")) { + return res.status(400).json({ ok: false, error: "provider-not-supported" }); + } + let artifact; + try { + artifact = await resolveFivemArtifactVersion(versionId); + } catch (artifactErr) { + return res.status(artifactErr.statusCode || 400).json({ ok: false, error: artifactErr.message || "invalid-fivem-version" }); + } + const applyResult = await applyFivemArtifactToServer({ bot, entry, artifact }); + if (!applyResult.ok) { + return res.status(applyResult.statusCode || 500).json(applyResult); + } + return res.json(applyResult); + } + + if (runtimeTemplate && runtimeTemplate !== "minecraft") { + const providerCfg = findProviderConfig(providerId); + if (!providerCfg || (runtimeTemplate && !providerSupportsTemplate(providerCfg, runtimeTemplate))) { + return res.status(400).json({ ok: false, error: "provider-not-supported" }); + } + + let versionCfg = findProviderVersionConfig(providerId, versionId); + if (!versionCfg && providerId === "python") { + const versions = mapPythonTagsToVersions(await fetchPythonDockerTags()); + const exists = versions.some(v => String(v.id) === String(versionId) || String(v.name) === String(versionId)); + if (exists) versionCfg = buildPythonVersionConfig(versionId, entry); + } + if (!versionCfg && providerId === "nodejs") { + const versions = mapNodeVersionsToList(await fetchNodeDockerTags()); + const exists = versions.some(v => String(v.id) === String(versionId) || String(v.name) === String(versionId)); + if (exists) versionCfg = buildNodeVersionConfig(versionId, entry); + } + + if (!versionCfg) return res.status(404).json({ ok: false, error: "version-not-found" }); + + const dockerCfg = versionCfg.docker || {}; + if (!dockerCfg.image || !dockerCfg.tag) return res.status(400).json({ ok: false, error: "missing-docker-config" }); + + const startFile = versionCfg.start || entry.start || (providerId === "python" ? "main.py" : "index.js"); + const port = clampAppPort(entry.port ?? 3001, 3001); + + const runtime = { + providerId: providerCfg.id, + versionId: versionCfg.id || versionId, + image: dockerCfg.image, + tag: dockerCfg.tag, + command: dockerCfg.command || null, + workdir: dockerCfg.workdir || "/app", + env: dockerCfg.env || {}, + volumes: dockerCfg.volumes || null, + }; + + const forwardUrl = `${baseUrl}/v1/servers/${encodeURIComponent(bot)}/runtime`; + const payload = { runtime, template: entry.template || runtimeTemplate || "nodejs", start: startFile, port }; + + const r = await httpRequestJson(forwardUrl, "POST", headers, payload, 60_000); + if (r.status !== 200 || !(r.json && r.json.ok)) { + const detail = (r.json && (r.json.detail || r.json.error)) || `node-status-${r.status}`; + console.error(`[versions/apply] runtime forward failed: status=${r.status}, error=${detail}, node=${node.name || node.address}`); + if (r.status === 401 || r.status === 0) { + return res.status(502).json({ ok: false, error: "node-auth-failed", detail: "Token mismatch. Re-deploy config.yml to the node." }); + } + return res.status(502).json({ ok: false, error: detail || `node-runtime-forward-failed-${r.status}` }); + } + + await upsertServerIndexEntry({ ...entry, runtime, start: startFile, port }); + return res.json({ ok: true, remote: true, msg: "runtime-updated", runtime }); + } + + let url = (bodyUrl && String(bodyUrl).trim()) || ""; + if (!url) { + if (!providerId || !versionId) return res.status(400).json({ ok: false, error: "missing-params" }); + const vcfg = findProviderVersionConfig(providerId, versionId); + url = vcfg?.url || vcfg?.link || vcfg?.download || vcfg?.href || ""; + if (!url) return res.status(404).json({ ok: false, error: "version-url-not-found" }); + } + + try { + const safe = await assertSafeRemoteUrl(url); + url = safe.toString(); + } catch { + return res.status(400).json({ ok: false, error: "invalid-url" }); + } + + let destRel = String(rawDestPath || "").trim(); + if (!destRel) destRel = "server.jar"; + destRel = destRel.replace(/^\/+/, ""); + if (destRel.includes("..") || destRel.includes("\\")) return res.status(400).json({ ok: false, error: "invalid-destPath" }); + const destFile = path.posix.basename(destRel); + if (!destFile || destFile === "." || destFile === "..") return res.status(400).json({ ok: false, error: "invalid-destPath" }); + + const applyResult = await applyRemoteAssetToServer({ + findServer, + isRemoteEntry, + findNodeByIdOrName, + buildNodeBaseUrl, + nodeUnderCloudflare, + nodeAuthHeadersFor, + httpRequestJson, + assertSafeRemoteUrl, + resolveRemoteFsContext, + nodeFsPost, + httpGetRaw, + remoteApplyProxyDownload: REMOTE_APPLY_PROXY_DOWNLOAD, + remoteApplyMaxBytes: REMOTE_APPLY_MAX_BYTES, + remoteApplyTimeoutMs: REMOTE_APPLY_TIMEOUT_MS, + remoteFetchMaxRedirects: REMOTE_FETCH_MAX_REDIRECTS, + }, { + serverName: bot, + entry, + url, + destPath: destRel, + }); + + if (!applyResult.ok) { + return res.status(applyResult.statusCode || 500).json(applyResult); + } + return res.json(applyResult); + } catch (e) { + console.error("versions/apply error", e); + return res.status(500).json({ ok: false, error: "server-error" }); + } +}); + +app.post("/api/servers/create", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "admin required" }); + + const { name: rawName, displayName: clientDisplayName, templateId, nodeId } = req.body || {}; + const name = sanitizeServerName(rawName); + if (!name) return res.status(400).json({ error: "invalid name" }); + + if (serverCreateLocks.has(name)) { + return res.status(429).json({ error: "action-in-progress", message: `Server "${name}" is already being created. Please choose a different name or wait.` }); + } + serverCreateLocks.add(name); + + try { + const displayName = sanitizeDisplayName(clientDisplayName || rawName) || name; + if (!templateId) return res.status(400).json({ error: "missing templateId" }); + + const template = findTemplateById(templateId); + if (!template) return res.status(400).json({ error: "unknown template" }); + const tpl = normalizeTemplateId(templateId); + + const targetNodeId = String(nodeId || "").trim(); + if (!targetNodeId || targetNodeId === "local") return res.status(400).json({ error: "nodeId required" }); + + const node = await findNodeByIdOrName(targetNodeId); + if (!node) return res.status(400).json({ error: "node not found" }); + + 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; + if (importUrl) { + if (!isValidArchiveUrl(importUrl)) { + return res.status(400).json({ error: "Invalid importUrl (must be http(s) and a supported archive extension)" }); + } + try { + await assertSafeRemoteUrl(importUrl); + } catch (e) { + return res.status(400).json({ error: `Unsafe importUrl: ${e.message}` }); + } + } + + const reqResources = req.body?.resources || {}; + const resources = {}; + const parsePositiveIntOrNull = (value) => { + if (value === null || value === undefined || String(value).trim() === "") return null; + const parsed = parseInt(value, 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : null; + }; + const parsePositiveFloatOrNull = (value) => { + if (value === null || value === undefined || String(value).trim() === "") return null; + const parsed = parseFloat(value); + return Number.isFinite(parsed) && parsed > 0 ? parsed : null; + }; + const effectiveNodeCapacity = await getEffectiveNodeCapacity(node); + const requestedRamMb = parsePositiveIntOrNull(reqResources.ramMb); + const requestedCpuCores = parsePositiveFloatOrNull(reqResources.cpuCores); + const requestedStorageMb = parsePositiveIntOrNull(reqResources.storageMb); + const requestedStorageGb = parsePositiveIntOrNull(reqResources.storageGb); + const effectiveDiskMb = effectiveNodeCapacity.diskGb > 0 ? Math.trunc(effectiveNodeCapacity.diskGb * 1024) : 0; + if (requestedRamMb != null) { + if (effectiveNodeCapacity.ramMb > 0 && requestedRamMb > effectiveNodeCapacity.ramMb) { + return res.status(400).json({ error: `RAM limit cannot exceed node maximum (${effectiveNodeCapacity.ramMb} MB).` }); + } + resources.ramMb = requestedRamMb; + } else if (effectiveNodeCapacity.ramMb > 0) { + resources.ramMb = effectiveNodeCapacity.ramMb; + } + if (requestedCpuCores != null) { + if (effectiveNodeCapacity.cpuCores > 0 && requestedCpuCores > effectiveNodeCapacity.cpuCores) { + return res.status(400).json({ error: `CPU cores cannot exceed node maximum (${effectiveNodeCapacity.cpuCores} cores).` }); + } + resources.cpuCores = requestedCpuCores; + } else if (effectiveNodeCapacity.cpuCores > 0) { + resources.cpuCores = effectiveNodeCapacity.cpuCores; + } + if (requestedStorageMb != null) { + if (effectiveDiskMb > 0 && requestedStorageMb > effectiveDiskMb) { + return res.status(400).json({ error: `Storage limit cannot exceed node maximum (${effectiveDiskMb} MB).` }); + } + resources.storageMb = requestedStorageMb; + } else if (requestedStorageGb != null) { + const requestedStorageFromGb = requestedStorageGb * 1024; + if (effectiveDiskMb > 0 && requestedStorageFromGb > effectiveDiskMb) { + return res.status(400).json({ error: `Storage limit cannot exceed node maximum (${effectiveDiskMb} MB).` }); + } + resources.storageMb = requestedStorageFromGb; + } else if (effectiveDiskMb > 0) { + resources.storageMb = effectiveDiskMb; + } + if (reqResources.swapMb != null) resources.swapMb = parseInt(reqResources.swapMb, 10); + if (reqResources.backupsMax != null) resources.backupsMax = parseInt(reqResources.backupsMax, 10) || 0; + if (reqResources.maxSchedules != null) resources.maxSchedules = parseInt(reqResources.maxSchedules, 10) || 0; + try { + Object.assign(resources, collectResourcePerformanceOptions(reqResources)); + Object.assign(resources, collectResourceAntiAbuseOptions(reqResources)); + } catch (e) { + return res.status(400).json({ error: e.message || "Invalid resource limits." }); + } + + 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) + : ""; + if (Object.prototype.hasOwnProperty.call(req.body || {}, "javaVersion") && tpl !== "minecraft") { + return res.status(400).json({ error: "Java version selection is only available for Minecraft templates." }); + } + if (Object.prototype.hasOwnProperty.call(req.body || {}, "javaVersion") && !requestedJavaVersion) { + return res.status(400).json({ error: "Unsupported Minecraft Java version." }); + } + if (tpl === "minecraft" && requestedJavaVersion) { + sanitizedDocker.image = DEFAULT_MINECRAFT_PROCESS_IMAGE; + sanitizedDocker.tag = minecraftJavaTag(requestedJavaVersion); + sanitizedDocker.javaVersion = requestedJavaVersion; + } + if (req.body?.startupCommand && String(req.body.startupCommand).trim()) { + return res.status(400).json({ error: "Raw Docker startup commands are no longer supported. Server containers are now created from structured template settings only." }); + } + const requestedCommand = normalizeLegacyRuntimeProcessCommandInput(templateId, req.body?.command); + const requestedCommandError = validateRuntimeProcessCommandInput(requestedCommand); + if (requestedCommandError) { + return res.status(400).json({ error: requestedCommandError }); + } + if (requestedCommand) { + sanitizedDocker.command = requestedCommand; + } + + let hostPortRaw = (req.body && (req.body.hostPort ?? req.body.port)) ?? null; + if (hostPortRaw != null && String(hostPortRaw).trim() !== "") { + const parsedHostPort = validatePort(hostPortRaw); + if (!parsedHostPort) { + return res.status(400).json({ error: "Invalid port. Choose a value between 1 and 65535." }); + } + hostPortRaw = parsedHostPort; + } else { + hostPortRaw = validatePort(template.defaultPort); + } + + 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.` }); + } + if (resolvedPort > 0) { + const conflict = await findServerUsingNodePort(node, resolvedPort, 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.`, + code: "port_in_use", + port: resolvedPort, + server: conflict.name || conflict.bot || null + }); + } + const livePort = await checkRemoteNodePortAvailability(node, resolvedPort); + 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}.`, + code: "port_in_use", + port: resolvedPort, + owner: livePort.owner || null, + reason: livePort.reason || null + }); + } + } + + const payload = { + name, + templateId, + mcFork, + mcVersion, + hostPort: hostPortRaw, + docker: sanitizedDocker, + autoStart: true, + asyncSetup: true, + importUrl: importUrl, + resources: Object.keys(resources).length > 0 ? resources : null + }; + if (tpl === "minecraft" && sanitizedDocker?.javaVersion) { + payload.javaVersion = sanitizedDocker.javaVersion; + } + const createResult = await createOnRemoteNode(node, payload); + + try { + const me = req.session.user; + const u = await findUserByEmail(me); + if (!(u && u.admin)) await addAccessForEmail(me, name); + } catch { } + + let savedPort = null; + if (hostPortRaw != null) { + savedPort = clampPort(hostPortRaw); + } else if (validatePort(template.defaultPort)) { + savedPort = clampPort(validatePort(template.defaultPort)); + } else if (tpl === "minecraft") { + savedPort = 25565; + } else if (tpl === "nodejs" || tpl === "discord-bot") { + savedPort = 3000; + } + + const serverEntry = { + name, + displayName, + template: templateId, + mcFork: tpl === "minecraft" ? mcFork : undefined, + mcVersion: tpl === "minecraft" ? mcVersion : undefined, + start: tpl === "minecraft" + ? "server.jar" + : (tpl === "nodejs" || tpl === "discord-bot" + ? "index.js" + : (tpl === "python" ? "main.py" : null)), + nodeId: node.uuid || node.id || node.name, + ip: node.address || null, + status: createResult?.asyncSetup + ? (String(createResult?.meta?.setupStatus || "").toLowerCase() === "failed" ? "error" : "installing") + : undefined, + setupStatus: createResult?.asyncSetup ? (createResult?.meta?.setupStatus || "queued") : undefined, + }; + if (savedPort != null) serverEntry.port = savedPort; + if (createResult?.meta?.setupMessage) serverEntry.setupMessage = createResult.meta.setupMessage; + if (Object.keys(resources).length > 0) serverEntry.resources = resources; + if (sanitizedDocker) serverEntry.docker = sanitizedDocker; + if (sanitizedDocker) { + serverEntry.runtime = { + image: sanitizedDocker.image, + tag: sanitizedDocker.tag, + command: sanitizedDocker.command, + volumes: sanitizedDocker.volumes, + workdir: sanitizedDocker.workdir, + env: sanitizedDocker.env, + ports: sanitizedDocker.ports, + javaVersion: sanitizedDocker.javaVersion, + adpanelStartup: sanitizedDocker.adpanelStartup, + install: sanitizedDocker.install, + }; + } + + await upsertServerIndexEntry(serverEntry); + + return res.json({ ok: true, name, displayName }); + } catch (e) { + console.error("[/api/servers/create] failed:", e); + return res.status(500).json({ + error: "create failed", + detail: String(e && e.message ? e.message : "").trim() || null + }); + } finally { + serverCreateLocks.delete(name); + } +}); + +const ALLOWED_ARCHIVE_EXTENSIONS = ['.zip', '.rar', '.7z', '.tar.gz', '.tgz', '.tar.bz2', '.tbz2']; + +function isValidArchiveUrl(url) { + if (!url) return false; + try { + const parsedUrl = new URL(url); + if (!['http:', 'https:'].includes(parsedUrl.protocol)) return false; + const pathname = parsedUrl.pathname.toLowerCase(); + return ALLOWED_ARCHIVE_EXTENSIONS.some(ext => pathname.endsWith(ext)); + } catch { + return false; + } +} + +app.delete("/api/settings/servers/:name", 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); + if (!result.ok) { + return res.status(result.statusCode || 500).json({ error: result.error || "delete failed" }); + } + return res.json(result); +}); + +app.post("/api/settings/servers/:name/template", async (req, res) => { + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + let nameParam = req.params.name || ""; + try { nameParam = decodeURIComponent(nameParam); } catch { } + const name = String(nameParam).trim(); + if (!name) return res.status(400).json({ error: "missing name" }); + + const rawTemplate = (req.body && (req.body.templateId || req.body.template)) || ""; + const templateId = normalizeTemplateId(rawTemplate); + if (!templateId) return res.status(400).json({ error: "invalid template id" }); + + const template = findTemplateById(templateId); + if (!template) return res.status(404).json({ error: "template not found" }); + + const list = await loadServersIndex(); + const idx = list.findIndex(e => e && e.name === name); + if (idx < 0) return res.status(404).json({ error: "server not found" }); + + const entry = list[idx]; + const technicalName = getTechnicalServerName(entry, name); + + if (isRemoteEntry(entry)) { + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) return res.status(400).json({ error: "node not found for server" }); + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return res.status(400).json({ error: "invalid node address" }); + + const headers = nodeAuthHeadersFor(node, true); + + let hostPort = entry.port || template.defaultPort || 8080; + const normalizedTemplateDocker = normalizeTemplateDockerForRuntime( + templateId, + template.docker, + defaultStartFileForTemplate(templateId) + ); + + const reinstallPayload = { + templateId, + docker: normalizedTemplateDocker || null, + hostPort, + }; + + if (!signPanelAdminReinstallHeaders(headers, node, technicalName, templateId)) { + return res.status(500).json({ error: "failed to sign reinstall request" }); + } + + console.log(`[template-change] Reinstalling server ${name} on node ${entry.nodeId} with template ${templateId}`); + + const r = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/reinstall`, + "POST", + headers, + reinstallPayload, + 3_600_000 + ); + + 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})`; + console.error(`[template-change] Reinstall failed for ${name}: ${msg}`); + return res.status(502).json({ error: msg }); + } + + console.log(`[template-change] Reinstall successful for ${name}`); + } + + const updatedEntry = Object.assign({}, entry, { + template: String(template.id || templateId), + }); + const normalizedTemplateDocker = normalizeTemplateDockerForRuntime( + templateId, + template.docker, + defaultStartFileForTemplate(templateId) + ); + if (normalizedTemplateDocker) { + updatedEntry.docker = normalizedTemplateDocker; + updatedEntry.runtime = { + image: normalizedTemplateDocker.image, + tag: normalizedTemplateDocker.tag, + command: normalizedTemplateDocker.command, + volumes: normalizedTemplateDocker.volumes, + workdir: normalizedTemplateDocker.workdir, + env: normalizedTemplateDocker.env, + ports: normalizedTemplateDocker.ports, + restart: normalizedTemplateDocker.restart, + console: normalizedTemplateDocker.console, + adpanelStartup: normalizedTemplateDocker.adpanelStartup, + install: normalizedTemplateDocker.install, + }; + } + delete updatedEntry.startupCommand; + if (updatedEntry.runtime && typeof updatedEntry.runtime === "object") delete updatedEntry.runtime.startupCommand; + if (updatedEntry.docker && typeof updatedEntry.docker === "object") delete updatedEntry.docker.startupCommand; + if (template.defaultPort) { + updatedEntry.port = template.defaultPort; + } + const tpl = normalizeTemplateId(templateId); + if (tpl === 'minecraft') { + updatedEntry.start = 'server.jar'; + } else if (tpl === 'nodejs' || tpl === 'discord-bot') { + updatedEntry.start = 'index.js'; + } else if (tpl === 'python') { + updatedEntry.start = 'main.py'; + } else { + updatedEntry.start = null; + } + + list[idx] = updatedEntry; + if (!(await saveServersIndex(list))) return res.status(500).json({ error: "failed to save servers" }); + + return res.json({ ok: true, server: list[idx] }); +}); + +app.post("/api/servers/:name/reinstall", async (req, res) => { + try { + if (!(await isAuthenticated(req))) 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 email = req.session.user; + const isAdminUser = await isAdmin(req); + + if (!isAdminUser && !(await userHasAccessToServer(email, name))) { + return res.status(403).json({ error: "no access to server" }); + } + + const perms = await getEffectivePermsForUserOnServer(email, name); + if (!perms.server_reinstall && !isAdminUser) { + return res.status(403).json({ error: "you do not have permission to reinstall this server" }); + } + + const entry = await findServer(name); + if (!entry) return res.status(404).json({ error: "server not found" }); + const technicalName = getTechnicalServerName(entry, name); + + if (!isRemoteEntry(entry)) return res.status(400).json({ error: "server is not on a remote node" }); + + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) return res.status(400).json({ error: "node not found for server" }); + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return res.status(400).json({ error: "invalid node address" }); + + const headers = nodeAuthHeadersFor(node, true); + + const templateId = normalizeTemplateId(entry.template) || "custom"; + const reinstallPayload = { + templateId, + }; + + 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( + `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/reinstall`, + "POST", + headers, + reinstallPayload, + 3_600_000 + ); + + 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})`; + console.error(`[reinstall] Failed for ${name}: ${msg}`); + return res.status(502).json({ error: msg }); + } + + console.log(`[reinstall] Server ${name} reinstalled successfully`); + const list = await loadServersIndex(); + const idx = list.findIndex(e => e && e.name === name); + if (idx >= 0) { + const updatedEntry = Object.assign({}, list[idx]); + delete updatedEntry.startupCommand; + if (updatedEntry.runtime && typeof updatedEntry.runtime === "object") { + updatedEntry.runtime = { ...updatedEntry.runtime }; + delete updatedEntry.runtime.startupCommand; + } + if (updatedEntry.docker && typeof updatedEntry.docker === "object") { + updatedEntry.docker = { ...updatedEntry.docker }; + delete updatedEntry.docker.startupCommand; + } + list[idx] = updatedEntry; + await saveServersIndex(list); + } + try { + if (typeof recordActivity === "function") { + await recordActivity(name, email, "reinstall", `Server reinstalled by ${email}`); + } + } catch (actErr) { + console.warn("[reinstall] Failed to record activity:", actErr); + } + + return res.json({ ok: true, name, template: templateId }); + } catch (err) { + console.error("[reinstall] Error:", err); + return res.status(500).json({ error: "internal error during reinstall" }); + } +}); + +app.patch("/api/settings/servers/:name/resources", async (req, res) => { + if (!(await isAuthenticated(req))) 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); + if (!isAdminUser) { + const hasAccess = await userHasAccessToServer(me, name); + if (!hasAccess) return res.status(403).json({ error: "not authorized" }); + } + + const serverEntry = await findServer(name); + 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); + 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)); + if (!baseUrl) return res.status(400).json({ error: "invalid node address" }); + + const body = req.body || {}; + const { resources, startupCommand, mainPort, command, javaVersion } = body; + if (startupCommand != null && String(startupCommand).trim()) { + return res.status(400).json({ error: "Editing raw Docker startup commands is no longer supported. Update ports/resources only." }); + } + const templateForCommand = normalizeTemplateId(serverEntry?.template || serverEntry?.type); + const templateInfoForCommand = findTemplateById(templateForCommand); + const isMinecraftServerForResources = isMinecraftTemplateLike(templateForCommand, templateInfoForCommand?.name || ""); + const javaVersionProvided = Object.prototype.hasOwnProperty.call(body, "javaVersion"); + const cleanJavaVersion = javaVersionProvided ? normalizeMinecraftJavaVersionInput(javaVersion) : ""; + if (javaVersionProvided) { + if (!isMinecraftServerForResources) { + return res.status(400).json({ error: "Java version selection is only available for Minecraft templates." }); + } + if (!cleanJavaVersion) { + return res.status(400).json({ error: "Unsupported Minecraft Java version." }); + } + } + const commandProvided = Object.prototype.hasOwnProperty.call(body, "command"); + const cleanCommand = commandProvided + ? normalizeLegacyRuntimeProcessCommandInput(templateForCommand, command) + : ""; + if (commandProvided) { + const cleanCommandError = validateRuntimeProcessCommandInput(cleanCommand); + if (cleanCommandError) { + return res.status(400).json({ error: cleanCommandError }); + } + } + const cleanedResourcePorts = Array.isArray(resources?.ports) ? validatePortListInput(resources.ports) : null; + if (Array.isArray(resources?.ports) && cleanedResourcePorts === null) { + return res.status(400).json({ error: "All server ports must be integers between 1 and 65535." }); + } + if (cleanedResourcePorts) { + for (const port of cleanedResourcePorts) { + if (!isPortInNodeAllocation(node, port)) { + return res.status(400).json({ error: `Port ${port} is not in this node's allocated ports.` }); + } + } + } + + const parsePositiveIntOrNull = (value) => { + if (value === null || value === undefined || String(value).trim() === "") return null; + const parsed = parseInt(value, 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : null; + }; + const parsePositiveFloatOrNull = (value) => { + if (value === null || value === undefined || String(value).trim() === "") return null; + const parsed = parseFloat(value); + return Number.isFinite(parsed) && parsed > 0 ? parsed : null; + }; + const effectiveNodeCapacity = await getEffectiveNodeCapacity(node); + const requestedRamMb = resources ? parsePositiveIntOrNull(resources.ramMb) : null; + const requestedCpuCores = resources ? parsePositiveFloatOrNull(resources.cpuCores) : null; + const requestedStorageMb = resources ? parsePositiveIntOrNull(resources.storageMb) : null; + const requestedStorageGb = resources ? parsePositiveIntOrNull(resources.storageGb) : null; + const effectiveDiskMb = effectiveNodeCapacity.diskGb > 0 ? Math.trunc(effectiveNodeCapacity.diskGb * 1024) : 0; + if (requestedRamMb != null && effectiveNodeCapacity.ramMb > 0 && requestedRamMb > effectiveNodeCapacity.ramMb) { + return res.status(400).json({ error: `RAM limit cannot exceed node maximum (${effectiveNodeCapacity.ramMb} MB).` }); + } + if (requestedCpuCores != null && effectiveNodeCapacity.cpuCores > 0 && requestedCpuCores > effectiveNodeCapacity.cpuCores) { + return res.status(400).json({ error: `CPU cores cannot exceed node maximum (${effectiveNodeCapacity.cpuCores} cores).` }); + } + if (requestedStorageMb != null && effectiveDiskMb > 0 && requestedStorageMb > effectiveDiskMb) { + return res.status(400).json({ error: `Storage limit cannot exceed node maximum (${effectiveDiskMb} MB).` }); + } + if (requestedStorageGb != null && effectiveDiskMb > 0 && requestedStorageGb * 1024 > effectiveDiskMb) { + return res.status(400).json({ error: `Storage limit cannot exceed node maximum (${effectiveDiskMb} MB).` }); + } + let requestedPerformanceOptions = {}; + let requestedAntiAbuseOptions = {}; + try { + requestedPerformanceOptions = resources ? collectResourcePerformanceOptions(resources) : {}; + requestedAntiAbuseOptions = resources ? collectResourceAntiAbuseOptions(resources) : {}; + } catch (e) { + return res.status(400).json({ error: e.message || "Invalid resource limits." }); + } + + const payload = {}; + if (resources) { + payload.resources = {}; + if (requestedRamMb != null) payload.resources.ramMb = requestedRamMb; + if (requestedCpuCores != null) payload.resources.cpuCores = requestedCpuCores; + if (requestedStorageMb != null) payload.resources.storageMb = requestedStorageMb; + else if (requestedStorageGb != null) payload.resources.storageMb = requestedStorageGb * 1024; + if (resources.swapMb != null) payload.resources.swapMb = parseInt(resources.swapMb, 10); + if (resources.backupsMax != null) payload.resources.backupsMax = parseInt(resources.backupsMax, 10) || 0; + if (resources.maxSchedules != null) payload.resources.maxSchedules = parseInt(resources.maxSchedules, 10) || 0; + Object.assign(payload.resources, requestedPerformanceOptions); + Object.assign(payload.resources, requestedAntiAbuseOptions); + if (cleanedResourcePorts) payload.resources.ports = cleanedResourcePorts; + } + if (commandProvided) payload.command = cleanCommand; + if (javaVersionProvided) payload.javaVersion = cleanJavaVersion; + let newMainPort = null; + if (mainPort != null) { + const mp = validatePort(mainPort); + if (!mp) return res.status(400).json({ error: "Main port must be an integer between 1 and 65535." }); + if (!isPortInNodeAllocation(node, mp)) { + return res.status(400).json({ error: `Port ${mp} is not in this node's allocated ports.` }); + } + if (cleanedResourcePorts && cleanedResourcePorts.includes(mp)) { + return res.status(400).json({ error: `Port ${mp} cannot be both the main port and an additional port.` }); + } + newMainPort = mp; + payload.mainPort = mp; + } + + try { + const headers = nodeAuthHeadersFor(node, true); + const r = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(name)}/resources`, + "PATCH", + headers, + payload, + 30_000 + ); + + 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})`; + return res.status(502).json({ error: msg }); + } + + const list = await loadServersIndex(); + const idx = list.findIndex(e => e && e.name === name); + if (idx >= 0) { + if (!list[idx].resources) list[idx].resources = {}; + if (resources) { + if (resources.ramMb != null) { + const n = parseInt(resources.ramMb, 10); + if (!Number.isNaN(n)) list[idx].resources.ramMb = n; + } + if (resources.cpuCores != null) { + const n = parseFloat(resources.cpuCores); + if (!Number.isNaN(n)) list[idx].resources.cpuCores = n; + } + if (resources.storageMb != null) { + const n = parseInt(resources.storageMb, 10); + if (!Number.isNaN(n)) list[idx].resources.storageMb = n; + delete list[idx].resources.storageGb; + } else if (resources.storageGb != null) { + const n = parseInt(resources.storageGb, 10); + if (!Number.isNaN(n)) list[idx].resources.storageMb = n * 1024; + delete list[idx].resources.storageGb; + } + if (resources.swapMb != null) list[idx].resources.swapMb = parseInt(resources.swapMb, 10); + if (resources.backupsMax != null) list[idx].resources.backupsMax = parseInt(resources.backupsMax, 10) || 0; + if (resources.maxSchedules != null) list[idx].resources.maxSchedules = parseInt(resources.maxSchedules, 10) || 0; + Object.assign(list[idx].resources, requestedPerformanceOptions); + Object.assign(list[idx].resources, requestedAntiAbuseOptions); + if (requestedAntiAbuseOptions.networkInboundLimitMb === 0) delete list[idx].resources.networkInboundLimitMb; + if (requestedAntiAbuseOptions.networkOutboundLimitMb === 0) delete list[idx].resources.networkOutboundLimitMb; + if (requestedAntiAbuseOptions.networkResetMinutes === 0) delete list[idx].resources.networkResetMinutes; + if (cleanedResourcePorts) list[idx].resources.ports = cleanedResourcePorts; + } + if (commandProvided) { + if (!list[idx].runtime || typeof list[idx].runtime !== "object") list[idx].runtime = {}; + if (!list[idx].docker || typeof list[idx].docker !== "object") list[idx].docker = {}; + list[idx].runtime.command = cleanCommand; + list[idx].docker.command = cleanCommand; + } + if (javaVersionProvided) { + if (!list[idx].runtime || typeof list[idx].runtime !== "object") list[idx].runtime = {}; + if (!list[idx].docker || typeof list[idx].docker !== "object") list[idx].docker = {}; + const javaTag = minecraftJavaTag(cleanJavaVersion); + list[idx].runtime.image = DEFAULT_MINECRAFT_PROCESS_IMAGE; + list[idx].runtime.tag = javaTag; + list[idx].runtime.javaVersion = cleanJavaVersion; + list[idx].docker.image = DEFAULT_MINECRAFT_PROCESS_IMAGE; + list[idx].docker.tag = javaTag; + list[idx].docker.javaVersion = cleanJavaVersion; + } + if (newMainPort != null) { + list[idx].port = newMainPort; + } + await saveServersIndex(list); + } + + try { + await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(name)}/stop`, "POST", headers, null, 30_000).catch(() => { }); + const effectivePort = newMainPort != null ? newMainPort : ((serverEntry && serverEntry.port != null) ? Number(serverEntry.port) : null); + const startPayload = (effectivePort != null && Number.isFinite(effectivePort)) ? { hostPort: effectivePort } : {}; + const rr = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(name)}/start`, "POST", headers, startPayload, 240_000); + if (rr.status !== 200 || !(rr.json && (rr.json.ok === true || rr.json.ok === undefined))) { + const msg = (rr.json && (rr.json.error || rr.json.detail)) ? (rr.json.error || rr.json.detail) : `remote start failed (${rr.status})`; + return res.status(502).json({ error: msg }); + } + } catch (e) { + return res.status(502).json({ error: "resources updated but restart failed", detail: e && e.message }); + } + + return res.json({ ok: true, message: "Resources updated" }); + } catch (e) { + console.error("[/api/settings/servers/:name/resources] failed:", e); + return res.status(500).json({ error: "failed to update resources" }); + } +}); + +app.get("/api/settings/servers/:name/resources", async (req, res) => { + if (!(await isAuthenticated(req))) 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); + if (!isAdminUser) { + const hasAccess = await userHasAccessToServer(me, name); + if (!hasAccess) return res.status(403).json({ error: "not authorized" }); + } + + const serverEntry = await findServer(name); + 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); + 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)); + if (!baseUrl) return res.status(400).json({ error: "invalid node address" }); + + try { + const headers = nodeAuthHeadersFor(node, true); + const r = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(name)}/resources`, + "GET", + headers, + null, + 10_000 + ); + + if (r.status !== 200) { + const msg = (r.json && r.json.error) ? r.json.error : `failed to get resources (${r.status})`; + return res.status(502).json({ error: msg }); + } + + const result = r.json || { ok: true, resources: {} }; + const nodeResources = (result.resources && typeof result.resources === "object") ? result.resources : {}; + const indexedResources = (serverEntry.resources && typeof serverEntry.resources === "object") ? serverEntry.resources : {}; + result.resources = { ...indexedResources, ...nodeResources }; + + 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; + } + if (typeof result.command === "string") { + result.command = normalizeLegacyRuntimeProcessCommandInput(resultTemplateId, result.command); + } else { + result.command = normalizeLegacyRuntimeProcessCommandInput(resultTemplateId, + serverEntry?.runtime?.command || + serverEntry?.docker?.command || + defaultRuntimeCommandForTemplate(serverEntry?.template, serverEntry?.docker, serverEntry?.start) + ); + } + if (typeof result.configuredCommand === "string") { + result.configuredCommand = normalizeLegacyRuntimeProcessCommandInput(resultTemplateId, result.configuredCommand); + } + if (typeof result.effectiveCommand === "string") { + result.effectiveCommand = normalizeLegacyRuntimeProcessCommandInput(resultTemplateId, result.effectiveCommand); + } else { + result.effectiveCommand = result.command; + } + if (typeof result.imageDefaultCommand === "string") { + result.imageDefaultCommand = normalizeLegacyRuntimeProcessCommandInput(resultTemplateId, result.imageDefaultCommand); + } + if (!result.command && result.effectiveCommand) { + result.command = result.effectiveCommand; + } + if (!result.hostPort && serverEntry.port != null) { + result.hostPort = Number(serverEntry.port); + } + if (isMinecraftTemplateLike(resultTemplateId, result.templateName || "")) { + const runtimeForJava = (serverEntry.runtime && typeof serverEntry.runtime === "object") + ? serverEntry.runtime + : ((serverEntry.docker && typeof serverEntry.docker === "object") ? serverEntry.docker : {}); + const selectedJavaVersion = + normalizeMinecraftJavaVersionInput(result.javaVersion) || + normalizeMinecraftJavaVersionInput(runtimeForJava.javaVersion) || + minecraftJavaVersionFromTag(runtimeForJava.tag) || + minecraftJavaVersionFromTag(String(result.imageRef || "").split(":").pop()) || + minecraftJavaVersionFromTag(DEFAULT_MINECRAFT_PROCESS_TAG); + result.minecraftJava = await minecraftJavaOptionsPayload(selectedJavaVersion); + result.javaVersion = result.minecraftJava.selected; + } + return res.json(result); + } catch (e) { + console.error("[/api/settings/servers/:name/resources GET] failed:", e); + return res.status(500).json({ error: "failed to get resources" }); + } +}); + +app.get("/api/settings/servers/:name/port-forwards", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "admin access required" }); + + 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 serverEntry = await findServer(name); + 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); + 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)); + if (!baseUrl) return res.status(400).json({ error: "invalid node address" }); + + try { + const headers = nodeAuthHeadersFor(node, true); + const r = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(name)}/port-forwards`, + "GET", headers, null, 10_000 + ); + if (r.status !== 200) { + const msg = (r.json && r.json.error) ? r.json.error : `failed to get port forwards (${r.status})`; + return res.status(502).json({ error: msg }); + } + const result = r.json || { ok: true, portForwards: [] }; + result.nodeAllocation = node.ports || null; + result.mainPort = serverEntry.port ? Number(serverEntry.port) : null; + if (!result.allocatedPorts) { + result.allocatedPorts = []; + } + return res.json(result); + } catch (e) { + console.error("[/api/settings/servers/:name/port-forwards GET] failed:", e); + return res.status(500).json({ error: "failed to get port forwards" }); + } +}); + +app.patch("/api/settings/servers/:name/port-forwards", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "admin access required" }); + + 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 serverEntry = await findServer(name); + 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); + 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)); + if (!baseUrl) return res.status(400).json({ error: "invalid node address" }); + + const { portForwards } = req.body || {}; + if (!Array.isArray(portForwards)) { + return res.status(400).json({ error: "portForwards must be an array" }); + } + + const mainPort = serverEntry.port ? Number(serverEntry.port) : 0; + const validated = []; + for (const rule of portForwards) { + const pub = validatePort(rule.publicPort); + const internal = validatePort(rule.internalPort); + if (!pub) { + return res.status(400).json({ error: `Invalid public port: ${rule.publicPort}` }); + } + if (!internal) { + return res.status(400).json({ error: `Invalid internal port: ${rule.internalPort}` }); + } + if (!isPortInNodeAllocation(node, pub)) { + return res.status(400).json({ error: `Public port ${pub} is not in this node's allocated ports.` }); + } + if (validated.some(v => v.publicPort === pub)) { + return res.status(400).json({ error: `Duplicate public port: ${pub}` }); + } + validated.push({ publicPort: pub, internalPort: internal }); + } + + try { + const headers = nodeAuthHeadersFor(node, true); + const r = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(name)}/port-forwards`, + "PATCH", headers, { portForwards: validated }, 30_000 + ); + if (r.status !== 200 || !(r.json && r.json.ok)) { + const msg = (r.json && r.json.error) ? r.json.error : `failed to update port forwards (${r.status})`; + return res.status(502).json({ error: msg }); + } + + try { + await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(name)}/stop`, "POST", headers, null, 30_000).catch(() => { }); + await new Promise(resolve => setTimeout(resolve, 3000)); + const startPayload = mainPort > 0 ? { hostPort: mainPort } : {}; + const rr = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(name)}/start`, + "POST", headers, startPayload, 240_000 + ); + if (rr.status !== 200 || !(rr.json && (rr.json.ok === true || rr.json.ok === undefined))) { + const msg = (rr.json && (rr.json.error || rr.json.detail)) ? (rr.json.error || rr.json.detail) : `remote start failed (${rr.status})`; + return res.status(502).json({ error: msg }); + } + } catch (e) { + return res.status(502).json({ error: "port forwards updated but restart failed", detail: e && e.message }); + } + + return res.json({ ok: true, message: "Port forwards updated" }); + } catch (e) { + console.error("[/api/settings/servers/:name/port-forwards PATCH] failed:", e); + return res.status(500).json({ error: "failed to update port forwards" }); + } +}); + +app.get("/api/settings/servers/:name/transfer", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + 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 job = getTransferJob(name) || (await getTransferJobFromRedis(name)); + return res.json({ ok: true, job: job || null }); +}); + +app.post("/api/settings/servers/:name/transfer", async (req, res) => { + if (!(await isAuthenticated(req))) return res.status(401).json({ error: "not authenticated" }); + if (!(await isAdmin(req))) return res.status(403).json({ error: "not authorized" }); + + 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 existingJob = getTransferJob(name) || (await getTransferJobFromRedis(name)); + if (existingJob && !existingJob.finishedAt) { + return res.json({ ok: true, job: existingJob, alreadyRunning: true }); + } + + const serverEntry = await findServer(name); + if (!serverEntry) return res.status(404).json({ error: "server not found" }); + if (!isRemoteEntry(serverEntry)) return res.status(400).json({ error: "server-not-on-node" }); + + const sourceNode = await findNodeByIdOrName(serverEntry.nodeId); + if (!sourceNode) return res.status(400).json({ error: "source node not found" }); + + const targetNodeId = String(req.body?.targetNodeId || req.body?.nodeId || "").trim(); + if (!targetNodeId) return res.status(400).json({ error: "targetNodeId required" }); + + const destNode = await findNodeByIdOrName(targetNodeId); + if (!destNode) return res.status(400).json({ error: "destination node not found" }); + + const srcId = String(sourceNode.uuid || sourceNode.id || sourceNode.name || ""); + const dstId = String(destNode.uuid || destNode.id || destNode.name || ""); + if (srcId && dstId && srcId === dstId) return res.status(400).json({ error: "cannot transfer to the same node" }); + + const prevStatus = serverEntry.status ?? null; + + setTransferJob(name, { + status: "preparing", + percent: 0, + message: "Preparing transfer", + error: null, + finishedAt: null, + sourceNodeId: srcId, + destNodeId: dstId, + }); + + try { + await db.query("UPDATE servers SET status = ? WHERE name = ?", ["transferring", serverEntry.name]); + } catch { } + + const job = getTransferJob(name); + res.json({ ok: true, job }); + + (async () => { + let phase = "preparing"; + let dbCommittedToNewNode = false; + try { + phase = "stopping"; + setTransferJob(name, { status: "stopping", percent: 2, message: "Stopping server" }); + + try { + const baseUrl = buildNodeBaseUrl(sourceNode.address, sourceNode.api_port || 8080, sourceNode.ssl_enabled, nodeUnderCloudflare(sourceNode)); + if (baseUrl) { + const headers = nodeAuthHeadersFor(sourceNode, true); + const resources = (serverEntry.resources && typeof serverEntry.resources === "object") ? serverEntry.resources : null; + if (resources && Object.keys(resources).length > 0) { + await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(serverEntry.name)}/resources`, + "PATCH", + headers, + { resources }, + 30_000 + ).catch(() => { }); + } + } + } catch { } + + { + const srcBase = buildNodeBaseUrl(sourceNode.address, sourceNode.api_port || 8080, sourceNode.ssl_enabled, nodeUnderCloudflare(sourceNode)); + if (srcBase) { + const headers = nodeAuthHeadersFor(sourceNode, true); + try { + const stopRes = await httpRequestJson( + `${srcBase}/v1/servers/${encodeURIComponent(serverEntry.name)}/stop?wait=true`, + "POST", headers, null, 60_000 + ); + if (stopRes.status === 200 && stopRes.json && stopRes.json.stopped) { + } else { + await stopServerOnNode(sourceNode, serverEntry.name); + } + } catch { + await stopServerOnNode(sourceNode, serverEntry.name); + } + } else { + await stopServerOnNode(sourceNode, serverEntry.name); + } + } + + setTransferJob(name, { status: "stopping", percent: 3, message: "Waiting for server to fully stop" }); + const stopped = await waitForServerStopped(sourceNode, serverEntry.name, { timeoutMs: 45_000, intervalMs: 2000 }); + if (!stopped) { + console.warn("[transfer] Server did not confirm stopped within timeout, proceeding anyway", { server: name }); + } + + let sourceMeta = null; + try { + const srcBase = buildNodeBaseUrl(sourceNode.address, sourceNode.api_port || 8080, sourceNode.ssl_enabled, nodeUnderCloudflare(sourceNode)); + if (srcBase) { + const srcHeaders = nodeAuthHeadersFor(sourceNode, true); + const infoRes = await httpRequestJson( + `${srcBase}/v1/servers/${encodeURIComponent(serverEntry.name)}`, + "GET", + srcHeaders, + null, + 30_000 + ); + if (infoRes.status === 200 && infoRes.json && infoRes.json.meta) { + sourceMeta = infoRes.json.meta; + } + } + } catch { } + + phase = "transferring"; + setTransferJob(name, { status: "transferring", percent: 5, message: "Transferring files" }); + + let extractTick = null; + let uploadFinished = false; + try { + await streamExportToImport({ + sourceNode, + destNode, + serverName: serverEntry.name, + onProgress: ({ percent }) => { + if (percent == null) return; + const p = Math.max(0, Math.min(100, percent)); + if (p >= 100) { + setTransferJob(name, { status: "finalizing", percent: 91, message: "Finalizing transfer (extracting)" }); + if (!uploadFinished) { + uploadFinished = true; + let cur = 91; + extractTick = setInterval(() => { + try { + const j = getTransferJob(name); + if (j && j.finishedAt) { + if (extractTick) { + clearInterval(extractTick); + extractTick = null; + } + return; + } + cur = Math.min(94, cur + 1); + setTransferJob(name, { status: "finalizing", percent: cur, message: "Finalizing transfer (extracting)" }); + if (cur >= 94 && extractTick) { + clearInterval(extractTick); + extractTick = null; + } + } catch { } + }, 5000); + } + return; + } + const mapped = 5 + Math.floor((p / 100) * 85); + const pct = Math.max(5, Math.min(90, mapped)); + setTransferJob(name, { status: "transferring", percent: pct, message: "Transferring files" }); + } + }); + } finally { + if (extractTick) { + try { clearInterval(extractTick); } catch { } + extractTick = null; + } + } + + phase = "finalizing"; + setTransferJob(name, { status: "finalizing", percent: 93, message: "Finalizing transfer (extracting)" }); + + phase = "resources"; + setTransferJob(name, { status: "finalizing", percent: 94, message: "Applying resources on destination node" }); + { + const baseUrl = buildNodeBaseUrl(destNode.address, destNode.api_port || 8080, destNode.ssl_enabled, nodeUnderCloudflare(destNode)); + if (!baseUrl) throw new Error("invalid destination node address"); + const headers = nodeAuthHeadersFor(destNode, true); + const eff = computeTransferEffectiveResources(serverEntry.resources, sourceNode, destNode); + + if (sourceMeta) { + const srcMetaRes = (sourceMeta.resources && typeof sourceMeta.resources === "object") ? sourceMeta.resources : null; + if (srcMetaRes && Array.isArray(srcMetaRes.ports) && srcMetaRes.ports.length > 0 && !Array.isArray(eff.ports)) { + eff.ports = srcMetaRes.ports.map(p => Number(p)).filter(p => p > 0); + } + } + + const patchPayload = { resources: eff }; + + const r = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(serverEntry.name)}/resources`, + "PATCH", + headers, + patchPayload, + 30_000 + ); + 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 apply resources (${r.status})`; + throw new Error(msg); + } + } + + phase = "starting"; + setTransferJob(name, { status: "starting", percent: 95, message: "Starting on new node" }); + const transferHostPort = serverEntry.port != null ? serverEntry.port + : (sourceMeta && sourceMeta.hostPort != null) ? Number(sourceMeta.hostPort) + : null; + await startServerOnNode(destNode, serverEntry.name, transferHostPort); + + setTransferJob(name, { status: "starting", percent: 95, message: "Waiting for server to be ready on new node" }); + const ready = await waitForServerReady(destNode, serverEntry.name, { timeoutMs: 30_000, intervalMs: 2000 }); + if (!ready) { + console.warn("[transfer] Server not confirmed ready on destination within timeout, proceeding with DB update", { server: name }); + } + + phase = "db-update"; + setTransferJob(name, { status: "finalizing", percent: 96, message: "Updating database" }); + const newNodeId = destNode.uuid || destNode.id || destNode.name; + await db.query( + "UPDATE servers SET node_id = ?, ip = ?, status = ? WHERE name = ?", + [newNodeId, destNode.address || null, prevStatus || "stopped", serverEntry.name] + ); + dbCommittedToNewNode = true; + + phase = "cleanup"; + setTransferJob(name, { status: "cleanup", percent: 97, message: "Cleaning up old node" }); + try { + await deleteServerOnNode(sourceNode, serverEntry.name, { filesOnly: true }); + } catch (cleanupErr) { + console.warn("[transfer] Source cleanup failed (non-fatal):", cleanupErr?.message || cleanupErr); + } + + setTransferJob(name, { status: "done", percent: 100, message: "Transfer complete", finishedAt: Date.now(), error: null }); + cleanupTransferJobLater(name); + } catch (err) { + const msg = err?.message || String(err); + const full = `phase=${phase}: ${msg}`; + console.error("[transfer] failed", { server: name, phase, error: msg }); + const prev = getTransferJob(name); + const pct = prev && typeof prev.percent === "number" ? prev.percent : 0; + setTransferJob(name, { status: "error", percent: pct, message: full, error: full, finishedAt: Date.now() }); + cleanupTransferJobLater(name); + + if (dbCommittedToNewNode) { + console.warn("[transfer] Error occurred after DB commit to destination. Server remains on new node.", { server: name, phase }); + } else { + try { + await db.query("UPDATE servers SET status = ? WHERE name = ?", [prevStatus || "stopped", serverEntry.name]); + } catch { } + try { + await startServerOnNode(sourceNode, serverEntry.name, serverEntry.port); + } catch { } + try { + await deleteServerOnNode(destNode, serverEntry.name); + } catch { } + } + } + })(); +}); + +function getSshTerminalWsTarget(req) { + const origin = getSshTerminalOrigin({ + ...req, + secure: isRequestSecure(req), + headers: req.headers, + get: req.get ? req.get.bind(req) : (name) => req.headers?.[String(name || "").toLowerCase()], + }); + const incoming = new URL(req.url || "", "http://adpanel.local"); + const target = new URL("/ws", origin); + target.search = incoming.search || ""; + return target; +} + +function proxySshTerminalUpgrade(req, socket, head) { + let target; + try { + target = getSshTerminalWsTarget(req); + } catch { + try { + socket.write("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); + } catch { } + socket.destroy(); + return; + } + + const isTls = target.protocol === "https:"; + const requester = isTls ? https : httpMod; + const headers = { ...req.headers }; + headers.host = target.host; + // Upstream websocket server validates Origin against Host. Preserve browser origin + // at the panel edge, but forward an upstream-matching Origin for the proxy hop. + headers.origin = `${target.protocol}//${target.host}`; + + const proxyReq = requester.request({ + protocol: target.protocol, + hostname: target.hostname, + port: target.port || (isTls ? 443 : 80), + method: "GET", + path: `${target.pathname}${target.search}`, + headers, + }); + + proxyReq.on("upgrade", (proxyRes, proxySocket, proxyHead) => { + try { + const lines = [`HTTP/1.1 ${proxyRes.statusCode || 101} ${proxyRes.statusMessage || "Switching Protocols"}`]; + for (const [k, v] of Object.entries(proxyRes.headers || {})) { + if (Array.isArray(v)) { + for (const one of v) lines.push(`${k}: ${one}`); + } else if (v !== undefined) { + lines.push(`${k}: ${v}`); + } + } + socket.write(`${lines.join("\r\n")}\r\n\r\n`); + if (proxyHead && proxyHead.length) socket.write(proxyHead); + if (head && head.length) proxySocket.write(head); + socket.pipe(proxySocket).pipe(socket); + } catch { + try { socket.destroy(); } catch { } + try { proxySocket.destroy(); } catch { } + } + }); + + proxyReq.on("response", (proxyRes) => { + try { + socket.write(`HTTP/1.1 ${proxyRes.statusCode || 502} ${proxyRes.statusMessage || "Bad Gateway"}\r\nConnection: close\r\n\r\n`); + } catch { } + socket.destroy(); + }); + + proxyReq.on("error", () => { + try { + socket.write("HTTP/1.1 502 Bad Gateway\r\nConnection: close\r\n\r\n"); + } catch { } + socket.destroy(); + }); + + proxyReq.end(); +} + +function attachSshTerminalUpgradeProxy(server) { + if (!server || typeof server.on !== "function") return; + server.on("upgrade", (req, socket, head) => { + try { + const parsed = new URL(req.url || "", "http://adpanel.local"); + if (parsed.pathname !== "/ssh-terminal/ws") return; + proxySshTerminalUpgrade(req, socket, head); + } catch { + try { socket.destroy(); } catch { } + } + }); +} + +const httpServer = httpMod.createServer(app); +httpServer.requestTimeout = 300000; +httpServer.headersTimeout = 60000; +httpServer.keepAliveTimeout = 5000; +attachSshTerminalUpgradeProxy(httpServer); +const SOCKET_HSTS_HEADER = "max-age=31536000; includeSubDomains"; +function applySocketSecurityHeaders(headers, req) { + if (!headers || typeof headers !== "object") return; + if (isRequestSecure(req)) { + headers["Strict-Transport-Security"] = SOCKET_HSTS_HEADER; + } +} +const io = new SocketIOServer(httpServer, { + maxHttpBufferSize: 1e6, + pingTimeout: 20000, + pingInterval: 25000, + allowEIO3: false, + cors: { + origin: process.env.BASE_URL || false, + methods: ["GET", "POST"], + credentials: true, + }, +}); +io.engine.on("initial_headers", applySocketSecurityHeaders); +io.engine.on("headers", applySocketSecurityHeaders); + + +broadcastDashboardUpdate = function (serverName, status) { + io.to('dashboard').emit('server:status', { + name: serverName, + status: status.status, + cpu: status.cpu, + memory: status.memory, + disk: status.disk, + nodeOnline: status.nodeOnline, + updatedAt: status.updatedAt + }); +}; + +broadcastNodeUpdate = function (nodeId, status) { + io.to('dashboard').emit('node:status', { + id: nodeId, + online: status.online, + latency: status.latency, + serverCount: status.serverCount, + updatedAt: status.updatedAt + }); +}; + +const LOG_CHUNK_MAX_CHARS = parseInt(process.env.LOG_CHUNK_MAX_CHARS || "", 10) || 10000; + +function stripAnsiSafe(input) { + const str = String(input || ""); + if (!str) return ""; + const out = []; + let i = 0; + while (i < str.length) { + const code = str.charCodeAt(i); + if (code === 0x1b || code === 0x9b) { + if (code === 0x9b) { + i = skipAnsiCsi(str, i + 1, out, i); + continue; + } + const next = str.charCodeAt(i + 1); + if (next === 0x5b) { + i = skipAnsiCsi(str, i + 2, out, i); + continue; + } + if (next === 0x5d) { + i = skipAnsiOsc(str, i + 2); + continue; + } + if (next === 0x50 || next === 0x58 || next === 0x5e || next === 0x5f) { + i = skipAnsiEscTerminated(str, i + 2); + continue; + } + if (next >= 0x40 && next <= 0x5f) { + i += 2; + continue; + } + i += 1; + continue; + } + if ((code < 0x20 || code === 0x7f) && code !== 0x0a && code !== 0x0d && code !== 0x09) { + i += 1; + continue; + } + out.push(str[i]); + i += 1; + } + return out.join(""); +} + +function skipAnsiCsi(str, idx, out = null, start = 0) { + let i = idx; + while (i < str.length) { + const c = str.charCodeAt(i); + if (c >= 0x40 && c <= 0x7e) { + if (out && str[i] === "m") out.push(str.slice(start, i + 1)); + return i + 1; + } + i += 1; + } + return str.length; +} + +function skipAnsiOsc(str, idx) { + let i = idx; + while (i < str.length) { + const c = str.charCodeAt(i); + if (c === 0x07) return i + 1; + if (c === 0x1b && str.charCodeAt(i + 1) === 0x5c) return i + 2; + i += 1; + } + return i; +} + +function skipAnsiEscTerminated(str, idx) { + let i = idx; + while (i < str.length) { + const c = str.charCodeAt(i); + if (c === 0x1b && str.charCodeAt(i + 1) === 0x5c) return i + 2; + i += 1; + } + return i; +} + +function cleanLog(name, chunk) { + if (!chunk) return ""; + let s = chunk.toString(); + if (LOG_CHUNK_MAX_CHARS > 0 && s.length > LOG_CHUNK_MAX_CHARS) { + s = s.slice(0, LOG_CHUNK_MAX_CHARS); + } + s = stripAnsiSafe(s); + s = s.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + s = s.replace(/^(?:stdout|stderr):\s?/gm, ""); + return s.trimEnd(); +} + +function getConsoleRoom(room) { + return `console:${String(room || "").trim()}`; +} + +function _emitLine(room, text) { + const cleaned = cleanLog(room, text); + if (!cleaned) return; + rememberConsoleLine(room, cleaned, "output"); + io.to(getConsoleRoom(room)).emit("output", escapeHtml(cleaned)); +} + +function emitOutput(socket, room, text) { + const cleaned = cleanLog(room, text); + if (!cleaned) return; + rememberConsoleLine(room, cleaned, "output"); + const safe = escapeHtml(cleaned); + try { io.to(getConsoleRoom(room)).emit("output", safe); } catch { } +} + +function panel(socket, room, msg) { + emitOutput(socket, room, `[ADPanel] ${msg}`); +} + +function emitPanel(room, message) { + _emitLine(room, `[ADPanel] ${message}`); +} + +const remoteLogClients = Object.create(null); +function tailLogsRemote(name, baseUrl, headers, options = {}) { + if (remoteLogClients[name]) return; + + const requestedTail = Number(options && options.tail); + const safeTail = Number.isFinite(requestedTail) && requestedTail >= 0 + ? Math.max(0, Math.min(10000, Math.trunc(requestedTail))) + : 0; + const query = `?tail=${encodeURIComponent(String(safeTail))}`; + const url = `${baseUrl}/v1/servers/${encodeURIComponent(name)}/logs${query}`; + const lib = url.startsWith("https:") ? https : httpMod; + + const hdrs = { ...(headers || {}) }; + delete hdrs["Content-Type"]; + + hdrs.Accept = "text/event-stream"; + hdrs["Cache-Control"] = "no-cache"; + hdrs.Connection = "keep-alive"; + + const req = lib.request(url, { method: "GET", headers: hdrs }); + + req.on("socket", (s) => { + try { s.setNoDelay(true); } catch { } + }); + + req.on("response", (res) => { + res.setEncoding("utf8"); + + const MAX_BUF = 256 * 1024; + let buf = ""; + let dataLines = []; + + function flushEvent() { + if (!dataLines.length) return; + const payload = dataLines.join("\n"); + dataLines = []; + + try { + const obj = JSON.parse(payload); + if (obj && obj.line) _emitLine(name, obj.line); + else if (typeof obj === "string") _emitLine(name, obj); + } catch { + _emitLine(name, payload); + } + } + + res.on("data", (chunk) => { + buf += chunk; + if (buf.length > MAX_BUF) buf = buf.slice(-MAX_BUF); + + while (true) { + const nl = buf.indexOf("\n"); + if (nl === -1) break; + + let line = buf.slice(0, nl); + buf = buf.slice(nl + 1); + + if (line.endsWith("\r")) line = line.slice(0, -1); + + if (line === "") { + flushEvent(); + continue; + } + + if (line.startsWith(":")) continue; + + if (line.startsWith("data:")) { + dataLines.push(line.slice(5).trimStart()); + } + } + }); + + res.on("end", () => { + try { flushEvent(); } catch { } + delete remoteLogClients[name]; + }); + + res.on("aborted", () => { + delete remoteLogClients[name]; + }); + }); + + req.on("error", () => { + delete remoteLogClients[name]; + }); + + req.end(); + remoteLogClients[name] = req; +} + +function stopTailLogsRemote(name) { + const req = remoteLogClients[name]; + if (!req) return; + try { req.destroy(); } catch (_) { } + delete remoteLogClients[name]; +} + +const ROOM_STATUS_INTERVAL_MS = 4000; +const roomStatusWatchers = new Map(); + +function getRoomClientCount(room) { + const set = io.sockets.adapter.rooms.get(room); + return set ? set.size : 0; +} + +function getConsoleRoomClientCount(room) { + const set = io.sockets.adapter.rooms.get(getConsoleRoom(room)); + return set ? set.size : 0; +} + +function stopRoomStatusWatcher(room) { + const rec = roomStatusWatchers.get(room); + if (rec?.timer) clearInterval(rec.timer); + roomStatusWatchers.delete(room); + stopTailLogsRemote(room); +} + +function startRoomStatusWatcher(room, baseUrl, headers) { + const existing = roomStatusWatchers.get(room); + if (existing) { + const nextUrl = String(baseUrl || ""); + if (nextUrl && existing.baseUrl !== nextUrl) { + existing.baseUrl = nextUrl; + existing.headers = headers; + existing.failures = 0; + if (!existing.nodeOnline) { + existing.nodeOnline = true; + io.to(room).emit("nodeStatus", { nodeOnline: true }); + } + } + return; + } + + const rec = { last: null, failures: 0, timer: null, nodeOnline: true, baseUrl, headers }; + + async function tick() { + if (getRoomClientCount(room) === 0) return stopRoomStatusWatcher(room); + if (getConsoleRoomClientCount(room) === 0) stopTailLogsRemote(room); + + try { + const { status, json } = await httpRequestJson( + `${rec.baseUrl}/v1/servers/${encodeURIComponent(room)}`, + "GET", + rec.headers, + null, + 3000 + ); + + if (status === 0) { + throw new Error("connection-failed"); + } + + if (status !== 200 || !json) { + if (!rec.nodeOnline) { + rec.nodeOnline = true; + io.to(room).emit("nodeStatus", { nodeOnline: true }); + } + throw new Error("bad-status"); + } + + const rawStatus = + (typeof json.status === "string" && json.status) || + (typeof json.state === "string" && json.state) || + ""; + + const label = normalizeStatusLabel(rawStatus) || "unknown"; + + rec.failures = 0; + + if (!rec.nodeOnline) { + rec.nodeOnline = true; + io.to(room).emit("nodeStatus", { nodeOnline: true }); + emitPanel(room, "Node connection restored"); + } + + 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}`); + + try { + const entry = await findServer(room); + if (entry) await upsertServerIndexEntry({ ...entry, status: label }); + } catch { } + } + + rec.last = label; + } catch { + rec.failures++; + + if (rec.failures >= 2 && rec.nodeOnline) { + rec.nodeOnline = false; + io.to(room).emit("nodeStatus", { nodeOnline: false }); + emitPanel(room, "Node connection lost"); + } + + if (rec.failures === 3) { + rec.last = "stopped"; + + try { + const entry = await findServer(room); + if (entry) await upsertServerIndexEntry({ ...entry, status: "stopped" }); + } catch { } + } + } + } + + rec.timer = setInterval(() => tick().catch(() => { }), ROOM_STATUS_INTERVAL_MS); + roomStatusWatchers.set(room, rec); + + tick().then(() => { + io.to(room).emit("nodeStatus", { nodeOnline: rec.nodeOnline }); + }).catch(() => { + io.to(room).emit("nodeStatus", { nodeOnline: rec.nodeOnline }); + }); +} + +const LIVE_STATUS_TTL_MS = 13_000; +const liveStatusCache = new Map(); + +const DASHBOARD_POLL_INTERVAL_MS = 5000; + +setInterval(() => { + try { + const now = Date.now(); + for (const [key, val] of liveStatusCache.entries()) { + if (now - val.ts > LIVE_STATUS_TTL_MS * 2) { + liveStatusCache.delete(key); + } + } + } catch (err) { console.debug("[liveStatusCache] sweep error:", err.message); } +}, 60_000).unref(); + +const dashboardWatchers = new Map(); +let dashboardSharedTimer = null; + +async function emitDashboardStatuses(socket, bots) { + if (!socket || !socket.connected) return; + const list = Array.isArray(bots) ? bots : []; + + try { + const results = await Promise.all(list.map((b) => queryLiveStatus(b))); + socket.emit("dashboard:statuses", results); + } catch { + } +} + +async function queryLiveStatus(botName) { + const name = String(botName || "").trim(); + if (!name) return { name: botName, status: "unknown" }; + + const cached = await getCachedServerStatusLenient(name); + if (cached) { + const result = { + name, + status: cached.status || "unknown" + }; + if (typeof cached.nodeOnline === "boolean") { + result.nodeOnline = cached.nodeOnline; + } + return result; + } + + return { name, status: "unknown" }; +} + +function ensureDashboardTimer() { + if (dashboardSharedTimer) return; + dashboardSharedTimer = setInterval(() => { + if (dashboardWatchers.size === 0) { + clearInterval(dashboardSharedTimer); + dashboardSharedTimer = null; + return; + } + for (const [id, rec] of dashboardWatchers.entries()) { + if (!rec.socket || !rec.socket.connected) { + dashboardWatchers.delete(id); + continue; + } + emitDashboardStatuses(rec.socket, rec.bots).catch(() => { }); + } + }, DASHBOARD_POLL_INTERVAL_MS); +} + +function stopDashboardWatcher(socket) { + if (!socket) return; + dashboardWatchers.delete(socket.id); + if (dashboardWatchers.size === 0 && dashboardSharedTimer) { + clearInterval(dashboardSharedTimer); + dashboardSharedTimer = null; + } +} + +function startDashboardWatcher(socket, bots) { + if (!socket || !socket.id) return; + stopDashboardWatcher(socket); + + const list = [...new Set((bots || []).filter(Boolean))]; + if (!list.length) return; + + emitDashboardStatuses(socket, list).catch(() => { }); + dashboardWatchers.set(socket.id, { socket, bots: list }); + ensureDashboardTimer(); +} + +const RESOURCE_STATS_POLL_MS = 3000; +const resourceStatsWatchers = new Map(); + +function getResourceRoom(serverName) { + return `res:${serverName}`; +} + +function getResourceRoomClientCount(serverName) { + const room = getResourceRoom(serverName); + const set = io.sockets.adapter.rooms.get(room); + return set ? set.size : 0; +} + +function stopResourceStatsWatcher(serverName) { + const rec = resourceStatsWatchers.get(serverName); + if (!rec) return; + if (rec.timer) clearInterval(rec.timer); + resourceStatsWatchers.delete(serverName); +} + +async function fetchResourceStatsFromNode(serverName, baseUrl, headers) { + try { + const { status, json } = await httpRequestJson( + `${baseUrl}/v1/servers/${encodeURIComponent(serverName)}`, + "GET", + headers, + null, + 4000 + ); + if (status !== 200 || !json || !json.ok) return null; + return json; + } catch { + return null; + } +} + +function buildResourcePayload(serverName, nodeStats, cachedStatus) { + if (nodeStats && nodeStats.stats) { + const stats = nodeStats.stats; + const statusLabel = normalizeStatusLabel(nodeStats.status || nodeStats.state) || 'unknown'; + return normalizeServerStatusRecord({ + server: serverName, + ok: true, + status: statusLabel, + nodeOnline: true, + cpu: stats.cpu?.percent ?? null, + cpuLimit: stats.cpu?.limit ?? null, + memory: { + used: stats.memory?.usedMb ?? 0, + total: stats.memory?.limitMb ?? 0, + percent: stats.memory?.percent ?? 0 + }, + disk: { + used: (stats.disk?.usedMb ?? 0) / 1024, + total: (stats.disk?.limitMb ?? 0) / 1024, + percent: stats.disk?.percent ?? 0 + }, + network: stats.network || nodeStats.network || null, + uptime: nodeStats.uptime ?? null, + ts: Date.now() + }); + } + if (nodeStats) { + const statusLabel = normalizeStatusLabel(nodeStats.status || nodeStats.state) || 'unknown'; + return normalizeServerStatusRecord({ + server: serverName, + ok: true, + status: statusLabel, + nodeOnline: true, + cpu: cachedStatus?.cpu ?? null, + cpuLimit: cachedStatus?.cpuLimit ?? null, + memory: cachedStatus?.memory ?? null, + disk: cachedStatus?.disk ?? null, + network: nodeStats.network || cachedStatus?.network || null, + uptime: nodeStats.uptime ?? cachedStatus?.uptime ?? null, + ts: Date.now() + }); + } + if (cachedStatus) { + const payload = normalizeServerStatusRecord({ + server: serverName, + ok: true, + status: normalizeStatusLabel(cachedStatus.status) || 'unknown', + cpu: cachedStatus.cpu ?? null, + cpuLimit: cachedStatus.cpuLimit ?? null, + memory: cachedStatus.memory ?? null, + disk: cachedStatus.disk ?? null, + network: cachedStatus.network ?? null, + uptime: cachedStatus.uptime ?? null, + ts: Date.now() + }); + if (cachedStatus.nodeOnline === true) payload.nodeOnline = true; + return payload; + } + return { server: serverName, ok: false, status: 'unknown', ts: Date.now() }; +} + +const MAX_RESOURCE_WATCHERS = Math.max(1, parseInt(process.env.MAX_RESOURCE_WATCHERS || "2000", 10) || 2000); +async function startResourceStatsWatcher(serverName) { + if (resourceStatsWatchers.has(serverName)) return; + if (resourceStatsWatchers.size >= MAX_RESOURCE_WATCHERS) return; + + const entry = await findServer(serverName); + if (!entry || !isRemoteEntry(entry)) return; + + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) return; + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return; + + const headers = nodeAuthHeadersFor(node, true); + const rec = { timer: null, last: null, baseUrl, headers, inFlight: false }; + + async function tick() { + if (getResourceRoomClientCount(serverName) === 0) { + stopResourceStatsWatcher(serverName); + return; + } + if (rec.inFlight) return; + rec.inFlight = true; + try { + const nodeStats = await fetchResourceStatsFromNode(serverName, rec.baseUrl, rec.headers); + const cachedStatus = await getCachedServerStatusLenient(serverName); + const payload = buildResourcePayload(serverName, nodeStats, cachedStatus); + rec.last = payload; + io.to(getResourceRoom(serverName)).emit('resources:data', payload); + } catch { + if (rec.last) { + io.to(getResourceRoom(serverName)).emit('resources:data', rec.last); + } + } finally { + rec.inFlight = false; + } + } + + rec.timer = setInterval(() => tick().catch(() => { }), RESOURCE_STATS_POLL_MS); + resourceStatsWatchers.set(serverName, rec); + + tick().catch(() => { }); +} + +setInterval(() => { + try { + for (const [name] of resourceStatsWatchers) { + if (getResourceRoomClientCount(name) === 0) { + stopResourceStatsWatcher(name); + } + } + } catch (err) { console.debug("[resourceStats] cleanup error:", err.message); } +}, 30_000).unref(); + +const SOCKET_ALLOWED_ORIGINS = (process.env.SOCKET_ALLOW_ORIGINS || "") + .split(",") + .map(s => s.trim()) + .filter(Boolean); + +function normalizeHostForSocket(value) { + const extracted = extractHostnameFromHeader(value); + return extracted ? extracted.toLowerCase() : ""; +} + +function isSocketOriginAllowed(headers) { + const originHeader = headers?.origin || headers?.Origin || ""; + const requestHost = normalizeHostForSocket(headers?.host || ""); + const allowlist = SOCKET_ALLOWED_ORIGINS.map(normalizeHostForSocket).filter(Boolean); + + if (!originHeader) return true; + + let originHost = ""; + try { + originHost = normalizeHostForSocket(new URL(originHeader).host); + } catch { + originHost = normalizeHostForSocket(originHeader); + } + + if (!originHost) return false; + + if (allowlist.length) return allowlist.includes(originHost); + return originHost === requestHost; +} + +function getSocketIp(socket) { + const ip = getRequestIp(socket.request); + if (ip && ip !== "unknown") return ip; + return socket.handshake?.address || "unknown"; +} + +const socketConnectionsPerIp = new Map(); + +io.use((socket, next) => { + const ip = getSocketIp(socket); + const cookieHeader = socket.request?.headers?.cookie; + if (!cookieHeader) { + console.warn(`[SECURITY] Socket connection rejected (No cookies): ${ip}`); + return next(new Error("Authentication required")); + } + if (!isSocketOriginAllowed(socket.handshake?.headers || {})) { + return next(new Error("origin-not-allowed")); + } + + sessionMiddleware(socket.request, socket.request.res || {}, (err) => { + if (err) return next(err); + const email = socket.request.session?.user; + if (!email) return next(new Error("unauthorized")); + + const currentConnections = socketConnectionsPerIp.get(ip) || 0; + if (currentConnections >= 10) { + console.warn(`[SECURITY] Max socket connections exceeded: ${ip}`); + return next(new Error("Too many connections from this IP")); + } + + socketConnectionsPerIp.set(ip, currentConnections + 1); + socket.on("disconnect", () => { + const count = socketConnectionsPerIp.get(ip) || 1; + if (count <= 1) socketConnectionsPerIp.delete(ip); + else socketConnectionsPerIp.set(ip, count - 1); + }); + + return 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_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; +const consoleHistoryNodeFetchCache = new Map(); +const consoleHistoryNodeFetchInflight = new Map(); + +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"), + })) + .filter((item) => item.line) + .slice(-CONSOLE_HISTORY_MAX_LINES); +} + +function cloneConsoleHistoryEntries(entries) { + return normalizeConsoleHistoryEntries(entries).map((item) => ({ + line: item.line, + ts: item.ts, + source: item.source, + })); +} + +function consoleHistoryEntryKey(item) { + return `${String(item?.source || "output")}\u0000${String(item?.line || "")}`; +} + +function findConsoleHistoryOverlap(baseEntries, incomingEntries) { + const base = normalizeConsoleHistoryEntries(baseEntries); + const incoming = normalizeConsoleHistoryEntries(incomingEntries); + if (!base.length || !incoming.length) return { start: -1, size: 0 }; + + const maxOverlap = Math.min(base.length, incoming.length, 200); + for (let size = maxOverlap; size > 0; size--) { + const baseStart = base.length - size; + for (let incomingStart = 0; incomingStart <= incoming.length - size; incomingStart++) { + let matched = true; + for (let i = 0; i < size; i++) { + if (consoleHistoryEntryKey(base[baseStart + i]) !== consoleHistoryEntryKey(incoming[incomingStart + i])) { + matched = false; + break; + } + } + if (matched) return { start: incomingStart, size }; + } + } + return { start: -1, size: 0 }; +} + +function mergeConsoleHistoryEntries(...groups) { + const merged = []; + for (const group of groups) { + const incoming = normalizeConsoleHistoryEntries(group); + if (!incoming.length) continue; + const overlap = findConsoleHistoryOverlap(merged, incoming); + const toAppend = overlap.size > 0 + ? incoming.slice(overlap.start + overlap.size) + : incoming; + for (const item of toAppend) { + merged.push(item); + if (merged.length > CONSOLE_HISTORY_MAX_LINES) merged.shift(); + } + } + return merged.slice(-CONSOLE_HISTORY_MAX_LINES); +} + +async function fetchRecentConsoleHistoryFromNode(serverName, limit = 100) { + const requestedLimit = Math.min(Math.max(parseInt(limit, 10) || 100, 1), CONSOLE_HISTORY_MAX_LINES); + const requestedName = String(serverName || "").trim(); + if (!requestedName) return []; + + const cacheKey = `${requestedName}:${requestedLimit}`; + const now = Date.now(); + const cached = consoleHistoryNodeFetchCache.get(cacheKey); + if (cached && (now - cached.ts) <= CONSOLE_HISTORY_NODE_CACHE_TTL_MS) { + return cloneConsoleHistoryEntries(cached.lines); + } + + const inFlight = consoleHistoryNodeFetchInflight.get(cacheKey); + if (inFlight) { + const shared = await inFlight; + return cloneConsoleHistoryEntries(shared); + } + + const fetchPromise = (async () => { + const entry = await findServer(requestedName); + if (!entry || !isRemoteEntry(entry)) return []; + + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) return []; + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return []; + + const fullUrl = `${baseUrl}/v1/servers/${encodeURIComponent(entry.name || requestedName)}/logs?tail=${encodeURIComponent(String(requestedLimit))}`; + const headers = { + ...nodeAuthHeadersFor(node, true), + Accept: "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }; + + const fetched = await new Promise((resolve) => { + try { + const lib = fullUrl.startsWith("https:") ? https : httpMod; + const req = lib.request(fullUrl, { method: "GET", headers }, (nres) => { + if (nres.statusCode !== 200) { + try { req.destroy(); } catch { } + resolve([]); + return; + } + + const collected = []; + let buf = ""; + let dataLines = []; + let settled = false; + + const finish = () => { + if (settled) return; + settled = true; + try { req.destroy(); } catch { } + resolve(collected.slice(-requestedLimit)); + }; + + const idleTimer = setTimeout(finish, 350); + idleTimer.unref?.(); + const maxTimer = setTimeout(finish, 1500); + maxTimer.unref?.(); + + const flushEvent = () => { + if (!dataLines.length) return; + const payload = dataLines.join("\n"); + dataLines = []; + try { + const parsed = JSON.parse(payload); + const line = typeof parsed?.line === "string" + ? parsed.line + : typeof parsed === "string" + ? parsed + : ""; + if (!line) return; + const item = { line: String(line), ts: Date.now(), source: "output" }; + collected.push(item); + } catch { } + }; + + nres.on("data", (chunk) => { + clearTimeout(idleTimer); + buf += Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk || ""); + + while (true) { + const nl = buf.indexOf("\n"); + if (nl === -1) break; + + let line = buf.slice(0, nl); + buf = buf.slice(nl + 1); + if (line.endsWith("\r")) line = line.slice(0, -1); + + if (line === "") { + flushEvent(); + continue; + } + + if (line.startsWith(":") || line.startsWith("event:")) continue; + if (line.startsWith("data:")) { + dataLines.push(line.slice(5).trimStart()); + } + } + }); + nres.on("end", () => { + clearTimeout(idleTimer); + clearTimeout(maxTimer); + flushEvent(); + finish(); + }); + nres.on("aborted", () => { + clearTimeout(idleTimer); + clearTimeout(maxTimer); + flushEvent(); + finish(); + }); + }); + + req.on("error", () => resolve([])); + req.setTimeout(2000, () => { + try { req.destroy(); } catch { } + resolve([]); + }); + req.end(); + } catch { + resolve([]); + } + }); + + const normalized = normalizeConsoleHistoryEntries(fetched); + consoleHistoryNodeFetchCache.set(cacheKey, { ts: Date.now(), lines: normalized }); + return normalized; + })().catch(() => { + const empty = []; + consoleHistoryNodeFetchCache.set(cacheKey, { ts: Date.now(), lines: empty }); + return empty; + }).finally(() => { + consoleHistoryNodeFetchInflight.delete(cacheKey); + }); + + consoleHistoryNodeFetchInflight.set(cacheKey, fetchPromise); + const fetched = await fetchPromise; + return cloneConsoleHistoryEntries(fetched); +} + +async function getConsoleHistorySnapshot(serverName, limit = 200, options = {}) { + const name = String(serverName || "").trim(); + if (!name) return { total: 0, lines: [] }; + + 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); + + if (history.length < nodeWarmThreshold || newestEntryIsCommand || historyIsStale) { + const nodeHistory = await fetchRecentConsoleHistoryFromNode(name, safeLimit); + if (nodeHistory.length > 0) { + history = mergeConsoleHistoryEntries(history, nodeHistory); + consoleHistory.set(name, history); + } + } + + const responseHistory = includeCommands + ? history + : history.filter((item) => String(item?.source || "output") !== "command"); + + return { + total: responseHistory.length, + lines: responseHistory.slice(-safeLimit).map((item) => ({ + line: String(item?.line || ""), + ts: Number(item?.ts || 0) || Date.now(), + source: String(item?.source || "output"), + })), + }; +} + +function resetConsoleHistoryState(serverName) { + const name = String(serverName || "").trim(); + if (!name) return; + + consoleHistory.delete(name); + + for (const key of Array.from(consoleHistoryNodeFetchCache.keys())) { + if (key.startsWith(`${name}:`)) { + consoleHistoryNodeFetchCache.delete(key); + } + } + + for (const key of Array.from(consoleHistoryNodeFetchInflight.keys())) { + if (key.startsWith(`${name}:`)) { + consoleHistoryNodeFetchInflight.delete(key); + } + } +} + +function rememberConsoleLine(bot, line, source = "output") { + if (!bot || !line) return; + const name = String(bot); + const item = normalizeConsoleHistoryEntries([{ line, ts: Date.now(), source }])[0]; + if (!item) return; + let arr = consoleHistory.get(name) || []; + + if (!consoleHistory.has(name) && consoleHistory.size >= CONSOLE_HISTORY_MAX_SERVERS) { + const oldest = consoleHistory.keys().next().value; + if (oldest !== undefined) consoleHistory.delete(oldest); + } + + 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"); +} + +async function removeLegacyConsoleHistoryStorage() { + try { + await fsp.rm(path.join(process.cwd(), "data", "console-history"), { recursive: true, force: true }); + } catch (err) { + console.warn("[consoleHistory] legacy cleanup warning:", err?.message || err); + } +} + +setInterval(() => { + try { + const now = Date.now(); + const ONE_DAY_MS = 24 * 60 * 60 * 1000; + for (const [key, history] of consoleHistory.entries()) { + if (!history || history.length === 0) { + consoleHistory.delete(key); + continue; + } + const lastEntry = history[history.length - 1]; + if (lastEntry && lastEntry.ts && (now - lastEntry.ts > ONE_DAY_MS)) { + consoleHistory.delete(key); + } + } + } catch (err) { console.debug("[consoleHistory] sweep error:", err.message); } +}, 60 * 60 * 1000).unref(); + +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" }); + + 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?.server_start && !perms?.console_read) { + return res.status(403).json({ error: "not authorized", permission: "server_start|console_read" }); + } + } + + resetConsoleHistoryState(serverName); + return res.json({ ok: true, server: serverName }); + } catch (err) { + return next(err); + } +}); + +app.get("/api/servers/:name/console-history", 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 (!isAdminUser) { + const perms = await getEffectivePermsForUserOnServer(email, serverName); + if (!perms?.console_read) { + return res.status(403).json({ error: "not authorized", permission: "console_read" }); + } + } + + const snapshot = await getConsoleHistorySnapshot(serverName, req.query.limit, { + includeCommands: String(req.query.includeCommands || "").trim() === "1", + }); + + return res.json({ ok: true, server: serverName, total: snapshot.total, lines: snapshot.lines }); + } catch (err) { + return next(err); + } +}); + +io.on("connection", async (socket) => { + let email = socket.request?.session?.user || null; + let user = null; + let isAdminUser = false; + let accessSet = new Set(); + try { + user = email ? await findUserByEmail(email) : null; + isAdminUser = !!(user && user.admin); + if (!isAdminUser && email) { + const accessList = await getAccessListForEmail(email); + accessSet = new Set(accessList || []); + } + } catch (err) { + console.error("[socket] init failed:", err); + email = null; + isAdminUser = false; + accessSet = new Set(); + } + let messageCount = 0; + socket.use((packet, next) => { + if (!packet) return next(); + messageCount += 1; + if (messageCount > 60) { + console.warn(`[SECURITY] Socket spam detected from IP: ${getSocketIp(socket)}`); + return socket.disconnect(true); + } + return next(); + }); + + const spamInterval = setInterval(() => { + messageCount = 0; + }, 60_000); + + function deny(room, msg = "Permission denied") { + try { socket.emit("output", msg); } catch { } + } + + async function hasPerm(botName, permKey) { + if (!email) return false; + if (isAdminUser) return true; + const perms = await getEffectivePermsForUserOnServer(email, botName); + return !!(perms && perms[permKey]); + } + + function canAccessBot(botName) { + if (!botName) return false; + if (isAdminUser) return true; + if (!email) return false; + if (accessSet.has("all")) return true; + return accessSet.has(botName); + } + + 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 canReadConsole = await hasPerm(name, "console_read"); + + 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); + }); + + socket.on("dashboard:watch", (payload) => { + const rawBots = (Array.isArray(payload) ? payload : (Array.isArray(payload?.bots) ? payload.bots : [])).slice(0, 500); + const bots = rawBots.map(b => String(b || "").trim()).filter(Boolean).filter(canAccessBot); + startDashboardWatcher(socket, bots); + }); + + socket.on("dashboard:subscribe", async (payload) => { + const rawBots = (Array.isArray(payload) ? payload : + Array.isArray(payload?.bots) ? payload.bots : []).slice(0, 500); + + socket.join('dashboard'); + + const statuses = {}; + const validNames = rawBots.map(n => String(n || '').trim()).filter(n => n && canAccessBot(n)); + const BATCH = 200; + for (let i = 0; i < validNames.length; i += BATCH) { + const batch = validNames.slice(i, i + BATCH); + const entries = await Promise.all(batch.map(async (safeName) => { + const cached = await getCachedServerStatusLenient(safeName); + if (!cached) return null; + const entry = { + status: cached.status, + cpu: cached.cpu, + memory: cached.memory, + disk: cached.disk, + updatedAt: cached.updatedAt + }; + if (typeof cached.nodeOnline === "boolean") { + entry.nodeOnline = cached.nodeOnline; + } + return [safeName, entry]; + })); + for (const e of entries) { + if (e) statuses[e[0]] = e[1]; + } + } + + socket.emit('dashboard:initial', { statuses }); + }); + + socket.on("dashboard:unsubscribe", () => { + socket.leave('dashboard'); + }); + + socket.on("resources:subscribe", async (payload) => { + const serverName = String(payload?.server || payload || '').trim(); + if (!serverName || !canAccessBot(serverName)) return; + const room = getResourceRoom(serverName); + try { await socket.join(room); } catch { } + startResourceStatsWatcher(serverName).catch(() => { }); + const watcher = resourceStatsWatchers.get(serverName); + if (watcher && watcher.last) { + try { socket.emit('resources:data', watcher.last); } catch { } + } + }); + + socket.on("resources:subscribe-bulk", async (payload) => { + const servers = (Array.isArray(payload?.servers || payload) + ? (payload?.servers || payload) + : []).slice(0, 100); + for (const raw of servers) { + const serverName = String(raw || '').trim(); + if (!serverName || !canAccessBot(serverName)) continue; + const room = getResourceRoom(serverName); + try { await socket.join(room); } catch { continue; } + startResourceStatsWatcher(serverName).catch(() => { }); + const watcher = resourceStatsWatchers.get(serverName); + if (watcher && watcher.last) { + try { socket.emit('resources:data', watcher.last); } catch { } + } + } + }); + + socket.on("resources:unsubscribe", (payload) => { + const serverName = String(payload?.server || payload || '').trim(); + if (!serverName) return; + const room = getResourceRoom(serverName); + try { socket.leave(room); } catch { } + }); + + socket.on("resources:unsubscribe-all", () => { + try { + for (const room of socket.rooms) { + if (room && room.startsWith('res:')) { + socket.leave(room); + } + } + } catch { } + }); + + socket.on("disconnect", () => { + clearInterval(spamInterval); + try { + for (const room of socket.rooms) { + if (room && room !== socket.id && getRoomClientCount(room) === 0) stopRoomStatusWatcher(room); + if (room && room.startsWith('res:')) { + const serverName = room.slice(4); + if (getResourceRoomClientCount(serverName) === 0) { + stopResourceStatsWatcher(serverName); + } + } + } + } catch { } + stopDashboardWatcher(socket); + }); + + 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 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); + 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) { + console.error("[socket][readFile] failed:", e); + socket.emit("fileData", { path: rel, content: "/* ERROR: failed to load file */" }); + } + }); + + 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."); + + 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); + 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) { + console.error("[socket][writeFile] failed:", e); + io.to(name).emit("toast", { type: "error", msg: "Save failed: internal error" }); + } + }); + + socket.on("deleteFile", async ({ bot, path: rel, isDir }) => { + 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 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); + 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) { + console.error("[socket][deleteFile] failed:", e); + io.to(name).emit("toast", { type: "error", msg: "Delete failed: internal error" }); + } + }); + + socket.on("action", async (data) => { + const { bot, cmd } = data || {}; + const botName = String(bot || "").trim(); + if (!botName) return; + + if (!canAccessBot(botName)) return deny(botName, "[ADPanel] You don't have access to this server."); + const canReadConsole = await hasPerm(botName, "console_read"); + 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."); + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) return _emitLine(botName, "[ADPanel] Invalid node address."); + + const headers = nodeAuthHeadersFor(node, true); + + 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); + panel(socket, botName, "Server starting"); + + const defaultPort = normalizeTemplateId(entry.template) === "minecraft" ? 25565 : 3001; + const chosenPort = entry.port ?? defaultPort; + const hostPort = normalizeTemplateId(entry.template) === "minecraft" ? clampPort(chosenPort) : clampAppPort(chosenPort, defaultPort); + + const r = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(botName)}/start?wait=false`, "POST", headers, { hostPort }, 1_000); + if (!([200, 202].includes(r.status)) || !(r.json && r.json.ok)) { + const msg = (r.json && (r.json.error || r.json.detail)) || `node status ${r.status}`; + emitPanel(botName, `Start failed: ${msg}`); + return; + } + + try { + const cur = await findServer(botName); + if (cur) await upsertServerIndexEntry({ ...cur, status: "starting" }); + } catch { } + + panel(socket, botName, "Start request accepted."); + if (canReadConsole) tailLogsRemote(botName, baseUrl, headers); + return; + } + + if (cmd === "stop") { + panel(socket, botName, "Server stopping"); + + const r = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(botName)}/stop`, "POST", headers, null, 1_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}`); + try { + const cur = await findServer(botName); + if (cur) await upsertServerIndexEntry({ ...cur, status: "stopped" }); + } catch { } + + panel(socket, botName, "Server stopped"); + return; + } + + if (cmd === "restart") { + resetConsoleHistoryState(botName); + 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); + return; + } + + if (cmd === "kill") { + emitPanel(botName, "Server killing"); + + const r = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(botName)}/kill`, "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 killed"); + return; + } + + _emitLine(botName, "Unknown cmd"); + } catch (e) { + _emitLine(botName, `[error] ${e?.message || String(e)}`); + } + }); + + socket.on("command", async (payload, ack) => { + const botName = String(payload?.bot || "").trim(); + const requestId = String(payload?.requestId || "").trim(); + const reply = (data) => { + if (typeof ack === "function") { + try { ack(data); } catch { } + } + }; + const commandCheck = typeof nodesRouter.sanitizeConsoleCommand === "function" + ? nodesRouter.sanitizeConsoleCommand(payload?.command) + : { ok: true, command: String(payload?.command || "").trim() }; + if (!botName || !commandCheck.ok) { + const errorCode = !botName ? "missing params" : (commandCheck.error || "invalid_command"); + if (botName && commandCheck.detail) { + _emitLine(botName, `[ADPanel] command rejected: ${commandCheck.detail}`); + } + reply({ ok: false, error: errorCode, detail: commandCheck.detail || null }); + return; + } + const trimmed = commandCheck.command; + + if (!canAccessBot(botName) || !(await hasPerm(botName, "console_write"))) { + deny(botName); + reply({ ok: false, error: "permission denied" }); + return; + } + + 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" }); + return; + } + + const node = await findNodeByIdOrName(entry.nodeId); + if (!node) { + _emitLine(botName, "[ADPanel] Node not found."); + reply({ ok: false, error: "node not found" }); + return; + } + + const baseUrl = buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!baseUrl) { + _emitLine(botName, "[ADPanel] Invalid node address."); + reply({ ok: false, error: "invalid node address" }); + return; + } + + const headers = nodeAuthHeadersFor(node, true); + const body = requestId ? { command: trimmed, requestId } : { command: trimmed }; + + try { + const r = await httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(botName)}/command`, "POST", headers, body, 20_000); + if (r.status !== 200 || !(r.json && r.json.ok)) { + const msg = (r.json && (r.json.error || r.json.detail)) || `node status ${r.status}`; + _emitLine(botName, "[ADPanel] command failed: " + msg); + reply({ ok: false, error: msg, status: r.status }); + return; + } + reply({ ok: true }); + } catch (e) { + _emitLine(botName, "[ADPanel] command error: " + (e?.message || String(e))); + reply({ ok: false, error: e?.message || String(e) }); + } + }); +}); + +let httpsServer = null; +const LISTEN_HOST = NGINX_ENABLED ? APP_HOST : HOST; +const LISTEN_HTTP_PORT = NGINX_ENABLED ? APP_PORT : HTTP_PORT; +const USE_HTTPS = ENABLE_HTTPS && !NGINX_ENABLED; +const ANSI_RESET = "\x1b[0m"; +const ANSI_BOLD = "\x1b[1m"; +const ANSI_YELLOW = "\x1b[33m"; +const ANSI_BRIGHT_YELLOW = "\x1b[93m"; +const ANSI_BRIGHT_CYAN = "\x1b[96m"; +let startupMaturityNoticePrinted = false; +let startupMaturityNoticeTimer = null; + +if (USE_HTTPS) { + try { + const httpsOptions = { + key: fs.readFileSync(SSL_KEY_PATH), + cert: fs.readFileSync(SSL_CERT_PATH), + }; + if (SSL_CA_PATH) httpsOptions.ca = fs.readFileSync(SSL_CA_PATH); + httpsServer = https.createServer(httpsOptions, app); + attachSshTerminalUpgradeProxy(httpsServer); + httpsAvailable = true; + } catch (err) { + console.error("[https] Failed to initialize HTTPS server:", err?.message || err); + } +} + +if (httpsServer) io.attach(httpsServer); + +function printStartupMaturityNotice() { + if (startupMaturityNoticePrinted) return; + startupMaturityNoticePrinted = true; + + const productName = process.env.APP_NAME || "ADPanel"; + const lines = [ + `${ANSI_BRIGHT_YELLOW}${ANSI_BOLD}====================================================================${ANSI_RESET}`, + `${ANSI_BRIGHT_YELLOW}${ANSI_BOLD} ${productName} Product Update${ANSI_RESET}`, + `${ANSI_BRIGHT_CYAN} ${productName} has reached its first stable release and is ready for production use.${ANSI_RESET}`, + `${ANSI_YELLOW} While the core platform is solid, we're continuing to refine the overall experience —${ANSI_RESET}`, + `${ANSI_YELLOW} from SaaS-level polish and workflow ergonomics to day-to-day operator usability.${ANSI_RESET}`, + `${ANSI_YELLOW} Expect steady improvements as we ship updates focused on reliability, smoother workflows, and a more intuitive UX.${ANSI_RESET}`, + `${ANSI_BRIGHT_YELLOW}${ANSI_BOLD}====================================================================${ANSI_RESET}`, + ]; + + console.log(""); + for (const line of lines) { + console.log(line); + } +} + +function scheduleStartupMaturityNotice(delayMs = 1500) { + if (startupMaturityNoticePrinted) return; + if (startupMaturityNoticeTimer) { + clearTimeout(startupMaturityNoticeTimer); + } + startupMaturityNoticeTimer = setTimeout(() => { + startupMaturityNoticeTimer = null; + printStartupMaturityNotice(); + }, delayMs); + startupMaturityNoticeTimer.unref?.(); +} + +async function startServers() { + try { + await ensureMySqlRunning(); + } catch (e) { + console.warn('[startup] Could not verify MySQL/MariaDB status:', e.message); + } + + await db.ensureSchema(); + await removeLegacyConsoleHistoryStorage(); + + try { + const [cols] = await db.pool.execute("SHOW COLUMNS FROM servers LIKE 'display_name'"); + if (!cols || cols.length === 0) { + await db.pool.execute("ALTER TABLE servers ADD COLUMN display_name VARCHAR(120) NULL AFTER name"); + console.log("[migration] Added display_name column to servers table"); + } + } catch (e) { + if (!String(e.message).includes("Duplicate column")) { + console.warn("[migration] display_name migration note:", e.message); + } + } + + startStatusPolling(); + + // Migrate database tools nginx configs to internal-only proxy + try { + migrateDbToolsNginxOnStartup(); + } catch (e) { + console.warn('[startup] DB tools nginx migration warning:', e.message); + } + + try { + const snippetsDir = '/etc/nginx/snippets'; + if (fs.existsSync('/etc/nginx')) { + fs.mkdirSync(snippetsDir, { recursive: true }); + const placeholderSnippets = ['pgadmin4.conf', 'phpmyadmin.conf', 'mongodb.conf']; + for (const snippet of placeholderSnippets) { + const snippetPath = path.join(snippetsDir, snippet); + if (!fs.existsSync(snippetPath)) { + fs.writeFileSync(snippetPath, `# Placeholder - will be populated when service is installed\n`, { mode: 0o644 }); + console.log(`[nginx] Created placeholder snippet: ${snippetPath}`); + } + } + } + } catch (e) { + console.debug('[nginx] Could not create placeholder snippets:', e.message); + } + + // Warm/recover DB tool backends on startup so first token access does not fail. + try { + const pgCfg = loadPgAdminConfig(); + if (pgCfg.enabled) { + const pgReady = await ensureDbToolBackendReady('pgadmin'); + if (!pgReady.ok) { + console.warn('[startup] pgAdmin backend readiness warning:', pgReady.error || 'unknown'); + } + } + + const phpCfg = loadDatabaseConfig(); + if (phpCfg.enabled && phpCfg.config) { + const phpReady = await ensureDbToolBackendReady('phpmyadmin'); + if (!phpReady.ok) { + console.warn('[startup] phpMyAdmin backend readiness warning:', phpReady.error || 'unknown'); + } + } + } catch (e) { + console.warn('[startup] DB backend warmup warning:', e.message); + } + + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'agent_access'`); + if (!cols || cols.length === 0) { + await db.query("ALTER TABLE users ADD COLUMN agent_access TINYINT(1) NOT NULL DEFAULT 0"); + console.log('[db] Added agent_access column to users table'); + } + } catch (err) { + if (!err.message?.includes('Duplicate column')) { + console.debug('[db] agent_access column check:', err.message); + } + } + + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'avatar_url'`); + if (!cols || cols.length === 0) { + await db.query(`ALTER TABLE users ADD COLUMN avatar_url VARCHAR(2048) DEFAULT NULL`); + console.log('[db] Added avatar_url column to users table'); + } + } catch (err) { + if (!err.message?.includes('Duplicate column')) { + console.debug('[db] avatar_url column check:', err.message); + } + } + + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'username'`); + if (!cols || cols.length === 0) { + await db.query(`ALTER TABLE users ADD COLUMN username VARCHAR(50) DEFAULT NULL`); + console.log('[db] Added username column to users table'); + } + } catch (err) { + if (!err.message?.includes('Duplicate column')) { + console.debug('[db] username column check:', err.message); + } + } + + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'username_changed_at'`); + if (!cols || cols.length === 0) { + await db.query(`ALTER TABLE users ADD COLUMN username_changed_at BIGINT UNSIGNED DEFAULT NULL`); + console.log('[db] Added username_changed_at column to users table'); + } + } catch (err) { + if (!err.message?.includes('Duplicate column')) { + console.debug('[db] username_changed_at column check:', err.message); + } + } + + try { + const [cols] = await db.pool.query(`SHOW COLUMNS FROM users LIKE 'preferences'`); + if (!cols || cols.length === 0) { + await db.query(`ALTER TABLE users ADD COLUMN preferences TEXT DEFAULT NULL`); + console.log('[db] Added preferences column to users table'); + } + } catch (err) { + if (!err.message?.includes('Duplicate column')) { + console.debug('[db] preferences column check:', err.message); + } + } + + if (SCHEDULER_ENABLED && SCHEDULER_REDIS_URL) { + setTimeout(async () => { + try { + await initializeScheduler(); + } catch (err) { + console.error("[scheduler] Deferred initialization failed:", err?.message || err); + } + }, 100); + } + + httpServer.listen(LISTEN_HTTP_PORT, LISTEN_HOST, () => { + console.log(`[ADPanel] HTTP listening on http://${LISTEN_HOST}:${LISTEN_HTTP_PORT}`); + if (NGINX_ENABLED) { + console.log("[ADPanel] NGINX_ENABLED=1; expecting reverse proxy in front."); + } + startMaintenanceChecker(); + startPanelAutoUpdateScheduler(); + startNodeAutoUpdateScheduler(); + if (!httpsServer) { + scheduleStartupMaturityNotice(); + } + }); + + if (httpsServer) { + httpsServer.listen(HTTPS_PORT, HOST, () => { + console.log(`[ADPanel] HTTPS listening on https://${HOST}:${HTTPS_PORT}`); + scheduleStartupMaturityNotice(); + }); + } +} + +startServers().catch((err) => { + console.error("[startup] Failed to initialize database schema:", err?.message || err); + process.exit(1); +}); diff --git a/init_subdomains.js b/init_subdomains.js new file mode 100644 index 0000000..21d440b --- /dev/null +++ b/init_subdomains.js @@ -0,0 +1,24 @@ +const db = require('./db'); +async function run() { + try { + await db.query(` + CREATE TABLE IF NOT EXISTS subdomains ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + server_id BIGINT UNSIGNED NOT NULL, + domain VARCHAR(255) NOT NULL, + status ENUM('pending', 'approved', 'canceled') NOT NULL DEFAULT 'pending', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id), + UNIQUE KEY uniq_subdomains_domain (domain), + 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; + `); + console.log("Subdomains table created."); + process.exit(0); + } catch (e) { + console.error(e); + process.exit(1); + } +} +run(); diff --git a/initialize.sh b/initialize.sh new file mode 100755 index 0000000..1bc4c44 --- /dev/null +++ b/initialize.sh @@ -0,0 +1,4501 @@ +#!/usr/bin/env bash + +if [ -t 1 ] && [ -z "${NO_COLOR:-}" ]; then + RED='\033[0;31m' + GREEN='\033[0;32m' + YELLOW='\033[1;33m' + CYAN='\033[0;36m' + MAGENTA='\033[1;35m' + BLUE='\033[0;34m' + WHITE='\033[1;37m' + BOLD='\033[1m' + DIM='\033[2m' + NC='\033[0m' +else + RED='' + GREEN='' + YELLOW='' + CYAN='' + MAGENTA='' + BLUE='' + WHITE='' + BOLD='' + DIM='' + NC='' +fi + +UI_RULE="======================================================================" +UI_SUBRULE="----------------------------------------------------------------------" + +ui_rule() { + local color="${1:-$DIM}" + printf "%b%s%b\n" "${color}" "${UI_RULE}" "${NC}" +} + +ui_subrule() { + local color="${1:-$DIM}" + printf "%b%s%b\n" "${color}" "${UI_SUBRULE}" "${NC}" +} + +ui_banner() { + printf '\n' + ui_rule "${MAGENTA}${BOLD}" + printf "%b%s%b\n" "${CYAN}${BOLD}" " ADPanel Initializer " "${NC}" + ui_rule "${MAGENTA}${BOLD}" + printf '\n' +} + +ui_section() { + printf '\n' + ui_subrule "${BLUE}${DIM}" + printf "%b%s%b\n" "${CYAN}${BOLD}" "$1" "${NC}" + ui_subrule "${BLUE}${DIM}" +} + +ui_info() { + printf "%b%s%b\n" "${CYAN}${BOLD}" "$1" "${NC}" +} + +ui_success() { + printf "%b%s%b\n" "${GREEN}${BOLD}" "$1" "${NC}" +} + +ui_warn() { + printf "%b%s%b\n" "${YELLOW}${BOLD}" "$1" "${NC}" +} + +ui_error() { + printf "%b%s%b\n" "${RED}${BOLD}" "$1" "${NC}" +} + +ui_menu_item() { + printf " %b%s%b\n" "${WHITE}${BOLD}" "$1" "${NC}" +} + +ui_kv() { + printf "%b%s%b %s\n" "${CYAN}${BOLD}" "$1" "${NC}" "$2" +} + +ui_prompt() { + printf "%b%s%b" "${MAGENTA}${BOLD}" "$1" "${NC}" +} + +SUDO="" +if [ "$EUID" -ne 0 ]; then + SUDO="sudo" +fi + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +if [ -n "$SCRIPT_DIR" ]; then + cd "$SCRIPT_DIR" || exit 1 +fi + +ui_banner +ui_section "Choose an option:" +ui_menu_item "1) Initialize Panel" +ui_menu_item "2) Change an user password" +ui_menu_item "3) Delete an user" +ui_menu_item "4) Create User" + +CHOICE="${ADPANEL_INIT_CHOICE:-}" +if [ -z "$CHOICE" ] && [ "${1:-}" == "--choice" ]; then + CHOICE="${2:-}" +elif [ -z "$CHOICE" ] && [[ "${1:-}" == --choice=* ]]; then + CHOICE="${1#--choice=}" +fi + +if [ -n "$CHOICE" ]; then + ui_info "Auto-selected option: ${CHOICE}" +else + read -p "$(ui_prompt "Enter choice (1, 2, 3 or 4): ")" CHOICE +fi + +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" +fi + +OS_ID="unknown" +OS_LIKE="" +PKG_MGR="unknown" +INIT_SYSTEM="unknown" +PKG_METADATA_READY="false" +PLATFORM_SUMMARY_SHOWN="false" +RHEL_EXTRA_REPOS_READY="false" + +REDIS_SERVER_CMD="redis-server" +REDIS_CLI_CMD="redis-cli" +NODE_MIN_MAJOR=18 +GO_MIN_VERSION="1.24.0" +GO_INSTALL_VERSION="1.24.11" + +MYSQL_HOST="" +MYSQL_PORT="" +MYSQL_USER="" +MYSQL_PASSWORD="" +MYSQL_DATABASE="" +MYSQL_URL="" + +ADMIN_DEFAULT_AVATAR="https://cdn.jsdelivr.net/gh/antonndev/ADCDn/admin-avatar.webp" +NORMAL_DEFAULT_AVATARS=( + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-1.webp" + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-2.webp" + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-3.webp" +) + +cmd_exists() { command -v "$1" >/dev/null 2>&1; } + +trim_ws() { + printf "%s" "$1" | sed -E 's/^[[:space:]]+//; s/[[:space:]]+$//' +} + +lower_trim() { + trim_ws "$1" | tr '[:upper:]' '[:lower:]' +} + +run_with_retries() { + local attempts="${ADPANEL_RETRY_ATTEMPTS:-3}" + local delay="${ADPANEL_RETRY_DELAY:-5}" + local attempt=1 + local rc=0 + + while [ "$attempt" -le "$attempts" ]; do + if "$@"; then + return 0 + fi + rc=$? + if [ "$attempt" -lt "$attempts" ]; then + ui_warn "Command failed (attempt ${attempt}/${attempts}); retrying in ${delay}s..." + sleep "$delay" + fi + attempt=$((attempt + 1)) + done + + return "$rc" +} + +apt_root() { + $SUDO env \ + DEBIAN_FRONTEND=noninteractive \ + NEEDRESTART_MODE=a \ + APT_LISTCHANGES_FRONTEND=none \ + "$@" +} + +apt_repair_state() { + [ "$PKG_MGR" = "apt" ] || return 0 + apt_root dpkg --configure -a >/dev/null 2>&1 || true + apt_root apt-get -y \ + -o Dpkg::Use-Pty=0 \ + -o DPkg::Lock::Timeout=300 \ + -o Dpkg::Options::=--force-confdef \ + -o Dpkg::Options::=--force-confold \ + -o Acquire::Retries=3 \ + -f install >/dev/null 2>&1 || true +} + +systemd_available() { + cmd_exists systemctl || return 1 + [ -d /run/systemd/system ] || return 1 + systemctl list-units >/dev/null 2>&1 +} + +pick_default_avatar_url() { + local role="${1:-user}" + if [ "$role" = "admin" ]; then + printf "%s" "$ADMIN_DEFAULT_AVATAR" + return 0 + fi + + local index=0 + if [ "${#NORMAL_DEFAULT_AVATARS[@]}" -gt 1 ]; then + index=$((RANDOM % ${#NORMAL_DEFAULT_AVATARS[@]})) + fi + + printf "%s" "${NORMAL_DEFAULT_AVATARS[$index]}" +} + +detect_platform() { + if [ -f /etc/os-release ]; then + . /etc/os-release + OS_ID="${ID:-unknown}" + OS_LIKE="${ID_LIKE:-}" + fi + + if systemd_available; then + INIT_SYSTEM="systemd" + elif cmd_exists rc-service; then + INIT_SYSTEM="openrc" + elif cmd_exists service; then + INIT_SYSTEM="sysv" + else + INIT_SYSTEM="unknown" + fi + + if cmd_exists apt-get; then + PKG_MGR="apt" + elif cmd_exists dnf; then + PKG_MGR="dnf" + elif cmd_exists yum; then + PKG_MGR="yum" + elif cmd_exists apk; then + PKG_MGR="apk" + elif cmd_exists pacman; then + PKG_MGR="pacman" + elif cmd_exists zypper; then + PKG_MGR="zypper" + else + PKG_MGR="unknown" + fi +} + +platform_summary() { + local summary="${OS_ID}" + if [ -n "$OS_LIKE" ]; then + summary="${summary} (like ${OS_LIKE})" + fi + printf "%s" "$summary" +} + +log_platform_summary() { + if [ "$PLATFORM_SUMMARY_SHOWN" = "true" ]; then + return 0 + fi + + ui_info "Detected operating system and package manager:" + ui_kv " OS:" "$(platform_summary)" + ui_kv " Package manager:" "$PKG_MGR" + ui_kv " Init system:" "$INIT_SYSTEM" + PLATFORM_SUMMARY_SHOWN="true" +} + +detect_default_panel_ip() { + local ip="" + + if cmd_exists curl; then + ip=$(curl -4 -s --max-time 3 ifconfig.me 2>/dev/null || true) + if [ -z "$ip" ]; then + ip=$(curl -4 -s --max-time 3 icanhazip.com 2>/dev/null || true) + fi + fi + + if [ -z "$ip" ] && cmd_exists hostname; then + ip=$(hostname -I 2>/dev/null | awk '{print $1}' || true) + fi + + if [ -z "$ip" ] && cmd_exists ip; then + ip=$(ip route get 1.1.1.1 2>/dev/null | awk '/src/ {for (i=1; i<=NF; i++) if ($i=="src") {print $(i+1); exit}}' || true) + fi + + if [ -z "$ip" ] && cmd_exists ifconfig; then + ip=$(ifconfig 2>/dev/null | awk '/inet / && $2 != "127.0.0.1" {print $2; exit}' | sed 's/^addr://' || true) + fi + + if [ -z "$ip" ]; then + ip="127.0.0.1" + fi + + printf "%s" "$ip" +} + +normalize_port() { + local value + value="$(trim_ws "${1:-}")" + local fallback="${2:-}" + if printf "%s" "$value" | grep -qE '^[0-9]+$' && [ "$value" -ge 1 ] 2>/dev/null && [ "$value" -le 65535 ] 2>/dev/null; then + printf "%s" "$value" + else + printf "%s" "$fallback" + fi +} + +build_public_url() { + local scheme="$1" + local host="$2" + local port="$3" + local default_port="80" + local port_segment="" + + if [ "$scheme" = "https" ]; then + default_port="443" + fi + + if [ -n "$port" ] && [ "$port" != "$default_port" ]; then + port_segment=":${port}" + fi + + printf "%s://%s%s" "$scheme" "$host" "$port_segment" +} + +require_sudo_if_needed() { + if [ "$EUID" -ne 0 ] && ! cmd_exists sudo; then + ui_error "sudo is required when running this script as a non-root user." + exit 1 + fi +} + +python_ready() { + cmd_exists python3 || cmd_exists python +} + +ensure_python_binary_alias() { + if cmd_exists python3; then + return 0 + fi + + if ! cmd_exists python; then + return 1 + fi + + local python_bin + python_bin="$(command -v python 2>/dev/null || true)" + if [ -z "$python_bin" ]; then + return 1 + fi + + if [ "$EUID" -eq 0 ] || [ -n "$SUDO" ]; then + $SUDO mkdir -p /usr/local/bin >/dev/null 2>&1 || true + $SUDO ln -sf "$python_bin" /usr/local/bin/python3 >/dev/null 2>&1 || true + hash -r 2>/dev/null || true + fi + + python_ready +} + +ensure_supported_package_manager() { + if [ "$PKG_MGR" != "unknown" ]; then + return 0 + fi + + ui_error "Could not detect a supported package manager on this system." + return 1 +} + +pkg_update() { + case "$PKG_MGR" in + apt) + apt_repair_state + run_with_retries apt_root apt-get -y \ + -o Dpkg::Use-Pty=0 \ + -o DPkg::Lock::Timeout=300 \ + -o Acquire::Retries=3 \ + update + ;; + dnf) + $SUDO dnf -y --setopt=timeout=60 makecache || $SUDO dnf -y --setopt=timeout=60 check-update || true + ;; + yum) + $SUDO yum -y makecache || $SUDO yum -y check-update || true + ;; + apk) + run_with_retries $SUDO apk update + ;; + pacman) + run_with_retries $SUDO pacman -Sy --noconfirm + ;; + zypper) + run_with_retries $SUDO zypper --non-interactive --gpg-auto-import-keys refresh + ;; + *) + return 1 + ;; + esac +} + +ensure_pkg_metadata() { + if [ "$PKG_METADATA_READY" = "true" ]; then + return 0 + fi + + if ! ensure_supported_package_manager; then + return 1 + fi + + ui_info "Refreshing package metadata for ${PKG_MGR}..." + if pkg_update; then + PKG_METADATA_READY="true" + return 0 + fi + + ui_warn "Package metadata refresh failed; continuing with the existing cache." + return 0 +} + +pkg_install() { + case "$PKG_MGR" in + apt) + apt_repair_state + run_with_retries apt_root apt-get install -y \ + -o Dpkg::Use-Pty=0 \ + -o DPkg::Lock::Timeout=300 \ + -o Dpkg::Options::=--force-confdef \ + -o Dpkg::Options::=--force-confold \ + -o Acquire::Retries=3 \ + "$@" + ;; + dnf) + run_with_retries $SUDO dnf install -y --setopt=timeout=60 "$@" + ;; + yum) + run_with_retries $SUDO yum install -y "$@" + ;; + apk) + run_with_retries $SUDO apk add --no-cache "$@" + ;; + pacman) + run_with_retries $SUDO pacman -S --noconfirm --needed "$@" + ;; + zypper) + run_with_retries $SUDO zypper --non-interactive --gpg-auto-import-keys in -l --auto-agree-with-licenses "$@" + ;; + *) + return 1 + ;; + esac +} + +enable_rhel_extra_repos() { + [ "$RHEL_EXTRA_REPOS_READY" = "true" ] && return 0 + RHEL_EXTRA_REPOS_READY="true" + + case "$PKG_MGR" in + dnf|yum) ;; + *) return 0 ;; + esac + + case "$OS_ID" in + fedora) + return 0 + ;; + esac + + ui_info "Checking optional RHEL-compatible repositories..." + if [ "$PKG_MGR" = "dnf" ]; then + $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 + fi + else + $SUDO yum install -y epel-release >/dev/null 2>&1 || true + if cmd_exists yum-config-manager; then + $SUDO yum-config-manager --enable crb >/dev/null 2>&1 || \ + $SUDO yum-config-manager --enable powertools >/dev/null 2>&1 || true + fi + fi + + PKG_METADATA_READY="false" + return 0 +} + +pkg_install_try_sets() { + local set + for set in "$@"; do + if pkg_install $set >/dev/null 2>&1; then + return 0 + fi + done + set="${*: -1}" + pkg_install $set +} + +install_node_runtime_packages() { + case "$PKG_MGR" in + apt|apk|pacman) + pkg_install_try_sets \ + "nodejs npm" + ;; + dnf|yum) + pkg_install_try_sets \ + "nodejs npm" \ + "nodejs nodejs-npm" \ + "nodejs22 npm" \ + "nodejs22 nodejs22-npm" \ + "nodejs22 nodejs-npm" \ + "nodejs20 npm" \ + "nodejs20 nodejs20-npm" \ + "nodejs20 nodejs-npm" \ + "nodejs18 npm" \ + "nodejs18 nodejs18-npm" \ + "nodejs18 nodejs-npm" \ + "nodejs" + ;; + zypper) + pkg_install_try_sets \ + "nodejs npm" \ + "nodejs22 npm22" \ + "nodejs20 npm20" \ + "nodejs18 npm18" \ + "nodejs16 npm16" \ + "nodejs22" \ + "nodejs20" \ + "nodejs18" \ + "nodejs16" \ + "nodejs" + ;; + *) + return 1 + ;; + esac +} + +install_npm_package_only() { + case "$PKG_MGR" in + apt|apk|pacman) + pkg_install npm + ;; + dnf|yum) + pkg_install_try_sets \ + "npm" \ + "nodejs22-npm" \ + "nodejs20-npm" \ + "nodejs18-npm" \ + "nodejs-npm" + ;; + zypper) + pkg_install_try_sets \ + "npm" \ + "npm22" \ + "npm20" \ + "npm18" \ + "npm16" + ;; + *) + return 1 + ;; + esac +} + +ensure_node_binary_alias() { + if cmd_exists node; then + return 0 + fi + + if ! cmd_exists nodejs; then + return 1 + fi + + local nodejs_bin + nodejs_bin="$(command -v nodejs 2>/dev/null || true)" + if [ -z "$nodejs_bin" ]; then + return 1 + fi + + if [ "$EUID" -eq 0 ] || [ -n "$SUDO" ]; then + $SUDO mkdir -p /usr/local/bin >/dev/null 2>&1 || true + $SUDO ln -sf "$nodejs_bin" /usr/local/bin/node >/dev/null 2>&1 || true + hash -r 2>/dev/null || true + fi + + cmd_exists node +} + +node_major_version() { + if ! cmd_exists node; then + echo 0 + return 0 + fi + + node -p "Number(process.versions.node.split('.')[0]) || 0" 2>/dev/null || echo 0 +} + +node_runtime_version_ok() { + local major + major="$(node_major_version)" + [ "$major" -ge "$NODE_MIN_MAJOR" ] 2>/dev/null +} + +node_runtime_ready() { + cmd_exists node && cmd_exists npm && node_runtime_version_ok +} + +download_file() { + local url="$1" + local dest="$2" + if cmd_exists curl; then + run_with_retries curl -fL --connect-timeout 15 --retry 3 --retry-delay 2 "$url" -o "$dest" + elif cmd_exists wget; then + run_with_retries wget -O "$dest" "$url" + else + return 1 + fi +} + +is_musl_libc() { + ldd --version 2>&1 | grep -qi musl +} + +node_official_arch() { + case "$(uname -m)" in + x86_64|amd64) echo "x64" ;; + aarch64|arm64) echo "arm64" ;; + armv7l) echo "armv7l" ;; + ppc64le) echo "ppc64le" ;; + s390x) echo "s390x" ;; + *) + return 1 + ;; + esac +} + +install_official_node_runtime() { + local arch="" + local tmpdir="" + local sums_url="https://nodejs.org/dist/latest-v20.x/SHASUMS256.txt" + local tarball="" + local expected="" + local actual="" + local node_dir="" + + arch="$(node_official_arch)" || { + ui_warn "Official Node.js binary fallback does not support CPU architecture: $(uname -m)." + return 1 + } + + if is_musl_libc; then + ui_warn "Detected musl libc; using distribution Node.js packages instead of the official glibc Node.js binary." + return 1 + fi + + if ! cmd_exists tar; then + ui_warn "tar is required for the official Node.js binary fallback." + return 1 + fi + + tmpdir="$(mktemp -d /tmp/adpanel-node.XXXXXX 2>/dev/null || mktemp -d)" + if [ -z "$tmpdir" ]; then + return 1 + fi + + ui_info "Trying official Node.js 20 LTS binary fallback..." + if ! download_file "$sums_url" "${tmpdir}/SHASUMS256.txt"; then + rm -rf "$tmpdir" >/dev/null 2>&1 || true + return 1 + fi + + tarball="$(awk -v suffix="linux-${arch}.tar.xz" '$2 ~ suffix "$" {print $2; exit}' "${tmpdir}/SHASUMS256.txt")" + if [ -z "$tarball" ]; then + tarball="$(awk -v suffix="linux-${arch}.tar.gz" '$2 ~ suffix "$" {print $2; exit}' "${tmpdir}/SHASUMS256.txt")" + fi + if [ -z "$tarball" ]; then + rm -rf "$tmpdir" >/dev/null 2>&1 || true + return 1 + fi + + if ! download_file "https://nodejs.org/dist/latest-v20.x/${tarball}" "${tmpdir}/${tarball}"; then + rm -rf "$tmpdir" >/dev/null 2>&1 || true + return 1 + fi + + expected="$(awk -v file="$tarball" '$2 == file {print $1; exit}' "${tmpdir}/SHASUMS256.txt")" + if [ -n "$expected" ] && cmd_exists sha256sum; then + actual="$(sha256sum "${tmpdir}/${tarball}" | awk '{print $1}')" + if [ "$expected" != "$actual" ]; then + ui_warn "Node.js binary checksum mismatch." + rm -rf "$tmpdir" >/dev/null 2>&1 || true + return 1 + fi + fi + + node_dir="${tarball%.tar.xz}" + node_dir="${node_dir%.tar.gz}" + + $SUDO mkdir -p /usr/local/lib/nodejs + case "$tarball" in + *.tar.xz) $SUDO tar -C /usr/local/lib/nodejs -xJf "${tmpdir}/${tarball}" ;; + *.tar.gz) $SUDO tar -C /usr/local/lib/nodejs -xzf "${tmpdir}/${tarball}" ;; + *) + rm -rf "$tmpdir" >/dev/null 2>&1 || true + return 1 + ;; + esac + + $SUDO ln -sf "/usr/local/lib/nodejs/${node_dir}/bin/node" /usr/local/bin/node + $SUDO ln -sf "/usr/local/lib/nodejs/${node_dir}/bin/npm" /usr/local/bin/npm + $SUDO ln -sf "/usr/local/lib/nodejs/${node_dir}/bin/npx" /usr/local/bin/npx + if [ -x "/usr/local/lib/nodejs/${node_dir}/bin/corepack" ]; then + $SUDO ln -sf "/usr/local/lib/nodejs/${node_dir}/bin/corepack" /usr/local/bin/corepack + fi + + rm -rf "$tmpdir" >/dev/null 2>&1 || true + hash -r 2>/dev/null || true + node_runtime_ready +} + +install_modern_node_runtime() { + case "$PKG_MGR" in + apt) + if cmd_exists curl; then + curl -fsSL https://deb.nodesource.com/setup_20.x | $SUDO bash - || return 1 + PKG_METADATA_READY="false" + ensure_pkg_metadata >/dev/null 2>&1 || true + pkg_install nodejs + return $? + fi + ;; + dnf|yum) + if cmd_exists curl; then + curl -fsSL https://rpm.nodesource.com/setup_20.x | $SUDO bash - || return 1 + PKG_METADATA_READY="false" + ensure_pkg_metadata >/dev/null 2>&1 || true + pkg_install nodejs + return $? + fi + ;; + zypper) + pkg_install_try_sets \ + "nodejs22 npm22" \ + "nodejs20 npm20" \ + "nodejs18 npm18" \ + "nodejs22" \ + "nodejs20" \ + "nodejs18" + return $? + ;; + apk|pacman) + install_node_runtime_packages + return $? + ;; + esac + + return 1 +} + +compiler_ready() { + cmd_exists gcc || cmd_exists cc || cmd_exists clang +} + +cpp_compiler_ready() { + cmd_exists g++ || cmd_exists c++ || cmd_exists clang++ +} + +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 + need_base="true" + fi + if ! compiler_ready || ! cpp_compiler_ready; then + need_base="true" + fi + + if [ "$need_base" != "true" ]; then + ui_success "Base system packages are already installed." + return 0 + fi + + if ! ensure_supported_package_manager; then + return 1 + fi + + log_platform_summary + ui_info "Installing base system packages for ${OS_ID}..." + ensure_pkg_metadata >/dev/null 2>&1 || true + + case "$PKG_MGR" in + apt) + pkg_install ca-certificates curl openssl tar xz-utils python3 make g++ + ;; + dnf|yum) + pkg_install ca-certificates curl openssl tar xz python3 make gcc gcc-c++ + ;; + apk) + pkg_install ca-certificates curl openssl tar xz python3 make g++ + ;; + pacman) + pkg_install ca-certificates curl openssl tar xz python make gcc + ;; + zypper) + pkg_install ca-certificates curl openssl tar xz python3 make gcc-c++ + ;; + *) + ui_error "Unsupported package manager for base system packages." + return 1 + ;; + esac + + if cmd_exists update-ca-certificates; then + $SUDO update-ca-certificates >/dev/null 2>&1 || true + 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 + ui_error "Failed to install one or more required base system packages." + return 1 + fi + if ! compiler_ready || ! cpp_compiler_ready; then + ui_error "A C/C++ compiler is still missing after package installation." + return 1 + fi + + ui_success "Base system packages installed successfully." + return 0 +} + +ensure_node_runtime() { + if ! cmd_exists node; then + ensure_node_binary_alias >/dev/null 2>&1 || true + fi + + if node_runtime_ready; then + ui_success "Node.js and npm are already installed." + ui_kv " node:" "$(node -v 2>/dev/null)" + ui_kv " npm:" "$(npm -v 2>/dev/null)" + return 0 + fi + + if cmd_exists node && ! node_runtime_version_ok; then + ui_warn "Installed Node.js is too old ($(node -v 2>/dev/null)); Node.js ${NODE_MIN_MAJOR}+ is required." + fi + + if ! ensure_supported_package_manager; then + return 1 + fi + + log_platform_summary + ui_info "Installing Node.js and npm..." + ensure_pkg_metadata >/dev/null 2>&1 || true + + if { ! cmd_exists node || ! cmd_exists npm || ! node_runtime_version_ok; } && install_modern_node_runtime; then + ensure_node_binary_alias >/dev/null 2>&1 || true + fi + + if { ! cmd_exists node || ! cmd_exists npm || ! node_runtime_version_ok; } && install_official_node_runtime; then + ensure_node_binary_alias >/dev/null 2>&1 || true + fi + + if { ! cmd_exists node || ! cmd_exists npm; } && ! install_node_runtime_packages; then + ui_warn "Combined Node.js/npm package installation failed; trying a smaller npm-only fallback if possible..." + fi + + if ! cmd_exists npm && ! install_npm_package_only; then + ui_warn "Separate npm package installation failed; checking if npm shipped with Node.js..." + fi + + ensure_node_binary_alias >/dev/null 2>&1 || true + + if { ! cmd_exists node || ! cmd_exists npm || ! node_runtime_version_ok; } && install_modern_node_runtime; then + ensure_node_binary_alias >/dev/null 2>&1 || true + fi + + if { ! cmd_exists node || ! cmd_exists npm || ! node_runtime_version_ok; } && install_official_node_runtime; then + ensure_node_binary_alias >/dev/null 2>&1 || true + fi + + if ! cmd_exists node || ! cmd_exists npm; then + ui_error "Node.js and npm are required but could not be installed automatically." + return 1 + fi + + if ! node_runtime_version_ok; then + ui_error "Node.js ${NODE_MIN_MAJOR}+ is required, but detected $(node -v 2>/dev/null)." + ui_warn "Install Node.js 20 LTS manually and re-run initialization." + return 1 + fi + + ui_success "Node.js and npm installed successfully." + ui_kv " node:" "$(node -v 2>/dev/null)" + ui_kv " npm:" "$(npm -v 2>/dev/null)" + return 0 +} + +version_at_least() { + local current="$1" + local required="$2" + local c_major=0 c_minor=0 c_patch=0 r_major=0 r_minor=0 r_patch=0 + + current="${current#v}" + current="${current#go}" + required="${required#v}" + required="${required#go}" + current="${current%%[-+~]*}" + required="${required%%[-+~]*}" + + IFS=. read -r c_major c_minor c_patch </dev/null && return 0 + [ "$c_major" -lt "$r_major" ] 2>/dev/null && return 1 + [ "$c_minor" -gt "$r_minor" ] 2>/dev/null && return 0 + [ "$c_minor" -lt "$r_minor" ] 2>/dev/null && return 1 + [ "$c_patch" -ge "$r_patch" ] 2>/dev/null +} + +go_version_value() { + local current="" + if ! cmd_exists go; then + echo "" + return 0 + fi + + current="$(go env GOVERSION 2>/dev/null || true)" + if [ -z "$current" ]; then + current="$(go version 2>/dev/null | awk '{print $3}' || true)" + fi + current="${current#go}" + echo "$current" +} + +go_runtime_ready() { + local current + current="$(go_version_value)" + [ -n "$current" ] && version_at_least "$current" "$GO_MIN_VERSION" +} + +go_official_arch() { + case "$(uname -m)" in + x86_64|amd64) echo "amd64" ;; + aarch64|arm64) echo "arm64" ;; + armv6l|armv7l) echo "armv6l" ;; + ppc64le) echo "ppc64le" ;; + s390x) echo "s390x" ;; + *) + return 1 + ;; + esac +} + +install_go_runtime_packages() { + case "$PKG_MGR" in + apt) + pkg_install_try_sets "golang-go" "golang" "go" + ;; + dnf|yum) + pkg_install_try_sets "golang" "go" + ;; + apk|pacman|zypper) + pkg_install_try_sets "go" "golang" + ;; + *) + return 1 + ;; + esac +} + +install_official_go_runtime() { + local arch="" + local tarball="" + local tmpdir="" + local url="" + local alt_url="" + + arch="$(go_official_arch)" || { + ui_warn "Official Go fallback does not support CPU architecture: $(uname -m)." + return 1 + } + + tarball="go${GO_INSTALL_VERSION}.linux-${arch}.tar.gz" + url="https://go.dev/dl/${tarball}" + alt_url="https://dl.google.com/go/${tarball}" + tmpdir="$(mktemp -d /tmp/adpanel-go.XXXXXX 2>/dev/null || mktemp -d)" + if [ -z "$tmpdir" ]; then + return 1 + fi + + ui_info "Installing official Go ${GO_INSTALL_VERSION} toolchain..." + if ! download_file "$url" "${tmpdir}/${tarball}"; then + if ! download_file "$alt_url" "${tmpdir}/${tarball}"; then + rm -rf "$tmpdir" >/dev/null 2>&1 || true + return 1 + fi + fi + + $SUDO rm -rf /usr/local/go + if ! $SUDO tar -C /usr/local -xzf "${tmpdir}/${tarball}"; then + rm -rf "$tmpdir" >/dev/null 2>&1 || true + return 1 + fi + + $SUDO ln -sf /usr/local/go/bin/go /usr/local/bin/go + $SUDO ln -sf /usr/local/go/bin/gofmt /usr/local/bin/gofmt + rm -rf "$tmpdir" >/dev/null 2>&1 || true + hash -r 2>/dev/null || true + go_runtime_ready +} + +ensure_go_runtime() { + if go_runtime_ready; then + ui_success "Go runtime is already installed." + ui_kv " go:" "$(go version 2>/dev/null)" + return 0 + fi + + if ! ensure_supported_package_manager; then + return 1 + fi + + log_platform_summary + ui_info "Installing Go runtime for ADPanel SSH terminal..." + ensure_pkg_metadata >/dev/null 2>&1 || true + + install_go_runtime_packages >/dev/null 2>&1 || true + if ! go_runtime_ready; then + install_official_go_runtime || true + fi + + if go_runtime_ready; then + ui_success "Go runtime installed successfully." + ui_kv " go:" "$(go version 2>/dev/null)" + return 0 + fi + + ui_warn "Go ${GO_MIN_VERSION}+ could not be installed automatically; SSH terminal service will be skipped." + return 1 +} + +project_extensions_ready() { + [ -d "${SCRIPT_DIR}/node_modules" ] || return 1 + + npm ls --omit=dev --depth=0 >/dev/null 2>&1 +} + +install_project_extensions() { + if ! ensure_node_runtime; then + return 1 + fi + + if project_extensions_ready; then + ui_success "Project extensions are already installed." + return 0 + fi + + ui_info "Installing extensions..." + if ! npm install --omit=dev --no-fund --no-audit; then + ui_error "npm install failed." + return 1 + fi + + if ! project_extensions_ready; then + ui_error "Extensions were installed, but required Node modules are still missing." + return 1 + fi + + ui_success "Project extensions installed successfully." + return 0 +} + +ensure_node_prerequisites() { + log_platform_summary + + if ! install_base_system_packages; then + return 1 + fi + + if ! ensure_node_runtime; then + return 1 + fi + + install_project_extensions +} + +service_enable() { + local svc="$1" + case "$INIT_SYSTEM" in + systemd) + $SUDO systemctl enable "$svc" >/dev/null 2>&1 || true + ;; + openrc) + $SUDO rc-update add "$svc" default >/dev/null 2>&1 || true + ;; + sysv) + if cmd_exists update-rc.d; then + $SUDO update-rc.d "$svc" defaults >/dev/null 2>&1 || true + elif cmd_exists chkconfig; then + $SUDO chkconfig "$svc" on >/dev/null 2>&1 || true + fi + ;; + esac +} + +service_start() { + local svc="$1" + case "$INIT_SYSTEM" in + systemd) + $SUDO systemctl start "$svc" >/dev/null 2>&1 || true + ;; + openrc) + $SUDO rc-service "$svc" start >/dev/null 2>&1 || true + ;; + sysv) + $SUDO service "$svc" start >/dev/null 2>&1 || true + ;; + esac +} + +service_stop() { + local svc="$1" + case "$INIT_SYSTEM" in + systemd) + $SUDO systemctl stop "$svc" >/dev/null 2>&1 || true + ;; + openrc) + $SUDO rc-service "$svc" stop >/dev/null 2>&1 || true + ;; + sysv) + $SUDO service "$svc" stop >/dev/null 2>&1 || true + ;; + esac +} + +service_restart() { + local svc="$1" + case "$INIT_SYSTEM" in + systemd) + $SUDO systemctl restart "$svc" >/dev/null 2>&1 || true + ;; + openrc) + $SUDO rc-service "$svc" restart >/dev/null 2>&1 || true + ;; + sysv) + $SUDO service "$svc" restart >/dev/null 2>&1 || true + ;; + esac +} + +service_reload() { + local svc="$1" + case "$INIT_SYSTEM" in + systemd) + $SUDO systemctl reload "$svc" >/dev/null 2>&1 || true + ;; + openrc) + $SUDO rc-service "$svc" reload >/dev/null 2>&1 || service_restart "$svc" + ;; + sysv) + $SUDO service "$svc" reload >/dev/null 2>&1 || service_restart "$svc" + ;; + esac +} + +detect_redis_commands() { + if cmd_exists redis-server; then + REDIS_SERVER_CMD="redis-server" + elif cmd_exists valkey-server; then + REDIS_SERVER_CMD="valkey-server" + elif cmd_exists valkey; then + REDIS_SERVER_CMD="valkey" + fi + + if cmd_exists redis-cli; then + REDIS_CLI_CMD="redis-cli" + elif cmd_exists valkey-cli; then + REDIS_CLI_CMD="valkey-cli" + elif cmd_exists valkey; then + REDIS_CLI_CMD="redis-cli" + fi +} + +detect_platform +require_sudo_if_needed +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 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" + local ecosystem_template_file="${panel_root}/ecosystem.config.template.js" + local ecosystem_file="${panel_root}/ecosystem.config.js" + local prep_script="${panel_root}/start.sh" + local pm2_runtime_bin="${panel_root}/node_modules/.bin/pm2-runtime" + local pm2_home_dir="${panel_root}/.pm2" + local exec_start_pre_line="" + local service_user="root" + local service_group="root" + + if ! systemd_available; then + ui_warn "systemd is not available; skipping ${service_name} systemd service setup." + return 1 + fi + + if [ ! -f "$runtime_script" ] || [ ! -f "$monitor_script" ] || [ ! -f "$ecosystem_generator_script" ]; then + ui_error "Required PM2 runtime scripts are missing in ${panel_root}/scripts." + return 1 + fi + + if [ ! -f "$ecosystem_template_file" ]; then + ui_error "Expected ecosystem template not found at ${ecosystem_template_file}." + return 1 + fi + + if [ ! -x "$pm2_runtime_bin" ] && ! cmd_exists pm2-runtime; then + ui_error "pm2-runtime not found. Ensure dependencies are installed with npm install." + return 1 + fi + + $SUDO chmod +x "$runtime_script" "$monitor_script" "$ecosystem_generator_script" >/dev/null 2>&1 || true + + if [ ! -f "$prep_script" ]; then + ui_warn "Expected preparation script not found at ${prep_script}." + ui_warn "The service will run as root without start.sh integration." + else + if ! $SUDO bash "$prep_script"; then + ui_error "Failed to run start.sh preparation before creating the service." + return 1 + fi + + if id -u adpanel >/dev/null 2>&1; then + service_user="adpanel" + service_group="adpanel" + exec_start_pre_line="ExecStartPre=/bin/bash ${prep_script}" + else + ui_warn "start.sh completed but user 'adpanel' does not exist; the service will run as root." + fi + fi + + $SUDO mkdir -p "$pm2_home_dir" >/dev/null 2>&1 || true + if id -u "$service_user" >/dev/null 2>&1; then + $SUDO chown -R "$service_user":"$service_group" "$pm2_home_dir" >/dev/null 2>&1 || true + fi + + if [ "$service_user" = "root" ]; then + if ! "$ecosystem_generator_script" --panel-dir "$panel_root" >/dev/null; then + ui_error "Failed to generate PM2 ecosystem configuration." + return 1 + fi + else + if [ "$EUID" -eq 0 ]; then + if cmd_exists runuser; then + if ! runuser -u "$service_user" -- "$ecosystem_generator_script" --panel-dir "$panel_root" >/dev/null; then + ui_error "Failed to generate PM2 ecosystem configuration for user ${service_user}." + return 1 + fi + else + if ! su -s /bin/bash -c "\"$ecosystem_generator_script\" --panel-dir \"$panel_root\" >/dev/null" "$service_user"; then + ui_error "Failed to generate PM2 ecosystem configuration for user ${service_user}." + return 1 + fi + fi + else + if ! $SUDO -u "$service_user" "$ecosystem_generator_script" --panel-dir "$panel_root" >/dev/null; then + ui_error "Failed to generate PM2 ecosystem configuration for user ${service_user}." + return 1 + fi + fi + fi + + cat </dev/null +[Unit] +Description=ADPanel PM2 Cluster Service +After=network.target + +[Service] +Type=simple +PermissionsStartOnly=true +WorkingDirectory=${panel_root} +User=${service_user} +Group=${service_group} +${exec_start_pre_line} +Environment=NODE_ENV=production +Environment=PANEL_DIR=${panel_root} +Environment=PM2_MONITOR_INTERVAL=300 +Environment=PM2_HOME=${pm2_home_dir} +ExecStart=${runtime_script} +Restart=always +RestartSec=10 +KillMode=mixed +KillSignal=SIGTERM +TimeoutStopSec=8 +LimitNOFILE=1048576 + +[Install] +WantedBy=multi-user.target +EOF + + if ! $SUDO systemctl daemon-reload; then + ui_error "Failed to reload systemd daemon after writing ${service_file}." + return 1 + fi + + if ! $SUDO systemctl enable "$service_name"; then + ui_error "Failed to enable ${service_name}.service." + return 1 + fi + + if $SUDO systemctl is-active --quiet "$service_name"; then + if ! $SUDO systemctl restart "$service_name"; then + ui_error "Failed to restart ${service_name}.service." + return 1 + fi + else + if ! $SUDO systemctl start "$service_name"; then + ui_error "Failed to start ${service_name}.service." + return 1 + fi + fi + + if $SUDO systemctl is-active --quiet "$service_name"; then + ui_success "${service_name}.service is active and enabled." + if [ -f "$ecosystem_file" ]; then + ui_info "PM2 ecosystem generated at: ${ecosystem_file}" + fi + else + ui_warn "${service_name}.service was created and enabled but is not active." + ui_warn "Check status with: systemctl status ${service_name}" + fi + + return 0 +} + +setup_adpanel_openrc_service() { + local service_name="adpanel" + local service_file="/etc/init.d/${service_name}" + local panel_root="$SCRIPT_DIR" + 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" + local pm2_runtime_bin="${panel_root}/node_modules/.bin/pm2-runtime" + local pm2_home_dir="${panel_root}/.pm2" + local prep_script="${panel_root}/start.sh" + local service_user="root" + local service_group="root" + + if ! cmd_exists rc-service || ! cmd_exists rc-update; then + ui_warn "OpenRC tools not found; skipping ${service_name} OpenRC setup." + return 1 + fi + + if [ ! -f "$runtime_script" ] || [ ! -f "$monitor_script" ] || [ ! -f "$ecosystem_generator_script" ]; then + ui_error "Required PM2 runtime scripts are missing in ${panel_root}/scripts." + return 1 + fi + + if [ ! -x "$pm2_runtime_bin" ] && ! cmd_exists pm2-runtime; then + ui_error "pm2-runtime not found. Ensure dependencies are installed with npm install." + return 1 + fi + + $SUDO chmod +x "$runtime_script" "$monitor_script" "$ecosystem_generator_script" >/dev/null 2>&1 || true + + if [ -f "$prep_script" ]; then + if ! $SUDO bash "$prep_script"; then + ui_warn "start.sh preparation failed; continuing OpenRC service setup as root." + fi + fi + + if id -u adpanel >/dev/null 2>&1; then + service_user="adpanel" + service_group="adpanel" + fi + + $SUDO mkdir -p "$pm2_home_dir" /var/log >/dev/null 2>&1 || true + if id -u "$service_user" >/dev/null 2>&1; then + $SUDO chown -R "$service_user":"$service_group" "$pm2_home_dir" >/dev/null 2>&1 || true + fi + + cat </dev/null +#!/sbin/openrc-run +name="ADPanel" +description="ADPanel PM2 Cluster Service" +directory="${panel_root}" +command="${runtime_script}" +command_user="${service_user}:${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 NODE_ENV="production" +export PANEL_DIR="${panel_root}" +export PM2_MONITOR_INTERVAL="300" +export PM2_HOME="${pm2_home_dir}" + +depend() { + need net + after mysql mariadb redis redis-server valkey nginx +} +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 + 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_sysv_service() { + local service_name="adpanel" + local service_file="/etc/init.d/${service_name}" + local panel_root="$SCRIPT_DIR" + 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" + local pm2_runtime_bin="${panel_root}/node_modules/.bin/pm2-runtime" + local pm2_home_dir="${panel_root}/.pm2" + local prep_script="${panel_root}/start.sh" + local service_user="root" + local service_group="root" + + if ! cmd_exists service; then + ui_warn "SysV service command not found; skipping ${service_name} SysV setup." + return 1 + fi + + if [ ! -f "$runtime_script" ] || [ ! -f "$monitor_script" ] || [ ! -f "$ecosystem_generator_script" ]; then + ui_error "Required PM2 runtime scripts are missing in ${panel_root}/scripts." + return 1 + fi + + if [ ! -x "$pm2_runtime_bin" ] && ! cmd_exists pm2-runtime; then + ui_error "pm2-runtime not found. Ensure dependencies are installed with npm install." + return 1 + fi + + $SUDO chmod +x "$runtime_script" "$monitor_script" "$ecosystem_generator_script" >/dev/null 2>&1 || true + + if [ -f "$prep_script" ]; then + if ! $SUDO bash "$prep_script"; then + ui_warn "start.sh preparation failed; continuing SysV service setup as root." + fi + fi + + if id -u adpanel >/dev/null 2>&1; then + service_user="adpanel" + service_group="adpanel" + fi + + $SUDO mkdir -p "$pm2_home_dir" /var/log /var/run >/dev/null 2>&1 || true + if id -u "$service_user" >/dev/null 2>&1; then + $SUDO chown -R "$service_user":"$service_group" "$pm2_home_dir" >/dev/null 2>&1 || true + 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 PM2 Cluster Service +### END INIT INFO + +NAME="${service_name}" +PANEL_DIR="${panel_root}" +DAEMON="${runtime_script}" +PIDFILE="/var/run/${service_name}.pid" +LOGFILE="/var/log/${service_name}.log" +SERVICE_USER="${service_user}" +PM2_HOME="${pm2_home_dir}" + +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 "NODE_ENV=production PANEL_DIR='\$PANEL_DIR' PM2_MONITOR_INTERVAL=300 PM2_HOME='\$PM2_HOME' 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 "NODE_ENV=production PANEL_DIR='\$PANEL_DIR' PM2_MONITOR_INTERVAL=300 PM2_HOME='\$PM2_HOME' 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' && NODE_ENV=production PANEL_DIR='\$PANEL_DIR' PM2_MONITOR_INTERVAL=300 PM2_HOME='\$PM2_HOME' nohup '\$DAEMON' >>'\$LOGFILE' 2>&1 & echo \\\$! > '\$PIDFILE'" "\$SERVICE_USER" + else + (cd "\$PANEL_DIR" && NODE_ENV=production PANEL_DIR="\$PANEL_DIR" PM2_MONITOR_INTERVAL=300 PM2_HOME="\$PM2_HOME" 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 + 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_service() { + case "$INIT_SYSTEM" in + systemd) + setup_adpanel_systemd_service + ;; + openrc) + setup_adpanel_openrc_service + ;; + sysv) + setup_adpanel_sysv_service + ;; + *) + ui_error "No supported init system detected. Start manually with: npm start" + return 1 + ;; + esac +} + +print_adpanel_service_commands() { + case "$INIT_SYSTEM" in + systemd) + ui_success "You can now manage ADPanel with systemd:" + ui_kv " Start:" "systemctl start adpanel" + ui_kv " Stop:" "systemctl stop adpanel" + ui_kv " Restart:" "systemctl restart adpanel" + ui_kv " Status:" "systemctl status adpanel" + ;; + openrc) + ui_success "You can now manage ADPanel with OpenRC:" + ui_kv " Start:" "rc-service adpanel start" + ui_kv " Stop:" "rc-service adpanel stop" + ui_kv " Restart:" "rc-service adpanel restart" + ui_kv " Status:" "rc-service adpanel status" + ;; + sysv) + ui_success "You can now manage ADPanel with SysV init:" + ui_kv " Start:" "service adpanel start" + ui_kv " Stop:" "service adpanel stop" + ui_kv " Restart:" "service adpanel restart" + ui_kv " Status:" "service adpanel status" + ;; + esac +} + +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 sshterm_main="${panel_root}/cmd/sshterm/main.go" + local go_cache_dir="${panel_root}/.cache-go" + local go_modcache_dir="${panel_root}/.gomodcache" + local service_user="root" + local service_group="root" + + if ! systemd_available; then + ui_warn "systemd is not available; skipping ${service_name} systemd service setup." + return 1 + fi + + if ! cmd_exists go; then + ui_warn "Go runtime not found; skipping ${service_name} service 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 + + 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 + + cat </dev/null +[Unit] +Description=ADPanel SSH Terminal Service +After=network.target + +[Service] +Type=simple +WorkingDirectory=${panel_root} +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=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' +NoNewPrivileges=true +PrivateTmp=true +ProtectKernelTunables=true +ProtectKernelModules=true +ProtectControlGroups=true +Restart=always +RestartSec=3 +LimitNOFILE=65535 + +[Install] +WantedBy=multi-user.target +EOF + + if ! $SUDO systemctl daemon-reload; then + ui_warn "Failed to reload systemd daemon for ${service_name}." + return 1 + fi + + $SUDO systemctl enable "$service_name" >/dev/null 2>&1 || true + if $SUDO systemctl is-active --quiet "$service_name"; then + $SUDO systemctl restart "$service_name" >/dev/null 2>&1 || true + else + $SUDO systemctl start "$service_name" >/dev/null 2>&1 || true + fi + + if $SUDO systemctl is-active --quiet "$service_name"; then + 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}" + fi + + return 0 +} + +install_certbot() { + ui_info "Installing certbot..." + if command -v certbot >/dev/null 2>&1; then + ui_success "certbot is already installed." + return 0 + fi + + if ! ensure_supported_package_manager; then + ui_error "Could not detect a supported package manager to install certbot." + ui_warn "Please install certbot manually and re-run initialization." + return 1 + fi + + enable_rhel_extra_repos + ensure_pkg_metadata >/dev/null 2>&1 || true + + if ! pkg_install_try_sets "certbot" "python3-certbot"; then + ui_error "certbot installation failed." + return 1 + fi + + if command -v certbot >/dev/null 2>&1; then + ui_success "certbot installed successfully." + return 0 + fi + + ui_error "certbot installation failed." + return 1 +} + +ensure_certbot_nginx_plugin() { + if command -v certbot >/dev/null 2>&1; then + if certbot plugins 2>/dev/null | grep -qi "nginx"; then + ui_success "certbot nginx plugin is already available." + return 0 + fi + fi + + ui_info "Installing certbot nginx plugin..." + if ! ensure_supported_package_manager; then + ui_warn "No supported package manager found for certbot nginx plugin." + return 1 + fi + + enable_rhel_extra_repos + ensure_pkg_metadata >/dev/null 2>&1 || true + + if ! pkg_install_try_sets \ + "python3-certbot-nginx" \ + "certbot-nginx" \ + "python-certbot-nginx" \ + "py3-certbot-nginx"; then + ui_warn "Could not install certbot nginx plugin automatically." + return 1 + fi + + if command -v certbot >/dev/null 2>&1 && certbot plugins 2>/dev/null | grep -qi "nginx"; then + ui_success "certbot nginx plugin installed." + return 0 + fi + + ui_warn "certbot nginx plugin might not be available on this system." + return 1 +} + +install_nginx() { + ui_info "Installing nginx..." + if command -v nginx >/dev/null 2>&1; then + ui_success "nginx is already installed." + ensure_certbot_nginx_plugin >/dev/null 2>&1 || true + return 0 + fi + + if ! ensure_supported_package_manager; then + ui_error "Could not detect a supported package manager to install nginx." + ui_warn "Please install nginx manually and re-run initialization." + return 1 + fi + + enable_rhel_extra_repos + ensure_pkg_metadata >/dev/null 2>&1 || true + if ! pkg_install nginx; then + ui_error "nginx installation failed." + return 1 + fi + + ensure_certbot_nginx_plugin >/dev/null 2>&1 || true + if command -v nginx >/dev/null 2>&1; then + ui_success "nginx installed successfully." + return 0 + fi + + ui_error "nginx installation failed." + return 1 +} + +install_optional_nginx_brotli_module() { + if ! ensure_supported_package_manager; then + return 1 + fi + + ensure_pkg_metadata >/dev/null 2>&1 || true + + case "$PKG_MGR" in + apt) + pkg_install_try_sets \ + "libnginx-mod-brotli" \ + "nginx-mod-http-brotli" + ;; + dnf|yum) + pkg_install_try_sets \ + "nginx-mod-brotli" \ + "nginx-module-brotli" \ + "nginx-mod-http-brotli" + ;; + zypper) + pkg_install_try_sets \ + "nginx-module-brotli" \ + "nginx-mod-brotli" + ;; + pacman) + pkg_install_try_sets \ + "nginx-mod-brotli" \ + "nginx-mainline-mod-brotli" + ;; + apk) + pkg_install_try_sets \ + "nginx-mod-http-brotli" \ + "nginx-brotli" + ;; + *) + return 1 + ;; + esac +} + +is_redis_installed() { + command -v redis-server >/dev/null 2>&1 || command -v redis-cli >/dev/null 2>&1 || \ + command -v valkey-server >/dev/null 2>&1 || command -v valkey-cli >/dev/null 2>&1 +} + + +is_mysql_installed() { + command -v mysql >/dev/null 2>&1 || command -v mariadb >/dev/null 2>&1 || \ + command -v mysqld >/dev/null 2>&1 || command -v mariadbd >/dev/null 2>&1 +} + +mysql_detect_cli() { + if cmd_exists mysql; then + echo "mysql" + elif cmd_exists mariadb; then + echo "mariadb" + else + echo "mysql" + fi +} + +mysql_detect_service_candidates() { + echo "mysql" + echo "mysqld" + echo "mariadb" + echo "mariadb-server" +} + +mysql_find_service() { + local svc="" + if [ "$INIT_SYSTEM" == "systemd" ]; then + local cand + while read -r cand; do + if systemctl list-unit-files 2>/dev/null | grep -qE "^${cand}\.service"; then + svc="$cand" + break + fi + done < <(mysql_detect_service_candidates) + echo "$svc" + return 0 + fi + + local cand + while read -r cand; do + if [ -x "/etc/init.d/${cand}" ] || [ -f "/etc/init.d/${cand}" ]; then + svc="$cand" + break + fi + done < <(mysql_detect_service_candidates) + + if [ -n "$svc" ]; then + echo "$svc" + else + echo "mariadb" + fi + return 0 +} + +mysql_init_datadir_if_needed() { + if [ -d /var/lib/mysql/mysql ]; then + return 0 + fi + + if cmd_exists rc-service && cmd_exists service; then + : + fi + + if cmd_exists mariadb-install-db; then + $SUDO mariadb-install-db --user=mysql --datadir=/var/lib/mysql >/dev/null 2>&1 || true + return 0 + fi + + if cmd_exists mysql_install_db; then + $SUDO mysql_install_db --user=mysql --datadir=/var/lib/mysql >/dev/null 2>&1 || true + return 0 + fi + + if cmd_exists rc-service; then + $SUDO rc-service mariadb setup >/dev/null 2>&1 || true + fi + + return 0 +} + +wait_for_mysql_ready() { + local retries=30 + local delay=2 + local cli + cli="$(mysql_detect_cli)" + + if ! cmd_exists "$cli"; then + return 1 + fi + + local i + for i in $(seq 1 "$retries"); do + if $SUDO "$cli" -e "SELECT 1;" >/dev/null 2>&1; then + return 0 + fi + sleep "$delay" + done + + return 1 +} + +install_mysql() { + if is_mysql_installed; then + local existing_svc + existing_svc="$(mysql_find_service)" + if [ -n "$existing_svc" ]; then + service_enable "$existing_svc" + service_start "$existing_svc" + fi + if ! wait_for_mysql_ready; then + ui_warn "MySQL/MariaDB is installed but did not respond yet; setup may need the root password prompt." + fi + ui_success "MySQL/MariaDB is already installed." + return 0 + fi + + ui_info "Installing MySQL/MariaDB..." + if ! ensure_supported_package_manager; then + ui_error "Could not detect a supported package manager to install MySQL/MariaDB." + return 1 + fi + + enable_rhel_extra_repos + ensure_pkg_metadata >/dev/null 2>&1 || true + + case "$PKG_MGR" in + apt) + pkg_install_try_sets \ + "mysql-server mysql-client" \ + "default-mysql-server default-mysql-client" \ + "mariadb-server mariadb-client" || return 1 + ;; + dnf|yum) + pkg_install_try_sets \ + "mariadb-server mariadb" \ + "mysql-server mysql" \ + "community-mysql-server community-mysql" || return 1 + ;; + zypper) + pkg_install_try_sets \ + "mariadb mariadb-client" \ + "mysql mysql-client" || return 1 + ;; + pacman) + pkg_install_try_sets \ + "mariadb" || return 1 + ;; + apk) + pkg_install_try_sets \ + "mariadb mariadb-client" || return 1 + ;; + *) + ui_error "Unsupported package manager for MySQL/MariaDB install." + return 1 + ;; + esac + + mysql_init_datadir_if_needed + + local svc + svc="$(mysql_find_service)" + if [ -n "$svc" ]; then + service_enable "$svc" + service_start "$svc" + else + service_enable mariadb + service_start mariadb + service_enable mysql + service_start mysql + fi + + if is_mysql_installed && wait_for_mysql_ready; then + ui_success "MySQL/MariaDB installed successfully." + return 0 + fi + + ui_error "MySQL/MariaDB installation failed or the service did not become ready." + return 1 +} + +secure_mariadb_binding() { + ui_info "Securing MariaDB/MySQL to listen on localhost only..." + + local conf_paths=( + "/etc/mysql/mariadb.conf.d/50-server.cnf" + "/etc/mysql/mysql.conf.d/mysqld.cnf" + "/etc/my.cnf.d/server.cnf" + "/etc/my.cnf.d/mariadb-server.cnf" + "/etc/my.cnf" + ) + + local conf_found="" + for cpath in "${conf_paths[@]}"; do + if [ -f "$cpath" ]; then + conf_found="$cpath" + break + fi + done + + if [ -z "$conf_found" ]; then + # Create a drop-in config if no existing config found + if [ -d "/etc/mysql/mariadb.conf.d" ]; then + conf_found="/etc/mysql/mariadb.conf.d/99-adpanel-security.cnf" + elif [ -d "/etc/mysql/mysql.conf.d" ]; then + conf_found="/etc/mysql/mysql.conf.d/99-adpanel-security.cnf" + elif [ -d "/etc/my.cnf.d" ]; then + conf_found="/etc/my.cnf.d/99-adpanel-security.cnf" + else + ui_warn "Could not find MariaDB/MySQL config directory. Skipping bind-address configuration." + return 1 + fi + $SUDO tee "$conf_found" >/dev/null <<'BINDEOF' +[mysqld] +bind-address = 127.0.0.1 +skip-networking = 0 +BINDEOF + ui_success "Created MariaDB security config at ${conf_found}" + else + # Update existing config + if grep -q "^bind-address" "$conf_found" 2>/dev/null; then + $SUDO sed -i 's/^bind-address[[:space:]]*=.*/bind-address = 127.0.0.1/' "$conf_found" + elif grep -q "^#.*bind-address" "$conf_found" 2>/dev/null; then + $SUDO sed -i 's/^#.*bind-address[[:space:]]*=.*/bind-address = 127.0.0.1/' "$conf_found" + elif grep -q "^\[mysqld\]" "$conf_found" 2>/dev/null; then + $SUDO sed -i '/^\[mysqld\]/a bind-address = 127.0.0.1' "$conf_found" + else + printf "\n[mysqld]\nbind-address = 127.0.0.1\n" | $SUDO tee -a "$conf_found" >/dev/null + fi + ui_success "MariaDB bind-address set to 127.0.0.1 in ${conf_found}" + fi + + # Restart MariaDB/MySQL to apply + local svc + svc="$(mysql_find_service)" + if [ -n "$svc" ]; then + service_restart "$svc" + else + service_restart mariadb + service_restart mysql + fi + + ui_success "MariaDB/MySQL is now listening on localhost only." + return 0 +} + +harden_firewall() { + ui_info "Hardening firewall rules..." + + local backend="" + + if cmd_exists ufw; then + backend="ufw" + elif cmd_exists firewall-cmd; then + backend="firewalld" + else + ensure_pkg_metadata >/dev/null 2>&1 || true + case "$PKG_MGR" in + apt|pacman) + if pkg_install ufw >/dev/null 2>&1; then + backend="ufw" + fi + ;; + dnf|yum|zypper) + if pkg_install firewalld >/dev/null 2>&1; then + backend="firewalld" + fi + ;; + esac + fi + + case "$backend" in + ufw) + $SUDO ufw deny 445/tcp >/dev/null 2>&1 || true + $SUDO ufw deny 445/udp >/dev/null 2>&1 || true + ui_success "Port 445 (SMB) blocked." + + $SUDO ufw deny 3306/tcp >/dev/null 2>&1 || true + ui_success "Port 3306 (MySQL) blocked from external access." + + if ! $SUDO ufw status | grep -q "Status: active"; then + $SUDO ufw --force enable >/dev/null 2>&1 || true + fi + $SUDO ufw reload >/dev/null 2>&1 || true + ui_success "Firewall hardened with ufw." + return 0 + ;; + firewalld) + service_enable firewalld + service_start 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." + + $SUDO firewall-cmd --permanent --add-rich-rule='rule family="ipv4" port port="3306" protocol="tcp" reject' >/dev/null 2>&1 || true + ui_success "Port 3306 (MySQL) blocked from external access." + + $SUDO firewall-cmd --reload >/dev/null 2>&1 || true + ui_success "Firewall hardened with firewalld." + return 0 + ;; + *) + if command -v iptables >/dev/null 2>&1; then + $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 || \ + $SUDO iptables -A INPUT -p udp --dport 445 -j DROP >/dev/null 2>&1 || true + ui_success "Port 445 (SMB) blocked." + + $SUDO iptables -C INPUT -p tcp --dport 3306 -j DROP >/dev/null 2>&1 || \ + $SUDO iptables -A INPUT -p tcp --dport 3306 -j DROP >/dev/null 2>&1 || true + ui_success "Port 3306 (MySQL) blocked from external access." + + if systemd_available; then + if systemctl list-unit-files | grep -q "^netfilter-persistent.service"; then + $SUDO systemctl reload netfilter-persistent >/dev/null 2>&1 || true + elif systemctl list-unit-files | grep -q "^iptables.service"; then + $SUDO systemctl reload iptables >/dev/null 2>&1 || true + fi + fi + if command -v service >/dev/null 2>&1; then + $SUDO service iptables reload >/dev/null 2>&1 || true + fi + ui_success "Firewall hardened with iptables." + return 0 + fi + ;; + esac + + ui_warn "No supported firewall manager was found or installed. Skipping firewall hardening." + return 1 +} + +mask_service_versions() { + ui_info "Masking service version fingerprints..." + + # --- Nginx: hide version in Server header globally --- + if [ -f /etc/nginx/nginx.conf ]; then + if ! grep -qE "^[[:space:]]*server_tokens[[:space:]]+off" /etc/nginx/nginx.conf 2>/dev/null; then + if grep -qE "^[[:space:]]*http[[:space:]]*\\{" /etc/nginx/nginx.conf 2>/dev/null; then + $SUDO sed -i '/^[[:space:]]*http[[:space:]]*{/a\ server_tokens off;' /etc/nginx/nginx.conf + else + # Fallback: append in http block area + $SUDO sed -i '/^[[:space:]]*include.*sites-enabled/i\ server_tokens off;' /etc/nginx/nginx.conf 2>/dev/null || true + fi + ui_success "Nginx server_tokens off added." + else + ui_info "Nginx server_tokens already disabled." + fi + fi + + # --- MariaDB/MySQL: remove version comment --- + local mysql_conf_dirs=( + "/etc/mysql/mariadb.conf.d" + "/etc/mysql/mysql.conf.d" + "/etc/my.cnf.d" + ) + local mysql_hardened=false + for confdir in "${mysql_conf_dirs[@]}"; do + if [ -d "$confdir" ]; then + local target="${confdir}/99-adpanel-version-mask.cnf" + $SUDO tee "$target" >/dev/null <<'MYSQLEOF' +[mysqld] +performance_schema = OFF +MYSQLEOF + ui_success "MariaDB/MySQL hardened in ${target}" + mysql_hardened=true + break + fi + done + if [ "$mysql_hardened" = false ] && [ -f /etc/my.cnf ]; then + if ! grep -q "performance_schema" /etc/my.cnf 2>/dev/null; then + if grep -q "^\[mysqld\]" /etc/my.cnf 2>/dev/null; then + $SUDO sed -i '/^\[mysqld\]/a performance_schema = OFF' /etc/my.cnf + else + printf "\n[mysqld]\nperformance_schema = OFF\n" | $SUDO tee -a /etc/my.cnf >/dev/null + fi + ui_success "MariaDB/MySQL hardened in /etc/my.cnf" + 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 + + # --- PHP: hide version from HTTP headers (for phpMyAdmin) --- + local php_ini_paths=( + "/etc/php/8.3/fpm/php.ini" + "/etc/php/8.2/fpm/php.ini" + "/etc/php/8.1/fpm/php.ini" + "/etc/php/8.0/fpm/php.ini" + "/etc/php/7.4/fpm/php.ini" + ) + for pini in "${php_ini_paths[@]}"; do + if [ -f "$pini" ]; then + if grep -qE "^expose_php[[:space:]]*=[[:space:]]*On" "$pini" 2>/dev/null; then + $SUDO sed -i 's/^expose_php[[:space:]]*=[[:space:]]*On/expose_php = Off/' "$pini" + ui_success "PHP expose_php disabled in ${pini}" + elif ! grep -q "^expose_php" "$pini" 2>/dev/null; then + echo "expose_php = Off" | $SUDO tee -a "$pini" >/dev/null + ui_success "PHP expose_php disabled in ${pini}" + fi + fi + done + # Restart PHP-FPM if running + local php_fpm_svc="" + if systemd_available; then + php_fpm_svc=$(systemctl list-units --type=service --state=running --no-legend 2>/dev/null | awk '{print $1}' | grep -E '^php[0-9.]+-fpm\.service$' | sort -r | head -1) + if [ -n "$php_fpm_svc" ]; then + $SUDO systemctl restart "$php_fpm_svc" 2>/dev/null || true + fi + fi + + # --- Apache: hide version (for pgAdmin4) --- + if [ -f /etc/apache2/apache2.conf ]; then + local apache_hardened=false + # ServerTokens Prod + if ! grep -qE "^ServerTokens[[:space:]]+Prod" /etc/apache2/apache2.conf 2>/dev/null; then + if grep -q "^ServerTokens" /etc/apache2/apache2.conf 2>/dev/null; then + $SUDO sed -i 's/^ServerTokens.*/ServerTokens Prod/' /etc/apache2/apache2.conf + else + echo "ServerTokens Prod" | $SUDO tee -a /etc/apache2/apache2.conf >/dev/null + fi + apache_hardened=true + fi + # ServerSignature Off + if ! grep -qE "^ServerSignature[[:space:]]+Off" /etc/apache2/apache2.conf 2>/dev/null; then + if grep -q "^ServerSignature" /etc/apache2/apache2.conf 2>/dev/null; then + $SUDO sed -i 's/^ServerSignature.*/ServerSignature Off/' /etc/apache2/apache2.conf + else + echo "ServerSignature Off" | $SUDO tee -a /etc/apache2/apache2.conf >/dev/null + fi + apache_hardened=true + fi + # Ensure headers module is enabled for Header directives + $SUDO a2enmod headers 2>/dev/null || true + if [ "$apache_hardened" = true ]; then + service_restart apache2 2>/dev/null || true + ui_success "Apache version fingerprint masked." + else + ui_info "Apache version already masked." + fi + fi + + # --- PostgreSQL: restrict version exposure --- + local pg_conf_found=false + for pgconf in $(find /etc/postgresql -name postgresql.conf 2>/dev/null); do + if [ -f "$pgconf" ]; then + # Disable server version in error messages to unauthenticated clients + if ! grep -qE "^password_encryption[[:space:]]*=[[:space:]]*scram-sha-256" "$pgconf" 2>/dev/null; then + if grep -q "^#\?password_encryption" "$pgconf" 2>/dev/null; then + $SUDO sed -i "s/^#\?password_encryption.*/password_encryption = scram-sha-256/" "$pgconf" + else + echo "password_encryption = scram-sha-256" | $SUDO tee -a "$pgconf" >/dev/null + fi + fi + if ! grep -qE "^log_hostname[[:space:]]*=[[:space:]]*off" "$pgconf" 2>/dev/null; then + if grep -q "^#\?log_hostname" "$pgconf" 2>/dev/null; then + $SUDO sed -i "s/^#\?log_hostname.*/log_hostname = off/" "$pgconf" + else + echo "log_hostname = off" | $SUDO tee -a "$pgconf" >/dev/null + fi + fi + pg_conf_found=true + fi + done + if [ "$pg_conf_found" = true ]; then + service_reload postgresql 2>/dev/null || true + ui_success "PostgreSQL hardened." + fi + + # --- MongoDB: reduce fingerprint exposure --- + if [ -f /etc/mongod.conf ]; then + # Ensure quiet mode is enabled to reduce protocol-level information leakage + if ! grep -qE "^[[:space:]]*quiet:[[:space:]]*true" /etc/mongod.conf 2>/dev/null; then + if grep -q "^systemLog:" /etc/mongod.conf 2>/dev/null; then + $SUDO sed -i '/^systemLog:/a\ quiet: true' /etc/mongod.conf + fi + service_restart mongod 2>/dev/null || true + ui_success "MongoDB fingerprint exposure reduced." + else + ui_info "MongoDB quiet mode already enabled." + fi + fi + + ui_success "Service version fingerprints masked." + return 0 +} + +mysql_sql_escape() { + printf "%s" "$1" | sed "s/\\\\/\\\\\\\\/g; s/'/''/g" +} + +mysql_exec_as_root() { + local sql="$1" + local root_pass="${2:-}" + local cli + cli="$(mysql_detect_cli)" + + if ! cmd_exists "$cli"; then + return 1 + fi + + if $SUDO "$cli" -e "$sql" >/dev/null 2>&1; then + return 0 + fi + + if [ -n "$root_pass" ]; then + if "$cli" -uroot -p"$root_pass" -h 127.0.0.1 -e "$sql" >/dev/null 2>&1; then + return 0 + fi + fi + + return 1 +} + +prompt_mysql_password() { + local p="" + while true; do + read -r -s -p "$(ui_prompt "Enter MySQL password for the new user: ")" p + printf '\n' >&2 + if [ -z "$p" ]; then + p="$(generate_base64url_token 32)" + ui_info "Generated a strong MySQL password automatically." >&2 + printf '%s' "$p" + return 0 + fi + if printf '%s' "$p" | grep -qE '[[:space:]]'; then + ui_error "MySQL password cannot contain spaces or newlines." >&2 + continue + fi + printf '%s' "$p" + return 0 + done +} + +setup_mysql() { + MYSQL_HOST="127.0.0.1" + MYSQL_PORT="3306" + MYSQL_USER="adpanel" + MYSQL_PASSWORD="" + MYSQL_DATABASE="adpanel" + MYSQL_URL="" + + ui_section "=== MySQL/MariaDB configuration (users/storage) ===" + read -p "$(ui_prompt "Do you want to configure MySQL/MariaDB now? (yes/no, default yes): ")" USE_MYSQL + USE_MYSQL="$(lower_trim "$USE_MYSQL")" + if [ -n "$USE_MYSQL" ] && [ "$USE_MYSQL" != "yes" ] && [ "$USE_MYSQL" != "y" ]; then + ui_warn "Skipping MySQL/MariaDB setup; leaving MYSQL_* empty in .env." + MYSQL_HOST="" + MYSQL_PORT="" + MYSQL_USER="" + MYSQL_PASSWORD="" + MYSQL_DATABASE="" + MYSQL_URL="" + return 0 + fi + + if ! install_mysql; then + ui_warn "MySQL/MariaDB install failed; leaving MYSQL_* empty in .env." + MYSQL_HOST="" + MYSQL_PORT="" + MYSQL_USER="" + MYSQL_PASSWORD="" + MYSQL_DATABASE="" + MYSQL_URL="" + return 1 + fi + + read -p "$(ui_prompt "MySQL host (default 127.0.0.1): ")" MYSQL_HOST_IN + MYSQL_HOST_IN="$(trim_ws "$MYSQL_HOST_IN")" + if [ -n "$MYSQL_HOST_IN" ]; then + MYSQL_HOST="$MYSQL_HOST_IN" + fi + + read -p "$(ui_prompt "MySQL port (default 3306): ")" MYSQL_PORT_IN + MYSQL_PORT_IN="$(trim_ws "$MYSQL_PORT_IN")" + if [ -n "$MYSQL_PORT_IN" ]; then + MYSQL_PORT="$(normalize_port "$MYSQL_PORT_IN" 3306)" + fi + + read -p "$(ui_prompt "MySQL database name (default adpanel): ")" MYSQL_DB_IN + MYSQL_DB_IN="$(trim_ws "$MYSQL_DB_IN")" + if [ -n "$MYSQL_DB_IN" ]; then + MYSQL_DATABASE="$MYSQL_DB_IN" + fi + + read -p "$(ui_prompt "MySQL username (default adpanel): ")" MYSQL_USER_IN + MYSQL_USER_IN="$(trim_ws "$MYSQL_USER_IN")" + if [ -n "$MYSQL_USER_IN" ]; then + MYSQL_USER="$MYSQL_USER_IN" + fi + + MYSQL_PASSWORD="$(prompt_mysql_password)" + + ui_info "MySQL settings chosen:" + ui_kv " USERNAME:" "${MYSQL_USER}" + ui_kv " HOST:" "${MYSQL_HOST}" + ui_kv " PORT:" "${MYSQL_PORT}" + ui_kv " PASSWORD:" "${MYSQL_PASSWORD}" + ui_kv " DATABASE:" "${MYSQL_DATABASE}" + + 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_warn "MySQL username contains unsupported characters; skipping automatic user creation." + elif ! printf "%s" "$esc_db" | grep -qE '^[A-Za-z0-9_]+$'; then + ui_warn "MySQL database name contains unsupported characters; skipping automatic DB creation." + else + local sql + sql=$(cat </dev/null || true) + else + out=$("$cli" -h "$host" -P "$port" -u "$user" -Nse \ + "SELECT COUNT(*) FROM information_schema.tables WHERE table_schema='${db}' AND table_name='${table}';" 2>/dev/null || true) + fi + + if [ "$out" == "1" ] || [ "$out" -gt 0 ] 2>/dev/null; then + ui_success "MySQL table ${db}.${table} is ready." + return 0 + fi + + printf "." + sleep "$delay" + done + + echo "" + return 1 +} + +bootstrap_db_and_create_admin() { + local admin_email="$1" + local admin_hash="$2" + local admin_secret="$3" + local admin_avatar_url="" + + admin_avatar_url="$(pick_default_avatar_url admin)" + + if [ -z "$MYSQL_URL" ] || [ -z "$MYSQL_DATABASE" ] || [ -z "$MYSQL_USER" ] || [ -z "$MYSQL_PASSWORD" ]; then + return 0 + fi + + if [ -z "$admin_email" ] || [ -z "$admin_hash" ]; then + return 0 + fi + + 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." + return 0 + fi + + ui_info "Bootstrapping database schema via: npm start" + local boot_log="/tmp/adpanel-npm-start-bootstrap.log" + local pid="" + + if cmd_exists timeout; then + timeout 90s npm start >"$boot_log" 2>&1 & + pid=$! + else + npm start >"$boot_log" 2>&1 & + pid=$! + fi + + if ! wait_for_mysql_table "$MYSQL_DATABASE" "users" "127.0.0.1" "$MYSQL_PORT" "$MYSQL_USER" "$MYSQL_PASSWORD"; then + ui_warn "users table did not appear. Check bootstrap log: ${boot_log}" + fi + + if [ -n "$pid" ] && kill -0 "$pid" >/dev/null 2>&1; then + kill "$pid" >/dev/null 2>&1 || true + sleep 2 + kill -9 "$pid" >/dev/null 2>&1 || true + fi + + ui_info "Seeding admin user via ${script_path}..." + + if [ -n "$admin_secret" ]; then + $SUDO node "$script_path" --email "$admin_email" --password-hash "$admin_hash" --admin --secret "$admin_secret" --avatar-url "$admin_avatar_url" + else + $SUDO node "$script_path" --email "$admin_email" --password-hash "$admin_hash" --admin --avatar-url "$admin_avatar_url" + fi + + return $? +} + + +install_redis() { + if is_redis_installed; then + ui_success "Redis (or compatible) is already installed." + detect_redis_commands + return 0 + fi + + ui_info "Installing Redis (This may take a few minutes)..." + if ! ensure_supported_package_manager; then + ui_error "Could not detect a supported package manager to install Redis." + return 1 + fi + + enable_rhel_extra_repos + ensure_pkg_metadata >/dev/null 2>&1 || true + + case "$PKG_MGR" in + apt) + pkg_install_try_sets \ + "redis-server redis-tools" \ + "redis-server" \ + "valkey-redis-compat" \ + "valkey valkey-tools" \ + "valkey-server valkey-tools" || return 1 + ;; + dnf|yum|zypper) + pkg_install_try_sets \ + "redis" \ + "redis-server redis" \ + "valkey" \ + "valkey-redis-compat" || return 1 + ;; + apk|pacman) + pkg_install_try_sets \ + "redis" \ + "valkey" \ + "valkey-redis-compat" || return 1 + ;; + *) + ui_error "Unsupported package manager for Redis install." + return 1 + ;; + esac + + detect_redis_commands + + if is_redis_installed; then + ui_success "Redis installed successfully." + return 0 + fi + + ui_error "Redis installation failed." + return 1 +} + +detect_redis_conf() { + local candidates=( + "/etc/redis/redis.conf" + "/etc/redis.conf" + "/usr/local/etc/redis/redis.conf" + "/etc/valkey/valkey.conf" + "/etc/valkey.conf" + ) + for f in "${candidates[@]}"; do + if [ -f "$f" ]; then + echo "$f" + return 0 + fi + done + echo "" + return 1 +} + +calculate_redis_maxmemory() { + local mem_kb="" + if [ -r /proc/meminfo ]; then + mem_kb=$(awk '/MemTotal:/ {print $2}' /proc/meminfo | head -n1) + fi + + if [ -n "$mem_kb" ]; then + local mem_mb=$((mem_kb / 1024)) + local mm_mb=$((mem_mb / 4)) + if [ "$mm_mb" -lt 64 ]; then mm_mb=64; fi + if [ "$mm_mb" -gt 2048 ]; then mm_mb=2048; fi + echo "${mm_mb}mb" + return 0 + fi + + echo "256mb" + return 0 +} + +redis_bind_line() { + if [ -r /proc/sys/net/ipv6/conf/all/disable_ipv6 ]; then + local disabled + disabled=$(cat /proc/sys/net/ipv6/conf/all/disable_ipv6 2>/dev/null || echo "1") + if [ "$disabled" == "0" ]; then + echo "bind 127.0.0.1 ::1" + return 0 + fi + fi + echo "bind 127.0.0.1" + return 0 +} + +redis_supervised_value() { + if [ "$INIT_SYSTEM" == "systemd" ]; then + echo "systemd" + else + echo "no" + fi +} + +redis_can_enable_activedefrag() { + detect_redis_commands + if ! cmd_exists "$REDIS_SERVER_CMD"; then + return 1 + fi + if ! cmd_exists timeout; then + return 1 + fi + + local tmp + tmp="$(mktemp /tmp/adpanel-redis-probe.XXXXXX.conf 2>/dev/null || echo "")" + if [ -z "$tmp" ]; then + return 1 + fi + + cat > "$tmp" <<'EOF' +port 0 +bind 127.0.0.1 +protected-mode yes +daemonize no +save "" +appendonly no +activedefrag yes +EOF + + local out rc + out="$(timeout 1 "$REDIS_SERVER_CMD" "$tmp" 2>&1 || true)" + rc=$? + + rm -f "$tmp" >/dev/null 2>&1 || true + + if echo "$out" | grep -qi "Active defragmentation cannot be enabled"; then + return 1 + fi + if echo "$out" | grep -qi "FATAL CONFIG FILE ERROR"; then + return 1 + fi + + if [ "$rc" -eq 124 ] || [ "$rc" -eq 0 ]; then + return 0 + fi + + return 1 +} + +configure_redis_auth() { + local conf="$1" + local password="$2" + if [ -z "$conf" ] || [ -z "$password" ]; then + return 1 + fi + + $SUDO sed -i '/^[[:space:]]*# === ADPANEL REDIS SETTINGS START ===$/,/^[[:space:]]*# === ADPANEL REDIS SETTINGS END ===$/d' "$conf" 2>/dev/null || true + + $SUDO sed -i '/^[[:space:]]*requirepass[[:space:]]/d' "$conf" 2>/dev/null || true + $SUDO sed -i '/^[[:space:]]*bind[[:space:]]/d' "$conf" 2>/dev/null || true + $SUDO sed -i '/^[[:space:]]*protected-mode[[:space:]]/d' "$conf" 2>/dev/null || true + $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:]]*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 + $SUDO sed -i '/^[[:space:]]*lazyfree-lazy-expire[[:space:]]/d' "$conf" 2>/dev/null || true + $SUDO sed -i '/^[[:space:]]*lazyfree-lazy-server-del[[:space:]]/d' "$conf" 2>/dev/null || true + $SUDO sed -i '/^[[:space:]]*activedefrag[[:space:]]/d' "$conf" 2>/dev/null || true + + local maxmemory + maxmemory=$(calculate_redis_maxmemory) + + local bindline + bindline=$(redis_bind_line) + + local supervised_val + supervised_val=$(redis_supervised_value) + + local enable_activedefrag="no" + if redis_can_enable_activedefrag; then + enable_activedefrag="yes" + fi + + cat </dev/null +${bindline} +protected-mode yes +supervised ${supervised_val} + +requirepass ${password} + +save "" +appendonly no + +maxmemory ${maxmemory} +maxmemory-policy noeviction + +lazyfree-lazy-eviction yes +lazyfree-lazy-expire yes +lazyfree-lazy-server-del yes +EOF + + if [ "$enable_activedefrag" == "yes" ]; then + echo "activedefrag yes" | $SUDO tee -a "$conf" >/dev/null + else + cat <<'EOF' | $SUDO tee -a "$conf" >/dev/null +EOF + fi + + cat </dev/null +EOF + + local acl_file + acl_file=$(grep -E '^[[:space:]]*aclfile[[:space:]]+' "$conf" | awk '{print $2}' | tail -n 1) + if [ -z "$acl_file" ] && [ -f "/etc/redis/users.acl" ]; then + acl_file="/etc/redis/users.acl" + fi + + if [ -n "$acl_file" ]; then + $SUDO mkdir -p "$(dirname "$acl_file")" >/dev/null 2>&1 || true + $SUDO sed -i "/^[[:space:]]*user[[:space:]]\\+default[[:space:]]\\+/d" "$acl_file" 2>/dev/null || true + echo "user default on >${password} ~* +@all" | $SUDO tee -a "$acl_file" >/dev/null + fi +} + +ensure_overcommit_memory() { + cmd_exists sysctl || return 0 + $SUDO sysctl -w vm.overcommit_memory=1 >/dev/null 2>&1 || true + if [ -f /etc/sysctl.conf ]; then + if grep -qE '^[[:space:]]*vm\.overcommit_memory' /etc/sysctl.conf; then + $SUDO sed -i "s|^[[:space:]]*vm\.overcommit_memory[[:space:]]*=.*|vm.overcommit_memory = 1|g" /etc/sysctl.conf + else + echo "vm.overcommit_memory = 1" | $SUDO tee -a /etc/sysctl.conf >/dev/null + fi + fi +} + +restart_redis_service() { + local svc="" + + 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 + svc="redis-server" + elif systemctl list-unit-files 2>/dev/null | grep -q "^redis.service"; then + svc="redis" + elif systemctl list-unit-files 2>/dev/null | grep -q "^valkey.service"; then + svc="valkey" + elif systemctl list-unit-files 2>/dev/null | grep -q "^valkey-server.service"; then + svc="valkey-server" + fi + + if [ -n "$svc" ]; then + $SUDO systemctl reset-failed "$svc" >/dev/null 2>&1 || true + service_enable "$svc" + service_restart "$svc" + return 0 + fi + fi + + for svc in redis-server redis valkey valkey-server; do + service_restart "$svc" + done + + return 0 +} + +configure_redis_firewall() { + ui_info "Redis stays bound to localhost only; skipping automatic firewall changes for port 6379." +} + +wait_for_redis() { + local host="$1" + local port="$2" + local pass="$3" + local retries=10 + local delay=2 + local max_wait=$((retries * delay)) + + detect_redis_commands + if ! command -v "$REDIS_CLI_CMD" >/dev/null 2>&1; then + return 1 + fi + + ui_info "Waiting for Redis to accept connections (up to ${max_wait}s)..." + + for i in $(seq 1 "$retries"); do + local out + if command -v timeout >/dev/null 2>&1; then + out=$(timeout 2 "$REDIS_CLI_CMD" -h "$host" -p "$port" -a "$pass" --no-auth-warning ping 2>/dev/null || true) + else + out=$("$REDIS_CLI_CMD" -h "$host" -p "$port" -a "$pass" --no-auth-warning ping 2>/dev/null || true) + fi + if [ "$out" == "PONG" ]; then + ui_success "Redis is ready." + return 0 + fi + printf "." + sleep "$delay" + done + + echo "" + return 1 +} + +prompt_redis_password() { + local pass1="" + while true; do + read -r -s -p "$(ui_prompt "Enter Redis password: ")" pass1 + printf '\n' >&2 + + if [ -z "$pass1" ]; then + pass1="$(generate_base64url_token 32)" + ui_info "Generated a strong Redis password automatically." >&2 + printf '%s' "$pass1" + return 0 + fi + if printf '%s' "$pass1" | grep -qE '[[:space:]]'; then + ui_error "Redis password cannot contain spaces or newlines." >&2 + continue + fi + + printf '%s' "$pass1" + return 0 + done +} + +setup_redis() { + REDIS_HOST="127.0.0.1" + REDIS_PORT="6379" + REDIS_USER="default" + REDIS_PASSWORD="" + REDIS_URL="" + SESSION_STORE="file" + + read -p "$(ui_prompt "Do you want to configure Redis (with password) for session storage? (yes/no, default yes): ")" USE_REDIS + USE_REDIS="$(lower_trim "$USE_REDIS")" + if [ -z "$USE_REDIS" ] || [ "$USE_REDIS" == "yes" ] || [ "$USE_REDIS" == "y" ]; then + : + else + ui_warn "Skipping Redis setup; using file sessions." + SESSION_STORE="file" + REDIS_PASSWORD="" + REDIS_URL="" + return 0 + fi + + if ! install_redis; then + ui_warn "Redis installation failed; falling back to file sessions." + SESSION_STORE="file" + REDIS_PASSWORD="" + REDIS_URL="" + return 1 + fi + + if ! is_redis_installed; then + ui_warn "Redis not detected after install; falling back to file sessions." + SESSION_STORE="file" + REDIS_PASSWORD="" + REDIS_URL="" + return 1 + fi + + detect_redis_commands + + REDIS_PASSWORD="$(prompt_redis_password)" + local conf + conf=$(detect_redis_conf) + if [ -z "$conf" ]; then + ui_warn "Redis config not found; skipping config changes." + else + configure_redis_auth "$conf" "$REDIS_PASSWORD" + fi + + ensure_overcommit_memory + ui_info "Restarting Redis..." + restart_redis_service + configure_redis_firewall + + local encoded_pass + encoded_pass=$(node -e "console.log(encodeURIComponent(process.argv[1] || ''))" "$REDIS_PASSWORD") + REDIS_URL="redis://${REDIS_USER}:${encoded_pass}@${REDIS_HOST}:${REDIS_PORT}" + SESSION_STORE="redis" + + if ! wait_for_redis "$REDIS_HOST" "$REDIS_PORT" "$REDIS_PASSWORD"; then + ui_warn "Redis did not respond to PING; falling back to file sessions." + SESSION_STORE="file" + REDIS_URL="" + REDIS_PASSWORD="" + return 1 + fi +} + +detect_nginx_layout() { + if [ -d /etc/nginx/sites-available ] && [ -d /etc/nginx/sites-enabled ]; then + echo "debian" + else + echo "confd" + fi +} + +detect_nginx_user() { + local nginx_user="" + + if [ -f /etc/nginx/nginx.conf ]; then + nginx_user=$(grep -E "^[[:space:]]*user[[:space:]]+" /etc/nginx/nginx.conf 2>/dev/null | head -1 | awk '{print $2}' | tr -d ';') + fi + + if [ -z "$nginx_user" ]; then + if id "www-data" >/dev/null 2>&1; then + nginx_user="www-data" + elif id "nginx" >/dev/null 2>&1; then + nginx_user="nginx" + elif id "http" >/dev/null 2>&1; then + nginx_user="http" + elif id "nobody" >/dev/null 2>&1; then + nginx_user="nobody" + fi + fi + + echo "$nginx_user" +} + +fix_nginx_static_permissions() { + local panel_root="$1" + local static_root="${panel_root}/public" + local nginx_user + nginx_user="$(detect_nginx_user)" + + ui_info "Setting permissions for nginx to serve static files..." + + if [ -z "$nginx_user" ]; then + ui_warn "Warning: Could not detect nginx user. Using world-readable permissions." + $SUDO chmod -R o+r "$static_root" 2>/dev/null || true + $SUDO find "$static_root" -type d -exec chmod o+rx {} \; 2>/dev/null || true + else + ui_success "Detected nginx user: ${nginx_user}" + $SUDO chmod -R o+r "$static_root" 2>/dev/null || true + $SUDO find "$static_root" -type d -exec chmod o+rx {} \; 2>/dev/null || true + fi + + local current_dir="$panel_root" + while [ "$current_dir" != "/" ] && [ -n "$current_dir" ]; do + $SUDO chmod o+x "$current_dir" 2>/dev/null || true + current_dir="$(dirname "$current_dir")" + done + + ui_success "Permissions set successfully." +} + +generate_base64url_token() { + local bytes="${1:-32}" + if command -v openssl >/dev/null 2>&1; then + openssl rand -base64 "$bytes" | tr '+/' '-_' | tr -d '=\n' + else + head -c "$bytes" /dev/urandom | od -An -tx1 | tr -d ' \n' + fi +} + +ensure_stealth_config() { + local panel_root="$1" + local stealth_dir="${panel_root}/data" + local stealth_path="${stealth_dir}/stealth.json" + + if [ -s "$stealth_path" ]; then + ui_info "Stealth config already present." + return 0 + fi + + local created_at + local cookie_secret + local challenge_secret + local html_variant_salt + + created_at="$(date -u +"%Y-%m-%dT%H:%M:%SZ")" + cookie_secret="$(generate_base64url_token 48)" + challenge_secret="$(generate_base64url_token 48)" + html_variant_salt="$(generate_base64url_token 24)" + + $SUDO mkdir -p "$stealth_dir" + cat </dev/null +{ + "enabled": true, + "cookieName": "adpanel_gate", + "cookieSecret": "${cookie_secret}", + "cookieTtlDays": 30, + "challengeSecret": "${challenge_secret}", + "htmlVariantSalt": "${html_variant_salt}", + "createdAt": "${created_at}", + "rotatedAt": "${created_at}" +} +EOF + $SUDO chmod 600 "$stealth_path" 2>/dev/null || true + ui_success "Generated stealth config." +} + +backup_path_for_restore() { + local source="$1" + local dest_base="$2" + + if [ -L "$source" ]; then + readlink "$source" > "${dest_base}.symlink" 2>/dev/null || true + elif [ -e "$source" ]; then + $SUDO cp -a "$source" "${dest_base}.file" >/dev/null 2>&1 || true + else + : > "${dest_base}.missing" + fi +} + +restore_path_from_backup() { + local target="$1" + local dest_base="$2" + + if [ -f "${dest_base}.symlink" ]; then + local link_target + link_target="$(cat "${dest_base}.symlink" 2>/dev/null || true)" + $SUDO rm -f "$target" >/dev/null 2>&1 || true + if [ -n "$link_target" ]; then + $SUDO ln -s "$link_target" "$target" >/dev/null 2>&1 || true + fi + elif [ -e "${dest_base}.file" ]; then + $SUDO rm -rf "$target" >/dev/null 2>&1 || true + $SUDO cp -a "${dest_base}.file" "$target" >/dev/null 2>&1 || true + elif [ -f "${dest_base}.missing" ]; then + $SUDO rm -rf "$target" >/dev/null 2>&1 || true + fi +} + +write_nginx_config() { + local server_name="${NGINX_SERVER_NAME:-$HOST}" + server_name="$(trim_ws "$server_name")" + if [ -z "$server_name" ] || [ "$server_name" == "0.0.0.0" ] || [ "$server_name" == "127.0.0.1" ] || [ "$server_name" == "localhost" ]; then + server_name="_" + fi + + # Detect nginx brotli module availability + local nginx_has_brotli="false" + if nginx -V 2>&1 | grep -q 'brotli' || find /etc/nginx/modules-enabled /usr/share/nginx/modules -maxdepth 1 -name '*brotli*' -print -quit 2>/dev/null | grep -q .; then + nginx_has_brotli="true" + fi + # Try to install brotli module if not present + if [ "$nginx_has_brotli" == "false" ]; then + if install_optional_nginx_brotli_module >/dev/null 2>&1; then + nginx_has_brotli="true" + ui_success "nginx brotli module installed." + fi + fi + if [ "$nginx_has_brotli" == "true" ]; then + ui_info "nginx brotli compression: enabled" + else + ui_info "nginx brotli compression: not available (using gzip only)" + fi + + local upstream_host="${APP_HOST}" + local upstream_port="${APP_PORT}" + local panel_root + panel_root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + local static_root="${panel_root}/public" + + local layout + layout="$(detect_nginx_layout)" + + local config_path="" + local ssl_config_path="" + + if [ "$layout" == "debian" ]; then + config_path="/etc/nginx/sites-available/adpanel.conf" + ssl_config_path="/etc/nginx/sites-available/adpanel-ssl.conf" + $SUDO mkdir -p /etc/nginx/sites-available /etc/nginx/sites-enabled >/dev/null 2>&1 || true + else + config_path="/etc/nginx/conf.d/adpanel.conf" + ssl_config_path="/etc/nginx/conf.d/adpanel-ssl.conf" + $SUDO mkdir -p /etc/nginx/conf.d >/dev/null 2>&1 || true + fi + + local backup_dir + backup_dir="$(mktemp -d /tmp/adpanel-nginx.XXXXXX 2>/dev/null || mktemp -d)" + backup_path_for_restore "$config_path" "${backup_dir}/adpanel.conf" + backup_path_for_restore "$ssl_config_path" "${backup_dir}/adpanel-ssl.conf" + backup_path_for_restore "/etc/nginx/sites-enabled/adpanel.conf" "${backup_dir}/enabled-adpanel.conf" + backup_path_for_restore "/etc/nginx/sites-enabled/adpanel-ssl.conf" "${backup_dir}/enabled-adpanel-ssl.conf" + backup_path_for_restore "/etc/nginx/sites-enabled/default" "${backup_dir}/enabled-default" + backup_path_for_restore "/etc/nginx/conf.d/adpanel-performance.conf" "${backup_dir}/adpanel-performance.conf" + + local has_ssl="false" + if [ "$ENABLE_HTTPS" == "true" ] && [ -n "$SSL_CERT_PATH" ] && [ -n "$SSL_KEY_PATH" ]; then + has_ssl="true" + fi + local https_port_segment="" + if [ "$has_ssl" == "true" ] && [ "$HTTPS_PORT" != "443" ]; then + https_port_segment=":${HTTPS_PORT}" + fi + + + cat </dev/null +map \$http_upgrade \$connection_upgrade { + default upgrade; + '' close; +} + +upstream adpanel_backend { + server ${upstream_host}:${upstream_port}; + keepalive 64; +} + +server { + listen ${HTTP_PORT}; + server_name ${server_name}; + server_tokens off; + client_max_body_size 1100m; + root ${static_root}; + + if (\$request_method = TRACE) { + return 444; + } + if (\$request_method = TRACK) { + return 444; + } + if (\$request_method = OPTIONS) { + return 204; + } + + sendfile on; + tcp_nopush on; + tcp_nodelay on; + keepalive_timeout 65; + keepalive_requests 1000; + +EOF + + if [ "$has_ssl" == "true" ] && [ "$FORCE_HTTPS" == "true" ]; then + cat </dev/null + return 301 https://\$host${https_port_segment}\$request_uri; +} +EOF + else + cat </dev/null + gzip on; + gzip_vary on; + gzip_min_length 256; + gzip_comp_level 2; + 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; + +EOF + if [ "$nginx_has_brotli" == "true" ]; then + cat </dev/null + brotli on; + brotli_comp_level 4; + 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; + +EOF + fi + cat </dev/null + + location = /_stealth/nginx-auth { + internal; + proxy_pass http://adpanel_backend/_stealth/nginx-auth; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + } + + location @adpanel_stealth_404 { + internal; + default_type text/plain; + add_header Cache-Control "no-store, private" always; + return 404 ""; + } + + location ^~ /.well-known/acme-challenge/ { + auth_request off; + access_log off; + try_files \$uri @adpanel_backend; + } + + location = /favicon.ico { + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + proxy_set_header Connection ""; + } + + location ^~ /auth-assets/ { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + proxy_set_header Connection ""; + } + + location = /branding-media/login-watermark { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + proxy_set_header Connection ""; + } + + location = /branding-media/login-background { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + proxy_set_header Connection ""; + } + + location = /login.css { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + try_files \$uri =404; + add_header Cache-Control "no-store, private" always; + add_header X-Content-Type-Options nosniff always; + access_log off; + } + + location = /images/adpanel-dark.webp { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + try_files \$uri =404; + add_header Cache-Control "no-store, private" always; + add_header X-Content-Type-Options nosniff always; + access_log off; + } + + location = /images/ADPanel-christmas.png { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + try_files \$uri =404; + add_header Cache-Control "no-store, private" always; + add_header X-Content-Type-Options nosniff always; + access_log off; + } + + location = /images/bgvid.webm { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + try_files \$uri =404; + add_header Cache-Control "no-store, private" always; + add_header X-Content-Type-Options nosniff always; + access_log off; + } + + location /css/ { + alias ${static_root}/css/; + expires 30d; + add_header Cache-Control "public, max-age=2592000, immutable"; + add_header X-Content-Type-Options nosniff always; + etag on; + access_log off; + open_file_cache max=1000 inactive=60s; + open_file_cache_valid 30s; + open_file_cache_min_uses 1; + } + + location /js/ { + alias ${static_root}/js/; + expires 30d; + add_header Cache-Control "public, max-age=2592000, immutable"; + add_header X-Content-Type-Options nosniff always; + etag on; + access_log off; + open_file_cache max=1000 inactive=60s; + open_file_cache_valid 30s; + open_file_cache_min_uses 1; + } + + location /images/ { + alias ${static_root}/images/; + expires 30d; + add_header Cache-Control "public, max-age=2592000, immutable"; + add_header X-Content-Type-Options nosniff always; + etag on; + access_log off; + open_file_cache max=500 inactive=60s; + open_file_cache_valid 30s; + open_file_cache_min_uses 1; + } + + location ~* \\.(?:woff2?|ttf|eot|otf)\$ { + try_files \$uri =404; + expires 365d; + add_header Cache-Control "public, max-age=31536000, immutable"; + add_header Access-Control-Allow-Origin "*"; + access_log off; + } + + location ~* ^/[^/]+\\.(?:css|js|mjs|png|jpe?g|gif|ico|svg|webp)\$ { + try_files \$uri =404; + expires 30d; + add_header Cache-Control "public, max-age=2592000, immutable"; + add_header X-Content-Type-Options nosniff always; + etag on; + access_log off; + } + + location / { + try_files \$uri @adpanel_backend; + } + + location ~ ^/api/nodes/server/[^/]+/logs\$ { + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + + proxy_buffering off; + proxy_cache off; + add_header X-Accel-Buffering no always; + + proxy_read_timeout 600s; + proxy_send_timeout 600s; + + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + + proxy_set_header Connection ""; + } + + location @adpanel_backend { + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_set_header Upgrade \$http_upgrade; + proxy_set_header Connection \$connection_upgrade; + + proxy_buffering on; + proxy_buffer_size 16k; + proxy_buffers 8 32k; + proxy_busy_buffers_size 64k; + + proxy_read_timeout 600s; + proxy_send_timeout 600s; + + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + } +} +EOF + fi + + if [ "$has_ssl" == "true" ]; then + cat </dev/null +server { + listen ${HTTPS_PORT} ssl http2; + server_name ${server_name}; + server_tokens off; + root ${static_root}; + + if (\$request_method = TRACE) { + return 444; + } + if (\$request_method = TRACK) { + return 444; + } + if (\$request_method = OPTIONS) { + return 204; + } + + ssl_certificate ${SSL_CERT_PATH}; + ssl_certificate_key ${SSL_KEY_PATH}; + ssl_protocols TLSv1.2 TLSv1.3; + ssl_prefer_server_ciphers off; + ssl_session_cache shared:SSL:10m; + ssl_session_timeout 1d; + ssl_session_tickets off; + + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + + client_max_body_size 1100m; + + sendfile on; + tcp_nopush on; + tcp_nodelay on; + keepalive_timeout 65; + keepalive_requests 1000; + + gzip on; + gzip_vary on; + gzip_min_length 256; + gzip_comp_level 2; + 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; + +EOF + if [ "$nginx_has_brotli" == "true" ]; then + cat </dev/null + brotli on; + brotli_comp_level 4; + 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; + +EOF + fi + cat </dev/null + + location = /_stealth/nginx-auth { + internal; + proxy_pass http://adpanel_backend/_stealth/nginx-auth; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_set_header Connection ""; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + } + + location @adpanel_stealth_404 { + internal; + default_type text/plain; + add_header Cache-Control "no-store, private" always; + return 404 ""; + } + + location ^~ /.well-known/acme-challenge/ { + auth_request off; + access_log off; + try_files \$uri @adpanel_backend; + } + + location = /favicon.ico { + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + proxy_set_header Connection ""; + } + + location ^~ /auth-assets/ { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + proxy_set_header Connection ""; + } + + location = /branding-media/login-watermark { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + proxy_set_header Connection ""; + } + + location = /branding-media/login-background { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_buffering off; + proxy_request_buffering off; + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + proxy_set_header Connection ""; + } + + location = /login.css { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + try_files \$uri =404; + add_header Cache-Control "no-store, private" always; + add_header X-Content-Type-Options nosniff always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + access_log off; + } + + location = /images/adpanel-dark.webp { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + try_files \$uri =404; + add_header Cache-Control "no-store, private" always; + add_header X-Content-Type-Options nosniff always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + access_log off; + } + + location = /images/ADPanel-christmas.png { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + try_files \$uri =404; + add_header Cache-Control "no-store, private" always; + add_header X-Content-Type-Options nosniff always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + access_log off; + } + + location = /images/bgvid.webm { + auth_request /_stealth/nginx-auth; + error_page 401 403 = @adpanel_stealth_404; + try_files \$uri =404; + add_header Cache-Control "no-store, private" always; + add_header X-Content-Type-Options nosniff always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + access_log off; + } + + location /css/ { + alias ${static_root}/css/; + expires 30d; + add_header Cache-Control "public, max-age=2592000, immutable"; + add_header X-Content-Type-Options nosniff always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + etag on; + access_log off; + open_file_cache max=1000 inactive=60s; + open_file_cache_valid 30s; + open_file_cache_min_uses 1; + } + + location /js/ { + alias ${static_root}/js/; + expires 30d; + add_header Cache-Control "public, max-age=2592000, immutable"; + add_header X-Content-Type-Options nosniff always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + etag on; + access_log off; + open_file_cache max=1000 inactive=60s; + open_file_cache_valid 30s; + open_file_cache_min_uses 1; + } + + location /images/ { + alias ${static_root}/images/; + expires 30d; + add_header Cache-Control "public, max-age=2592000, immutable"; + add_header X-Content-Type-Options nosniff always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + etag on; + access_log off; + open_file_cache max=500 inactive=60s; + open_file_cache_valid 30s; + open_file_cache_min_uses 1; + } + + location ~* \\.(?:woff2?|ttf|eot|otf)\$ { + try_files \$uri =404; + expires 365d; + add_header Cache-Control "public, max-age=31536000, immutable"; + add_header Access-Control-Allow-Origin "*"; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + access_log off; + } + + location ~* ^/[^/]+\\.(?:css|js|mjs|png|jpe?g|gif|ico|svg|webp)\$ { + try_files \$uri =404; + expires 30d; + add_header Cache-Control "public, max-age=2592000, immutable"; + add_header X-Content-Type-Options nosniff always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + etag on; + access_log off; + } + + location / { + try_files \$uri @adpanel_backend; + } + + location ~ ^/api/nodes/server/[^/]+/logs\$ { + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + + proxy_buffering off; + proxy_cache off; + add_header X-Accel-Buffering no always; + add_header Strict-Transport-Security "max-age=63072000; includeSubDomains" always; + + proxy_read_timeout 600s; + proxy_send_timeout 600s; + + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + + proxy_set_header Connection ""; + } + + location @adpanel_backend { + proxy_pass http://adpanel_backend; + proxy_http_version 1.1; + proxy_set_header Host \$host; + proxy_set_header X-Forwarded-Host \$host; + proxy_set_header X-Forwarded-Port \$server_port; + proxy_set_header X-Real-IP \$remote_addr; + proxy_set_header X-Forwarded-For \$remote_addr; + proxy_set_header X-Forwarded-Proto \$scheme; + proxy_set_header Upgrade \$http_upgrade; + proxy_set_header Connection \$connection_upgrade; + + proxy_buffering on; + proxy_buffer_size 16k; + proxy_buffers 8 32k; + proxy_busy_buffers_size 64k; + + proxy_read_timeout 600s; + proxy_send_timeout 600s; + + proxy_hide_header X-Powered-By; + proxy_hide_header Server; + } +} +EOF + else + $SUDO rm -f "$ssl_config_path" >/dev/null 2>&1 || true + fi + + if [ "$layout" == "debian" ]; then + $SUDO ln -sf "$config_path" /etc/nginx/sites-enabled/adpanel.conf + if [ -f "$ssl_config_path" ]; then + $SUDO ln -sf "$ssl_config_path" /etc/nginx/sites-enabled/adpanel-ssl.conf + else + $SUDO rm -f /etc/nginx/sites-enabled/adpanel-ssl.conf + fi + fi + + fix_nginx_static_permissions "$panel_root" + + apply_nginx_performance_profile + + if $SUDO nginx -t; then + if [ "$layout" == "debian" ] && [ -f /etc/nginx/sites-enabled/default ]; then + $SUDO rm -f /etc/nginx/sites-enabled/default + if ! $SUDO nginx -t; then + ui_warn "nginx failed after disabling the default site; restoring the default site." + restore_path_from_backup "/etc/nginx/sites-enabled/default" "${backup_dir}/enabled-default" + $SUDO nginx -t >/dev/null 2>&1 || true + fi + fi + service_reload nginx + rm -rf "$backup_dir" >/dev/null 2>&1 || true + return 0 + fi + + ui_warn "Generated nginx configuration failed validation; restoring the previous nginx config." + restore_path_from_backup "$config_path" "${backup_dir}/adpanel.conf" + restore_path_from_backup "$ssl_config_path" "${backup_dir}/adpanel-ssl.conf" + restore_path_from_backup "/etc/nginx/sites-enabled/adpanel.conf" "${backup_dir}/enabled-adpanel.conf" + restore_path_from_backup "/etc/nginx/sites-enabled/adpanel-ssl.conf" "${backup_dir}/enabled-adpanel-ssl.conf" + restore_path_from_backup "/etc/nginx/sites-enabled/default" "${backup_dir}/enabled-default" + restore_path_from_backup "/etc/nginx/conf.d/adpanel-performance.conf" "${backup_dir}/adpanel-performance.conf" + $SUDO nginx -t >/dev/null 2>&1 && service_reload nginx || true + rm -rf "$backup_dir" >/dev/null 2>&1 || true + return 1 +} + +apply_nginx_performance_profile() { + local nginx_conf="/etc/nginx/nginx.conf" + local perf_conf="/etc/nginx/conf.d/adpanel-performance.conf" + local cache_dir="/var/cache/nginx/adpanel" + local nginx_user="" + + if [ ! -f "$nginx_conf" ]; then + ui_warn "nginx.conf not found; skipping nginx performance profile." + return 0 + fi + + nginx_user="$(detect_nginx_user)" + $SUDO mkdir -p "$cache_dir" >/dev/null 2>&1 || true + if [ -n "$nginx_user" ] && id "$nginx_user" >/dev/null 2>&1; then + $SUDO chown -R "$nginx_user":"$nginx_user" "$cache_dir" >/dev/null 2>&1 || true + fi + + # Raise FD and connection capacity while keeping worker auto-scaling enabled. + if ! grep -qE '^[[:space:]]*worker_rlimit_nofile[[:space:]]+' "$nginx_conf"; then + $SUDO sed -i '/^worker_processes[[:space:]]\+auto;/a worker_rlimit_nofile 65535;' "$nginx_conf" || true + fi + + $SUDO sed -i -E 's/^[[:space:]]*worker_connections[[:space:]]+[0-9]+;/ worker_connections 4096;/' "$nginx_conf" || true + $SUDO sed -i 's/^[[:space:]]*#[[:space:]]*multi_accept[[:space:]]\+on;/ multi_accept on;/' "$nginx_conf" || true + + if ! grep -qE '^[[:space:]]*use[[:space:]]+epoll;' "$nginx_conf"; then + $SUDO sed -i '/^[[:space:]]*multi_accept[[:space:]]\+on;/a\ use epoll;' "$nginx_conf" || true + fi + + 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; +EOF +} + +BCRYPT_CODE=" +let bcrypt; +try { bcrypt = require('bcrypt'); } catch (e) { + console.log('Using bcryptjs fallback'); + bcrypt = require('bcryptjs'); +} +module.exports = bcrypt; +" + +change_password() { + ui_section "=== Change an user password ===" + + if ! ensure_node_prerequisites; then + ui_error "Cannot continue without the required Node.js runtime and extensions." + return 1 + fi + + read -p "$(ui_prompt "Enter user email: ")" EMAIL + + read -s -p "$(ui_prompt "Enter current password: ")" CURRENT + echo "" + + while true; do + read -s -p "$(ui_prompt "Enter new password: ")" NEW1 + echo "" + read -s -p "$(ui_prompt "Confirm new password: ")" NEW2 + echo "" + if [ "$NEW1" != "$NEW2" ]; then + ui_error "Passwords do not match. Try again." + else + break + fi + done + + HASH=$(node -e " + let bcrypt; + try { bcrypt = require('bcrypt'); } catch (e) { bcrypt = require('bcryptjs'); } + console.log(bcrypt.hashSync(process.argv[1] || '', 10)); + " "$NEW1") + + if [ -z "$CREATE_USER_SCRIPT" ]; then + ui_error "create-user.js not found; cannot update password." + exit 1 + fi + + if [ -n "$CURRENT" ]; then + $SUDO node "$CREATE_USER_SCRIPT" --update-password --email "$EMAIL" --password-hash "$HASH" --current-password "$CURRENT" + else + $SUDO node "$CREATE_USER_SCRIPT" --update-password --email "$EMAIL" --password-hash "$HASH" + fi +} + +delete_user() { + ui_section "=== Delete an user ===" + + if ! ensure_node_prerequisites; then + ui_error "Cannot continue without the required Node.js runtime and extensions." + return 1 + fi + + read -p "$(ui_prompt "Enter user email: ")" EMAIL + ui_warn "This will permanently delete the user: ${EMAIL}" + read -p "$(ui_prompt "Type YES to confirm: ")" CONFIRM + if [ "$CONFIRM" != "YES" ]; then + ui_warn "Cancelled." + exit 0 + fi + + if [ -z "$CREATE_USER_SCRIPT" ]; then + ui_error "create-user.js not found; cannot delete user." + exit 1 + fi + + $SUDO node "$CREATE_USER_SCRIPT" --delete --email "$EMAIL" +} + +initialize_panel() { + ui_section "=== Panel Initialization ===" + + read -p "$(ui_prompt "Enter admin email: ")" EMAIL + read -s -p "$(ui_prompt "Enter admin password: ")" PASSWORD + echo "" + + if ! ensure_node_prerequisites; then + ui_error "Cannot continue without the required system packages, Node.js runtime, and extensions." + return 1 + fi + + SECRET=$(node - <<'EOF' +const speakeasy = require('speakeasy'); +console.log(speakeasy.generateSecret({length: 20}).base32); +EOF +) + + ui_warn "Your 2FA secret (manual entry works too): $SECRET" + + ui_info "Scan this QR code in your Authenticator app:" + node -e " + const speakeasy = require('speakeasy'); + const qrcode = require('qrcode-terminal'); + const otpAuth = speakeasy.otpauthURL({ + secret: process.argv[1], + label: process.argv[2], + issuer: 'ADPanel', + encoding: 'base32' + }); + qrcode.generate(otpAuth, { small: true }); + " "$SECRET" "$EMAIL" + + HASH=$(node -e " + let bcrypt; + try { bcrypt = require('bcrypt'); } catch (e) { bcrypt = require('bcryptjs'); } + console.log(bcrypt.hashSync(process.argv[1] || '', 10)); + " "$PASSWORD") + + ui_section "=== Network & HTTPS configuration ===" + + read -p "$(ui_prompt "Enter host to bind (default 0.0.0.0): ")" HOST + HOST=${HOST:-0.0.0.0} + + read -p "$(ui_prompt "Do you want to use a domain name for the panel? (yes/no, default no): ")" DOMAIN_CHOICE + DOMAIN_CHOICE="$(lower_trim "$DOMAIN_CHOICE")" + PANEL_DOMAIN="" + if [ "$DOMAIN_CHOICE" == "yes" ] || [ "$DOMAIN_CHOICE" == "y" ]; then + read -p "$(ui_prompt "Enter domain (e.g. panel.example.com): ")" PANEL_DOMAIN + PANEL_DOMAIN="$(trim_ws "$PANEL_DOMAIN")" + if echo "$PANEL_DOMAIN" | tr '[:upper:]' '[:lower:]' | grep -q "adpanel"; then + ui_warn "This hostname contains 'adpanel'. Public TLS certificates are logged in Certificate Transparency logs, so a neutral hostname is better for stealth." + fi + fi + + if [ -n "$PANEL_DOMAIN" ]; then + NGINX_SERVER_NAME="$PANEL_DOMAIN" + CSRF_ALLOWED_HOSTS="$PANEL_DOMAIN" + PANEL_PUBLIC_HOST="$PANEL_DOMAIN" + else + ui_info "Detecting public IP..." + inputs_ip="$(detect_default_panel_ip)" + + ui_warn "No domain selected. To prevent CSRF issues, we need the IP you will use to access the panel." + read -p "$(ui_prompt "Enter panel IP (default ${inputs_ip}): ")" PANEL_IP_IN + PANEL_IP_IN="$(trim_ws "$PANEL_IP_IN")" + if [ -z "$PANEL_IP_IN" ]; then + PANEL_IP_IN="$inputs_ip" + fi + + NGINX_SERVER_NAME="$PANEL_IP_IN" + CSRF_ALLOWED_HOSTS="$PANEL_IP_IN" + PANEL_PUBLIC_HOST="$PANEL_IP_IN" + ui_success "Configured for IP access: ${PANEL_IP_IN}" + fi + + read -p "$(ui_prompt "Do you want to enable HTTPS? (yes/no, default yes): ")" HTTPS_CHOICE + HTTPS_CHOICE="$(lower_trim "$HTTPS_CHOICE")" + + if [ -z "$HTTPS_CHOICE" ] || [ "$HTTPS_CHOICE" == "yes" ] || [ "$HTTPS_CHOICE" == "y" ]; then + ENABLE_HTTPS=true + + read -p "$(ui_prompt "Enter HTTP port (default 80): ")" HTTP_PORT + HTTP_PORT="$(normalize_port "$HTTP_PORT" 80)" + + read -p "$(ui_prompt "Enter HTTPS port (default 443): ")" HTTPS_PORT + HTTPS_PORT="$(normalize_port "$HTTPS_PORT" 443)" + + read -p "$(ui_prompt "Force redirect HTTP to HTTPS? (yes/no, default yes): ")" FORCE_CHOICE + FORCE_CHOICE="$(lower_trim "$FORCE_CHOICE")" + if [ -z "$FORCE_CHOICE" ] || [ "$FORCE_CHOICE" == "yes" ] || [ "$FORCE_CHOICE" == "y" ]; then + FORCE_HTTPS=true + else + FORCE_HTTPS=false + fi + + SESSION_COOKIE_SECURE=true + if [ "$HTTP_PORT" != "80" ]; then + ui_warn "Note: Let's Encrypt validation typically needs port 80 reachable. HTTP_PORT=$HTTP_PORT may cause issues." + fi + + else + ENABLE_HTTPS=false + FORCE_HTTPS=false + SESSION_COOKIE_SECURE=false + + read -p "$(ui_prompt "Enter HTTP port (default 80): ")" HTTP_PORT + HTTP_PORT="$(normalize_port "$HTTP_PORT" 80)" + + HTTPS_PORT=443 + fi + + NGINX_ENABLED=false + APP_HOST="127.0.0.1" + APP_PORT=3001 + if [ "$HTTP_PORT" == "$APP_PORT" ] || [ "$HTTPS_PORT" == "$APP_PORT" ]; then + APP_PORT=3002 + fi + + SSL_KEY_PATH= + SSL_CERT_PATH= + + ui_info "Generating strong SESSION_SECRET..." + SESSION_SECRET=$(node - <<'EOF' +const crypto = require('crypto'); +const min = 64; +const max = 99; +const length = Math.floor(Math.random() * (max - min + 1)) + min; +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-'; +let result = ''; +const bytes = crypto.randomBytes(length); +for (let i = 0; i < length; i++) { + result += chars[bytes[i] % chars.length]; +} +console.log(result); +EOF +) + + ui_info "Generating DUMMY_HASH..." + DUMMY_HASH=$(node - <<'EOF' +const crypto = require('crypto'); +const bcrypt = require('bcryptjs'); +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; +const length = 64; +let raw = ''; +const bytes = crypto.randomBytes(length); +for (let i = 0; i < length; i++) { + raw += chars[bytes[i] % chars.length]; +} +const hash = bcrypt.hashSync(raw, 10); +console.log(hash); +EOF +) + + ui_section "=== Captcha configuration (optional) ===" + read -p "$(ui_prompt "Enter SITE_KEY (leave blank to disable captcha): ")" SITE_KEY + SITE_KEY="$(trim_ws "$SITE_KEY")" + read -s -p "$(ui_prompt "Enter SECRET_KEY (leave blank to disable captcha): ")" SECRET_KEY + echo "" + SECRET_KEY="$(trim_ws "$SECRET_KEY")" + + setup_redis || true + if ! setup_mysql; then + ui_error "MySQL/MariaDB setup failed. The panel needs a working database for user storage." + return 1 + fi + + # Enterprise security: lock down MariaDB and optionally harden firewall + if is_mysql_installed; then + secure_mariadb_binding || true + fi + FIREWALL_HARDEN="${ADPANEL_FIREWALL_HARDEN:-}" + if [ -z "$FIREWALL_HARDEN" ]; then + read -p "$(ui_prompt "Apply firewall hardening for SMB/MySQL? This may install or enable a firewall service (yes/no, default no): ")" FIREWALL_HARDEN + fi + FIREWALL_HARDEN="$(lower_trim "$FIREWALL_HARDEN")" + if [ "$FIREWALL_HARDEN" == "yes" ] || [ "$FIREWALL_HARDEN" == "y" ]; then + harden_firewall + else + 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)" + + if install_nginx; then + service_enable nginx + service_start nginx + if write_nginx_config; then + NGINX_ENABLED=true + else + NGINX_ENABLED=false + ui_warn "nginx installed but ADPanel nginx config could not be validated; panel will run directly." + fi + else + ui_warn "nginx install failed; panel will run without reverse proxy." + fi + + if [ "$ENABLE_HTTPS" == "true" ]; then + if [ -z "$PANEL_DOMAIN" ]; then + ui_warn "No domain provided; skipping Let's Encrypt certificate generation." + else + if install_certbot; then + ensure_certbot_nginx_plugin >/dev/null 2>&1 || true + ui_info "Requesting Let's Encrypt certificate for: ${PANEL_DOMAIN}" + ui_info "Running certbot in non-interactive mode with admin email: ${EMAIL}" + if [ "$NGINX_ENABLED" == "true" ]; then + $SUDO certbot --nginx -d "$PANEL_DOMAIN" --non-interactive --agree-tos -m "$EMAIL" --keep-until-expiring + else + $SUDO certbot certonly --standalone -d "$PANEL_DOMAIN" --non-interactive --agree-tos -m "$EMAIL" --keep-until-expiring + fi + + if [ $? -eq 0 ]; then + SSL_KEY_PATH="/etc/letsencrypt/live/$PANEL_DOMAIN/privkey.pem" + SSL_CERT_PATH="/etc/letsencrypt/live/$PANEL_DOMAIN/fullchain.pem" + ui_success "Certificate obtained successfully!" + else + ui_error "certbot failed or was cancelled. SSL paths will be left empty." + SSL_KEY_PATH= + SSL_CERT_PATH= + fi + else + ui_error "certbot could not be installed. SSL paths will be left empty." + SSL_KEY_PATH= + SSL_CERT_PATH= + fi + fi + fi + + if [ "$ENABLE_HTTPS" == "true" ] && { [ -z "$SSL_CERT_PATH" ] || [ -z "$SSL_KEY_PATH" ]; }; then + ui_warn "HTTPS enabled but SSL cert/key missing. Falling back to HTTP-only." + ENABLE_HTTPS=false + FORCE_HTTPS=false + SESSION_COOKIE_SECURE=false + fi + + if [ "$NGINX_ENABLED" == "true" ]; then + if ! write_nginx_config; then + NGINX_ENABLED=false + ui_warn "Final nginx config validation failed; panel will run directly." + fi + fi + + if [ "$NGINX_ENABLED" != "true" ]; then + if [ "$HTTP_PORT" -lt 1024 ] 2>/dev/null; then + ui_warn "nginx is not enabled; using HTTP_PORT=3001 so the non-root panel service can bind safely." + HTTP_PORT=3001 + fi + if [ "$ENABLE_HTTPS" == "true" ] && [ "$HTTPS_PORT" -lt 1024 ] 2>/dev/null; then + ui_warn "nginx is not enabled; using HTTPS_PORT=3443 so the non-root panel service can bind safely." + HTTPS_PORT=3443 + fi + fi + + local public_scheme="http" + local public_port="$HTTP_PORT" + if [ "$ENABLE_HTTPS" == "true" ]; then + public_scheme="https" + public_port="$HTTPS_PORT" + 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" + + cat < .env +HOST=$HOST +CSRF_ALLOWED_HOSTS=$CSRF_ALLOWED_HOSTS +PANEL_PUBLIC_URL=$PANEL_PUBLIC_URL +HTTP_PORT=$HTTP_PORT +HTTPS_PORT=$HTTPS_PORT +ENABLE_HTTPS=$ENABLE_HTTPS +FORCE_HTTPS=$FORCE_HTTPS +SSL_KEY_PATH=$SSL_KEY_PATH +SSL_CERT_PATH=$SSL_CERT_PATH +SESSION_COOKIE_SECURE=$SESSION_COOKIE_SECURE +SESSION_STORE=$SESSION_STORE +NGINX_ENABLED=$NGINX_ENABLED +APP_HOST=$APP_HOST +${APP_PORT_LINE} +STEALTH_MODE=true +STEALTH_COOKIE_TTL_DAYS=30 +STEALTH_RESPONSE_FLOOR_MS=90 +STEALTH_ALLOW_HEALTHCHECK=false +SITE_KEY="$SITE_KEY" +SECRET_KEY="$SECRET_KEY" +REDIS_HOST=$REDIS_HOST +REDIS_PORT=$REDIS_PORT +REDIS_USER=$REDIS_USER +REDIS_PASSWORD="$REDIS_PASSWORD" +REDIS_URL="$REDIS_URL" +MYSQL_HOST=$MYSQL_HOST +MYSQL_PORT=$MYSQL_PORT +MYSQL_USER=$MYSQL_USER +MYSQL_PASSWORD="$MYSQL_PASSWORD" +MYSQL_DATABASE=$MYSQL_DATABASE +MYSQL_URL="$MYSQL_URL" +LOGIN_SUSPICIOUS_ATTEMPTS=5 +LOGIN_SUSPICIOUS_FAST_WINDOW_MS=20000 +LOGIN_SUSPICIOUS_FAST_ATTEMPTS=3 +LOGIN_SUSPICIOUS_WINDOW_MS=300000 +SESSION_SECRET="$SESSION_SECRET" +DUMMY_HASH="$DUMMY_HASH" +BROTLI_QUALITY=4 +SSH_TERM_PORT=9393 +SSH_TERM_PUBLIC_URL=$SSH_TERM_PUBLIC_URL_VALUE +EOF + + ui_success ".env file created with network and security settings." + + if bootstrap_db_and_create_admin "$EMAIL" "$HASH" "$SECRET"; then + ui_success "Admin account created in database." + else + ui_warn "Panel setup completed, but admin account creation in database failed." + fi + ui_warn "Panel setup complete!" + 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}." + fi +} + +load_mysql_env() { + if [ ! -f "${SCRIPT_DIR}/.env" ]; then + ui_error ".env not found. Run 'Initialize Panel' first." + return 1 + fi + + local values + values=$(node - <<'EOF' +const fs = require("fs"); +const path = require("path"); +const envPath = path.join(process.cwd(), ".env"); +if (!fs.existsSync(envPath)) process.exit(2); +let parsed = {}; +try { + const dotenv = require("dotenv"); + parsed = dotenv.parse(fs.readFileSync(envPath, "utf8")); +} catch (err) { + console.error(err && err.message ? err.message : String(err)); + process.exit(3); +} +const keys = ["MYSQL_URL", "MYSQL_HOST", "MYSQL_PORT", "MYSQL_USER", "MYSQL_PASSWORD", "MYSQL_DATABASE"]; +for (const key of keys) { + const raw = parsed[key]; + process.stdout.write((raw == null ? "" : String(raw)).replace(/\r?\n/g, "")); + process.stdout.write("\n"); +} +EOF +) + if [ $? -ne 0 ]; then + ui_error "Failed to read MySQL settings from .env." + return 1 + fi + + IFS=$'\n' read -r MYSQL_URL MYSQL_HOST MYSQL_PORT MYSQL_USER MYSQL_PASSWORD MYSQL_DATABASE <<< "$values" + + 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." + return 1 + fi + + return 0 +} + +create_user() { + ui_section "=== Create New User ===" + + if ! ensure_node_prerequisites; then + ui_error "Cannot continue without the required Node.js runtime and extensions." + return 1 + fi + + read -p "$(ui_prompt "Enter user email: ")" EMAIL + EMAIL="$(trim_ws "$EMAIL")" + if [ -z "$EMAIL" ]; then + ui_error "Email cannot be empty." + return 1 + fi + while true; do + read -s -p "$(ui_prompt "Enter user password: ")" PASS1 + echo "" + read -s -p "$(ui_prompt "Confirm user password: ")" PASS2 + echo "" + if [ "$PASS1" != "$PASS2" ]; then + ui_error "Passwords do not match. Try again." + else + break + fi + done + + read -p "$(ui_prompt "Should this user be an admin? (y/n): ")" ISADMIN + + SECRET=$(node - <<'EOF' +const speakeasy = require('speakeasy'); +console.log(speakeasy.generateSecret({length: 20}).base32); +EOF +) + + ui_warn "Your 2FA secret (manual entry works too): $SECRET" + + ui_info "Scan this QR code in your Authenticator app:" + node -e " + const speakeasy = require('speakeasy'); + const qrcode = require('qrcode-terminal'); + const otpAuth = speakeasy.otpauthURL({ + secret: process.argv[1], + label: process.argv[2], + issuer: 'ADPanel', + encoding: 'base32' + }); + qrcode.generate(otpAuth, { small: true }); + " "$SECRET" "$EMAIL" + + local create_script="$CREATE_USER_SCRIPT" + if [ -z "$create_script" ]; then + ui_error "create-user.js not found; cannot create user." + return 1 + fi + + if ! load_mysql_env; then + return 1 + fi + + local admin_flag="" + local avatar_url="" + if lower_trim "$ISADMIN" | grep -qE '^y'; then + admin_flag="--admin" + avatar_url="$(pick_default_avatar_url admin)" + else + avatar_url="$(pick_default_avatar_url user)" + fi + ui_info "Assigned avatar: ${avatar_url}" + + local env_cmd=(env) + [ -n "$MYSQL_URL" ] && env_cmd+=("MYSQL_URL=$MYSQL_URL") + [ -n "$MYSQL_HOST" ] && env_cmd+=("MYSQL_HOST=$MYSQL_HOST") + [ -n "$MYSQL_PORT" ] && env_cmd+=("MYSQL_PORT=$MYSQL_PORT") + [ -n "$MYSQL_USER" ] && env_cmd+=("MYSQL_USER=$MYSQL_USER") + env_cmd+=("MYSQL_PASSWORD=$MYSQL_PASSWORD") + [ -n "$MYSQL_DATABASE" ] && env_cmd+=("MYSQL_DATABASE=$MYSQL_DATABASE") + + local cmd=("${env_cmd[@]}" node "$create_script" --email "$EMAIL" --password "$PASS1" --secret "$SECRET") + if [ -n "$admin_flag" ]; then + cmd+=("$admin_flag") + fi + if [ -n "$avatar_url" ]; then + cmd+=("--avatar-url" "$avatar_url") + fi + if [ -n "$SUDO" ]; then + cmd=("$SUDO" "${cmd[@]}") + fi + + "${cmd[@]}" + local rc=$? + if [ "$rc" -ne 0 ]; then + ui_error "Failed to create user in MySQL." + return "$rc" + fi + + ui_success "User created successfully in MySQL." +} + +if [ "$CHOICE" == "1" ]; then + initialize_panel +elif [ "$CHOICE" == "2" ]; then + change_password +elif [ "$CHOICE" == "3" ]; then + delete_user +elif [ "$CHOICE" == "4" ]; then + create_user +else + ui_error "Invalid choice. Exiting." + exit 1 +fi diff --git a/middleware/auth.js b/middleware/auth.js new file mode 100644 index 0000000..7d67d4e --- /dev/null +++ b/middleware/auth.js @@ -0,0 +1,46 @@ +const fs = require("fs"); +const fsp = require("fs/promises"); +const path = require("path"); +const bcrypt = require("bcrypt"); +const speakeasy = require("speakeasy"); + +const USERS_FILE = path.join(__dirname, "..", "users.json"); + +let users = {}; +try { + users = JSON.parse(fs.readFileSync(USERS_FILE, "utf8")); +} catch { + users = {}; +} + +async function saveUsers() { + try { + const json = JSON.stringify(users, null, 2); + await fsp.writeFile(USERS_FILE, json, "utf8"); + } catch (e) { + console.error("Failed to save users data:", e); + } +} + +function authMiddleware(req, res, next) { + if (req.path.startsWith("/register")) return next(); + + const sessionUser = req.session?.user; + if (!sessionUser) { + return res.redirect("/login"); + } + + if (!Object.prototype.hasOwnProperty.call(users, sessionUser)) { + req.session.destroy(() => {}); + return res.redirect("/login"); + } + const user = users[sessionUser]; + if (!user) { + req.session.destroy(() => {}); + return res.redirect("/login"); + } + + next(); +} + +module.exports = { authMiddleware, users, saveUsers }; diff --git a/mysql-schema.sql b/mysql-schema.sql new file mode 100644 index 0000000..fda9689 --- /dev/null +++ b/mysql-schema.sql @@ -0,0 +1,189 @@ +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, + admin TINYINT(1) NOT NULL DEFAULT 0, + avatar_url VARCHAR(2048) NULL, + preferences JSON NULL, + recovery_codes 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_users_email (email) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS nodes ( + id VARCHAR(64) NOT NULL, + uuid VARCHAR(64) NULL, + name VARCHAR(120) NOT NULL, + address VARCHAR(255) NOT NULL, + ram_mb INT NOT NULL DEFAULT 0, + disk_gb INT NOT NULL DEFAULT 0, + ports JSON NOT NULL, + token_id VARCHAR(64) NULL, + token VARCHAR(255) NULL, + created_at BIGINT NULL, + api_port INT NOT NULL DEFAULT 8080, + sftp_port INT NOT NULL DEFAULT 2022, + port_ok TINYINT(1) NULL, + last_seen BIGINT NULL, + last_check BIGINT NULL, + online TINYINT(1) NULL, + build_config JSON NULL, + max_upload_mb INT NOT NULL DEFAULT 10240, + PRIMARY KEY (id), + UNIQUE KEY uniq_nodes_uuid (uuid) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS servers ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + name VARCHAR(120) NOT NULL, + display_name VARCHAR(120) NULL, + legacy_id VARCHAR(120) NULL, + bot VARCHAR(120) NULL, + template VARCHAR(64) NULL, + start VARCHAR(255) NULL, + node_id VARCHAR(64) NULL, + ip VARCHAR(255) NULL, + port INT NULL, + status VARCHAR(32) NULL, + runtime JSON NULL, + docker JSON NULL, + acl JSON NULL, + resources JSON 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_servers_name (name), + KEY idx_servers_node (node_id), + KEY idx_servers_legacy (legacy_id), + KEY idx_servers_bot (bot), + KEY idx_servers_status (status), + 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 user_access ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT UNSIGNED NOT NULL, + server_name VARCHAR(120) NOT NULL, + PRIMARY KEY (id), + UNIQUE KEY uniq_user_access (user_id, server_name), + 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 ai_chats ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + user_email VARCHAR(255) NOT NULL DEFAULT '', + title VARCHAR(255) NOT NULL DEFAULT 'New Chat', + created_by BIGINT UNSIGNED NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY idx_ai_chats_user (user_email), + KEY idx_ai_chats_created (created_at), + CONSTRAINT fk_ai_chats_user FOREIGN KEY (created_by) REFERENCES users(id) ON DELETE SET NULL +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS ai_messages ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + chat_id BIGINT UNSIGNED NOT NULL, + role ENUM('user', 'assistant', 'system') NOT NULL, + content LONGTEXT NOT NULL, + image_data LONGTEXT NULL, + thinking_time_ms INT UNSIGNED NULL, + thinking_content LONGTEXT NULL, + model VARCHAR(255) NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY idx_ai_messages_chat (chat_id), + KEY idx_ai_messages_created (created_at), + CONSTRAINT fk_ai_messages_chat FOREIGN KEY (chat_id) REFERENCES ai_chats(id) ON DELETE CASCADE +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS user_ai_model_selections ( + user_id BIGINT UNSIGNED NOT NULL, + provider VARCHAR(64) NOT NULL, + model VARCHAR(255) NOT NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (user_id), + KEY idx_user_ai_model_provider (provider), + CONSTRAINT fk_user_ai_model_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_agent_jobs ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + chat_id BIGINT UNSIGNED NOT NULL, + user_id BIGINT UNSIGNED NOT NULL, + user_email VARCHAR(255) NOT NULL, + server_name VARCHAR(120) NOT NULL, + provider VARCHAR(64) NOT NULL, + model VARCHAR(255) NOT NULL, + prompt LONGTEXT NOT NULL, + status ENUM('queued','running','completed','failed') NOT NULL DEFAULT 'queued', + source VARCHAR(64) NOT NULL DEFAULT 'manual', + source_ref VARCHAR(255) NULL, + error TEXT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + started_at TIMESTAMP NULL, + completed_at TIMESTAMP NULL, + PRIMARY KEY (id), + KEY idx_ai_agent_jobs_user (user_id, created_at), + KEY idx_ai_agent_jobs_status (status, created_at), + KEY idx_ai_agent_jobs_chat (chat_id), + CONSTRAINT fk_ai_agent_jobs_chat FOREIGN KEY (chat_id) REFERENCES ai_chats(id) ON DELETE CASCADE, + CONSTRAINT fk_ai_agent_jobs_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 server_planner_items ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + server_name VARCHAR(120) NOT NULL, + title VARCHAR(255) NOT NULL, + prompt LONGTEXT NOT NULL, + is_done TINYINT(1) NOT NULL DEFAULT 0, + sort_order INT NOT NULL DEFAULT 0, + created_by_email VARCHAR(255) NOT NULL, + updated_by_email VARCHAR(255) NOT NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY idx_server_planner_server (server_name), + KEY idx_server_planner_sort (server_name, is_done, sort_order, updated_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + +CREATE TABLE IF NOT EXISTS user_status ( + user_id BIGINT UNSIGNED NOT NULL, + status_text VARCHAR(80) NOT NULL DEFAULT 'Available', + expires_at BIGINT UNSIGNED NULL, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (user_id), + KEY idx_user_status_expires (expires_at), + CONSTRAINT fk_user_status_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 sftp_credentials ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + user_id BIGINT UNSIGNED NOT NULL, + server_name VARCHAR(120) NOT NULL, + sftp_username VARCHAR(255) NOT NULL, + sftp_password_hash VARCHAR(255) NOT 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_sftp_user_server (user_id, server_name), + UNIQUE KEY uniq_sftp_username (sftp_username), + KEY idx_sftp_server (server_name), + CONSTRAINT fk_sftp_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 subdomains ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + server_id BIGINT UNSIGNED NOT NULL, + domain VARCHAR(255) NOT NULL, + status ENUM('pending', 'approved', 'canceled') NOT NULL DEFAULT 'pending', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id), + UNIQUE KEY uniq_subdomains_domain (domain), + 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; diff --git a/nodes.js b/nodes.js new file mode 100644 index 0000000..97a862f --- /dev/null +++ b/nodes.js @@ -0,0 +1,3102 @@ +const express = require("express"); +const fs = require("fs"); +const fsp = require("fs/promises"); +const path = require("path"); +const crypto = require("crypto"); +const net = require("net"); +const dns = require("dns").promises; +const http = require("http"); +const https = require("https"); +const ipRangeCheck = require("ip-range-check"); +let _Busboy; function getLazyBusboy() { if (!_Busboy) _Busboy = require("busboy"); return _Busboy; } +const db = require("./db"); + +const ACTIVITY_LOGS_DIR = path.join(__dirname, ".activity-logs"); +const ACTIVITY_LOG_BATCH_INTERVAL = parseInt(process.env.ACTIVITY_LOG_BATCH_INTERVAL || "", 10) || 1000; +const ACTIVITY_LOG_MAX_SIZE = parseInt(process.env.ACTIVITY_LOG_MAX_SIZE || "", 10) || 5 * 1024 * 1024; +const ACTIVITY_LOG_MAX_FILES = parseInt(process.env.ACTIVITY_LOG_MAX_FILES || "", 10) || 10; +const ACTIVITY_LOG_MAX_BUFFER_SIZE = 100; +const ACTIVITY_LOG_MAX_SERVERS = parseInt(process.env.ACTIVITY_LOG_MAX_SERVERS || "", 15) || 5000; + +try { fs.mkdirSync(ACTIVITY_LOGS_DIR, { recursive: true }); } catch { } + +const activityLogBuffers = new Map(); +const activityLogWriteTimers = new Map(); + +function getActivityLogPath(serverName) { + const safeName = String(serverName).replace(/[^a-zA-Z0-9_-]/g, "_"); + return path.join(ACTIVITY_LOGS_DIR, `${safeName}.log`); +} + +function validatePortInput(value) { + if (value === undefined || value === null) return null; + const str = String(value).trim(); + if (!/^[1-9]\d{0,4}$/.test(str)) return null; + const port = Number(str); + if (!Number.isInteger(port) || port < 1 || port > 65535) return null; + return port; +} + +async function rotateActivityLogIfNeeded(serverName) { + const logPath = getActivityLogPath(serverName); + try { + const stats = await fsp.stat(logPath).catch(() => null); + if (!stats || stats.size < ACTIVITY_LOG_MAX_SIZE) return; + + const safeName = String(serverName).replace(/[^a-zA-Z0-9_-]/g, "_"); + const rotatedPath = logPath.replace(/\.log$/, `.${Date.now()}.log`); + await fsp.rename(logPath, rotatedPath); + + setImmediate(async () => { + try { + const files = await fsp.readdir(ACTIVITY_LOGS_DIR); + const serverFiles = files + .filter(f => f.startsWith(safeName + ".") && f.endsWith(".log") && f !== `${safeName}.log`) + .sort() + .reverse(); + for (let i = ACTIVITY_LOG_MAX_FILES; i < serverFiles.length; i++) { + await fsp.unlink(path.join(ACTIVITY_LOGS_DIR, serverFiles[i])).catch(() => { }); + } + } catch { } + }); + } catch { } +} + +async function flushActivityLogs(serverName) { + const buffer = activityLogBuffers.get(serverName); + if (!buffer || buffer.length === 0) return; + + activityLogBuffers.set(serverName, []); + activityLogWriteTimers.delete(serverName); + + const logPath = getActivityLogPath(serverName); + const lines = buffer.map(entry => JSON.stringify(entry)).join("\n") + "\n"; + + try { + await rotateActivityLogIfNeeded(serverName); + await fsp.appendFile(logPath, lines, "utf8"); + } catch (err) { + console.error(`[activity-log] Write error for ${serverName}:`, err?.message || err); + } +} + +let _webhookDispatcher = null; +function setWebhookDispatcher(fn) { _webhookDispatcher = fn; } + +function recordActivity(serverName, action, details, userEmail, userIp) { + if (!serverName) return; + + const entry = { + ts: Date.now(), + action: String(action || "unknown"), + details: details || null, + user: String(userEmail || "unknown"), + ip: String(userIp || "unknown"), + }; + + if (!activityLogBuffers.has(serverName)) { + if (activityLogBuffers.size >= ACTIVITY_LOG_MAX_SERVERS) { + const oldest = activityLogBuffers.keys().next().value; + if (oldest) { + flushActivityLogs(oldest); + activityLogBuffers.delete(oldest); + if (activityLogWriteTimers.has(oldest)) { + clearTimeout(activityLogWriteTimers.get(oldest)); + activityLogWriteTimers.delete(oldest); + } + } + } + activityLogBuffers.set(serverName, []); + } + const buffer = activityLogBuffers.get(serverName); + buffer.push(entry); + + if (_webhookDispatcher) { + try { _webhookDispatcher(entry.action, entry.details, entry.user, serverName); } catch (e) {} + } + + if (buffer.length >= ACTIVITY_LOG_MAX_BUFFER_SIZE) { + if (activityLogWriteTimers.has(serverName)) { + clearTimeout(activityLogWriteTimers.get(serverName)); + activityLogWriteTimers.delete(serverName); + } + setImmediate(() => flushActivityLogs(serverName)); + return; + } + + if (!activityLogWriteTimers.has(serverName)) { + const timerId = setTimeout(() => flushActivityLogs(serverName), ACTIVITY_LOG_BATCH_INTERVAL); + activityLogWriteTimers.set(serverName, timerId); + } +} + +function getRequestIp(req) { + const xff = req.headers["x-forwarded-for"]; + if (xff) { + const first = String(xff).split(",")[0].trim(); + if (first) return first; + } + return req.ip || req.connection?.remoteAddress || "unknown"; +} + +const MAX_CONSOLE_COMMAND_LENGTH = parseInt(process.env.MAX_CONSOLE_COMMAND_LENGTH || "", 10) || 512; + +function sanitizeConsoleCommand(rawValue) { + const raw = String(rawValue || "").replace(/\0/g, "").trim(); + if (!raw) { + return { ok: false, error: "empty_command" }; + } + if (raw.length > MAX_CONSOLE_COMMAND_LENGTH) { + return { + ok: false, + error: "command_too_long", + detail: `Console commands must be ${MAX_CONSOLE_COMMAND_LENGTH} characters or fewer.`, + }; + } + if (/[\r\n]/.test(raw)) { + return { + ok: false, + error: "multiline_command_not_allowed", + detail: "Only one console command can be sent at a time.", + }; + } + if (/[\u0001-\u0008\u000B\u000C\u000E-\u001F\u007F]/.test(raw)) { + return { + ok: false, + error: "invalid_command_characters", + detail: "Console commands cannot include control characters.", + }; + } + return { ok: true, command: raw }; +} + +let _getEffectivePermsForUserOnServer = null; +let _isAdmin = null; +let _userHasAccessToServer = null; +function setPermissionCheckers(getPerms, isAdminFn, hasAccessFn) { + _getEffectivePermsForUserOnServer = getPerms; + _isAdmin = isAdminFn; + _userHasAccessToServer = hasAccessFn || null; +} + +async function checkUserPerm(req, serverName, permKey) { + if (!_getEffectivePermsForUserOnServer || !_isAdmin) { + console.error("[SECURITY] Permission checkers not configured - denying access"); + return false; + } + const userEmail = req.session?.user; + if (!userEmail) return false; + if (await _isAdmin(req)) return true; + const perms = await _getEffectivePermsForUserOnServer(userEmail, serverName); + return !!(perms && perms[permKey]); +} + +async function checkServerAccess(req, serverName) { + const userEmail = req.session?.user; + if (!userEmail) return { ok: false, status: 401, error: "not authenticated" }; + if (_isAdmin && await _isAdmin(req)) return { ok: true }; + if (_userHasAccessToServer) { + const hasAccess = await _userHasAccessToServer(userEmail, serverName); + if (!hasAccess) return { ok: false, status: 403, error: "no access to server" }; + } else { + console.error("[SECURITY] userHasAccessToServer not configured - denying non-admin access"); + return { ok: false, status: 403, error: "access checker not configured" }; + } + return { ok: true }; +} +const PORT = process.env.NODES_PORT ? Number(process.env.NODES_PORT) : 3550; +const HEARTBEAT_TTL_MS = 120_000; +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(); + +(async () => { + try { + await db.query("ALTER TABLE nodes ADD COLUMN max_upload_mb INT NOT NULL DEFAULT 10240"); + console.log("[nodes] Migration: added max_upload_mb column to nodes table"); + } catch (e) { + if (e && e.code !== "ER_DUP_FIELDNAME" && !String(e.message || "").includes("Duplicate column")) { + console.warn("[nodes] Migration warning (max_upload_mb):", e.message); + } + } +})(); + +(async () => { + try { + await db.query("ALTER TABLE nodes ADD COLUMN sftp_port INT NOT NULL DEFAULT 2022 AFTER api_port"); + console.log("[nodes] Migration: added sftp_port column to nodes table"); + } catch (e) { + if (e && e.code !== "ER_DUP_FIELDNAME" && !String(e.message || "").includes("Duplicate column")) { + console.warn("[nodes] Migration warning (sftp_port):", e.message); + } + } +})(); + +function safeCompare(a, b) { + if (typeof a !== "string" || typeof b !== "string") return false; + const bufA = Buffer.from(a); + const bufB = Buffer.from(b); + if (bufA.length !== bufB.length) { + crypto.timingSafeEqual(bufA, bufA); + return false; + } + return crypto.timingSafeEqual(bufA, bufB); +} + +function parseDbJson(value, fallback) { + if (value === undefined || value === null || value === "") return fallback; + if (typeof value === "object") return value; + try { + return JSON.parse(value); + } catch { + return fallback; + } +} + +function toDbJson(value, fallback) { + if (value === undefined || value === null) return fallback; + return JSON.stringify(value); +} +function uid() { return crypto.randomUUID(); } + +function randTokenId() { + return "tok_" + crypto.randomBytes(8).toString("hex"); +} + +function randSecret() { + const ts = Buffer.alloc(8); + const now = BigInt(Date.now()); + ts.writeBigUInt64BE(now); + const rand = crypto.randomBytes(32); + const combined = Buffer.concat([ts, rand]); + return combined + .toString("base64") + .replace(/\+/g, "-") + .replace(/\//g, "_") + .replace(/=+$/, ""); +} +function sanitizeName(raw) { + let s = String(raw || "").trim(); + if (!s) return ""; + s = s.replace(/[^\w\-. ]+/g, " ").replace(/\s+/g, " ").trim(); + s = s.replace(/\s/g, "-"); + if (s.length > 100) s = s.slice(0, 100); + return s; +} +function isInt(n) { return Number.isInteger(n); } +function toInt(n, def = 0) { const x = Number(n); return Number.isFinite(x) ? Math.round(x) : def; } +function clampPort(p) { + const n = toInt(p, 8080); + if (n < 1 || n > 65535) return 8080; + return n; +} +function normalizePorts(input) { + if (!input) return { mode: "range", start: 25565, count: 10 }; + if (Array.isArray(input)) { + const ports = Array.from(new Set(input.map(p => toInt(p)).filter(p => p >= 1 && p <= 65535))); + return { mode: "list", ports }; + } + if (typeof input === "object") { + if (input.mode === "range") { + let start = toInt(input.start, 25565); + let count = toInt(input.count, 10); + if (start < 1 || start > 65535) start = 25565; + if (count < 1) count = 1; + if (start + count - 1 > 65535) count = 65535 - start + 1; + return { mode: "range", start, count }; + } + if (input.mode === "list") { + const ports = Array.from(new Set((input.ports || []) + .map(p => toInt(p)) + .filter(p => p >= 1 && p <= 65535))); + return { mode: "list", ports }; + } + } + return { mode: "range", start: 25565, count: 10 }; +} +function isPortInNodeAllocation(node, port) { + const p = Number(port); + if (!Number.isFinite(p) || p < 1 || p > 65535) return false; + const alloc = node && node.ports; + if (!alloc) return true; + if (alloc.mode === "range") { + const start = Number(alloc.start || 0); + const count = Number(alloc.count || 0); + if (start <= 0 || count <= 0) return true; + return p >= start && p < start + count; + } + if (alloc.mode === "list" && Array.isArray(alloc.ports)) { + if (alloc.ports.length === 0) return true; + return alloc.ports.includes(p); + } + return true; +} + +function truthyFlag(value) { + if (typeof value === "boolean") return value; + if (typeof value === "number") return value === 1; + if (typeof value === "string") { + const normalized = value.trim().toLowerCase(); + return normalized === "true" || normalized === "1" || normalized === "yes" || normalized === "on"; + } + return false; +} + +const CLOUDFLARE_HTTPS_EDGE_PORTS = new Set([443, 2053, 2083, 2087, 2096, 8443]); +const CLOUDFLARE_IPS_V4_URL = "https://www.cloudflare.com/ips-v4"; +const CLOUDFLARE_IPS_V6_URL = "https://www.cloudflare.com/ips-v6"; +const CLOUDFLARE_IP_CACHE_TTL_MS = 6 * 60 * 60 * 1000; +const CLOUDFLARE_IP_RANGES_FALLBACK = Object.freeze([ + "173.245.48.0/20", + "103.21.244.0/22", + "103.22.200.0/22", + "103.31.4.0/22", + "141.101.64.0/18", + "108.162.192.0/18", + "190.93.240.0/20", + "188.114.96.0/20", + "197.234.240.0/22", + "198.41.128.0/17", + "162.158.0.0/15", + "104.16.0.0/13", + "104.24.0.0/14", + "172.64.0.0/13", + "131.0.72.0/22", + "2400:cb00::/32", + "2606:4700::/32", + "2803:f800::/32", + "2405:b500::/32", + "2405:8100::/32", + "2a06:98c0::/29", + "2c0f:f248::/32", +]); +const cloudflareDnsResolver = new dns.Resolver(); +cloudflareDnsResolver.setServers(["1.1.1.1", "1.0.0.1"]); +let cloudflareIpRangesCache = { expiresAt: 0, ranges: CLOUDFLARE_IP_RANGES_FALLBACK }; +let cloudflareIpRangesInFlight = null; + +function cloudflareHttpsEdgePort(port) { + const p = clampPort(port || 443); + return CLOUDFLARE_HTTPS_EDGE_PORTS.has(p) ? p : 443; +} + +function isCloudflareHttpsPort(port) { + return CLOUDFLARE_HTTPS_EDGE_PORTS.has(clampPort(port || 0)); +} + +function hasExplicitHostPort(host) { + const value = String(host || "").trim(); + if (value.startsWith("[")) return /\]:\d+$/.test(value); + return /^[^:]+:\d+$/.test(value); +} + +function explicitHostPort(host) { + const value = String(host || "").trim(); + const match = value.startsWith("[") + ? value.match(/\]:(\d+)$/) + : value.match(/^[^:]+:(\d+)$/); + return match ? Number(match[1]) : null; +} + +function stripExplicitHostPort(host) { + const value = String(host || "").trim(); + if (!hasExplicitHostPort(value)) return value; + if (value.startsWith("[")) return value.replace(/\]:\d+$/, "]"); + return value.replace(/:\d+$/, ""); +} + +function httpsGetText(url, timeoutMs = 5000) { + return new Promise((resolve, reject) => { + const req = https.get(url, { timeout: timeoutMs, headers: { "User-Agent": "ADPanel/Cloudflare-Proxy-Check" } }, (res) => { + if (res.statusCode !== 200) { + res.resume(); + reject(new Error(`Cloudflare IP list returned ${res.statusCode}`)); + return; + } + const chunks = []; + res.on("data", chunk => chunks.push(chunk)); + res.on("end", () => resolve(Buffer.concat(chunks).toString("utf8"))); + }); + req.on("timeout", () => req.destroy(new Error("Cloudflare IP list timeout"))); + req.on("error", reject); + }); +} + +function parseCloudflareIpList(text) { + return String(text || "") + .split(/\r?\n/) + .map(line => line.trim()) + .filter(line => line && !line.startsWith("#")); +} + +async function getCloudflareIpRanges() { + const now = Date.now(); + if (cloudflareIpRangesCache.expiresAt > now && cloudflareIpRangesCache.ranges.length) { + return cloudflareIpRangesCache.ranges; + } + if (cloudflareIpRangesInFlight) return cloudflareIpRangesInFlight; + cloudflareIpRangesInFlight = (async () => { + try { + const [v4, v6] = await Promise.all([ + httpsGetText(CLOUDFLARE_IPS_V4_URL), + httpsGetText(CLOUDFLARE_IPS_V6_URL), + ]); + const ranges = [...parseCloudflareIpList(v4), ...parseCloudflareIpList(v6)]; + if (!ranges.length) throw new Error("empty Cloudflare IP list"); + cloudflareIpRangesCache = { expiresAt: now + CLOUDFLARE_IP_CACHE_TTL_MS, ranges }; + return ranges; + } catch (err) { + console.warn("[cloudflare-check] Falling back to bundled Cloudflare IP ranges:", err?.message || err); + cloudflareIpRangesCache = { expiresAt: now + 15 * 60 * 1000, ranges: CLOUDFLARE_IP_RANGES_FALLBACK }; + return cloudflareIpRangesCache.ranges; + } finally { + cloudflareIpRangesInFlight = null; + } + })(); + return cloudflareIpRangesInFlight; +} + +function extractHostnameForCloudflareCheck(address) { + const raw = String(address || "").trim(); + if (!raw) return ""; + let host = ""; + if (/^https?:\/\//i.test(raw)) { + try { + host = new URL(raw).hostname; + } catch { + return ""; + } + } else { + const withoutPath = raw.split(/[/?#]/)[0]; + if (withoutPath.startsWith("[")) { + const end = withoutPath.indexOf("]"); + host = end > 0 ? withoutPath.slice(1, end) : ""; + } else { + const colonCount = (withoutPath.match(/:/g) || []).length; + host = colonCount === 1 ? withoutPath.split(":")[0] : withoutPath; + } + } + host = String(host || "").trim().toLowerCase(); + if (!host || host === "localhost" || net.isIP(host)) return ""; + return /^[a-z0-9.-]+$/i.test(host) ? host : ""; +} + +async function resolvePublicHostnameIps(hostname) { + const resolvers = [ + { name: "Cloudflare DNS", resolver: cloudflareDnsResolver }, + { name: "system DNS", resolver: dns }, + ]; + const errors = []; + for (const entry of resolvers) { + const [v4, v6] = await Promise.all([ + entry.resolver.resolve4(hostname).catch(err => { + errors.push(`${entry.name} A: ${err?.code || err?.message || "failed"}`); + return []; + }), + entry.resolver.resolve6(hostname).catch(err => { + errors.push(`${entry.name} AAAA: ${err?.code || err?.message || "failed"}`); + return []; + }), + ]); + const ips = [...v4, ...v6].filter(Boolean); + if (ips.length) return { ips, resolver: entry.name }; + } + return { ips: [], resolver: "", error: errors.join("; ") }; +} + +async function verifyCloudflareProxiedAddress(address) { + const hostname = extractHostnameForCloudflareCheck(address); + if (!hostname) { + return { + ok: false, + error: "Under Cloudflare requires a public hostname, not an IP address or localhost.", + }; + } + const [{ ips, resolver, error }, ranges] = await Promise.all([ + resolvePublicHostnameIps(hostname), + getCloudflareIpRanges(), + ]); + if (!ips.length) { + return { + ok: false, + error: `Could not resolve ${hostname} in public DNS for Cloudflare proxy verification.`, + detail: error || null, + }; + } + const nonCloudflareIps = ips.filter(ip => !ipRangeCheck(ip, ranges)); + if (nonCloudflareIps.length) { + return { + ok: false, + error: `${hostname} is not proxied by Cloudflare. Turn on the orange-cloud proxy in Cloudflare DNS, then try again.`, + detail: `Resolved via ${resolver}: ${ips.join(", ")}. Non-Cloudflare IPs: ${nonCloudflareIps.join(", ")}`, + }; + } + return { ok: true, hostname, ips, resolver }; +} + +function nodeUnderCloudflare(node) { + const bc = (node && typeof node.buildConfig === "object") ? node.buildConfig : {}; + return truthyFlag(node?.under_cloudflare) + || truthyFlag(node?.cloudflare_proxy) + || truthyFlag(bc.under_cloudflare) + || truthyFlag(bc.cloudflare_proxy); +} + +function hardenNode(n) { + const clone = Object.assign({ + id: uid(), + uuid: "", + name: "node", + address: "", + ram_mb: 0, + disk_gb: 0, + ports: { mode: "range", start: 25565, count: 10 }, + token_id: randTokenId(), + token: randSecret(), + createdAt: Date.now(), + api_port: 8080, + sftp_port: 2022, + port_ok: null, + last_seen: null, + last_check: null, + online: null, + buildConfig: {}, + under_cloudflare: false, + max_upload_mb: 10240 + }, n || {}); + if (!clone.id) clone.id = uid(); + if (!clone.uuid) clone.uuid = clone.id; + if (!isInt(clone.ram_mb)) clone.ram_mb = toInt(clone.ram_mb, 0); + if (!isInt(clone.disk_gb)) clone.disk_gb = toInt(clone.disk_gb, 0); + clone.name = sanitizeName(clone.name || "node"); + clone.address = String(clone.address || "").trim(); + clone.ports = normalizePorts(clone.ports); + if (!clone.token_id) clone.token_id = randTokenId(); + if (!clone.token) clone.token = randSecret(); + if (!clone.createdAt) clone.createdAt = Date.now(); + clone.api_port = clampPort(clone.api_port || 8080); + clone.sftp_port = clampPort(clone.sftp_port || 2022); + clone.max_upload_mb = Math.max(1, Math.min(100000, toInt(clone.max_upload_mb, 10240))); + clone.buildConfig = (clone.buildConfig && typeof clone.buildConfig === "object") ? clone.buildConfig : {}; + clone.under_cloudflare = nodeUnderCloudflare(clone); + clone.buildConfig.under_cloudflare = !!clone.under_cloudflare; + if (typeof clone.port_ok !== "boolean") clone.port_ok = null; + if (clone.last_seen != null) clone.last_seen = Number(clone.last_seen); + if (clone.last_check != null) clone.last_check = Number(clone.last_check); + return clone; +} +function mapNodeRow(row) { + const bc = parseDbJson(row.build_config, {}); + return hardenNode({ + id: row.id, + uuid: row.uuid, + name: row.name, + address: row.address, + ram_mb: row.ram_mb, + disk_gb: row.disk_gb, + ports: parseDbJson(row.ports, { mode: "range", start: 25565, count: 10 }), + token_id: row.token_id, + token: row.token, + createdAt: row.created_at ? Number(row.created_at) : null, + api_port: row.api_port, + sftp_port: row.sftp_port != null ? Number(row.sftp_port) : 2022, + port_ok: row.port_ok === null ? null : !!row.port_ok, + last_seen: row.last_seen, + last_check: row.last_check, + online: row.online === null ? null : !!row.online, + buildConfig: bc, + ssl_enabled: !!bc.ssl_enabled, + under_cloudflare: nodeUnderCloudflare({ buildConfig: bc }), + max_upload_mb: row.max_upload_mb != null ? Number(row.max_upload_mb) : 10240, + }); +} + +async function loadNodes() { + const rows = await db.query("SELECT * FROM nodes"); + return rows.map(mapNodeRow); +} + +async function loadNodesPaginated(page, limit, search) { + page = Math.max(1, parseInt(page, 10) || 1); + limit = Math.max(1, Math.min(100, parseInt(limit, 10) || 50)); + const offset = (page - 1) * limit; + let countSql = "SELECT COUNT(*) AS total FROM nodes"; + let dataSql = "SELECT * FROM nodes"; + const params = []; + const countParams = []; + if (search && typeof search === "string" && search.trim()) { + const pattern = `%${search.trim()}%`; + const where = " WHERE LOWER(name) LIKE ? OR LOWER(address) LIKE ? OR LOWER(id) LIKE ? OR LOWER(uuid) LIKE ?"; + countSql += where; + dataSql += where; + countParams.push(pattern, pattern, pattern, pattern); + params.push(pattern, pattern, pattern, pattern); + } + // MariaDB on this project rejects prepared placeholders inside LIMIT/OFFSET. + dataSql += ` ORDER BY name ASC LIMIT ${limit} OFFSET ${offset}`; + const [countRows, dataRows] = await Promise.all([ + db.query(countSql, countParams), + db.query(dataSql, params) + ]); + const total = Number(countRows[0]?.total || 0); + return { nodes: dataRows.map(mapNodeRow), total, page, limit, totalPages: Math.ceil(total / limit) || 1 }; +} + +async function findNodeByIdOrName(idOrName) { + const key = String(idOrName || "").trim().toLowerCase(); + if (!key) return null; + const rows = await db.query( + "SELECT * FROM nodes WHERE id = ? OR uuid = ? OR LOWER(name) = ? LIMIT 1", + [key, key, key] + ); + return rows.length ? mapNodeRow(rows[0]) : null; +} + +async function insertNode(node) { + const payload = hardenNode(node); + const online = computeOnline(payload); + await db.query( + `INSERT INTO nodes + (id, uuid, name, address, ram_mb, disk_gb, ports, token_id, token, created_at, api_port, sftp_port, port_ok, last_seen, last_check, online, build_config, max_upload_mb) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + payload.id, + payload.uuid || payload.id, + payload.name, + payload.address, + payload.ram_mb, + payload.disk_gb, + toDbJson(payload.ports, "{}"), + payload.token_id, + payload.token, + payload.createdAt || Date.now(), + payload.api_port || 8080, + payload.sftp_port || 2022, + payload.port_ok === null ? null : payload.port_ok ? 1 : 0, + payload.last_seen ?? null, + payload.last_check ?? null, + online ? 1 : 0, + toDbJson(payload.buildConfig || {}, "{}"), + payload.max_upload_mb, + ] + ); + return payload; +} + +async function saveNode(node) { + const payload = hardenNode(node); + const online = computeOnline(payload); + await db.query( + `UPDATE nodes SET + uuid = ?, name = ?, address = ?, ram_mb = ?, disk_gb = ?, ports = ?, token_id = ?, token = ?, created_at = ?, + api_port = ?, sftp_port = ?, port_ok = ?, last_seen = ?, last_check = ?, online = ?, build_config = ?, max_upload_mb = ? + WHERE id = ?`, + [ + payload.uuid || payload.id, + payload.name, + payload.address, + payload.ram_mb, + payload.disk_gb, + toDbJson(payload.ports, "{}"), + payload.token_id, + payload.token, + payload.createdAt || Date.now(), + payload.api_port || 8080, + payload.sftp_port || 2022, + payload.port_ok === null ? null : payload.port_ok ? 1 : 0, + payload.last_seen ?? null, + payload.last_check ?? null, + online ? 1 : 0, + toDbJson(payload.buildConfig || {}, "{}"), + payload.max_upload_mb, + payload.id, + ] + ); + return payload; +} + +async function deleteNode(nodeId) { + await db.query("DELETE FROM nodes WHERE id = ? OR uuid = ?", [nodeId, nodeId]); +} + +function sanitizeUpdatePayload(body) { + const out = {}; + if (typeof body.name !== "undefined") out.name = sanitizeName(body.name); + if (typeof body.address !== "undefined") out.address = String(body.address || "").trim(); + if (typeof body.cpu_cores !== "undefined") out.cpu_cores = toInt(body.cpu_cores, 0); + if (typeof body.ram_mb !== "undefined") out.ram_mb = toInt(body.ram_mb, 0); + else if (typeof body.ramMB !== "undefined") out.ram_mb = toInt(body.ramMB, 0); + else if (typeof body.ram_gb !== "undefined") out.ram_mb = toInt(body.ram_gb, 0) * 1024; + if (typeof body.disk_gb !== "undefined") out.disk_gb = toInt(body.disk_gb, 0); + else if (typeof body.storage_gb !== "undefined") out.disk_gb = toInt(body.storage_gb, 0); + else if (typeof body.storageGB !== "undefined") out.disk_gb = toInt(body.storageGB, 0); + if (typeof body.ports !== "undefined" || + typeof body.port_list !== "undefined" || + typeof body.ports_list !== "undefined" || + typeof body.mode !== "undefined") { + const candidate = body.ports ?? body.ports_list ?? body; + out.ports = normalizePorts(candidate); + } + if (typeof body.api_port !== "undefined") out.api_port = clampPort(body.api_port); + if (typeof body.sftp_port !== "undefined") out.sftp_port = clampPort(body.sftp_port); + if (typeof body.max_upload_mb !== "undefined") { + out.max_upload_mb = Math.max(1, Math.min(100000, toInt(body.max_upload_mb, 10240))); + } + if (typeof body.ssl_enabled !== "undefined") out.ssl_enabled = truthyFlag(body.ssl_enabled); + if (typeof body.under_cloudflare !== "undefined") out.under_cloudflare = truthyFlag(body.under_cloudflare); + else if (typeof body.cloudflare_proxy !== "undefined") out.under_cloudflare = truthyFlag(body.cloudflare_proxy); + return out; +} +function computeOnline(n) { + const fresh = !!(n.last_seen && (Date.now() - Number(n.last_seen)) < HEARTBEAT_TTL_MS); + return !!(fresh && n.port_ok === true); +} +function toPublic(n, includeSecrets = false) { + const bc = n.buildConfig || {}; + const out = { + id: n.id, + uuid: n.uuid, + name: n.name, + address: n.address, + cpu_cores: bc.cpu_cores || 0, + ram_mb: n.ram_mb, + disk_gb: n.disk_gb, + ports: n.ports, + createdAt: n.createdAt, + api_port: n.api_port, + sftp_port: n.sftp_port || 2022, + max_upload_mb: n.max_upload_mb || 10240, + ssl_enabled: !!bc.ssl_enabled, + under_cloudflare: nodeUnderCloudflare(n), + port_ok: n.port_ok, + last_seen: n.last_seen, + online: computeOnline(n), + buildConfig: bc + }; + if (includeSecrets) { + out.token_id = n.token_id; + out.token = n.token; + } + return out; +} + +function includeNodeSecrets(req) { + return !!(req && req.isAdmin); +} +function buildNodeBaseUrl(address, port, sslEnabled, underCloudflare = false) { + let base = String(address || "").trim(); + if (!base) return null; + const cloudflareProxy = truthyFlag(underCloudflare); + if (/^https?:\/\//i.test(base)) { + try { + const u = new URL(base); + u.hash = ""; + u.search = ""; + u.pathname = ""; + if (cloudflareProxy) { + u.protocol = "https:"; + const edgePort = cloudflareHttpsEdgePort(u.port || port); + u.port = edgePort === 443 ? "" : String(edgePort); + return u.origin; + } + if (!u.port) u.port = String(port || 8080); + return u.toString().replace(/\/$/, ""); + } catch { + } + } + if (cloudflareProxy) { + base = base.split(/[/?#]/)[0]; + const edgePort = cloudflareHttpsEdgePort(explicitHostPort(base) || port); + base = stripExplicitHostPort(base); + if (edgePort !== 443) base += `:${edgePort}`; + return `https://${base}`; + } + const proto = sslEnabled ? "https" : "http"; + return `${proto}://${base}:${clampPort(port || 8080)}`; +} +function httpRequestJson(fullUrl, method = "GET", headers = {}, timeoutMs = 2500) { + return new Promise((resolve) => { + try { + const lib = fullUrl.startsWith("https:") ? https : http; + const req = lib.request(fullUrl, { method, headers }, (res) => { + const { statusCode } = res; + const chunks = []; + res.on("data", (d) => chunks.push(d)); + res.on("end", () => { + const bodyStr = Buffer.concat(chunks).toString("utf8"); + try { + const json = bodyStr ? JSON.parse(bodyStr) : null; + resolve({ status: statusCode, json }); + } catch { + resolve({ status: statusCode, json: null }); + } + }); + }); + req.on("timeout", () => { try { req.destroy(); } catch { } resolve({ status: 0, json: null }); }); + req.on("error", () => resolve({ status: 0, json: null })); + req.setTimeout(timeoutMs); + req.end(); + } catch { + resolve({ status: 0, json: null }); + } + }); +} +const DEFAULT_NODE_TIMEOUT_MS = 10000; +const LONG_NODE_TIMEOUT_MS = 120000; +function isRecoverableNodeCreateStatus(status) { + return status === 0 || status === 520 || status === 522 || status === 523 || status === 524; +} +function isLoopbackAddress(value) { + const host = String(value || "").trim().toLowerCase(); + return host === "localhost" || host === "127.0.0.1" || host === "::1" || host === "[::1]"; +} + +function callNodeApiOnce(fullUrl, method = "GET", headers = {}, body = null, timeoutMs = DEFAULT_NODE_TIMEOUT_MS) { + return new Promise((resolve) => { + try { + const isHttps = fullUrl.startsWith("https:"); + const lib = isHttps ? https : http; + const req = lib.request(fullUrl, { method, headers }, (res) => { + const chunks = []; + res.on("data", (d) => chunks.push(d)); + res.on("end", () => { + const bodyStr = Buffer.concat(chunks).toString("utf8"); + try { + const json = bodyStr ? JSON.parse(bodyStr) : null; + resolve({ status: res.statusCode, json, error: null }); + } catch { + resolve({ status: res.statusCode, json: null, error: null }); + } + }); + }); + req.on("timeout", () => { + try { req.destroy(new Error("timeout")); } catch { } + resolve({ status: 0, json: null, error: "timeout" }); + }); + req.on("error", (err) => resolve({ status: 0, json: null, error: err?.message || "request error" })); + req.setTimeout(timeoutMs); + if (body) req.write(JSON.stringify(body)); + req.end(); + } catch { + resolve({ status: 0, json: null, error: "request setup failed" }); + } + }); +} + +async function resolveLoopbackNodeBase(node, timeoutMs = 1200) { + if (!node || isLoopbackAddress(node.address)) return null; + const candidates = []; + + const primaryProto = node.ssl_enabled ? "https" : "http"; + candidates.push(`${primaryProto}://127.0.0.1:${clampPort(node.api_port || 8080)}`); + candidates.push(`${primaryProto}://localhost:${clampPort(node.api_port || 8080)}`); + if (primaryProto === "https") { + candidates.push(`http://127.0.0.1:${clampPort(node.api_port || 8080)}`); + candidates.push(`http://localhost:${clampPort(node.api_port || 8080)}`); + } + + const expectedUuid = String(node.uuid || node.id || "").trim(); + for (const base of candidates) { + const probe = await callNodeApiOnce(`${base}/health`, "GET", {}, null, timeoutMs); + if (probe.status !== 200 || !probe.json) continue; + const gotUuid = String(probe.json.uuid || "").trim(); + if (expectedUuid && gotUuid && gotUuid === expectedUuid) { + return base; + } + } + return null; +} + +async function callNodeApi(node, pathSuffix, method = "GET", body = null, timeoutMs = DEFAULT_NODE_TIMEOUT_MS) { + const base = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); + if (!base) return { status: 0, json: null, error: "invalid node base url" }; + + const safeSuffix = String(pathSuffix || "").startsWith("/") + ? String(pathSuffix) + : `/${String(pathSuffix || "")}`; + + const headers = { + "Authorization": `Bearer ${node.token}`, + "X-Node-Token": node.token || "", + "X-Node-Token-Id": node.token_id || "", + "Content-Type": "application/json", + }; + + const primaryRes = await callNodeApiOnce(`${base}${safeSuffix}`, method, headers, body, timeoutMs); + if (primaryRes.status !== 0) return primaryRes; + + const fallbackBase = await resolveLoopbackNodeBase(node, Math.min(timeoutMs, 1500)); + if (!fallbackBase || fallbackBase === base) return primaryRes; + + const fallbackRes = await callNodeApiOnce(`${fallbackBase}${safeSuffix}`, method, headers, body, timeoutMs); + if (fallbackRes.status !== 0) { + return { ...fallbackRes, via: "loopback-fallback" }; + } + return primaryRes; +} + +async function waitForNodeServerReady(node, name, { timeoutMs = 30_000, intervalMs = 2000 } = {}) { + const safeName = encodeURIComponent(String(name || "")); + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const result = await callNodeApi(node, `/v1/servers/${safeName}`, "GET", null, Math.min(intervalMs, 10_000)); + if (result.status === 200 && result.json && (result.json.ok === true || result.json.name || result.json.status)) { + return true; + } + await new Promise(resolve => setTimeout(resolve, intervalMs)); + } + return false; +} +function extractHostnameForNodeTls(address) { + const raw = String(address || "").trim(); + if (!raw) return ""; + let host = ""; + if (/^https?:\/\//i.test(raw)) { + try { + host = new URL(raw).hostname; + } catch { + return ""; + } + } else { + const withoutPath = raw.split(/[/?#]/)[0]; + if (withoutPath.startsWith("[")) { + const end = withoutPath.indexOf("]"); + host = end > 0 ? withoutPath.slice(1, end) : withoutPath; + } else { + const colonCount = (withoutPath.match(/:/g) || []).length; + host = colonCount === 1 ? withoutPath.split(":")[0] : withoutPath; + } + } + host = String(host || "").trim().toLowerCase(); + if (!host || host === "localhost" || net.isIP(host)) return ""; + if (!/^[a-z0-9.-]+$/i.test(host)) return ""; + return host; +} +function defaultNodeTlsPaths(node) { + if (!node || !node.ssl_enabled) return { cert: "", key: "" }; + const host = extractHostnameForNodeTls(node.address); + if (!host) return { cert: "", key: "" }; + return { + cert: `/etc/letsencrypt/live/${host}/fullchain.pem`, + key: `/etc/letsencrypt/live/${host}/privkey.pem`, + }; +} +function yamlDoubleQuote(value) { + return `"${String(value || "").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; +} +async function resolveNodeForServer(serverName) { + const name = String(serverName || "").trim(); + if (!name) return { server: null, node: null, nodeId: null }; + const srv = await findServerByNameOrId(name); + if (!srv) return { server: null, node: null, nodeId: null }; + const rawNodeId = (srv.node || srv.nodeId || srv.node_id || ""); + const key = String(rawNodeId || "").trim(); + if (!key) return { server: srv, node: null, nodeId: null }; + const node = await findNodeByIdOrName(key); + return { server: srv, node, nodeId: node ? node.uuid : null }; +} +function httpRequestJsonWithBody(fullUrl, method = "POST", body = null, headers = {}, timeoutMs = 8000) { + return new Promise((resolve) => { + try { + const lib = fullUrl.startsWith("https:") ? https : http; + const payload = body ? Buffer.from(JSON.stringify(body)) : null; + const req = lib.request(fullUrl, { + method, + headers: { + "Content-Type": "application/json", + ...(payload ? { "Content-Length": payload.length } : {}), + ...headers + } + }, (res) => { + const { statusCode } = res; + const chunks = []; + res.on("data", (d) => chunks.push(d)); + res.on("end", () => { + const bodyStr = Buffer.concat(chunks).toString("utf8"); + try { + const json = bodyStr ? JSON.parse(bodyStr) : null; + resolve({ status: statusCode, json }); + } catch { + resolve({ status: statusCode, json: null }); + } + }); + }); + req.on("timeout", () => { try { req.destroy(); } catch { } resolve({ status: 0, json: null }); }); + req.on("error", () => resolve({ status: 0, json: null })); + req.setTimeout(timeoutMs); + if (payload) req.write(payload); + req.end(); + } catch { + resolve({ status: 0, json: null }); + } + }); +} +function httpJson(fullUrl, { method = "GET", headers = {}, body = null, timeoutMs = 5000 } = {}) { + return new Promise((resolve) => { + try { + const lib = fullUrl.startsWith("https:") ? https : http; + const opts = { method, headers }; + const req = lib.request(fullUrl, opts, (res) => { + const chunks = []; + res.on("data", (d) => chunks.push(d)); + res.on("end", () => { + const text = Buffer.concat(chunks).toString("utf8"); + let json = null; + try { json = text ? JSON.parse(text) : null; } catch { } + resolve({ status: res.statusCode, json, text }); + }); + }); + req.on("timeout", () => { try { req.destroy(); } catch { } resolve({ status: 0, json: null }); }); + req.on("error", () => resolve({ status: 0, json: null })); + req.setTimeout(timeoutMs); + if (body != null) { + const data = typeof body === "string" ? body : JSON.stringify(body); + if (!headers["Content-Type"]) req.setHeader("Content-Type", "application/json"); + req.setHeader("Content-Length", Buffer.byteLength(data)); + req.write(data); + } + req.end(); + } catch { + resolve({ status: 0, json: null }); + } + }); +} +function tcpCheck(host, port, timeoutMs = 2000) { + return new Promise((resolve) => { + try { + const socket = new net.Socket(); + let finished = false; + const done = (ok) => { + if (finished) return; + finished = true; + try { socket.destroy(); } catch { } + resolve(!!ok); + }; + socket.setTimeout(timeoutMs); + socket.once("connect", () => done(true)); + socket.once("timeout", () => done(false)); + socket.once("error", () => done(false)); + socket.connect(clampPort(port || 8080), host); + } catch { + resolve(false); + } + }); +} +async function activeCheckNode(node, opts = { force: false }) { + const now = Date.now(); + if (!opts.force && node.last_check && (now - Number(node.last_check)) < 5000) return; + node.last_check = now; + + let ok = false; + const baseUrl = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); + if (baseUrl) { + const checkTimeout = 1500; + try { + const [infoRes, healthRes] = await Promise.all([ + httpRequestJson(`${baseUrl}/v1/info`, "GET", { "Authorization": `Bearer ${node.token}` }, checkTimeout), + httpRequestJson(`${baseUrl}/health`, "GET", {}, checkTimeout) + ]); + + if (infoRes.status === 200 && infoRes.json && infoRes.json.ok && infoRes.json.node) { + const uuid = String(infoRes.json.node.uuid || ""); + if (uuid && (uuid === node.uuid || uuid === node.id)) ok = true; + if (infoRes.json.node.volumesDir) { + node.volumesDir = String(infoRes.json.node.volumesDir); + const cacheKey = String(node.uuid || node.id || ""); + if (cacheKey) _nodeVolumeDirCache.set(cacheKey, node.volumesDir); + } + } + if (!ok && healthRes.status === 200 && healthRes.json && healthRes.json.uuid) { + const uuid = String(healthRes.json.uuid || ""); + if (uuid && (uuid === node.uuid || uuid === node.id)) ok = true; + } + if (!ok && healthRes.status === 200 && infoRes.status === 401) { + console.warn(`[node-check] Node ${node.name} (${node.address}) is reachable but auth FAILED. Token mismatch — re-deploy config.yml.`); + } + } catch { + ok = false; + } + } + node.port_ok = !!ok; + if (ok) { + node.last_seen = now; + } +} +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 sslEnabled = !!node.ssl_enabled; + const tlsPaths = defaultNodeTlsPaths(node); + const lines = [ + `debug: false`, + `uuid: ${node.uuid}`, + `token_id: ${node.token_id}`, + `token: ${node.token}`, + `auth:`, + ` token_id: ${node.token_id}`, + ` token: ${node.token}`, + `api:`, + ` host: 0.0.0.0`, + ` port: ${node.api_port || 8080}`, + ` ssl:`, + ` enabled: ${sslEnabled}`, + ` cert: "${tlsPaths.cert}"`, + ` key: "${tlsPaths.key}"`, + ` upload_limit: ${node.max_upload_mb || 10240}`, + `system:`, + ` data: /var/lib/node`, + ` sftp:`, + ` bind_port: ${node.sftp_port || 2022}`, + `allowed_mounts: []`, + `panel:`, + ` url: ${panelUrl}`, + ` node_id: ${node.uuid}` + ]; + if (PANEL_HMAC_SECRET) { + lines.push(` hmac_secret: ${yamlDoubleQuote(PANEL_HMAC_SECRET)}`); + } + 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}`; + } + 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 +} +restart_adaemon +echo "Config saved to /var/lib/node/config.yml and ADaemon restarted"`; +} +const app = express(); +app.use(express.json({ limit: "2mb" })); +app.use(express.urlencoded({ extended: true })); +const CORS_ALLOWED_ORIGINS = new Set( + (process.env.NODES_CORS_ORIGINS || "") + .split(",") + .map(s => s.trim()) + .filter(Boolean) +); + +function sameOrigin(req, origin) { + const host = req.get("host"); + if (!host) return false; + const proto = (req.get("x-forwarded-proto") || req.protocol || "http"); + const expected = `${proto}://${host}`; + return origin === expected; +} + +function applyCors(req, res) { + const origin = req.get("origin"); + if (!origin) return; + if (CORS_ALLOWED_ORIGINS.size > 0) { + if (!CORS_ALLOWED_ORIGINS.has(origin)) return; + } else if (!sameOrigin(req, origin)) { + return; + } + res.header("Access-Control-Allow-Origin", origin); + res.header("Access-Control-Allow-Credentials", "true"); + res.header("Access-Control-Allow-Methods", "GET,POST,PATCH,DELETE,OPTIONS"); + res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With, X-Node-Token-Id"); +} + +app.use((req, res, next) => { + applyCors(req, res); + if (req.method === "OPTIONS") return res.sendStatus(204); + next(); +}); + +const NODES_PUBLIC_ROUTES = new Set([ + "/health", + "/api/nodes/:id/heartbeat", + "/api/nodes/:id/config.yml", +]); + +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 || ""; + + if (path === "/health") return next(); + + if (/^\/api\/nodes\/[^/]+\/heartbeat$/.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" }); + } + } + + next(); +}); + +app.get("/health", (_req, res) => res.json({ ok: true })); +app.get("/api/nodes", async (req, res) => { + const wantPaginated = req.query.page || req.query.limit || req.query.search; + if (wantPaginated) { + const result = await loadNodesPaginated(req.query.page, req.query.limit, req.query.search); + return res.json({ + nodes: result.nodes.map((n) => toPublic(n, includeNodeSecrets(req))), + total: result.total, + page: result.page, + limit: result.limit, + totalPages: result.totalPages + }); + } + const list = await loadNodes(); + res.json({ nodes: list.map((n) => toPublic(n, includeNodeSecrets(req))) }); +}); +app.get("/api/nodes/:id", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "not found" }); + res.json(toPublic(node, includeNodeSecrets(req))); +}); +app.post("/api/nodes/:id/check", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "not found" }); + await activeCheckNode(node, { force: true }); + await saveNode(node); + const isOnline = computeOnline(node); + res.json({ ok: isOnline, node: toPublic(node, includeNodeSecrets(req)) }); +}); +app.get("/api/nodes/:id/ports/check", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ ok: false, error: "node_not_found" }); + const port = validatePortInput(req.query?.port); + if (!port) return res.status(400).json({ ok: false, error: "invalid_port" }); + + if (!isPortInNodeAllocation(node, port)) { + const alloc = node.ports || {}; + let allocDesc = "none"; + if (alloc.mode === "range") allocDesc = `range ${alloc.start}\u2013${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 ? "\u2026" : ""}]`; + return res.json({ ok: true, port, available: false, reason: "outside-allocation", detail: `Port ${port} is not in this node's allocated ports (${allocDesc}).` }); + } + + const result = await callNodeApi(node, `/v1/ports/check?port=${encodeURIComponent(String(port))}`, "GET", null, 10_000); + if (result.status === 200 && result.json && result.json.ok) { + return res.json(result.json); + } + return res.json({ ok: true, port, available: null, verified: false, status: result.status || 0 }); +}); +app.post("/api/nodes/:id/servers/create", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "node_not_found" }); + const name = String(req.body?.name || "").trim(); + const templateId = String(req.body?.templateId || "minecraft"); + const mcFork = String(req.body?.mcFork || "paper"); + const mcVersion = String(req.body?.mcVersion || "1.21.8"); + const requestedHostPort = req.body?.hostPort; + const hostPort = requestedHostPort == null || String(requestedHostPort).trim() === "" + ? 25565 + : validatePortInput(requestedHostPort); + const autoStart = !!req.body?.autoStart; + if (!name) return res.status(400).json({ error: "missing_name" }); + if (!hostPort) return res.status(400).json({ error: "invalid_host_port" }); + + if (hostPort > 0 && !isPortInNodeAllocation(node, hostPort)) { + const alloc = node.ports || {}; + let allocDesc = "none"; + if (alloc.mode === "range") allocDesc = `range ${alloc.start}\u2013${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 ? "\u2026" : ""}]`; + return res.status(400).json({ error: `Port ${hostPort} is not in this node's allocated ports (${allocDesc}).` }); + } + if (hostPort > 0) { + const portCheck = await callNodeApi(node, `/v1/ports/check?port=${encodeURIComponent(String(hostPort))}`, "GET", null, 10_000); + if (portCheck.status === 200 && portCheck.json?.ok && portCheck.json.available === false) { + const owner = portCheck.json.owner ? ` by ${portCheck.json.owner}` : ""; + return res.status(409).json({ error: `Port ${hostPort} is already in use on this node${owner}.`, code: "port_in_use" }); + } + } + + const { status, json } = await callNodeApi( + node, "/v1/servers/create", "POST", + { name, templateId, mcFork, mcVersion, hostPort, autoStart }, + LONG_NODE_TIMEOUT_MS + ); + if (status === 200 && json && json.ok) return res.json(json); + if (isRecoverableNodeCreateStatus(status)) { + const recovered = await waitForNodeServerReady(node, name, { + timeoutMs: nodeUnderCloudflare(node) ? 180_000 : 30_000, + intervalMs: 3000, + }); + if (recovered) return res.json({ ok: true, name, recovered: true }); + } + return res.status(500).json({ error: "node_create_failed", status, detail: json && json.error }); +}); +app.post("/api/nodes", async (req, res) => { + const body = req.body || {}; + const name = sanitizeName(body.name || body.node || body.id); + const address = String(body.address || body.ip || body.fqdn || "").trim(); + if (!name) return res.status(400).json({ error: "invalid name" }); + if (!address) return res.status(400).json({ error: "invalid address" }); + const nameKey = name.toLowerCase(); + const exists = await db.query("SELECT id FROM nodes WHERE LOWER(name) = ? LIMIT 1", [nameKey]); + if (exists.length) { + return res.status(400).json({ error: "node already exists" }); + } + const cpu_cores = toInt(body.cpu_cores, 0); + const ram_mb = + (typeof body.ram_mb !== "undefined") ? toInt(body.ram_mb, 0) : + (typeof body.ramMB !== "undefined") ? toInt(body.ramMB, 0) : + (typeof body.ram_gb !== "undefined") ? toInt(body.ram_gb, 0) * 1024 : 0; + const disk_gb = + (typeof body.disk_gb !== "undefined") ? toInt(body.disk_gb, 0) : + (typeof body.storage_gb !== "undefined") ? toInt(body.storage_gb, 0) : + (typeof body.storageGB !== "undefined") ? toInt(body.storageGB, 0) : 0; + const ports = normalizePorts(body.ports); + const api_port = clampPort(body.api_port || 8080); + const sftp_port = clampPort(body.sftp_port || 2022); + const max_upload_mb = Math.max(1, Math.min(100000, toInt(body.max_upload_mb, 10240))); + const ssl_enabled = truthyFlag(body.ssl_enabled); + const under_cloudflare = !!(ssl_enabled && truthyFlag(body.under_cloudflare)); + if (under_cloudflare && !isCloudflareHttpsPort(api_port)) { + return res.status(400).json({ error: "Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443." }); + } + if (under_cloudflare) { + const cloudflareCheck = await verifyCloudflareProxiedAddress(address); + if (!cloudflareCheck.ok) { + return res.status(400).json({ + error: cloudflareCheck.error, + detail: cloudflareCheck.detail || undefined, + }); + } + } + const node = await insertNode({ + id: uid(), + uuid: undefined, + name, + address, + ram_mb, + disk_gb, + ports, + token_id: randTokenId(), + token: randSecret(), + createdAt: Date.now(), + api_port, + sftp_port, + max_upload_mb, + port_ok: null, + last_seen: null, + last_check: null, + buildConfig: { + cpu_cores, + ssl_enabled, + under_cloudflare + } + }); + res.json(toPublic(node, includeNodeSecrets(req))); +}); +app.patch("/api/nodes/:id", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "not found" }); + const current = hardenNode(node); + const upd = sanitizeUpdatePayload(req.body || {}); + if (typeof upd.name !== "undefined" && upd.name) current.name = upd.name; + if (typeof upd.address !== "undefined") current.address = upd.address; + if (typeof upd.cpu_cores !== "undefined" && upd.cpu_cores >= 0) { + current.buildConfig = current.buildConfig || {}; + current.buildConfig.cpu_cores = upd.cpu_cores; + } + if (typeof upd.ssl_enabled !== "undefined") { + current.buildConfig = current.buildConfig || {}; + current.buildConfig.ssl_enabled = !!upd.ssl_enabled; + if (!current.buildConfig.ssl_enabled) current.buildConfig.under_cloudflare = false; + } + if (typeof upd.under_cloudflare !== "undefined") { + current.buildConfig = current.buildConfig || {}; + current.buildConfig.under_cloudflare = !!(upd.under_cloudflare && current.buildConfig.ssl_enabled); + } + if (typeof upd.ram_mb !== "undefined" && upd.ram_mb >= 0) current.ram_mb = upd.ram_mb; + if (typeof upd.disk_gb !== "undefined" && upd.disk_gb >= 0) current.disk_gb = upd.disk_gb; + if (typeof upd.ports !== "undefined") current.ports = normalizePorts(upd.ports); + if (typeof upd.api_port !== "undefined") current.api_port = clampPort(upd.api_port); + if (typeof upd.sftp_port !== "undefined") current.sftp_port = clampPort(upd.sftp_port); + if (typeof upd.max_upload_mb !== "undefined") current.max_upload_mb = upd.max_upload_mb; + if (current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare && !isCloudflareHttpsPort(current.api_port)) { + return res.status(400).json({ error: "Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443." }); + } + if (current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare) { + const cloudflareCheck = await verifyCloudflareProxiedAddress(current.address); + if (!cloudflareCheck.ok) { + return res.status(400).json({ + error: cloudflareCheck.error, + detail: cloudflareCheck.detail || undefined, + }); + } + } + current.last_check = null; + const saved = await saveNode(current); + res.json(toPublic(saved, includeNodeSecrets(req))); +}); +app.delete("/api/nodes/:id", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "not found" }); + const assignedServers = await db.query( + "SELECT COUNT(*) AS cnt FROM servers WHERE node_id = ?", + [node.id] + ); + const serverCount = Number(assignedServers[0]?.cnt || 0); + if (serverCount > 0) { + return res.status(409).json({ + error: `Cannot delete node — ${serverCount} server${serverCount === 1 ? " is" : "s are"} still assigned to it. Reassign or delete them first.` + }); + } + await deleteNode(node.id); + res.json({ ok: true, deleted: node.id }); +}); +app.get("/api/nodes/:id/build", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "not found" }); + res.json({ build: node.buildConfig || {} }); +}); +app.post("/api/nodes/:id/build", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "not found" }); + const incoming = (req.body && typeof req.body === "object") ? req.body : {}; + const current = hardenNode(node); + const nextBuild = Object.assign({}, current.buildConfig || {}, incoming); + if (Object.prototype.hasOwnProperty.call(incoming, "ssl_enabled")) { + nextBuild.ssl_enabled = truthyFlag(incoming.ssl_enabled); + if (!nextBuild.ssl_enabled) nextBuild.under_cloudflare = false; + } + if (Object.prototype.hasOwnProperty.call(incoming, "under_cloudflare") || Object.prototype.hasOwnProperty.call(incoming, "cloudflare_proxy")) { + nextBuild.under_cloudflare = !!(nextBuild.ssl_enabled && truthyFlag(incoming.under_cloudflare ?? incoming.cloudflare_proxy)); + } + current.buildConfig = nextBuild; + current.under_cloudflare = nodeUnderCloudflare(current); + if (current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare && !isCloudflareHttpsPort(current.api_port)) { + return res.status(400).json({ error: "Under Cloudflare requires daemon port 443, 2053, 2083, 2087, 2096, or 8443." }); + } + if (current.buildConfig?.ssl_enabled && current.buildConfig?.under_cloudflare) { + const cloudflareCheck = await verifyCloudflareProxiedAddress(current.address); + if (!cloudflareCheck.ok) { + return res.status(400).json({ + error: cloudflareCheck.error, + detail: cloudflareCheck.detail || undefined, + }); + } + } + Object.assign(node, current); + await saveNode(node); + res.json({ ok: true }); +}); +app.get("/api/nodes/:id/config.yml", async (req, res) => { + const bootstrapHeader = req.get("X-Node-Bootstrap") || ""; + const bearerToken = (req.get("authorization") || "").replace(/^Bearer\s+/i, ""); + + const node = await findNodeByIdOrName(req.params.id); + + if (req.isAdmin) { + } + else if (NODE_BOOTSTRAP_TOKEN && bootstrapHeader && safeCompare(bootstrapHeader, NODE_BOOTSTRAP_TOKEN)) { + } + else if (bearerToken && node && safeCompare(bearerToken, node.token)) { + } + else { + return res.status(401).send("authentication required"); + } + + if (!node) return res.status(404).send("not found"); + const yml = buildConfigYml(node, req); + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private"); + res.setHeader("Pragma", "no-cache"); + res.setHeader("Content-Type", "text/yaml; charset=utf-8"); + res.send(yml); +}); +app.get("/api/nodes/:id/one-time-command", async (req, res) => { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "not found" }); + res.json({ command: oneTimeCommand(node, req) }); +}); +app.post("/api/nodes/:id/heartbeat", async (req, res) => { + try { + const node = await findNodeByIdOrName(req.params.id); + if (!node) return res.status(404).json({ error: "not found" }); + const current = hardenNode(node); + + const authHeader = req.get("authorization") || ""; + const bearer = authHeader.startsWith("Bearer ") ? authHeader.slice(7) : null; + const body = req.body || {}; + const bodyToken = body.token || null; + const bodyTokenId = body.token_id || null; + + if (!bearer && !bodyToken) { + return res.status(401).json({ error: "authentication required" }); + } + + if (bearer && !safeCompare(bearer, current.token)) { + return res.status(401).json({ error: "invalid token" }); + } + + if (!bearer && bodyToken && !safeCompare(bodyToken, current.token)) { + return res.status(401).json({ error: "invalid token" }); + } + + if (bodyTokenId && !safeCompare(bodyTokenId, current.token_id)) { + return res.status(401).json({ error: "invalid token_id" }); + } + + if (typeof body.api_port !== "undefined") current.api_port = clampPort(body.api_port); + current.last_seen = Date.now(); + current.port_ok = true; + current.last_check = Date.now(); + await saveNode(current); + return res.json({ + ok: true, + now: current.last_seen, + port_ok: current.port_ok, + online: computeOnline(current) + }); + } catch (e) { + console.error("[heartbeat] failed:", e && e.message); + return res.status(500).json({ error: "heartbeat failed" }); + } +}); +const HC_BATCH_SIZE = parseInt(process.env.HC_BATCH_SIZE || "10", 10) || 10; +const HC_INTERVAL_MS = parseInt(process.env.HC_INTERVAL_MS || "5000", 10) || 5000; +let _hcOffset = 0; +setInterval(async () => { + try { + const countRows = await db.query("SELECT COUNT(*) AS total FROM nodes"); + const total = Number(countRows[0]?.total || 0); + if (total === 0) { _hcOffset = 0; return; } + if (_hcOffset >= total) _hcOffset = 0; + const batch = await db.query( + `SELECT * FROM nodes ORDER BY id ASC LIMIT ${HC_BATCH_SIZE} OFFSET ${_hcOffset}` + ); + _hcOffset += HC_BATCH_SIZE; + const nodes = batch.map(mapNodeRow); + for (const n of nodes) { + try { + await activeCheckNode(n, { force: true }); + await saveNode(n); + } catch (_) { } + } + } catch (_) { } +}, HC_INTERVAL_MS); +const NODE_VOLUME_ROOT = "/var/lib/node/servers"; +const _nodeVolumeDirCache = new Map(); +function getNodeVolumesDir(node) { + const key = String(node.uuid || node.id || ""); + return (key && _nodeVolumeDirCache.get(key)) || node.volumesDir || NODE_VOLUME_ROOT; +} +function mapServerRow(row) { + return { + id: row.id, + name: row.name, + legacy_id: row.legacy_id, + bot: row.bot, + template: row.template, + start: row.start, + node_id: row.node_id, + nodeId: row.node_id, + node: row.node_id, + ip: row.ip, + port: row.port, + status: row.status, + runtime: parseDbJson(row.runtime, null), + docker: parseDbJson(row.docker, null), + acl: parseDbJson(row.acl, null), + resources: parseDbJson(row.resources, null), + }; +} + +async function findServerByNameOrId(name) { + const key = String(name || "").trim(); + if (!key) return null; + const lower = key.toLowerCase(); + const numericId = /^\d+$/.test(key) ? Number(key) : null; + const rows = await db.query( + "SELECT * FROM servers WHERE LOWER(name) = ? OR LOWER(legacy_id) = ? OR LOWER(bot) = ? OR id = ? LIMIT 1", + [lower, lower, lower, numericId] + ); + return rows.length ? mapServerRow(rows[0]) : null; +} +function serverNodeRef(srv) { + return (srv && (srv.node || srv.nodeId || srv.node_id)) || null; +} +function buildServerInfo(srv) { + if (!srv) return {}; + const ip = srv.ip || srv.host || srv.address || srv.hostname || null; + const port = srv.port || srv.server_port || srv.bind_port || null; + const start = srv.start || srv.startFile || srv.entry || null; + return { ip, port, start }; +} +function nodeHeaders(node) { + return { + "Authorization": `Bearer ${node.token || ""}`, + "X-Node-Token": node.token || "", + "X-Node-Token-Id": node.token_id || "" + }; +} +function nodeUrl(node, suffix) { + const base = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); + return `${base}${suffix}`; +} + +function finiteNumber(value) { + const num = Number(value); + return Number.isFinite(num) ? num : null; +} + +function nodeUploadLimitMb(node) { + const configured = finiteNumber(node?.max_upload_mb); + return configured && configured > 0 ? configured : 10240; +} + +function formatBytesForMessage(bytes) { + const num = finiteNumber(bytes); + if (!num || num <= 0) return "0 B"; + const units = ["B", "KB", "MB", "GB", "TB"]; + let value = num; + let index = 0; + while (value >= 1024 && index < units.length - 1) { + value /= 1024; + index += 1; + } + return `${value.toFixed(value >= 10 || index === 0 ? 0 : 1)} ${units[index]}`; +} + +function parseNodeDiskSnapshot(payload) { + const disk = payload?.disk || {}; + const statsDisk = payload?.stats?.disk || {}; + let usedBytes = finiteNumber(disk.usedBytes); + let limitBytes = finiteNumber(disk.limitBytes); + + if (usedBytes == null) { + const usedMb = finiteNumber(disk.usedMb ?? statsDisk.usedMb); + const usedGb = finiteNumber(disk.usedGb ?? statsDisk.usedGb); + if (usedMb != null) usedBytes = usedMb * 1024 * 1024; + else if (usedGb != null) usedBytes = usedGb * 1024 * 1024 * 1024; + } + if (limitBytes == null) { + const limitMb = finiteNumber(disk.limitMb ?? statsDisk.limitMb); + const limitGb = finiteNumber(disk.limitGb ?? statsDisk.limitGb); + if (limitMb != null) limitBytes = limitMb * 1024 * 1024; + else if (limitGb != null) limitBytes = limitGb * 1024 * 1024 * 1024; + } + + usedBytes = Math.max(0, Math.round(usedBytes || 0)); + limitBytes = limitBytes && limitBytes > 0 ? Math.round(limitBytes) : 0; + const remainingBytes = limitBytes > 0 ? Math.max(0, limitBytes - usedBytes) : null; + return { + usedBytes, + limitBytes, + remainingBytes, + percentUsed: limitBytes > 0 ? Math.min(100, (usedBytes / limitBytes) * 100) : 0, + }; +} + +async function fetchServerDiskSnapshot(ctx, serverName, timeoutMs = 5000) { + if (!ctx?.remote || !ctx.node) return null; + const nodeServerName = ctx.nodeServerName || sanitizeName(ctx.server?.name || serverName); + if (!nodeServerName) return null; + const result = await httpJson(nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(nodeServerName)}`), { + method: "GET", + headers: nodeHeaders(ctx.node), + timeoutMs, + }); + if (result.status !== 200 || !result.json) return null; + return parseNodeDiskSnapshot(result.json); +} + +function buildDiskLimitUploadError(snapshot, incomingBytes, replacedBytes = 0) { + const limitBytes = finiteNumber(snapshot?.limitBytes); + if (!limitBytes || limitBytes <= 0) return null; + const usedBytes = Math.max(0, Math.round(finiteNumber(snapshot?.usedBytes) || 0)); + const uploadBytes = Math.max(0, Math.round(finiteNumber(incomingBytes) || 0)); + const replaceBytes = Math.max(0, Math.round(finiteNumber(replacedBytes) || 0)); + const extraBytes = Math.max(0, uploadBytes - replaceBytes); + const projectedBytes = usedBytes + extraBytes; + if (projectedBytes <= limitBytes) return null; + const remainingBytes = Math.max(0, limitBytes - usedBytes); + return { + ok: false, + error: "disk_limit_exceeded", + message: `Upload would exceed this server's disk limit. Used: ${formatBytesForMessage(usedBytes)} / ${formatBytesForMessage(limitBytes)}. File: ${formatBytesForMessage(uploadBytes)}. Remaining: ${formatBytesForMessage(remainingBytes)}.`, + usedBytes, + limitBytes, + remainingBytes, + incomingBytes: uploadBytes, + projectedBytes, + usedMb: usedBytes / (1024 * 1024), + limitMb: limitBytes / (1024 * 1024), + }; +} + +function sanitizeNodeUploadFilename(raw) { + let s = String(raw || "").trim().replace(/\\/g, "/"); + s = path.posix.basename(s); + s = s.replace(/\s+/g, "-").replace(/[^\w\-_.]+/g, "").replace(/^[-_.]+|[-_.]+$/g, ""); + while (s && !/^[A-Za-z0-9]/.test(s)) s = s.slice(1); + if (s.length > 120) s = s.slice(0, 120); + return s || "upload.bin"; +} + +async function fetchRemoteReplacementBytes(ctx, absDir, originalName, timeoutMs = 5000) { + if (!ctx?.remote || !ctx.node) return null; + const safeName = sanitizeNodeUploadFilename(originalName); + if (!safeName) return null; + const result = await httpJson(nodeUrl(ctx.node, "/v1/fs/list"), { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), + body: { path: absDir, depth: 1 }, + timeoutMs, + }); + if (result.status !== 200 || !result.json || result.json.ok !== true || !Array.isArray(result.json.entries)) { + return null; + } + const existing = result.json.entries.find((entry) => entry && entry.name === safeName); + if (!existing || existing.type === "dir" || existing.isDir) return 0; + const size = finiteNumber(existing.size); + return size && size > 0 ? size : 0; +} + +function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb) { + return new Promise((resolve) => { + let settled = false; + let nodeReq = null; + + const done = (result) => { + if (settled) return; + settled = true; + resolve(result); + }; + + try { + const fullUrl = nodeUrl(node, "/v1/fs/upload"); + const lib = fullUrl.startsWith("https:") ? https : http; + + const boundary = `----ADPanelUpload${crypto.randomBytes(16).toString("hex")}`; + const safeOriginalName = String(originalName || "upload.bin").replace(/[\r\n"]/g, "_"); + + const dirPart = + `--${boundary}\r\n` + + `Content-Disposition: form-data; name="dir"\r\n\r\n` + + `${destDir}\r\n`; + + const fileHeader = + `--${boundary}\r\n` + + `Content-Disposition: form-data; name="file"; filename="${safeOriginalName}"\r\n` + + `Content-Type: application/octet-stream\r\n\r\n`; + + const fileFooter = `\r\n--${boundary}--\r\n`; + + const preamble = Buffer.from(dirPart + fileHeader, "utf8"); + const epilogue = Buffer.from(fileFooter, "utf8"); + + const headers = { + ...nodeHeaders(node), + "Content-Type": `multipart/form-data; boundary=${boundary}`, + }; + + nodeReq = lib.request(fullUrl, { method: "POST", headers }, (res) => { + const chunks = []; + let total = 0; + res.on("data", (d) => { + if (total < 64 * 1024) { + chunks.push(d); + total += d.length; + } + }); + res.on("end", () => { + if (settled) return; + const bodyStr = Buffer.concat(chunks).toString("utf8"); + let json = null; + try { json = bodyStr ? JSON.parse(bodyStr) : null; } catch { } + done({ status: res.statusCode, json }); + }); + }); + + nodeReq.setTimeout(UPLOAD_TIMEOUT_MS); + nodeReq.on("timeout", () => { + try { nodeReq.destroy(); } catch { } + done({ status: 0, json: { error: "upload_timeout" } }); + }); + nodeReq.on("error", (err) => { + done({ status: 0, json: { error: "upload_network_error", detail: err.message } }); + }); + + nodeReq.write(preamble); + + let written = 0; + sourceStream.on("data", (chunk) => { + if (settled) return; + written += chunk.length; + if (maxBytes > 0 && written > maxBytes) { + try { sourceStream.destroy(); } catch { } + try { nodeReq.destroy(); } catch { } + done({ + status: 413, + json: { + error: "file_too_large", + message: `File exceeds this node's upload limit of ${maxMb || Math.round(maxBytes / 1024 / 1024)} MB`, + limit_mb: maxMb || Math.round(maxBytes / 1024 / 1024), + }, + }); + return; + } + if (!nodeReq.write(chunk)) { + sourceStream.pause(); + nodeReq.once("drain", () => { + if (!settled) sourceStream.resume(); + }); + } + }); + sourceStream.on("end", () => { + if (settled) return; + nodeReq.write(epilogue); + nodeReq.end(); + }); + sourceStream.on("error", (err) => { + if (settled) return; + try { nodeReq.destroy(); } catch { } + done({ status: 0, json: { error: "upload_stream_error", detail: err.message } }); + }); + } catch (err) { + try { if (nodeReq) nodeReq.destroy(); } catch { } + done({ status: 0, json: { error: "stream_error", detail: err.message } }); + } + }); +} + +function safeJoinUnix(base, rel) { + const b = base.endsWith("/") ? base.slice(0, -1) : base; + const raw = String(rel || "").replace(/\\/g, "/"); + const norm = path.posix.normalize("/" + raw).replace(/^\/+/, ""); + const joined = `${b}/${norm}`; + if (!joined.startsWith(b + "/") && joined !== b) throw new Error("path traversal"); + return joined; +} + +function maskPathErrorMessage(err, fallback = "bad_path") { + const msg = err && err.message ? String(err.message) : ""; + const lower = msg.toLowerCase(); + if (lower.includes("traversal") || lower.includes("path")) return "invalid path"; + return msg || fallback; +} +function mapFsEntries(entries) { + const out = []; + (entries || []).forEach(e => { + if (!e || !e.name) return; + const entry = { name: e.name, isDir: !!(e.type === "dir" || e.isDir) }; + if (typeof e.size === "number") entry.size = e.size; + out.push(entry); + }); + return out; +} +async function remoteContext(serverName) { + const srv = await findServerByNameOrId(serverName); + if (!srv) return { exists: false }; + const ref = serverNodeRef(srv); + if (!ref) return { exists: true, remote: false, info: buildServerInfo(srv) }; + const node = await findNodeByIdOrName(ref); + if (!node) return { exists: true, remote: false, info: buildServerInfo(srv) }; + const volRoot = getNodeVolumesDir(node); + const nodeServerName = sanitizeName(srv.name || serverName); + const baseDir = `${volRoot}/${nodeServerName}`; + return { + exists: true, + remote: true, + server: srv, + node, + nodeId: node.uuid, + nodeServerName, + baseDir, + info: buildServerInfo(srv) + }; +} +app.get("/api/nodes/server/:name/info", async (req, res) => { + res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate"); + const serverName = req.params.name; + + const accessCheck = await checkServerAccess(req, serverName); + if (!accessCheck.ok) { + return res.status(accessCheck.status).json({ error: accessCheck.error }); + } + + const ctx = await remoteContext(serverName); + if (!ctx.exists) { + console.log(`[node-info] Server ${serverName} not found`); + return res.json({ ok: false, remote: false, info: null, nodeOnline: false }); + } + if (ctx.remote && ctx.node) { + try { await activeCheckNode(ctx.node, { force: true }); } catch (e) { + console.log(`[node-info] activeCheckNode error for ${req.params.name}:`, e.message); + } + const nodeOnline = computeOnline(ctx.node); + const maxUploadMb = nodeUploadLimitMb(ctx.node); + const disk = await fetchServerDiskSnapshot(ctx, serverName, 5000).catch(() => null); + console.log(`[node-info] Server ${req.params.name} - remote: true, port_ok: ${ctx.node.port_ok}, last_seen: ${ctx.node.last_seen}, nodeOnline: ${nodeOnline}`); + return res.json({ + ok: true, + remote: true, + nodeId: ctx.node.uuid, + info: ctx.info || {}, + baseDir: ctx.baseDir, + maxUploadMb, + maxUploadBytes: Math.round(maxUploadMb * 1024 * 1024), + disk, + nodeOnline + }); + } + console.log(`[node-info] Server ${req.params.name} - remote: false (no nodeId), returning nodeOnline: true`); + return res.json({ ok: true, remote: false, nodeId: null, info: ctx.info || {}, nodeOnline: true }); +}); +app.get("/api/nodes/server/:name/entries", async (req, res) => { + const serverName = req.params.name; + + const accessCheck = await checkServerAccess(req, serverName); + if (!accessCheck.ok) { + return res.status(accessCheck.status).json({ error: accessCheck.error }); + } + + if (!(await checkUserPerm(req, serverName, "files_read"))) { + return res.status(403).json({ error: "permission denied", permission: "files_read" }); + } + + 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 } } + ); + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_list_failed" }); + return res.json({ path: rel, entries: mapFsEntries(json.entries || []) }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); +app.get("/api/nodes/server/:name/file", async (req, res) => { + const serverName = req.params.name; + + const accessCheck = await checkServerAccess(req, serverName); + if (!accessCheck.ok) { + return res.status(accessCheck.status).json({ error: accessCheck.error }); + } + + if (!(await checkUserPerm(req, serverName, "files_read"))) { + return res.status(403).json({ error: "permission denied", permission: "files_read" }); + } + + 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" }); + const rel = String(req.query.path || ""); + try { + 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" } } + ); + 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 : "" }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); +app.get("/api/nodes/server/:name/download", async (req, res) => { + const serverName = req.params.name; + + const accessCheck = await checkServerAccess(req, serverName); + if (!accessCheck.ok) { + return res.status(accessCheck.status).json({ error: accessCheck.error }); + } + + if (!(await checkUserPerm(req, serverName, "files_read"))) { + return res.status(403).json({ error: "permission denied", permission: "files_read" }); + } + + 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" }); + const rel = String(req.query.path || ""); + 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 url = new URL(nodeUrl(ctx.node, "/v1/fs/download")); + const reqOpts = { + hostname: url.hostname, + port: url.port, + path: url.pathname, + method: "POST", + headers: Object.assign({ + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(postData) + }, nodeHeaders(ctx.node)), + timeout: 300000 + }; + const proxyReq = lib.request(reqOpts, (proxyRes) => { + if (proxyRes.statusCode !== 200) { + return res.status(proxyRes.statusCode || 502).json({ error: "download failed" }); + } + if (proxyRes.headers["content-type"]) res.setHeader("Content-Type", proxyRes.headers["content-type"]); + if (proxyRes.headers["content-disposition"]) res.setHeader("Content-Disposition", proxyRes.headers["content-disposition"]); + if (proxyRes.headers["content-length"]) res.setHeader("Content-Length", proxyRes.headers["content-length"]); + proxyRes.pipe(res); + }); + proxyReq.on("error", () => res.status(502).json({ error: "node connection failed" })); + proxyReq.on("timeout", () => { proxyReq.destroy(); res.status(504).json({ error: "download timeout" }); }); + proxyReq.write(postData); + proxyReq.end(); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); +app.post("/api/nodes/server/:name/file", async (req, res) => { + const serverName = req.params.name; + + const accessCheck = await checkServerAccess(req, serverName); + if (!accessCheck.ok) { + 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 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" }); + const rel = String(req.body.path || ""); + const content = String((req.body && req.body.content) || ""); + try { + 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" } } + ); + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + 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)); + + return res.json({ ok: true }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); +app.post("/api/nodes/server/:name/delete", async (req, res) => { + const ctx = await remoteContext(req.params.name); + 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" }); + + const accessCheck = await checkServerAccess(req, req.params.name); + if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); + + if (!(await checkUserPerm(req, req.params.name, "files_delete"))) { + return res.status(403).json({ error: "permission denied", permission: "files_delete" }); + } + const rel = String(req.body.path || ""); + const isDir = !!req.body.isDir; + try { + 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 } } + ); + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_delete_failed" }); + + const userEmail = req.session?.user || "unknown"; + recordActivity(req.params.name, "file_delete", { path: rel, isDir }, userEmail, getRequestIp(req)); + + return res.json({ ok: true }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); + +app.post("/api/nodes/server/:name/delete-batch", async (req, res) => { + const ctx = await remoteContext(req.params.name); + 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" }); + + const accessCheck = await checkServerAccess(req, req.params.name); + if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); + + if (!(await checkUserPerm(req, req.params.name, "files_delete"))) { + return res.status(403).json({ error: "permission denied", permission: "files_delete" }); + } + + const items = req.body.items; + if (!Array.isArray(items) || items.length === 0) { + return res.status(400).json({ error: "items array required" }); + } + if (items.length > 500) { + return res.status(400).json({ error: "too many items (max 500)" }); + } + + try { + const fullItems = items.map(item => ({ + path: safeJoinUnix(ctx.baseDir, String(item.path || "")), + isDir: !!item.isDir + })); + + const { status, json } = await httpJson( + nodeUrl(ctx.node, "/v1/fs/delete-batch"), + { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), + body: { items: fullItems }, + timeoutMs: 120000 + } + ); + + if (status !== 200 || !json) { + return res.status(502).json({ error: "node_batch_delete_failed" }); + } + + const userEmail = req.session?.user || "unknown"; + recordActivity(req.params.name, "file_delete_batch", { + count: items.length, + success: json.success || 0, + failed: json.failed || 0 + }, userEmail, getRequestIp(req)); + + return res.json(json); + } catch (e) { + console.error("[delete-batch] Error:", e); + return res.status(500).json({ error: "batch_delete_error", detail: e.message }); + } +}); + +app.post("/api/nodes/server/:name/rename", async (req, res) => { + const ctx = await remoteContext(req.params.name); + 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" }); + + const accessCheck = await checkServerAccess(req, req.params.name); + if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); + + if (!(await checkUserPerm(req, req.params.name, "files_rename"))) { + return res.status(403).json({ error: "permission denied", permission: "files_rename" }); + } + const rel = String(req.body.path || ""); + const newName = sanitizeName(req.body.newName || ""); + if (!newName) return res.status(400).json({ error: "invalid newName" }); + try { + 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 } } + ); + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_rename_failed" }); + + const userEmail = req.session?.user || "unknown"; + recordActivity(req.params.name, "file_rename", { src: rel, dest: newName }, userEmail, getRequestIp(req)); + + return res.json({ ok: true }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); +app.post("/api/nodes/server/:name/extract", async (req, res) => { + const ctx = await remoteContext(req.params.name); + 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" }); + + const accessCheck = await checkServerAccess(req, req.params.name); + if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); + + if (!(await checkUserPerm(req, req.params.name, "files_create"))) { + return res.status(403).json({ error: "permission denied", permission: "files_create" }); + } + const rel = String(req.body.path || ""); + try { + 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 } } + ); + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_extract_failed" }); + + const userEmail = req.session?.user || "unknown"; + recordActivity(req.params.name, "file_extract", { path: rel }, userEmail, getRequestIp(req)); + + return res.json({ ok: true, msg: json.msg || "Extracted" }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); +app.post("/api/nodes/server/:name/archive", async (req, res) => { + const ctx = await remoteContext(req.params.name); + 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" }); + + const accessCheck = await checkServerAccess(req, req.params.name); + if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); + + if (!(await checkUserPerm(req, req.params.name, "files_archive"))) { + return res.status(403).json({ error: "permission denied", permission: "files_archive" }); + } + + const paths = req.body.paths; + const destDir = String(req.body.destDir || ""); + + if (!Array.isArray(paths) || paths.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 } + ); + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status !== 200 || !json || !json.ok) { + return res.status(502).json({ error: json?.error || "archive failed" }); + } + + const userEmail = req.session?.user || "unknown"; + recordActivity(req.params.name, "file_archive", { paths, destDir, archiveName: json.name }, userEmail, getRequestIp(req)); + + return res.json({ ok: true, path: json.path, name: json.name }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); +app.post("/api/nodes/server/:name/upload", async (req, res) => { + const ctx = await remoteContext(req.params.name); + 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" }); + + const accessCheck = await checkServerAccess(req, req.params.name); + if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); + + if (!(await checkUserPerm(req, req.params.name, "files_upload"))) { + return res.status(403).json({ error: "permission denied", permission: "files_upload" }); + } + + let rel = ""; + let fileSeen = false; + let responded = false; + let uploadPromise = null; + const nodeMaxMb = nodeUploadLimitMb(ctx.node); + const nodeMaxBytes = nodeMaxMb * 1024 * 1024; + + const respond = (status, payload) => { + if (responded || res.headersSent) return; + responded = true; + res.status(status).json(payload); + }; + + const bb = getLazyBusboy()({ + headers: req.headers, + limits: { files: 1, fields: 8, fieldSize: 64 * 1024 }, + }); + + bb.on("field", (name, value) => { + if (name === "path") rel = String(value || ""); + }); + + bb.on("file", (name, fileStream, info) => { + if (responded) { + fileStream.resume(); + return; + } + if (name !== "file") { + fileStream.resume(); + return; + } + if (fileSeen) { + fileStream.resume(); + respond(400, { error: "too_many_files" }); + return; + } + fileSeen = true; + + uploadPromise = (async () => { + const originalName = String(info?.filename || "upload"); + const full = safeJoinUnix(ctx.baseDir, rel ? rel : ""); + const diskSnapshot = await fetchServerDiskSnapshot(ctx, req.params.name, 5000).catch(() => null); + const replacedBytes = await fetchRemoteReplacementBytes(ctx, full, originalName, 5000).catch(() => null); + const incomingLength = Number(req.headers["content-length"] || 0) || 0; + const diskLimitError = replacedBytes == null ? null : buildDiskLimitUploadError(diskSnapshot, incomingLength, replacedBytes); + if (diskLimitError) { + fileStream.resume(); + return { status: 507, json: diskLimitError }; + } + return streamUploadToNode(ctx.node, fileStream, originalName, full, nodeMaxBytes, nodeMaxMb); + })(); + + uploadPromise.then((result) => { + if (responded) return; + if (result.status === 507 && result.json?.error === "disk_limit_exceeded") { + respond(507, result.json); + return; + } + if (result.status === 413) { + respond(413, result.json || { + error: "file_too_large", + message: `File exceeds this node's upload limit of ${nodeMaxMb} MB`, + limit_mb: nodeMaxMb, + }); + return; + } + if (result.status !== 200 || !result.json || !result.json.ok) { + respond(502, { error: "node_upload_failed", detail: result.json?.error }); + return; + } + + const userEmail = req.session?.user || "unknown"; + recordActivity(req.params.name, "file_upload", { path: rel, filename: info?.filename || "upload" }, userEmail, getRequestIp(req)); + + respond(200, { ok: true, msg: result.json.msg || "Uploaded" }); + }).catch((e) => { + respond(400, { error: maskPathErrorMessage(e) }); + }); + }); + + bb.on("error", (err) => { + respond(400, { error: "bad_multipart", detail: err.message }); + }); + + bb.on("finish", () => { + if (!responded && !fileSeen) { + respond(400, { error: "no_file" }); + } + }); + + req.pipe(bb); +}); + +// ============= URL Uploader (remote node) ============= +function isUploaderPrivateIPv4(ip) { + const parts = String(ip || "").split(".").map(Number); + if (parts.length !== 4 || parts.some(n => !Number.isInteger(n) || n < 0 || n > 255)) return true; + const [a, b] = parts; + if (a === 0) return true; + if (a === 10) return true; + if (a === 127) return true; + if (a === 169 && b === 254) return true; + if (a === 172 && b >= 16 && b <= 31) return true; + if (a === 192 && b === 168) return true; + if (a === 100 && b >= 64 && b <= 127) return true; + if (a === 198 && (b === 18 || b === 19)) return true; + if (a >= 224) return true; + return false; +} +function isUploaderPrivateIPv6(ip) { + const v = String(ip || "").toLowerCase(); + if (v === "::" || v === "::1") return true; + if (v.startsWith("fc") || v.startsWith("fd")) return true; + if (v.startsWith("fe8") || v.startsWith("fe9") || v.startsWith("fea") || v.startsWith("feb")) return true; + if (v.startsWith("::ffff:")) { + const tail = v.slice("::ffff:".length); + if (net.isIP(tail) === 4) return isUploaderPrivateIPv4(tail); + } + return false; +} +async function uploaderAssertSafeRemoteUrl(inputUrl) { + let s = String(inputUrl || "").trim(); + if (!s) throw new Error("Empty URL"); + if (s.length > 2048) throw new Error("URL too long"); + if (/[\s\u0000-\u001F\u007F]/.test(s)) throw new Error("Invalid characters in URL"); + if (!/^[a-zA-Z][a-zA-Z0-9+.\-]*:\/\//.test(s)) s = "https://" + s; + + let u; + try { u = new URL(s); } catch (_) { throw new Error("Invalid URL"); } + const proto = (u.protocol || "").toLowerCase(); + if (proto !== "http:" && proto !== "https:") throw new Error("Only http(s) URLs are allowed"); + if (u.username || u.password) throw new Error("Credentials in URL are not allowed"); + if (!u.hostname) throw new Error("Invalid hostname"); + const hostLower = u.hostname.toLowerCase(); + if (hostLower === "localhost" || hostLower.endsWith(".localhost") || hostLower.endsWith(".local")) { + throw new Error("Localhost URLs are not allowed"); + } + + const dnsp = require("dns").promises; + if (net.isIP(u.hostname)) { + const t = net.isIP(u.hostname); + if (t === 4 ? isUploaderPrivateIPv4(u.hostname) : isUploaderPrivateIPv6(u.hostname)) { + throw new Error("Private IP is not allowed"); + } + } else { + let answers = []; + try { answers = await dnsp.lookup(u.hostname, { all: true, verbatim: true }); } catch (_) { throw new Error("DNS lookup failed"); } + if (!answers || answers.length === 0) throw new Error("DNS lookup failed"); + for (const a of answers) { + if (!a || !a.address) continue; + const t = net.isIP(a.address); + if ((t === 4 && isUploaderPrivateIPv4(a.address)) || (t === 6 && isUploaderPrivateIPv6(a.address))) { + throw new Error("Hostname resolves to a private/internal IP"); + } + } + } + return u; +} +app.post("/api/nodes/server/:name/upload-url", async (req, res) => { + const ctx = await remoteContext(req.params.name); + 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" }); + + const accessCheck = await checkServerAccess(req, req.params.name); + if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); + + if (!(await checkUserPerm(req, req.params.name, "files_upload"))) { + return res.status(403).json({ error: "permission denied", permission: "files_upload" }); + } + + const rawUrl = String(req.body?.url || "").trim(); + const rel = String(req.body?.path || ""); + + if (!rawUrl) return res.status(400).json({ error: "missing url" }); + if (rawUrl.length > 2048) return res.status(400).json({ error: "url too long" }); + + let validatedUrl; + try { + validatedUrl = await uploaderAssertSafeRemoteUrl(rawUrl); + } catch (err) { + return res.status(400).json({ error: "invalid_url", message: err.message || "Invalid URL" }); + } + + try { + const full = safeJoinUnix(ctx.baseDir, rel); + const result = await httpJson( + nodeUrl(ctx.node, "/v1/fs/uploadUrl"), + { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), + body: { dir: full, url: validatedUrl.toString() }, + timeoutMs: 30 * 60 * 1000 + } + ); + + const { status, json } = result; + + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status === 413 && json) { + return res.status(413).json(json); + } + if (status !== 200 || !json || json.ok !== true) { + const msg = (json && (json.error || json.message)) || `node_upload_url_failed (HTTP ${status})`; + return res.status(502).json({ error: "node_upload_url_failed", message: msg }); + } + + const userEmail = req.session?.user || "unknown"; + recordActivity( + req.params.name, + "file_upload_url", + { path: rel, url: validatedUrl.toString(), filename: json.filename || null, size: json.bytes || null }, + userEmail, + getRequestIp(req) + ); + + return res.json({ ok: true, msg: json.msg || "Uploaded from URL", filename: json.filename || null, bytes: json.bytes || null }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } +}); +// ============= /URL Uploader ============= + +async function startPayloadFor(name) { + const srv = await findServerByNameOrId(name); + // Node daemon /start accepts only hostPort + env; keep payload strict to avoid 400 invalid request body. + const chosenPort = validatePortInput(srv?.hostPort ?? srv?.port ?? srv?.server_port); + const payload = {}; + if (chosenPort != null) payload.hostPort = chosenPort; + + try { + const subs = await db.query("SELECT domain FROM subdomains WHERE server_id = ? AND status = 'approved'", [srv.id]); + if (subs.length > 0) { + const joined = subs.map(s => s.domain).join(","); + payload.env = { TRUSTED_SUBDOMAINS: joined }; + } + } catch (e) { + console.error("Failed to fetch subdomains for payload:", e); + } + + return payload; +} +async function seedRuntimeOnNode(node, name) { + try { + const srv = await findServerByNameOrId(name); + const tpl = String(srv?.template || "").toLowerCase(); + const isMinecraft = tpl === "minecraft"; + const isRuntimeTemplate = ["nodejs", "python", "discord-bot"].includes(tpl); + if (srv && tpl && !isMinecraft && isRuntimeTemplate) { + const runtimePayload = { + runtime: srv.runtime || {}, + template: tpl, + start: srv.start || srv.startFile || srv.entry || null, + port: srv.hostPort || srv.port || srv.server_port || null, + nodeId: node?.uuid || node?.id || null, + }; + await callNodeApi( + node, + `/v1/servers/${encodeURIComponent(name)}/runtime`, + "POST", + runtimePayload, + LONG_NODE_TIMEOUT_MS + ).catch(() => { }); + } + } catch (_) { } +} + +async function performPanelServerAction(req, serverName, cmdRaw) { + const targetServer = String(serverName || "").trim(); + const cmdValue = String(cmdRaw || "").toLowerCase(); + const cmd = (cmdValue === "run") ? "start" : cmdValue; + + const ctx = await remoteContext(targetServer); + if (!ctx.exists) return { status: 404, body: { error: "server not found" } }; + if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote" } }; + + const accessCheck = await checkServerAccess(req, targetServer); + if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; + + let requiredPerms = ["server_start"]; + if (cmd === "start") requiredPerms = ["server_start"]; + else if (cmd === "restart") requiredPerms = ["server_stop", "server_start"]; + else if (cmd === "stop" || cmd === "kill") requiredPerms = ["server_stop"]; + else if (cmd === "status") requiredPerms = []; + else return { status: 400, body: { error: "invalid_cmd" } }; + + for (const requiredPerm of requiredPerms) { + if (!(await checkUserPerm(req, targetServer, requiredPerm))) { + return { status: 403, body: { error: "permission denied", permission: requiredPerm } }; + } + } + + let path = null; + let method = "POST"; + let payload = null; + if (cmd === "start") { + try { + if (ctx.node) await seedRuntimeOnNode(ctx.node, targetServer); + } catch (_) { } + path = `/v1/servers/${encodeURIComponent(targetServer)}/start?wait=false`; + payload = await startPayloadFor(targetServer); + } else if (cmd === "stop") { + path = `/v1/servers/${encodeURIComponent(targetServer)}/stop`; + } else if (cmd === "kill") { + path = `/v1/servers/${encodeURIComponent(targetServer)}/kill`; + } else if (cmd === "restart") { + path = `/v1/servers/${encodeURIComponent(targetServer)}/restart`; + } else if (cmd === "status") { + method = "GET"; + path = `/v1/servers/${encodeURIComponent(targetServer)}`; + } + + if (cmd !== "status") { + const actionMap = { start: "server_start", stop: "server_stop", restart: "server_restart", kill: "server_kill" }; + const actionName = actionMap[cmd] || `server_${cmd}`; + const userEmail = req.session?.user || "unknown"; + recordActivity(targetServer, actionName, null, userEmail, getRequestIp(req)); + } + + const timeoutMs = cmd === "start" ? LONG_NODE_TIMEOUT_MS : DEFAULT_NODE_TIMEOUT_MS; + let result = await callNodeApi(ctx.node, path, method, payload, timeoutMs); + if (result.status === 0 && cmd === "start") { + result = await callNodeApi(ctx.node, path, method, payload, timeoutMs); + } + const { status, json, error } = result; + if ((status === 200 || status === 202) && json && (json.ok === true || json.ok === undefined)) { + return { status: 200, body: json || { ok: true } }; + } + const detail = (json && (json.detail || json.error || json.message)) || error || `HTTP ${status}`; + console.warn(`[nodes-action] ${targetServer} ${cmd} failed: status=${status} detail=${String(detail)}`); + return { + status: 502, + body: { + error: "node_action_failed", + status, + detail, + response: json || null, + }, + }; +} + +async function performPanelConsoleCommand(req, serverName, rawCommand, requestId = "") { + const targetServer = String(serverName || "").trim(); + const ctx = await remoteContext(targetServer); + if (!ctx.exists) return { status: 404, body: { error: "server not found" } }; + if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote" } }; + + const accessCheck = await checkServerAccess(req, targetServer); + if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; + + if (!(await checkUserPerm(req, targetServer, "console_write"))) { + return { status: 403, body: { error: "permission denied", permission: "console_write" } }; + } + + const commandCheck = sanitizeConsoleCommand(rawCommand); + if (!commandCheck.ok) { + return { status: 400, body: { error: commandCheck.error, detail: commandCheck.detail || null } }; + } + const command = commandCheck.command; + const commandRequestId = String(requestId || "").trim(); + + const userEmail = req.session?.user || "unknown"; + recordActivity(targetServer, "console_command", { command }, userEmail, getRequestIp(req)); + + const { status, json } = await callNodeApi( + ctx.node, + `/v1/servers/${encodeURIComponent(targetServer)}/command`, + "POST", + commandRequestId ? { command, requestId: commandRequestId } : { command } + ); + if (status === 200 && json && json.ok) return { status: 200, body: json }; + return { + status: 502, + body: { + error: "node_command_failed", + status, + detail: (json && (json.detail || json.error)) || `status ${status}`, + }, + }; +} + +async function performPanelListBackups(req, serverName) { + const targetServer = String(serverName || "").trim(); + const accessCheck = await checkServerAccess(req, targetServer); + if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; + + if (!(await checkUserPerm(req, targetServer, "backups_view"))) { + return { status: 403, body: { error: "forbidden", detail: "You do not have permission to view backups" } }; + } + + const ctx = await remoteContext(targetServer); + if (!ctx.exists) return { status: 404, body: { error: "server not found", detail: "Server does not exist in database" } }; + if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote", detail: "Server is not associated with a node" } }; + + const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(targetServer)}/backups`); + const { status, json, text } = await httpJson(url, { method: "GET", headers: nodeHeaders(ctx.node), timeoutMs: 15000 }); + + if (status === 0) { + return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } }; + } + if (status !== 200 || !json || !json.ok) { + return { status: 502, body: { error: "node_backup_list_failed", detail: json?.error || text || `status ${status}` } }; + } + return { status: 200, body: { ok: true, backups: json.backups || [] } }; +} + +async function performPanelCreateBackup(req, serverName, backupName, description) { + const targetServer = String(serverName || "").trim(); + const accessCheck = await checkServerAccess(req, targetServer); + if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; + + if (!(await checkUserPerm(req, targetServer, "backups_create"))) { + return { status: 403, body: { error: "forbidden", detail: "You do not have permission to create backups" } }; + } + + const ctx = await remoteContext(targetServer); + if (!ctx.exists) return { status: 404, body: { error: "server not found", detail: "Server does not exist in database" } }; + if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote", detail: "Server is not associated with a node" } }; + + const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(targetServer)}/backups`); + const { status, json, text } = await httpJson(url, { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), + body: { name: backupName, description }, + timeoutMs: 120000, + }); + + if (status === 0) { + return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } }; + } + if (status === 507 && json?.error === "disk_limit_exceeded") { + return { status: 507, body: json }; + } + if (status !== 200 || !json || !json.ok) { + return { status: 502, body: { error: "node_backup_create_failed", detail: json?.error || text || `status ${status}` } }; + } + + const userEmail = req.session?.user || "unknown"; + const userIp = getRequestIp(req); + recordActivity(targetServer, "backup_create", { backupId: json.backup?.id, name: json.backup?.name }, userEmail, userIp); + + return { status: 200, body: { ok: true, backup: json.backup } }; +} + +async function performPanelRestoreBackup(req, serverName, backupIdRaw, deleteOldFiles) { + const targetServer = String(serverName || "").trim(); + const accessCheck = await checkServerAccess(req, targetServer); + if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; + + if (!(await checkUserPerm(req, targetServer, "backups_create"))) { + return { status: 403, body: { error: "forbidden", detail: "You do not have permission to restore backups" } }; + } + + const ctx = await remoteContext(targetServer); + if (!ctx.exists) return { status: 404, body: { error: "server not found", detail: "Server does not exist in database" } }; + if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote", detail: "Server is not associated with a node" } }; + + const backupId = String(backupIdRaw || "").trim(); + if (!backupId) return { status: 400, body: { error: "missing backup id" } }; + + const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(targetServer)}/backups/${encodeURIComponent(backupId)}/restore`); + const { status, json, text } = await httpJson(url, { + method: "POST", + headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), + body: { deleteOldFiles: !!deleteOldFiles }, + timeoutMs: 300000, + }); + + if (status === 0) { + return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } }; + } + if (status === 507 && json?.error === "disk_limit_exceeded") { + return { status: 507, body: json }; + } + if (status !== 200 || !json || !json.ok) { + return { status: 502, body: { error: "node_backup_restore_failed", detail: json?.error || text || `status ${status}` } }; + } + + const userEmail = req.session?.user || "unknown"; + const userIp = getRequestIp(req); + recordActivity(targetServer, "backup_restore", { backupId, deleteOldFiles: !!deleteOldFiles }, userEmail, userIp); + + return { status: 200, body: { ok: true } }; +} + +async function performPanelDeleteBackup(req, serverName, backupIdRaw) { + const targetServer = String(serverName || "").trim(); + const accessCheck = await checkServerAccess(req, targetServer); + if (!accessCheck.ok) return { status: accessCheck.status, body: { error: accessCheck.error } }; + + if (!(await checkUserPerm(req, targetServer, "backups_delete"))) { + return { status: 403, body: { error: "forbidden", detail: "You do not have permission to delete backups" } }; + } + + const ctx = await remoteContext(targetServer); + if (!ctx.exists) return { status: 404, body: { error: "server not found", detail: "Server does not exist in database" } }; + if (!ctx.remote || !ctx.node) return { status: 400, body: { error: "not_remote", detail: "Server is not associated with a node" } }; + + const backupId = String(backupIdRaw || "").trim(); + if (!backupId) return { status: 400, body: { error: "missing backup id" } }; + + const url = nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(targetServer)}/backups/${encodeURIComponent(backupId)}`); + const { status, json, text } = await httpJson(url, { + method: "DELETE", + headers: nodeHeaders(ctx.node), + timeoutMs: 30000, + }); + + if (status === 0) { + return { status: 502, body: { error: "node_unreachable", detail: "Could not connect to node agent" } }; + } + if (status !== 200 || !json || !json.ok) { + return { status: 502, body: { error: "node_backup_delete_failed", detail: json?.error || text || `status ${status}` } }; + } + + const userEmail = req.session?.user || "unknown"; + const userIp = getRequestIp(req); + recordActivity(targetServer, "backup_delete", { backupId }, userEmail, userIp); + + return { status: 200, body: { ok: true } }; +} +app.post("/api/nodes/server/:name/action", async (req, res) => { + try { + const result = await performPanelServerAction(req, req.params.name, req.body && (req.body.cmd || req.body.action)); + return res.status(result.status).json(result.body); + } catch (e) { + return res.status(500).json({ error: "bridge_failed", detail: e && e.message }); + } +}); +app.post("/api/nodes/server/:name/command", async (req, res) => { + try { + const result = await performPanelConsoleCommand(req, req.params.name, req.body && req.body.command, req.body && req.body.requestId); + return res.status(result.status).json(result.body); + } catch (e) { + return res.status(500).json({ error: "bridge_failed", detail: e && e.message }); + } +}); + +app.post("/api/nodes/server/:name/extract-image", async (req, res) => { + try { + const ctx = await remoteContext(req.params.name); + 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" }); + + const payload = { + image: req.body?.image || "", + tag: req.body?.tag || "", + extractPath: req.body?.extractPath || "", + paths: Array.isArray(req.body?.paths) ? req.body.paths : [] + }; + + const userEmail = req.session?.user || "unknown"; + recordActivity(req.params.name, "extract_image", { image: payload.image || "(from meta)" }, userEmail, getRequestIp(req)); + + const { status, json } = await callNodeApi( + ctx.node, + `/v1/servers/${encodeURIComponent(req.params.name)}/extract-image`, + "POST", + payload, + LONG_NODE_TIMEOUT_MS + ); + + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status === 200 && json) return res.json(json); + return res.status(502).json({ error: "extract_failed", status, detail: json && json.error }); + } catch (e) { + return res.status(500).json({ error: "bridge_failed", detail: e && e.message }); + } +}); + +app.post("/api/nodes/:id/server/action", async (req, res) => { + try { + const name = String((req.body && req.body.name) || "").trim(); + const cmd = String((req.body && req.body.cmd) || "").trim(); + if (!name || !cmd) return res.status(400).json({ error: "missing name/cmd" }); + const result = await performPanelServerAction(req, name, req.body && req.body.cmd); + return res.status(result.status).json(result.body); + } catch (e) { + return res.status(500).json({ error: "bridge_failed", detail: e && e.message }); + } +}); +app.post("/api/nodes/:id/server/command", async (req, res) => { + try { + const name = String((req.body && req.body.name) || "").trim(); + const command = String((req.body && req.body.command) || "").trim(); + if (!name || !command) return res.status(400).json({ error: "missing name/command" }); + const result = await performPanelConsoleCommand(req, name, req.body && req.body.command, req.body && req.body.requestId); + return res.status(result.status).json(result.body); + } catch (e) { + return res.status(500).json({ error: "bridge_failed", detail: e && e.message }); + } +}); +app.post("/api/nodes/server/:name/create", async (req, res) => { + try { + const ctx = await remoteContext(req.params.name); + 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" }); + + const accessCheck = await checkServerAccess(req, req.params.name); + if (!accessCheck.ok) return res.status(accessCheck.status).json({ error: accessCheck.error }); + + if (!(await checkUserPerm(req, req.params.name, "files_create"))) { + return res.status(403).json({ error: "permission denied", permission: "files_create" }); + } + const typeRaw = String((req.body && req.body.type) || "").toLowerCase(); + const nameRaw = String((req.body && req.body.name) || ""); + const relPath = String((req.body && req.body.path) || ""); + if (typeRaw !== "file" && typeRaw !== "folder") return res.status(400).json({ error: "invalid_type" }); + const safeName = sanitizeName(nameRaw); + if (!safeName) return res.status(400).json({ error: "invalid_name" }); + try { + const relativePosix = path.posix.join(relPath || "", safeName); + const target = safeJoinUnix(ctx.baseDir, relativePosix); + const payload = typeRaw === "folder" + ? { path: safeJoinUnix(target, ".keep"), content: "", encoding: "utf8" } + : { path: target, content: "", encoding: "utf8" }; + const { status, json } = await httpJson( + nodeUrl(ctx.node, "/v1/fs/write"), + { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: payload } + ); + if (status === 507 && json?.error === "disk_limit_exceeded") { + return res.status(507).json(json); + } + if (status !== 200 || !json || !json.ok) { + const errMsg = json?.error || ''; + if (errMsg.includes('exist') || errMsg.includes('EEXIST')) { + return res.status(400).json({ error: "already_exists", message: `A ${typeRaw} with that name already exists` }); + } + return res.status(502).json({ error: "node_create_failed", message: `Failed to create ${typeRaw}. It may already exist.` }); + } + + const userEmail = req.session?.user || "unknown"; + const actionType = typeRaw === "folder" ? "folder_create" : "file_create"; + recordActivity(req.params.name, actionType, { path: relativePosix, type: typeRaw }, userEmail, getRequestIp(req)); + + return res.json({ ok: true, path: relativePosix }); + } catch (e) { + return res.status(400).json({ error: maskPathErrorMessage(e) }); + } + } catch (e) { + return res.status(500).json({ error: "bridge_failed", detail: e && e.message }); + } +}); + + +app.get("/api/nodes/server/:name/backups", async (req, res) => { + try { + const result = await performPanelListBackups(req, req.params.name); + return res.status(result.status).json(result.body); + } catch (e) { + console.error("[backups] List error:", e); + return res.status(500).json({ error: "bridge_failed", detail: e?.message }); + } +}); + +app.post("/api/nodes/server/:name/backups", async (req, res) => { + try { + const result = await performPanelCreateBackup(req, req.params.name, req.body?.name, req.body?.description); + return res.status(result.status).json(result.body); + } catch (e) { + console.error("[backups] Create error:", e); + return res.status(500).json({ error: "bridge_failed", detail: e?.message }); + } +}); + +app.post("/api/nodes/server/:name/backups/:backupId/restore", async (req, res) => { + try { + const result = await performPanelRestoreBackup(req, req.params.name, req.params.backupId, req.body?.deleteOldFiles); + return res.status(result.status).json(result.body); + } catch (e) { + console.error("[backups] Restore error:", e); + return res.status(500).json({ error: "bridge_failed", detail: e?.message }); + } +}); + +app.delete("/api/nodes/server/:name/backups/:backupId", async (req, res) => { + try { + const result = await performPanelDeleteBackup(req, req.params.name, req.params.backupId); + return res.status(result.status).json(result.body); + } catch (e) { + console.error("[backups] Delete error:", e); + return res.status(500).json({ error: "bridge_failed", detail: e?.message }); + } +}); + +app.get("/api/nodes/server/:name/logs", async (req, res) => { + try { + const serverName = req.params.name; + + const accessCheck = await checkServerAccess(req, serverName); + if (!accessCheck.ok) { + return res.status(accessCheck.status).json({ error: accessCheck.error }); + } + + if (!(await checkUserPerm(req, serverName, "console_read"))) { + return res.status(403).json({ error: "permission denied", permission: "console_read" }); + } + + const { node } = await resolveNodeForServer(serverName); + if (!node) return res.status(404).json({ error: "server_or_node_not_found" }); + + const base = buildNodeBaseUrl(node.address, node.api_port, node.ssl_enabled, nodeUnderCloudflare(node)); + const tailRaw = String(req.query?.tail || "").trim(); + let tailQuery = ""; + if (/^\d+$/.test(tailRaw)) { + const tail = Math.max(0, Math.min(10000, parseInt(tailRaw, 10))); + tailQuery = `?tail=${encodeURIComponent(String(tail))}`; + } + const fullUrl = `${base}/v1/servers/${encodeURIComponent(serverName)}/logs${tailQuery}`; + const isHttps = fullUrl.startsWith("https:"); + const lib = isHttps ? https : http; + const nreq = lib.request(fullUrl, { + method: "GET", + headers: { + ...nodeHeaders(node), + "Accept": "text/event-stream", + "Cache-Control": "no-cache", + "Connection": "keep-alive" + } + }, (nres) => { + if (nres.statusCode !== 200) { + const chunks = []; + nres.on("data", (chunk) => { + if (Buffer.concat(chunks).length < 16 * 1024) chunks.push(Buffer.from(chunk)); + }); + nres.on("end", () => { + const detail = Buffer.concat(chunks).toString("utf8").slice(0, 2000); + if (!res.headersSent) { + return res.status(nres.statusCode || 502).json({ error: "node_logs_failed", detail: detail || `status ${nres.statusCode || 502}` }); + } + try { res.end(); } catch { } + }); + return; + } + + res.setHeader("Content-Type", "text/event-stream"); + res.setHeader("Cache-Control", "no-cache, no-transform"); + res.setHeader("Connection", "keep-alive"); + res.setHeader("X-Accel-Buffering", "no"); + res.flushHeaders?.(); + + nres.on("data", (chunk) => { + try { + res.write(chunk); + res.flush?.(); + } catch { } + }); + nres.on("end", () => { try { res.end(); } catch { } }); + }); + nreq.on("socket", (socket) => { + try { socket.setNoDelay(true); } catch { } + }); + nreq.on("error", () => { try { res.end(); } catch { } }); + nreq.end(); + req.on("close", () => { try { nreq.destroy(); } catch { } }); + } catch { + try { res.end(); } catch { } + } +}); +if (require.main === module) { + app.listen(PORT, () => console.log(`[nodes.js] Nodes API on :${PORT}`)); +} + +module.exports = app; +module.exports.remoteContext = remoteContext; +module.exports.httpJson = httpJson; +module.exports.nodeUrl = nodeUrl; +module.exports.nodeHeaders = nodeHeaders; +module.exports.nodeUnderCloudflare = nodeUnderCloudflare; +module.exports.callNodeApi = callNodeApi; +module.exports.resolveNodeForServer = resolveNodeForServer; +module.exports.recordActivity = recordActivity; +module.exports.seedRuntimeOnNode = seedRuntimeOnNode; +module.exports.setWebhookDispatcher = setWebhookDispatcher; +module.exports.setPermissionCheckers = setPermissionCheckers; +module.exports.startPayloadFor = startPayloadFor; +module.exports.sanitizeConsoleCommand = sanitizeConsoleCommand; +module.exports.performPanelServerAction = performPanelServerAction; +module.exports.performPanelConsoleCommand = performPanelConsoleCommand; +module.exports.performPanelListBackups = performPanelListBackups; +module.exports.performPanelCreateBackup = performPanelCreateBackup; +module.exports.performPanelRestoreBackup = performPanelRestoreBackup; +module.exports.performPanelDeleteBackup = performPanelDeleteBackup; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..0077da3 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,4944 @@ +{ + "name": "adpanel-final-v12", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "adpanel-final-v12", + "version": "1.0.0", + "license": "ISC", + "dependencies": { + "@fortawesome/fontawesome-free": "^7.2.0", + "adm-zip": "^0.5.16", + "ansi_up": "^6.0.6", + "bcrypt": "^6.0.0", + "bcryptjs": "^3.0.3", + "busboy": "^1.6.0", + "bullmq": "^5.66.7", + "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", + "express-rate-limit": "^8.3.2", + "express-session": "^1.19.0", + "form-data": "^4.0.5", + "helmet": "^8.1.0", + "hpp": "^0.2.3", + "inquirer": "^13.3.2", + "ip-range-check": "^0.2.0", + "multer": "^1.4.5-lts.1", + "mysql2": "^3.11.5", + "nodemon": "^3.1.14", + "ora": "^9.3.0", + "pm2": "^6.0.14", + "qrcode": "^1.5.4", + "qrcode-terminal": "^0.12.0", + "rate-limit-redis": "^4.3.1", + "redis": "^5.11.0", + "session-file-store": "^1.5.0", + "socket.io": "^4.8.3", + "speakeasy": "^2.0.0", + "tar": "^7.5.13", + "ws": "^8.19.0" + } + }, + "node_modules/@fortawesome/fontawesome-free": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/@fortawesome/fontawesome-free/-/fontawesome-free-7.2.0.tgz", + "integrity": "sha512-3DguDv/oUE+7vjMeTSOjCSG+KeawgVQOHrKRnvUuqYh1mfArrh7s+s8hXW3e4RerBA1+Wh+hBqf8sJNpqNrBWg==", + "license": "(CC-BY-4.0 AND OFL-1.1 AND MIT)", + "engines": { + "node": ">=6" + } + }, + "node_modules/@inquirer/ansi": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@inquirer/ansi/-/ansi-2.0.4.tgz", + "integrity": "sha512-DpcZrQObd7S0R/U3bFdkcT5ebRwbTTC4D3tCc1vsJizmgPLxNJBo+AAFmrZwe8zk30P2QzgzGWZ3Q9uJwWuhIg==", + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + } + }, + "node_modules/@inquirer/checkbox": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-5.1.2.tgz", + "integrity": "sha512-PubpMPO2nJgMufkoB3P2wwxNXEMUXnBIKi/ACzDUYfaoPuM7gSTmuxJeMscoLVEsR4qqrCMf5p0SiYGWnVJ8kw==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.4", + "@inquirer/core": "^11.1.7", + "@inquirer/figures": "^2.0.4", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/confirm": { + "version": "6.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-6.0.10.tgz", + "integrity": "sha512-tiNyA73pgpQ0FQ7axqtoLUe4GDYjNCDcVsbgcA5anvwg2z6i+suEngLKKJrWKJolT//GFPZHwN30binDIHgSgQ==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.1.7", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core": { + "version": "11.1.7", + "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-11.1.7.tgz", + "integrity": "sha512-1BiBNDk9btIwYIzNZpkikIHXWeNzNncJePPqwDyVMhXhD1ebqbpn1mKGctpoqAbzywZfdG0O4tvmsGIcOevAPQ==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.4", + "@inquirer/figures": "^2.0.4", + "@inquirer/type": "^4.0.4", + "cli-width": "^4.1.0", + "fast-wrap-ansi": "^0.2.0", + "mute-stream": "^3.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/core/node_modules/mute-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", + "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "node_modules/@inquirer/core/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@inquirer/editor": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-5.0.10.tgz", + "integrity": "sha512-VJx4XyaKea7t8hEApTw5dxeIyMtWXre2OiyJcICCRZI4hkoHsMoCnl/KbUnJJExLbH9csLLHMVR144ZhFE1CwA==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.1.7", + "@inquirer/external-editor": "^2.0.4", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/expand": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-5.0.10.tgz", + "integrity": "sha512-fC0UHJPXsTRvY2fObiwuQYaAnHrp3aDqfwKUJSdfpgv18QUG054ezGbaRNStk/BKD5IPijeMKWej8VV8O5Q/eQ==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.1.7", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@inquirer/external-editor/-/external-editor-2.0.4.tgz", + "integrity": "sha512-Prenuv9C1PHj2Itx0BcAOVBTonz02Hc2Nd2DbU67PdGUaqn0nPCnV34oDyyoaZHnmfRxkpuhh/u51ThkrO+RdA==", + "license": "MIT", + "dependencies": { + "chardet": "^2.1.1", + "iconv-lite": "^0.7.2" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/external-editor/node_modules/iconv-lite": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz", + "integrity": "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw==", + "license": "MIT", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/@inquirer/figures": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@inquirer/figures/-/figures-2.0.4.tgz", + "integrity": "sha512-eLBsjlS7rPS3WEhmOmh1znQ5IsQrxWzxWDxO51e4urv+iVrSnIHbq4zqJIOiyNdYLa+BVjwOtdetcQx1lWPpiQ==", + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + } + }, + "node_modules/@inquirer/input": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-5.0.10.tgz", + "integrity": "sha512-nvZ6qEVeX/zVtZ1dY2hTGDQpVGD3R7MYPLODPgKO8Y+RAqxkrP3i/3NwF3fZpLdaMiNuK0z2NaYIx9tPwiSegQ==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.1.7", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/number": { + "version": "4.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-4.0.10.tgz", + "integrity": "sha512-Ht8OQstxiS3APMGjHV0aYAjRAysidWdwurWEo2i8yI5xbhOBWqizT0+MU1S2GCcuhIBg+3SgWVjEoXgfhY+XaA==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.1.7", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/password": { + "version": "5.0.10", + "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-5.0.10.tgz", + "integrity": "sha512-QbNyvIE8q2GTqKLYSsA8ATG+eETo+m31DSR0+AU7x3d2FhaTWzqQek80dj3JGTo743kQc6mhBR0erMjYw5jQ0A==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.4", + "@inquirer/core": "^11.1.7", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/prompts": { + "version": "8.3.2", + "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-8.3.2.tgz", + "integrity": "sha512-yFroiSj2iiBFlm59amdTvAcQFvWS6ph5oKESls/uqPBect7rTU2GbjyZO2DqxMGuIwVA8z0P4K6ViPcd/cp+0w==", + "license": "MIT", + "dependencies": { + "@inquirer/checkbox": "^5.1.2", + "@inquirer/confirm": "^6.0.10", + "@inquirer/editor": "^5.0.10", + "@inquirer/expand": "^5.0.10", + "@inquirer/input": "^5.0.10", + "@inquirer/number": "^4.0.10", + "@inquirer/password": "^5.0.10", + "@inquirer/rawlist": "^5.2.6", + "@inquirer/search": "^4.1.6", + "@inquirer/select": "^5.1.2" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/rawlist": { + "version": "5.2.6", + "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-5.2.6.tgz", + "integrity": "sha512-jfw0MLJ5TilNsa9zlJ6nmRM0ZFVZhhTICt4/6CU2Dv1ndY7l3sqqo1gIYZyMMDw0LvE1u1nzJNisfHEhJIxq5w==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.1.7", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/search": { + "version": "4.1.6", + "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-4.1.6.tgz", + "integrity": "sha512-3/6kTRae98hhDevENScy7cdFEuURnSpM3JbBNg8yfXLw88HgTOl+neUuy/l9W0No5NzGsLVydhBzTIxZP7yChQ==", + "license": "MIT", + "dependencies": { + "@inquirer/core": "^11.1.7", + "@inquirer/figures": "^2.0.4", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/select": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-5.1.2.tgz", + "integrity": "sha512-kTK8YIkHV+f02y7bWCh7E0u2/11lul5WepVTclr3UMBtBr05PgcZNWfMa7FY57ihpQFQH/spLMHTcr0rXy50tA==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.4", + "@inquirer/core": "^11.1.7", + "@inquirer/figures": "^2.0.4", + "@inquirer/type": "^4.0.4" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@inquirer/type": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-4.0.4.tgz", + "integrity": "sha512-PamArxO3cFJZoOzspzo6cxVlLeIftyBsZw/S9bKY5DzxqJVZgjoj1oP8d0rskKtp7sZxBycsoer1g6UeJV1BBA==", + "license": "MIT", + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/@ioredis/commands": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.5.0.tgz", + "integrity": "sha512-eUgLqrMf8nJkZxT24JvVRrQya1vZkQh8BBeYNwGDqa5I0VUi8ACx7uFvAaLxintokpTenkK6DASvo/bvNbBGow==" + }, + "node_modules/@isaacs/fs-minipass": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz", + "integrity": "sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w==", + "dependencies": { + "minipass": "^7.0.4" + }, + "engines": { + "node": ">=18.0.0" + } + }, + "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==", + "cpu": [ + "arm64" + ], + "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==", + "cpu": [ + "x64" + ], + "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==", + "cpu": [ + "arm" + ], + "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==", + "cpu": [ + "arm64" + ], + "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==", + "cpu": [ + "x64" + ], + "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==", + "cpu": [ + "x64" + ], + "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", + "integrity": "sha512-ZcNHqQjMuNRcQ7Z1zJbFIQZO/BDKV3KbiTckWdfbUaYhj7uNmUwb+FbdDWSCkvxNr9dBJQwvV17o6QBkAvgO0g==", + "bin": { + "blessed": "bin/tput.js" + }, + "engines": { + "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", + "integrity": "sha512-nmWzrA/BQZik3VBz+npRcNIu01kdBhWL0mxKmP1ciF/gTcujPTQqt027N9fc1pK9ERM8RipFhymw7RcmCyOEYA==", + "dependencies": { + "async": "^2.6.3", + "debug": "~4.3.1", + "eventemitter2": "^6.3.1", + "extrareqp2": "^1.0.0", + "ws": "^7.0.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/@pm2/js-api/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/js-api/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/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", + "integrity": "sha512-SXsM27SGH3yTWKc2fKR4SYNxsmnvuBQ9dd6QHtEWmiZ/VqaOYPAIlS8+vMcn27YLtAEBGvNRSh3TPNvtjZgfqA==", + "dependencies": { + "debug": "^4.3.1" + } + }, + "node_modules/@redis/bloom": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-5.11.0.tgz", + "integrity": "sha512-KYiVilAhAFN3057afUb/tfYJpsEyTkQB+tQcn5gVVA7DgcNOAj8lLxe4j8ov8BF6I9C1Fe/kwlbuAICcTMX8Lw==", + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@redis/client": "^5.11.0" + } + }, + "node_modules/@redis/client": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/@redis/client/-/client-5.11.0.tgz", + "integrity": "sha512-GHoprlNQD51Xq2Ztd94HHV94MdFZQ3CVrpA04Fz8MVoHM0B7SlbmPEVIjwTbcv58z8QyjnrOuikS0rWF03k5dQ==", + "license": "MIT", + "dependencies": { + "cluster-key-slot": "1.1.2" + }, + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@node-rs/xxhash": "^1.1.0" + }, + "peerDependenciesMeta": { + "@node-rs/xxhash": { + "optional": true + } + } + }, + "node_modules/@redis/json": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/@redis/json/-/json-5.11.0.tgz", + "integrity": "sha512-1iAy9kAtcD0quB21RbPTbUqqy+T2Uu2JxucwE+B4A+VaDbIRvpZR6DMqV8Iqaws2YxJYB3GC5JVNzPYio2ErUg==", + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@redis/client": "^5.11.0" + } + }, + "node_modules/@redis/search": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/@redis/search/-/search-5.11.0.tgz", + "integrity": "sha512-g1l7f3Rnyk/xI99oGHIgWHSKFl45Re5YTIcO8j/JE8olz389yUFyz2+A6nqVy/Zi031VgPDWscbbgOk8hlhZ3g==", + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@redis/client": "^5.11.0" + } + }, + "node_modules/@redis/time-series": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-5.11.0.tgz", + "integrity": "sha512-TWFeOcU4xkj0DkndnOyhtxvX1KWD+78UHT3XX3x3XRBUGWeQrKo3jqzDsZwxbggUgf9yLJr/akFHXru66X5UQA==", + "license": "MIT", + "engines": { + "node": ">= 18" + }, + "peerDependencies": { + "@redis/client": "^5.11.0" + } + }, + "node_modules/@socket.io/component-emitter": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@socket.io/component-emitter/-/component-emitter-3.1.2.tgz", + "integrity": "sha512-9BCxFwvbGg/RsZK9tjXd8s4UcwR0MWeFQ1XEKIQVVvAGJyINdrqKMcTRyLoK8Rse1GjzLV9cwjWV1olXRWEXVA==" + }, + "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==" + }, + "node_modules/@types/cors": { + "version": "2.8.19", + "resolved": "https://registry.npmjs.org/@types/cors/-/cors-2.8.19.tgz", + "integrity": "sha512-mFNylyeyqN93lfe/9CSxOGREz8cpzAhH+E93xJ4xWQf62V8sQ/24reV2nyzUWM6H6Xji+GGHpkbLe7pVoUEskg==", + "dependencies": { + "@types/node": "*" + } + }, + "node_modules/@types/node": { + "version": "24.10.0", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.0.tgz", + "integrity": "sha512-qzQZRBqkFsYyaSWXuEHc2WR9c0a0CXwiE5FWUvn7ZM+vdy1uZLfCunD38UzhuB7YN/J11ndbDBcTmOdxJo9Q7A==", + "dependencies": { + "undici-types": "~7.16.0" + } + }, + "node_modules/accepts": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", + "integrity": "sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==", + "dependencies": { + "mime-types": "~2.1.34", + "negotiator": "0.6.3" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/adm-zip": { + "version": "0.5.16", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.16.tgz", + "integrity": "sha512-TGw5yVi4saajsSEgz25grObGHEUaDrniwvA2qwSC060KfqGPdglhvPMA2lPIoxs3PQIItj2iag35fONcQqgUaQ==", + "license": "MIT", + "engines": { + "node": ">=12.0" + } + }, + "node_modules/agent-base": { + "version": "7.1.4", + "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.4.tgz", + "integrity": "sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ==", + "engines": { + "node": ">= 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==" + }, + "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==", + "dependencies": { + "amp": "0.3.1" + } + }, + "node_modules/ansi_up": { + "version": "6.0.6", + "resolved": "https://registry.npmjs.org/ansi_up/-/ansi_up-6.0.6.tgz", + "integrity": "sha512-yIa1x3Ecf8jWP4UWEunNjqNX6gzE4vg2gGz+xqRGY+TBSucnYp6RRdPV4brmtg6bQ1ljD48mZ5iGSEj7QEpRKA==", + "license": "MIT", + "engines": { + "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", + "integrity": "sha512-Bq3SmSpyFHaWjPk8If9yc6svM8c56dB5BAtW4Qbw5jHTwwXXcTLoRMkpDJp6VL0XzlWaCHTXrkFURMYmD0sLqg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, + "node_modules/ansis": { + "version": "4.0.0-node10", + "resolved": "https://registry.npmjs.org/ansis/-/ansis-4.0.0-node10.tgz", + "integrity": "sha512-BRrU0Bo1X9dFGw6KgGz6hWrqQuOlVEDOzkb0QSLZY9sXHqA7pNj7yHPVJRz7y/rj4EOJ3d/D5uxH+ee9leYgsg==", + "engines": { + "node": ">=10" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/append-field": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz", + "integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, + "node_modules/array-flatten": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/array-flatten/-/array-flatten-1.1.1.tgz", + "integrity": "sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==" + }, + "node_modules/asn1.js": { + "version": "5.4.1", + "resolved": "https://registry.npmjs.org/asn1.js/-/asn1.js-5.4.1.tgz", + "integrity": "sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==", + "dependencies": { + "bn.js": "^4.0.0", + "inherits": "^2.0.1", + "minimalistic-assert": "^1.0.0", + "safer-buffer": "^2.1.0" + } + }, + "node_modules/ast-types": { + "version": "0.13.4", + "resolved": "https://registry.npmjs.org/ast-types/-/ast-types-0.13.4.tgz", + "integrity": "sha512-x1FCFnFifvYDDzTaLII71vG5uvDwgtmDTEVWAxrgeiR8VjMONcCXJx7E+USjDtHlwFmt9MysbqgF9b9Vjr6w+w==", + "dependencies": { + "tslib": "^2.0.1" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/async": { + "version": "3.2.6", + "resolved": "https://registry.npmjs.org/async/-/async-3.2.6.tgz", + "integrity": "sha512-htCUDlxyyCLMgaM3xXg0C0LW2xqfuQ6p05pCEIsXuyQ+a1koYKTuBMzRNwmybfLgvJDMd0r1LTn4+E0Ti6C2AA==" + }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/aws-ssl-profiles": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", + "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", + "engines": { + "node": ">= 6.0.0" + } + }, + "node_modules/bagpipe": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/bagpipe/-/bagpipe-0.3.5.tgz", + "integrity": "sha512-42sAlmPDKes1nLm/aly+0VdaopSU9br+jkRELedhQxI5uXHgtk47I83Mpmf4zoNTRMASdLFtUkimlu/Z9zQ8+g==" + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/base32.js": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/base32.js/-/base32.js-0.0.1.tgz", + "integrity": "sha512-EGHIRiegFa62/SsA1J+Xs2tIzludPdzM064N9wjbiEgHnGnJ1V0WEpA4pEwCYT5nDvZk3ubf0shqaCS7k6xeUQ==" + }, + "node_modules/base64id": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/base64id/-/base64id-2.0.0.tgz", + "integrity": "sha512-lGe34o6EHj9y3Kts9R4ZYs/Gr+6N7MCaMlIFA3F1R2O5/m7K06AxfSeO5530PEERE6/WyEg3lsuyw4GHlPZHog==", + "engines": { + "node": "^4.5.0 || >= 5.9" + } + }, + "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==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/bcrypt": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/bcrypt/-/bcrypt-6.0.0.tgz", + "integrity": "sha512-cU8v/EGSrnH+HnxV2z0J7/blxH8gq7Xh2JFT6Aroax7UohdmiJJlxApMxtKfuI7z68NvvVcmR78k2LbT6efhRg==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "node-addon-api": "^8.3.0", + "node-gyp-build": "^4.8.4" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/bcryptjs": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz", + "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==", + "license": "BSD-3-Clause", + "bin": { + "bcrypt": "bin/bcrypt" + } + }, + "node_modules/binary-extensions": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.3.0.tgz", + "integrity": "sha512-Ceh+7ox5qe7LJuLHoY0feh3pHuUDHAcRUeyL2VYghZwfpkNIy/+8Ocg0a3UuSoYzavmylwuLWQOf3hl0jjMMIw==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "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==" + }, + "node_modules/bodec": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/bodec/-/bodec-0.1.0.tgz", + "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==", + "dependencies": { + "bytes": "~3.1.2", + "content-type": "~1.0.5", + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", + "type-is": "~1.6.18", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/body-parser/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/body-parser/node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "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==" + }, + "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==", + "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==", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/brace-expansion/node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/buffer-from": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz", + "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==", + "dependencies": { + "cron-parser": "4.9.0", + "ioredis": "5.9.2", + "msgpackr": "1.11.5", + "node-abort-controller": "3.1.1", + "semver": "7.7.3", + "tslib": "2.8.1", + "uuid": "11.1.0" + } + }, + "node_modules/busboy": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz", + "integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==", + "dependencies": { + "streamsearch": "^1.1.0" + }, + "engines": { + "node": ">=10.16.0" + } + }, + "node_modules/bytes": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", + "integrity": "sha512-/Nf7TyzTx6S3yRJObOAV7956r8cr2+Oj8AC5dt8wSP3BQAoeX58NoHyCU8P8zGkNXStjTSi6fzO6F0pBdcYbEg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/camelcase": { + "version": "5.3.1", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-5.3.1.tgz", + "integrity": "sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg==", + "engines": { + "node": ">=6" + } + }, + "node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chardet": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/chardet/-/chardet-2.1.1.tgz", + "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", + "integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==", + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "funding": { + "url": "https://paulmillr.com/funding/" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/chownr": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/chownr/-/chownr-3.0.0.tgz", + "integrity": "sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g==", + "engines": { + "node": ">=18" + } + }, + "node_modules/cli-cursor": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-5.0.0.tgz", + "integrity": "sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==", + "license": "MIT", + "dependencies": { + "restore-cursor": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-spinners": { + "version": "3.4.0", + "resolved": "https://registry.npmjs.org/cli-spinners/-/cli-spinners-3.4.0.tgz", + "integrity": "sha512-bXfOC4QcT1tKXGorxL3wbJm6XJPDqEnij2gQ2m7ESQuE+/z9YFIWnl/5RpTiKWbMq3EVKR4fRLJGn6DVfu0mpw==", + "license": "MIT", + "engines": { + "node": ">=18.20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-tableau": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/cli-tableau/-/cli-tableau-2.0.1.tgz", + "integrity": "sha512-he+WTicka9cl0Fg/y+YyxcN6/bfQ/1O3QmgxRXDhABKqLzvoOSM4fMzp39uMyLBulAFuywD2N7UaoQE7WaADxQ==", + "dependencies": { + "chalk": "3.0.0" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/cli-tableau/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/cli-tableau/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/cli-tableau/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/cli-tableau/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/cli-width": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/cli-width/-/cli-width-4.1.0.tgz", + "integrity": "sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==", + "license": "ISC", + "engines": { + "node": ">= 12" + } + }, + "node_modules/cliui": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-6.0.0.tgz", + "integrity": "sha512-t6wbgtoCXvAzst7QgXxJYqPt0usEfbgQdftEPbLL/cvv6HPE5VgvqCuAIDR0NgU52ds6rFwqrgakNLrHEjCbrQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^6.2.0" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/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/cliui/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/wrap-ansi": { + "version": "6.2.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz", + "integrity": "sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/compressible": { + "version": "2.0.18", + "resolved": "https://registry.npmjs.org/compressible/-/compressible-2.0.18.tgz", + "integrity": "sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==", + "dependencies": { + "mime-db": ">= 1.43.0 < 2" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/compression": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/compression/-/compression-1.8.1.tgz", + "integrity": "sha512-9mAqGPHLakhCLeNyxPkK4xVo746zQ/czLH1Ky+vkitMnWfWZps8r0qXuwhwizagCRttsL4lfG4pIOvaWLpAP0w==", + "dependencies": { + "bytes": "3.1.2", + "compressible": "~2.0.18", + "debug": "2.6.9", + "negotiator": "~0.6.4", + "on-headers": "~1.1.0", + "safe-buffer": "5.2.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/compression/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/compression/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/compression/node_modules/negotiator": { + "version": "0.6.4", + "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-0.6.4.tgz", + "integrity": "sha512-myRT3DiWPHqho5PrJaIRyaMv2kgYf0mUVgBNOYMuCH5Ki1yEiQaf/ZJuQ62nvpc44wL5WDbTX7yGJi1Neevw8w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/concat-stream": { + "version": "1.6.2", + "resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-1.6.2.tgz", + "integrity": "sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==", + "engines": [ + "node >= 0.8" + ], + "dependencies": { + "buffer-from": "^1.0.0", + "inherits": "^2.0.3", + "readable-stream": "^2.2.2", + "typedarray": "^0.0.6" + } + }, + "node_modules/concat-stream/node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==" + }, + "node_modules/concat-stream/node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/concat-stream/node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==" + }, + "node_modules/concat-stream/node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/connect-redis": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/connect-redis/-/connect-redis-9.0.0.tgz", + "integrity": "sha512-QwzyvUePTMvEzG1hy45gZYw3X3YHrjmEdSkayURlcZft7hqadQ3X39wYkmCqblK2rGlw+XItELYt6GnyG6DEIQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "express-session": ">=1", + "redis": ">=5" + } + }, + "node_modules/content-disposition": { + "version": "0.5.4", + "resolved": "https://registry.npmjs.org/content-disposition/-/content-disposition-0.5.4.tgz", + "integrity": "sha512-FveZTNuGw04cxlAiWbzi6zTAL/lhehaWbTtgluJh4/E95DqMwTmha3KZN1aAWA8cFIhHzMZUvLevkw5Rqk+tSQ==", + "dependencies": { + "safe-buffer": "5.2.1" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/content-type": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/content-type/-/content-type-1.0.5.tgz", + "integrity": "sha512-nTjqfcBFEipKdXCv4YDQWCfmcLZKm81ldF0pAopTvyrFGVbcR6P/VAAd5G7N+0tTr8QqiU0tFadD6FK4NtJwOA==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", + "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-parser": { + "version": "1.4.7", + "resolved": "https://registry.npmjs.org/cookie-parser/-/cookie-parser-1.4.7.tgz", + "integrity": "sha512-nGUvgXnotP3BsjiLX2ypbQnWoGUPIIfHQNZkkC668ntrzGWEZVW70HDEB1qnNGMicPje6EttlIgzo51YSwNQGw==", + "dependencies": { + "cookie": "0.7.2", + "cookie-signature": "1.0.6" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/cookie-parser/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/cookie-signature": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", + "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==" + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==" + }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/cron-parser": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/cron-parser/-/cron-parser-4.9.0.tgz", + "integrity": "sha512-p0SaNjrHOnQeR8/VnfGbmg9te2kfyYSQ7Sc/j/6DtPL3JQvKxmjO9TSjNFpujqV3vEYYBvNNvXSxzyksBWAx1Q==", + "dependencies": { + "luxon": "^3.2.1" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/croner": { + "version": "4.1.97", + "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/dayjs": { + "version": "1.11.15", + "resolved": "https://registry.npmjs.org/dayjs/-/dayjs-1.11.15.tgz", + "integrity": "sha512-MC+DfnSWiM9APs7fpiurHGCoeIx0Gdl6QZBy+5lu8MbYKN5FZEXqOgrundfibdfhGZ15o9hzmZ2xJjZnbvgKXQ==" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/decamelize": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-1.2.0.tgz", + "integrity": "sha512-z2S+W9X73hAUUki+N+9Za2lBlun89zigOyGrsax+KUQ6wKW4ZoWpEYBkGhQjwAjjDCkWxhY0VKEhk8wzY7F5cA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/degenerator": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/degenerator/-/degenerator-5.0.1.tgz", + "integrity": "sha512-TllpMR/t0M5sqCXfj85i4XaAzxmS5tVA16dqvdkMwGmzI+dXLXnw3J+3Vdv7VKw+ThlTMboK6i9rnZ6Nntj5CQ==", + "dependencies": { + "ast-types": "^0.13.4", + "escodegen": "^2.1.0", + "esprima": "^4.0.1" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "engines": { + "node": ">=0.10" + } + }, + "node_modules/depd": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", + "integrity": "sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/destroy": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/destroy/-/destroy-1.2.0.tgz", + "integrity": "sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg==", + "engines": { + "node": ">= 0.8", + "npm": "1.2.8000 || >= 1.4.16" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "optional": true, + "engines": { + "node": ">=8" + } + }, + "node_modules/dijkstrajs": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/dijkstrajs/-/dijkstrajs-1.0.3.tgz", + "integrity": "sha512-qiSlmBq9+BCdCA/L46dw8Uy93mloxsPSbwnm5yrKn2vMPiy8KyAskTF6zuV/j5BMsmOGZDPs7KjU+mjb670kfA==" + }, + "node_modules/dotenv": { + "version": "17.2.3", + "resolved": "https://registry.npmjs.org/dotenv/-/dotenv-17.2.3.tgz", + "integrity": "sha512-JVUnt+DUIzu87TABbhPmNfVdBDt18BLOWjMUFJMSi/Qqg7NTYtabbvSNJGOJ7afbRuv9D/lngizHtP7QyLQ+9w==", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://dotenvx.com" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/ee-first": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/ee-first/-/ee-first-1.1.1.tgz", + "integrity": "sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow==" + }, + "node_modules/ejs": { + "version": "3.1.10", + "resolved": "https://registry.npmjs.org/ejs/-/ejs-3.1.10.tgz", + "integrity": "sha512-UeJmFfOrAQS8OJWPZ4qtgHyWExa088/MtK5UEyoJGFH67cDEXkZSviOiKRCZ4Xij0zxI3JECgYs3oKx+AizQBA==", + "dependencies": { + "jake": "^10.8.5" + }, + "bin": { + "ejs": "bin/cli.js" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/encodeurl": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-2.0.0.tgz", + "integrity": "sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg==", + "engines": { + "node": ">= 0.8" + } + }, + "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==", + "dependencies": { + "@types/cors": "^2.8.12", + "@types/node": ">=10.0.0", + "accepts": "~1.3.4", + "base64id": "2.0.0", + "cookie": "~0.7.2", + "cors": "~2.8.5", + "debug": "~4.3.1", + "engine.io-parser": "~5.2.1", + "ws": "~8.17.1" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "node_modules/engine.io-parser": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/engine.io-parser/-/engine.io-parser-5.2.3.tgz", + "integrity": "sha512-HqD3yTBfnBxIrbnM1DoD6Pcq8NECnh8d4As1Qgh0z5Gg3jRRIqijury0CL3ghu/edArpUYiYqQiDUQBIs4np3Q==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/engine.io/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "engines": { + "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", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/escape-html": { + "version": "1.0.3", + "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==", + "dependencies": { + "esprima": "^4.0.1", + "estraverse": "^5.2.0", + "esutils": "^2.0.2" + }, + "bin": { + "escodegen": "bin/escodegen.js", + "esgenerate": "bin/esgenerate.js" + }, + "engines": { + "node": ">=6.0" + }, + "optionalDependencies": { + "source-map": "~0.6.1" + } + }, + "node_modules/esprima": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/esprima/-/esprima-4.0.1.tgz", + "integrity": "sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A==", + "bin": { + "esparse": "bin/esparse.js", + "esvalidate": "bin/esvalidate.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/etag": { + "version": "1.8.1", + "resolved": "https://registry.npmjs.org/etag/-/etag-1.8.1.tgz", + "integrity": "sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/eventemitter2": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eventemitter2/-/eventemitter2-5.0.1.tgz", + "integrity": "sha512-5EM1GHXycJBS6mauYAbVKT1cVs7POKWb2NXD4Vyt8dDqeZa7LaDK1/sjtL+Zb0lzTpSNil4596Dyu97hz37QLg==" + }, + "node_modules/express": { + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", + "dependencies": { + "accepts": "~1.3.8", + "array-flatten": "1.1.1", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", + "content-type": "~1.0.4", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", + "debug": "2.6.9", + "depd": "2.0.0", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", + "merge-descriptors": "1.0.3", + "methods": "~1.1.2", + "on-finished": "~2.4.1", + "parseurl": "~1.3.3", + "path-to-regexp": "~0.1.12", + "proxy-addr": "~2.0.7", + "qs": "~6.14.0", + "range-parser": "~1.2.1", + "safe-buffer": "5.2.1", + "send": "~0.19.0", + "serve-static": "~1.16.2", + "setprototypeof": "1.2.0", + "statuses": "~2.0.1", + "type-is": "~1.6.18", + "utils-merge": "1.0.1", + "vary": "~1.1.2" + }, + "engines": { + "node": ">= 0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "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==", + "license": "MIT", + "dependencies": { + "ip-address": "10.1.0" + }, + "engines": { + "node": ">= 16" + }, + "funding": { + "url": "https://github.com/sponsors/express-rate-limit" + }, + "peerDependencies": { + "express": ">= 4.11" + } + }, + "node_modules/express-session": { + "version": "1.19.0", + "resolved": "https://registry.npmjs.org/express-session/-/express-session-1.19.0.tgz", + "integrity": "sha512-0csaMkGq+vaiZTmSMMGkfdCOabYv192VbytFypcvI0MANrp+4i/7yEkJ0sbAEhycQjntaKGzYfjfXQyVb7BHMA==", + "license": "MIT", + "dependencies": { + "cookie": "~0.7.2", + "cookie-signature": "~1.0.7", + "debug": "~2.6.9", + "depd": "~2.0.0", + "on-headers": "~1.1.0", + "parseurl": "~1.3.3", + "safe-buffer": "~5.2.1", + "uid-safe": "~2.1.5" + }, + "engines": { + "node": ">= 0.8.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/express-session/node_modules/cookie": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/express-session/node_modules/cookie-signature": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==" + }, + "node_modules/express-session/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express-session/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/express/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/express/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/extrareqp2": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/extrareqp2/-/extrareqp2-1.0.0.tgz", + "integrity": "sha512-Gum0g1QYb6wpPJCVypWP3bbIuaibcFiJcpuPM10YSXp/tzqi84x9PJageob+eN4xVRIOto4wjSGNLyMD54D2xA==", + "dependencies": { + "follow-redirects": "^1.14.0" + } + }, + "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==" + }, + "node_modules/fast-string-truncated-width": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz", + "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==", + "license": "MIT" + }, + "node_modules/fast-string-width": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz", + "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==", + "license": "MIT", + "dependencies": { + "fast-string-truncated-width": "^3.0.2" + } + }, + "node_modules/fast-wrap-ansi": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.0.tgz", + "integrity": "sha512-rLV8JHxTyhVmFYhBJuMujcrHqOT2cnO5Zxj37qROj23CP39GXubJRBUFF0z8KFK77Uc0SukZUf7JZhsVEQ6n8w==", + "license": "MIT", + "dependencies": { + "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", + "integrity": "sha512-w1cEuf3S+DrLCQL7ET6kz+gmlJdbq9J7yXCSjK/OZCPA+qEN1WyF4ZAf0YYJa4/shHJra2t/d/r8SV4Ji+x+8Q==", + "dependencies": { + "minimatch": "^5.0.1" + } + }, + "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==", + "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==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/finalhandler": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", + "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "dependencies": { + "debug": "2.6.9", + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "on-finished": "2.4.1", + "parseurl": "~1.3.3", + "statuses": "2.0.1", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/finalhandler/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/finalhandler/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "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==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, + "node_modules/form-data": { + "version": "4.0.5", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz", + "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "es-set-tostringtag": "^2.1.0", + "hasown": "^2.0.2", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/forwarded": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/forwarded/-/forwarded-0.2.0.tgz", + "integrity": "sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/fresh/-/fresh-0.5.2.tgz", + "integrity": "sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/fs-extra": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/fs-extra/-/fs-extra-8.1.0.tgz", + "integrity": "sha512-yhlQgA6mnOJUKOsRUFsgJdQCvkKhcz8tlZG5HBQfReYZy46OwLcY+Zia0mtdHsOo9y/hP+CxMN0TU9QxoOtG4g==", + "dependencies": { + "graceful-fs": "^4.2.0", + "jsonfile": "^4.0.0", + "universalify": "^0.1.0" + }, + "engines": { + "node": ">=6 <7 || >=8" + } + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/generate-function": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", + "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", + "dependencies": { + "is-property": "^1.0.2" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-east-asian-width": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.5.0.tgz", + "integrity": "sha512-CQ+bEO+Tva/qlmw24dCejulK5pMzVnUOFOijVogd3KQs07HnRIgp8TGipvCCRT06xeYEbpbgwaCxglFyiuIcmA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-uri": { + "version": "6.0.5", + "resolved": "https://registry.npmjs.org/get-uri/-/get-uri-6.0.5.tgz", + "integrity": "sha512-b1O07XYq8eRuVzBNgJLstU6FYc1tS6wnMtF1I1D9lE8LxZSOGZ7LhxN54yPP6mGw5f2CkXY2BQUL9Fx41qvcIg==", + "dependencies": { + "basic-ftp": "^5.0.2", + "data-uri-to-buffer": "^6.0.2", + "debug": "^4.3.4" + }, + "engines": { + "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", + "integrity": "sha512-bLQypt14llVXBg0S0u8q8HmU7g9p3ysH+NvVlae5vILuUvs759665HvmR5+wb04KjHyjFcDRxdYb4kyNnluMUQ==" + }, + "node_modules/git-sha1": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/git-sha1/-/git-sha1-0.1.2.tgz", + "integrity": "sha512-2e/nZezdVlyCopOCYHeW0onkbZg7xP1Ad6pndPy1rCygeRykefUS6r7oA5cJRGEFvseiaz5a/qUHFVX1dd6Isg==" + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==" + }, + "node_modules/has-flag": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", + "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", + "engines": { + "node": ">=4" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/helmet": { + "version": "8.1.0", + "resolved": "https://registry.npmjs.org/helmet/-/helmet-8.1.0.tgz", + "integrity": "sha512-jOiHyAZsmnr8LqoPGmCjYAaiuWwjAPLgY8ZX2XrmHawt99/u1y6RgrZMTeoPfpUbV96HOalYgz1qzkRbw54Pmg==", + "engines": { + "node": ">=18.0.0" + } + }, + "node_modules/hpp": { + "version": "0.2.3", + "resolved": "https://registry.npmjs.org/hpp/-/hpp-0.2.3.tgz", + "integrity": "sha512-4zDZypjQcxK/8pfFNR7jaON7zEUpXZxz4viyFmqjb3kWNWAHsLEUmWXcdn25c5l76ISvnD6hbOGO97cXUI3Ryw==", + "license": "ISC", + "dependencies": { + "lodash": "^4.17.12", + "type-is": "^1.6.12" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/http-errors": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", + "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "dependencies": { + "depd": "2.0.0", + "inherits": "2.0.4", + "setprototypeof": "1.2.0", + "statuses": "2.0.1", + "toidentifier": "1.0.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/http-proxy-agent": { + "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==", + "dependencies": { + "agent-base": "^7.1.0", + "debug": "^4.3.4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/https-proxy-agent": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz", + "integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "4" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/iconv-lite": { + "version": "0.4.24", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.4.24.tgz", + "integrity": "sha512-v3MXnZAcvnywkTUEZomIActle7RXXeedOR31wwl7VlyoXO4Qi9arvSenNQWne1TcRwhCL1HwLI21bEqdpj8/rA==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/ignore-by-default": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/ignore-by-default/-/ignore-by-default-1.0.1.tgz", + "integrity": "sha512-Ius2VYcGNk7T90CppJqcIkS5ooHUZyIQK+ClZfMfMNFEF9VSE73Fq+906u/CWu92x4gzZMWOwfFYckPObzdEbA==" + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/ini": { + "version": "1.3.8", + "resolved": "https://registry.npmjs.org/ini/-/ini-1.3.8.tgz", + "integrity": "sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew==" + }, + "node_modules/inquirer": { + "version": "13.3.2", + "resolved": "https://registry.npmjs.org/inquirer/-/inquirer-13.3.2.tgz", + "integrity": "sha512-bh/OjBGxNR9qvfQj1n5bxtIF58mbOTp2InN5dKuwUK03dXcDGFsjlDinQRuXMZ4EGiJaFieUWHCAaxH2p7iUBw==", + "license": "MIT", + "dependencies": { + "@inquirer/ansi": "^2.0.4", + "@inquirer/core": "^11.1.7", + "@inquirer/prompts": "^8.3.2", + "@inquirer/type": "^4.0.4", + "mute-stream": "^3.0.0", + "run-async": "^4.0.6", + "rxjs": "^7.8.2" + }, + "engines": { + "node": ">=23.5.0 || ^22.13.0 || ^21.7.0 || ^20.12.0" + }, + "peerDependencies": { + "@types/node": ">=18" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + } + } + }, + "node_modules/inquirer/node_modules/mute-stream": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/mute-stream/-/mute-stream-3.0.0.tgz", + "integrity": "sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==", + "license": "ISC", + "engines": { + "node": "^20.17.0 || >=22.9.0" + } + }, + "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==", + "dependencies": { + "@ioredis/commands": "1.5.0", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.4", + "denque": "^2.1.0", + "lodash.defaults": "^4.2.0", + "lodash.isarguments": "^3.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "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==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, + "node_modules/ip-range-check": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/ip-range-check/-/ip-range-check-0.2.0.tgz", + "integrity": "sha512-oaM3l/3gHbLlt/tCWLvt0mj1qUaI+STuRFnUvARGCujK9vvU61+2JsDpmkMzR4VsJhuFXWWgeKKVnwwoFfzCqw==", + "license": "MIT", + "dependencies": { + "ipaddr.js": "^1.0.1" + } + }, + "node_modules/ipaddr.js": { + "version": "1.9.1", + "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-1.9.1.tgz", + "integrity": "sha512-0KI/607xoxSToH7GjN1FfSbLoU0+btTicjsQSWQlh/hZykN8KpmMf7uYwPW3R+akZ6R/w18ZlXSHBYXiYUPO3g==", + "engines": { + "node": ">= 0.10" + } + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "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", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-interactive": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-interactive/-/is-interactive-2.0.0.tgz", + "integrity": "sha512-qP1vozQRI+BMOPcjFzrjXuQvdak2pHNUMZoeG2eRbiSqyvbEf/wQtEOTOX1guk6E3t36RkaqiSt8A/6YElNxLQ==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-property": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", + "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==" + }, + "node_modules/is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==" + }, + "node_modules/is-unicode-supported": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-2.1.0.tgz", + "integrity": "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/jake": { + "version": "10.9.4", + "resolved": "https://registry.npmjs.org/jake/-/jake-10.9.4.tgz", + "integrity": "sha512-wpHYzhxiVQL+IV05BLE2Xn34zW1S223hvjtqk0+gsPrwd/8JNLXJgZZM/iPFsYc1xyphF+6M6EvdE5E9MBGkDA==", + "dependencies": { + "async": "^3.2.6", + "filelist": "^1.0.4", + "picocolors": "^1.1.1" + }, + "bin": { + "jake": "bin/cli.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/js-git": { + "version": "0.7.8", + "resolved": "https://registry.npmjs.org/js-git/-/js-git-0.7.8.tgz", + "integrity": "sha512-+E5ZH/HeRnoc/LW0AmAyhU+mNcWBzAKE+30+IDMLSLbbK+Tdt02AdkOKq9u15rlJsDEGFqtgckc8ZM59LhhiUA==", + "dependencies": { + "bodec": "^0.1.0", + "culvert": "^0.1.2", + "git-sha1": "^0.1.2", + "pako": "^0.2.5" + } + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "optional": true + }, + "node_modules/jsonfile": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/jsonfile/-/jsonfile-4.0.0.tgz", + "integrity": "sha512-m6F1R3z8jjlf2imQHS2Qez5sjKWQzbuuhuJ/FKYFRZvPE3PuHcSMVZzfsLhGVOkfd20obL5SWEBew5ShlquNxg==", + "optionalDependencies": { + "graceful-fs": "^4.1.6" + } + }, + "node_modules/kruptein": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/kruptein/-/kruptein-2.2.3.tgz", + "integrity": "sha512-BTwprBPTzkFT9oTugxKd3WnWrX630MqUDsnmBuoa98eQs12oD4n4TeI0GbpdGcYn/73Xueg2rfnw+oK4dovnJg==", + "dependencies": { + "asn1.js": "^5.4.1" + }, + "engines": { + "node": ">6" + } + }, + "node_modules/lodash": { + "version": "4.17.23", + "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.23.tgz", + "integrity": "sha512-LgVTMpQtIopCi79SJeDiP0TfWi5CNEc/L/aRdTh3yIvmZXTnheWpKjSZhnvMl8iXbC1tFg9gdHHDMLoV7CnG+w==" + }, + "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==" + }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==" + }, + "node_modules/log-symbols": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-7.0.1.tgz", + "integrity": "sha512-ja1E3yCr9i/0hmBVaM0bfwDjnGy8I/s6PP4DFp+yP+a+mrHO4Rm7DtmnqROTUkHIkqffC84YY7AeqX6oFk0WFg==", + "license": "MIT", + "dependencies": { + "is-unicode-supported": "^2.0.0", + "yoctocolors": "^2.1.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/long": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", + "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==" + }, + "node_modules/lru.min": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.3.tgz", + "integrity": "sha512-Lkk/vx6ak3rYkRR0Nhu4lFUT2VDnQSxBe8Hbl7f36358p6ow8Bnvr8lrLt98H8J1aGxfhbX4Fs5tYg2+FTwr5Q==", + "engines": { + "bun": ">=1.0.0", + "deno": ">=1.30.0", + "node": ">=8.0.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/wellwelwel" + } + }, + "node_modules/luxon": { + "version": "3.7.2", + "resolved": "https://registry.npmjs.org/luxon/-/luxon-3.7.2.tgz", + "integrity": "sha512-vtEhXh/gNjI9Yg1u4jX/0YVPMvxzHuGgCm6tC5kZyb08yjGWGnqAjGJvcXbqQR2P3MyMEFnRbpcdFS6PBcLqew==", + "engines": { + "node": ">=12" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/media-typer": { + "version": "0.3.0", + "resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz", + "integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/merge-descriptors": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/merge-descriptors/-/merge-descriptors-1.0.3.tgz", + "integrity": "sha512-gaNvAS7TZ897/rVaZ0nMtAyxNyi/pdbjbAwUpFQpN70GqnVfOiXpeUUMKRBmzXaSQ8DdTX4/0ms62r2K+hE6mQ==", + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/methods": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/methods/-/methods-1.1.2.tgz", + "integrity": "sha512-iclAHeNqNm68zFtnZ0e+1L2yUIdvzNoauKU4WBA3VvH/vPFieF7qfRlwUZU+DA9P9bPXIS90ulxoUoCH23sV2w==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/mime/-/mime-1.6.0.tgz", + "integrity": "sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg==", + "bin": { + "mime": "cli.js" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mimic-function": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/mimic-function/-/mimic-function-5.0.1.tgz", + "integrity": "sha512-VP79XUPxV2CigYP3jWwAUFSku2aKqBH7uTAapFWCBqutsbmDo96KY5o8uh6U+/YSIn5OxJnXp73beVkpqMIGhA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/minimalistic-assert": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/minimalistic-assert/-/minimalistic-assert-1.0.1.tgz", + "integrity": "sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==" + }, + "node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/minipass": { + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/minipass/-/minipass-7.1.2.tgz", + "integrity": "sha512-qOOzS1cBTWYF4BH8fVePDBOO9iptMnGUEZwNc/cMWnTV2nVLZ7VoNWEPHkYczZA0pdoA7dl6e7FL659nX9S2aw==", + "engines": { + "node": ">=16 || 14 >=14.17" + } + }, + "node_modules/minizlib": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-3.1.0.tgz", + "integrity": "sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw==", + "dependencies": { + "minipass": "^7.1.2" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/mkdirp": { + "version": "0.5.6", + "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz", + "integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==", + "dependencies": { + "minimist": "^1.2.6" + }, + "bin": { + "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==", + "optionalDependencies": { + "msgpackr-extract": "^3.0.2" + } + }, + "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==", + "hasInstallScript": true, + "optional": true, + "dependencies": { + "node-gyp-build-optional-packages": "5.2.2" + }, + "bin": { + "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" + } + }, + "node_modules/multer": { + "version": "1.4.5-lts.2", + "resolved": "https://registry.npmjs.org/multer/-/multer-1.4.5-lts.2.tgz", + "integrity": "sha512-VzGiVigcG9zUAoCNU+xShztrlr1auZOlurXynNvO9GiWD1/mTBbUljOKY+qMeazBqXgRnjzeEgJI/wyjJUHg9A==", + "deprecated": "Multer 1.x is impacted by a number of vulnerabilities, which have been patched in 2.x. You should upgrade to the latest 2.x version.", + "dependencies": { + "append-field": "^1.0.0", + "busboy": "^1.0.0", + "concat-stream": "^1.5.2", + "mkdirp": "^0.5.4", + "object-assign": "^4.1.1", + "type-is": "^1.6.4", + "xtend": "^4.0.0" + }, + "engines": { + "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", + "integrity": "sha512-AEGW7QLLSuSnjCS4pk3EIqOmogegmze9h8EyrndavUQnIUcfkVal/sK7QznE+a3bc6rzPbAiui9Jcb+96tPwYA==", + "dependencies": { + "aws-ssl-profiles": "^1.1.1", + "denque": "^2.1.0", + "generate-function": "^2.3.1", + "iconv-lite": "^0.7.0", + "long": "^5.2.1", + "lru.min": "^1.0.0", + "named-placeholders": "^1.1.3", + "seq-queue": "^0.0.5", + "sqlstring": "^2.3.2" + }, + "engines": { + "node": ">= 8.0" + } + }, + "node_modules/mysql2/node_modules/iconv-lite": { + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz", + "integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==", + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/named-placeholders": { + "version": "1.1.6", + "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", + "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", + "dependencies": { + "lru.min": "^1.1.0" + }, + "engines": { + "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", + "integrity": "sha512-+EUsqGPLsM+j/zdChZjsnX51g4XrHFOIXwfnCVPGlQk/k5giakcKsuxCObBRu6DSm9opw/O6slWbJdghQM4bBg==", + "engines": { + "node": ">= 0.6" + } + }, + "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==", + "engines": { + "node": ">= 0.4.0" + } + }, + "node_modules/node-abort-controller": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/node-abort-controller/-/node-abort-controller-3.1.1.tgz", + "integrity": "sha512-AGK2yQKIjRuqnc6VkX2Xj5d+QW8xZ87pa1UK6yA6ouUyuxfHuMP6umE5QK7UmTeOAymo+Zx1Fxiuw9rVx8taHQ==" + }, + "node_modules/node-addon-api": { + "version": "8.5.0", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.5.0.tgz", + "integrity": "sha512-/bRZty2mXUIFY/xU5HLvveNHlswNJej+RnxBjOMkidWfwZzgTbPG1E3K5TOxRLOR+5hX7bSofy8yf1hZevMS8A==", + "engines": { + "node": "^18 || ^20 || >= 21" + } + }, + "node_modules/node-gyp-build": { + "version": "4.8.4", + "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", + "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", + "bin": { + "node-gyp-build": "bin.js", + "node-gyp-build-optional": "optional.js", + "node-gyp-build-test": "build-test.js" + } + }, + "node_modules/node-gyp-build-optional-packages": { + "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==", + "optional": true, + "dependencies": { + "detect-libc": "^2.0.1" + }, + "bin": { + "node-gyp-build-optional-packages": "bin.js", + "node-gyp-build-optional-packages-optional": "optional.js", + "node-gyp-build-optional-packages-test": "build-test.js" + } + }, + "node_modules/nodemon": { + "version": "3.1.14", + "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.14.tgz", + "integrity": "sha512-jakjZi93UtB3jHMWsXL68FXSAosbLfY0In5gtKq3niLSkrWznrVBzXFNOEMJUfc9+Ke7SHWoAZsiMkNP3vq6Jw==", + "dependencies": { + "chokidar": "^3.5.2", + "debug": "^4", + "ignore-by-default": "^1.0.1", + "minimatch": "^10.2.1", + "pstree.remy": "^1.1.8", + "semver": "^7.5.3", + "simple-update-notifier": "^2.0.0", + "supports-color": "^5.5.0", + "touch": "^3.1.0", + "undefsafe": "^2.0.5" + }, + "bin": { + "nodemon": "bin/nodemon.js" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/nodemon" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/on-finished": { + "version": "2.4.1", + "resolved": "https://registry.npmjs.org/on-finished/-/on-finished-2.4.1.tgz", + "integrity": "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg==", + "dependencies": { + "ee-first": "1.1.1" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/on-headers": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/on-headers/-/on-headers-1.1.0.tgz", + "integrity": "sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/onetime": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-7.0.0.tgz", + "integrity": "sha512-VXJjc87FScF88uafS3JllDgvAm+c/Slfz06lorj2uAY34rlUu0Nt+v8wreiImcrgAjjIHp1rXpTDlLOGw29WwQ==", + "license": "MIT", + "dependencies": { + "mimic-function": "^5.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ora": { + "version": "9.3.0", + "resolved": "https://registry.npmjs.org/ora/-/ora-9.3.0.tgz", + "integrity": "sha512-lBX72MWFduWEf7v7uWf5DHp9Jn5BI8bNPGuFgtXMmr2uDz2Gz2749y3am3agSDdkhHPHYmmxEGSKH85ZLGzgXw==", + "license": "MIT", + "dependencies": { + "chalk": "^5.6.2", + "cli-cursor": "^5.0.0", + "cli-spinners": "^3.2.0", + "is-interactive": "^2.0.0", + "is-unicode-supported": "^2.1.0", + "log-symbols": "^7.0.1", + "stdin-discarder": "^0.3.1", + "string-width": "^8.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-try": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/p-try/-/p-try-2.2.0.tgz", + "integrity": "sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ==", + "engines": { + "node": ">=6" + } + }, + "node_modules/pac-proxy-agent": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/pac-proxy-agent/-/pac-proxy-agent-7.2.0.tgz", + "integrity": "sha512-TEB8ESquiLMc0lV8vcd5Ql/JAKAoyzHFXaStwjkzpOpC5Yv+pIzLfHvjTSdf3vpa2bMiUQrg9i6276yn8666aA==", + "dependencies": { + "@tootallnate/quickjs-emscripten": "^0.23.0", + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "get-uri": "^6.0.1", + "http-proxy-agent": "^7.0.0", + "https-proxy-agent": "^7.0.6", + "pac-resolver": "^7.0.1", + "socks-proxy-agent": "^8.0.5" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pac-resolver": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/pac-resolver/-/pac-resolver-7.0.1.tgz", + "integrity": "sha512-5NPgf87AT2STgwa2ntRMr45jTKrYBGkVU36yT0ig/n/GMAa3oPqhZfIQ2kMEimReg0+t9kZViDVZ83qfVUlckg==", + "dependencies": { + "degenerator": "^5.0.0", + "netmask": "^2.0.2" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/pako": { + "version": "0.2.9", + "resolved": "https://registry.npmjs.org/pako/-/pako-0.2.9.tgz", + "integrity": "sha512-NUcwaKxUxWrZLpDG+z/xZaCgQITkA/Dv4V/T6bw7VON6l1Xz/VnrBqrYjZQ12TamKHzITTfOEIYUj48y2KXImA==" + }, + "node_modules/parseurl": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/parseurl/-/parseurl-1.3.3.tgz", + "integrity": "sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "engines": { + "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==" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "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==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/pidusage": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/pidusage/-/pidusage-3.0.2.tgz", + "integrity": "sha512-g0VU+y08pKw5M8EZ2rIGiEBaB8wrQMjYGFfW2QVIfyT8V+fq8YFLkvlz4bz5ljvFDJYNFCWT3PWqcRr2FKO81w==", + "dependencies": { + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pm2": { + "version": "6.0.14", + "resolved": "https://registry.npmjs.org/pm2/-/pm2-6.0.14.tgz", + "integrity": "sha512-wX1FiFkzuT2H/UUEA8QNXDAA9MMHDsK/3UHj6Dkd5U7kxyigKDA5gyDw78ycTQZAuGCLWyUX5FiXEuVQWafukA==", + "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", + "ansis": "4.0.0-node10", + "async": "3.2.6", + "chokidar": "3.6.0", + "cli-tableau": "2.0.1", + "commander": "2.15.1", + "croner": "4.1.97", + "dayjs": "1.11.15", + "debug": "4.4.3", + "enquirer": "2.3.6", + "eventemitter2": "5.0.1", + "fclone": "1.0.11", + "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", + "semver": "7.7.2", + "source-map-support": "0.5.21", + "sprintf-js": "1.1.2", + "vizion": "~2.2.1" + }, + "bin": { + "pm2": "bin/pm2", + "pm2-dev": "bin/pm2-dev", + "pm2-docker": "bin/pm2-docker", + "pm2-runtime": "bin/pm2-runtime" + }, + "engines": { + "node": ">=16.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", + "integrity": "sha512-YJx6RXKrVrWaphEYf++EdOOx9EH18vM8RSZN/P1Y+NokTKqYAca/ejXwVLyiEpNju4HPZEk3Y2uZouwMqUlcgg==", + "dependencies": { + "run-series": "^1.1.8", + "tv4": "^1.3.0" + }, + "engines": { + "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", + "integrity": "sha512-ACOhlONEXdCTVwKieBIQLSi2tQZ8eKinhcr9JpZSUAL8Qy0ajIgRtsLxG/lwPOW3JEKqPyw/UaHmTWhUzpP4kA==", + "optional": true, + "dependencies": { + "async": "^3.2.0", + "debug": "^4.3.1", + "pidusage": "^2.0.21", + "systeminformation": "^5.7", + "tx2": "~1.0.4" + } + }, + "node_modules/pm2-sysmonit/node_modules/pidusage": { + "version": "2.0.21", + "resolved": "https://registry.npmjs.org/pidusage/-/pidusage-2.0.21.tgz", + "integrity": "sha512-cv3xAQos+pugVX+BfXpHsbyz/dLzX+lr44zNMsYiGxUw+kV5sgQCIcLd1z+0vq+KyC7dJ+/ts2PsfgWfSC3WXA==", + "optional": true, + "dependencies": { + "safe-buffer": "^5.2.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/pm2/node_modules/commander": { + "version": "2.15.1", + "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", + "integrity": "sha512-RF0Fw+rO5AMf9MAyaRXI4AV0Ulj5lMHqVxxdSgiVbixSCXoEmmX/jk0CuJw4+3SqroYO9VoUh+HcuJivvtJemA==", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/pngjs": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/pngjs/-/pngjs-5.0.0.tgz", + "integrity": "sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==", + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "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", + "integrity": "sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==", + "dependencies": { + "forwarded": "0.2.0", + "ipaddr.js": "1.9.1" + }, + "engines": { + "node": ">= 0.10" + } + }, + "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==", + "dependencies": { + "agent-base": "^7.0.2", + "debug": "^4.3.4", + "http-proxy-agent": "^7.0.1", + "https-proxy-agent": "^7.0.3", + "lru-cache": "^7.14.1", + "pac-proxy-agent": "^7.0.1", + "proxy-from-env": "^1.1.0", + "socks-proxy-agent": "^8.0.2" + }, + "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==" + }, + "node_modules/pstree.remy": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/pstree.remy/-/pstree.remy-1.1.8.tgz", + "integrity": "sha512-77DZwxQmxKnu3aR542U+X8FypNzbfJ+C5XQDk3uWjWxn6151aIMGthWYRXTqT1E5oJvg+ljaa2OJi+VfvCOQ8w==" + }, + "node_modules/qrcode": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/qrcode/-/qrcode-1.5.4.tgz", + "integrity": "sha512-1ca71Zgiu6ORjHqFBDpnSMTR2ReToX4l1Au1VFLyVeBTFavzQnv5JxMFr3ukHVKpSrSA2MCk0lNJSykjUfz7Zg==", + "license": "MIT", + "dependencies": { + "dijkstrajs": "^1.0.1", + "pngjs": "^5.0.0", + "yargs": "^15.3.1" + }, + "bin": { + "qrcode": "bin/qrcode" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/qrcode-terminal": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/qrcode-terminal/-/qrcode-terminal-0.12.0.tgz", + "integrity": "sha512-EXtzRZmC+YGmGlDFbXKxQiMZNwCLEO6BANKXG4iCtSIM0yqc/pappSx3RIKr4r0uh5JsBckOXeKrB3Iz7mdQpQ==", + "bin": { + "qrcode-terminal": "bin/qrcode-terminal.js" + } + }, + "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==", + "dependencies": { + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">=0.6" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/random-bytes": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/random-bytes/-/random-bytes-1.0.0.tgz", + "integrity": "sha512-iv7LhNVO047HzYR3InF6pUcUsPQiHTM1Qal51DcGSuZFBil1aBBWG5eHPNek7bvILMaYJ/8RU1e8w1AMdHmLQQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/range-parser": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/range-parser/-/range-parser-1.2.1.tgz", + "integrity": "sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/rate-limit-redis": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/rate-limit-redis/-/rate-limit-redis-4.3.1.tgz", + "integrity": "sha512-+a1zU8+D7L8siDK9jb14refQXz60vq427VuiplgnaLk9B2LnvGe/APLTfhwb4uNIL7eWVknh8GnRp/unCj+lMA==", + "engines": { + "node": ">= 16" + }, + "peerDependencies": { + "express-rate-limit": ">= 6" + } + }, + "node_modules/raw-body": { + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", + "dependencies": { + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/raw-body/node_modules/http-errors": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", + "dependencies": { + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" + }, + "engines": { + "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" + } + }, + "node_modules/raw-body/node_modules/statuses": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", + "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", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/redis": { + "version": "5.11.0", + "resolved": "https://registry.npmjs.org/redis/-/redis-5.11.0.tgz", + "integrity": "sha512-YwXjATVDT+AuxcyfOwZn046aml9jMlQPvU1VXIlLDVAExe0u93aTfPYSeRgG4p9Q/Jlkj+LXJ1XEoFV+j2JKcQ==", + "license": "MIT", + "dependencies": { + "@redis/bloom": "5.11.0", + "@redis/client": "5.11.0", + "@redis/json": "5.11.0", + "@redis/search": "5.11.0", + "@redis/time-series": "5.11.0" + }, + "engines": { + "node": ">= 18" + } + }, + "node_modules/redis-errors": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "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", + "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==" + }, + "node_modules/restore-cursor": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-5.1.0.tgz", + "integrity": "sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==", + "license": "MIT", + "dependencies": { + "onetime": "^7.0.0", + "signal-exit": "^4.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/restore-cursor/node_modules/signal-exit": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz", + "integrity": "sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw==", + "license": "ISC", + "engines": { + "node": ">=14" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/retry": { + "version": "0.12.0", + "resolved": "https://registry.npmjs.org/retry/-/retry-0.12.0.tgz", + "integrity": "sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==", + "engines": { + "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", + "integrity": "sha512-IoDlSLTs3Yq593mb3ZoKWKXMNu3UpObxhgA/Xuid5p4bbfi2jdY1Hj0m1K+0/tEuQTxIGMhQDqGjKb7RuxGpAQ==", + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/run-series": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/run-series/-/run-series-1.1.9.tgz", + "integrity": "sha512-Arc4hUN896vjkqCYrUXquBFtRZdv1PfLbTYP71efP6butxyQ0kWpiNJyAgsxscmQg1cqvHY32/UCBzXedTpU2g==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/rxjs": { + "version": "7.8.2", + "resolved": "https://registry.npmjs.org/rxjs/-/rxjs-7.8.2.tgz", + "integrity": "sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.1.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/safer-buffer": { + "version": "2.1.2", + "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==", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/send": { + "version": "0.19.0", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", + "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "dependencies": { + "debug": "2.6.9", + "depd": "2.0.0", + "destroy": "1.2.0", + "encodeurl": "~1.0.2", + "escape-html": "~1.0.3", + "etag": "~1.8.1", + "fresh": "0.5.2", + "http-errors": "2.0.0", + "mime": "1.6.0", + "ms": "2.1.3", + "on-finished": "2.4.1", + "range-parser": "~1.2.1", + "statuses": "2.0.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/send/node_modules/debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "dependencies": { + "ms": "2.0.0" + } + }, + "node_modules/send/node_modules/debug/node_modules/ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==" + }, + "node_modules/send/node_modules/encodeurl": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", + "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/seq-queue": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz", + "integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q==" + }, + "node_modules/serve-static": { + "version": "1.16.2", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", + "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "dependencies": { + "encodeurl": "~2.0.0", + "escape-html": "~1.0.3", + "parseurl": "~1.3.3", + "send": "0.19.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/session-file-store": { + "version": "1.5.0", + "resolved": "https://registry.npmjs.org/session-file-store/-/session-file-store-1.5.0.tgz", + "integrity": "sha512-60IZaJNzyu2tIeHutkYE8RiXVx3KRvacOxfLr2Mj92SIsRIroDsH0IlUUR6fJAjoTW4RQISbaOApa2IZpIwFdQ==", + "dependencies": { + "bagpipe": "^0.3.5", + "fs-extra": "^8.0.1", + "kruptein": "^2.0.4", + "object-assign": "^4.1.1", + "retry": "^0.12.0", + "write-file-atomic": "3.0.3" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/set-blocking": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", + "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==" + }, + "node_modules/setprototypeof": { + "version": "1.2.0", + "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==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "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==", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "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==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==" + }, + "node_modules/simple-update-notifier": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/simple-update-notifier/-/simple-update-notifier-2.0.0.tgz", + "integrity": "sha512-a2B9Y0KlNXl9u/vsW6sTIu9vGEpfKu2wRV6l1H3XEas/0gUIzGzBoP/IouTcUQbm9JWZLH3COxyn03TYlFax6w==", + "dependencies": { + "semver": "^7.5.3" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socket.io": { + "version": "4.8.3", + "resolved": "https://registry.npmjs.org/socket.io/-/socket.io-4.8.3.tgz", + "integrity": "sha512-2Dd78bqzzjE6KPkD5fHZmDAKRNe3J15q+YHDrIsy9WEkqttc7GY+kT9OBLSMaPbQaEd0x1BjcmtMtXkfpc+T5A==", + "dependencies": { + "accepts": "~1.3.4", + "base64id": "~2.0.0", + "cors": "~2.8.5", + "debug": "~4.4.1", + "engine.io": "~6.6.0", + "socket.io-adapter": "~2.5.2", + "socket.io-parser": "~4.2.4" + }, + "engines": { + "node": ">=10.2.0" + } + }, + "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==", + "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 + } + } + }, + "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==", + "dependencies": { + "@socket.io/component-emitter": "~3.1.0", + "debug": "~4.3.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==", + "dependencies": { + "ip-address": "^10.0.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks-proxy-agent": { + "version": "8.0.5", + "resolved": "https://registry.npmjs.org/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz", + "integrity": "sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw==", + "dependencies": { + "agent-base": "^7.1.2", + "debug": "^4.3.4", + "socks": "^2.8.3" + }, + "engines": { + "node": ">= 14" + } + }, + "node_modules/source-map": { + "version": "0.6.1", + "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.6.1.tgz", + "integrity": "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g==", + "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", + "integrity": "sha512-lW2A2s5LKi8rwu77ewisuUOtlCydF/hmQSOJjpTqTj1gZLkNgTaYnyvfxy2WBr4T/h+9c4g8HIITfj83OkFQFw==", + "license": "MIT", + "dependencies": { + "base32.js": "0.0.1" + }, + "engines": { + "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", + "integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==", + "engines": { + "node": ">= 0.6" + } + }, + "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==" + }, + "node_modules/statuses": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", + "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/stdin-discarder": { + "version": "0.3.1", + "resolved": "https://registry.npmjs.org/stdin-discarder/-/stdin-discarder-0.3.1.tgz", + "integrity": "sha512-reExS1kSGoElkextOcPkel4NE99S0BWxjUHQeDFnR8S993JxpPX7KU4MNmO19NXhlJp+8dmdCbKQVNgLJh2teA==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/streamsearch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz", + "integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==", + "engines": { + "node": ">=10.0.0" + } + }, + "node_modules/string-width": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.2.0.tgz", + "integrity": "sha512-6hJPQ8N0V0P3SNmP6h2J99RLuzrWz2gvT7VnK5tKvrNqJoyS9W4/Fb8mo31UiPvy00z7DQXkP2hnKBVav76thw==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, + "node_modules/supports-color": { + "version": "5.5.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", + "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "dependencies": { + "has-flag": "^3.0.0" + }, + "engines": { + "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==", + "optional": true, + "os": [ + "darwin", + "linux", + "win32", + "freebsd", + "openbsd", + "netbsd", + "sunos", + "android" + ], + "bin": { + "systeminformation": "lib/cli.js" + }, + "engines": { + "node": ">=8.0.0" + }, + "funding": { + "type": "Buy me a coffee", + "url": "https://www.buymeacoffee.com/systeminfo" + } + }, + "node_modules/tar": { + "version": "7.5.13", + "resolved": "https://registry.npmjs.org/tar/-/tar-7.5.13.tgz", + "integrity": "sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng==", + "license": "BlueOak-1.0.0", + "dependencies": { + "@isaacs/fs-minipass": "^4.0.0", + "chownr": "^3.0.0", + "minipass": "^7.1.2", + "minizlib": "^3.1.0", + "yallist": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/toidentifier": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/toidentifier/-/toidentifier-1.0.1.tgz", + "integrity": "sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==", + "engines": { + "node": ">=0.6" + } + }, + "node_modules/touch": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/touch/-/touch-3.1.1.tgz", + "integrity": "sha512-r0eojU4bI8MnHr8c5bNo7lJDdI2qXlWWJk6a9EAFG7vbhTjElYhBVS3/miuE0uOuoLdb8Mc/rVfsmm6eo5o9GA==", + "bin": { + "nodetouch": "bin/nodetouch.js" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "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", + "integrity": "sha512-afizzfpJgvPr+eDkREK4MxJ/+r8nEEHcmitwgnPUqpaP+FpwQyadnxNoSACbgc/b1LsZYtODGoPiFxQrgJgjvw==", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/tx2": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/tx2/-/tx2-1.0.5.tgz", + "integrity": "sha512-sJ24w0y03Md/bxzK4FU8J8JveYYUbSs2FViLJ2D/8bytSiyPRbuE3DyL/9UKYXTZlV3yXq0L8GLlhobTnekCVg==", + "optional": true, + "dependencies": { + "json-stringify-safe": "^5.0.1" + } + }, + "node_modules/type-is": { + "version": "1.6.18", + "resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz", + "integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==", + "dependencies": { + "media-typer": "0.3.0", + "mime-types": "~2.1.24" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/typedarray": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz", + "integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==" + }, + "node_modules/typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "dependencies": { + "is-typedarray": "^1.0.0" + } + }, + "node_modules/uid-safe": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/uid-safe/-/uid-safe-2.1.5.tgz", + "integrity": "sha512-KPHm4VL5dDXKz01UuEd88Df+KzynaohSL9fBh096KWAxSKZQDI2uBrVqtvRM4rwrIrRRKsdLNML/lnaaVSRioA==", + "dependencies": { + "random-bytes": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/undefsafe": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/undefsafe/-/undefsafe-2.0.5.tgz", + "integrity": "sha512-WxONCrssBM8TSPRqN5EmsjVrsv4A8X12J4ArBiiayv3DyyG3ZlIg6yysuuSYdZsVz3TKcTg2fd//Ujd4CHV1iA==" + }, + "node_modules/undici-types": { + "version": "7.16.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz", + "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==" + }, + "node_modules/universalify": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/universalify/-/universalify-0.1.2.tgz", + "integrity": "sha512-rBJeI5CXAlmy1pV+617WB9J63U6XcazHHF2f2dbJix4XzpUF0RS3Zbj0FGIOCAva5P/d/GBOYaACQ1w+0azUkg==", + "engines": { + "node": ">= 4.0.0" + } + }, + "node_modules/unpipe": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/unpipe/-/unpipe-1.0.0.tgz", + "integrity": "sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==" + }, + "node_modules/utils-merge": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", + "integrity": "sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA==", + "engines": { + "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", + "integrity": "sha512-BNGbWLfd0eUPabhkXUVm0j8uuvREyTh5ovRa/dyow/BqAbZJyC+5fU+IzQOzmAKzYqYRAISoRhdQr3eIZ/PXqg==", + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/vizion": { + "version": "2.2.1", + "resolved": "https://registry.npmjs.org/vizion/-/vizion-2.2.1.tgz", + "integrity": "sha512-sfAcO2yeSU0CSPFI/DmZp3FsFE9T+8913nv1xWBOyzODv13fwkn6Vl7HqxGpkr9F608M+8SuFId3s+BlZqfXww==", + "dependencies": { + "async": "^2.6.3", + "git-node-fs": "^1.0.0", + "ini": "^1.3.5", + "js-git": "^0.7.8" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/vizion/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/which-module": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/which-module/-/which-module-2.0.1.tgz", + "integrity": "sha512-iBdZ57RDvnOR9AGBhML2vFZf7h8vmBjhoaZqODJBFWHVtKkDmKuHai3cx5PgVMrX5YDNp27AofYbAwctSS+vhQ==" + }, + "node_modules/write-file-atomic": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/write-file-atomic/-/write-file-atomic-3.0.3.tgz", + "integrity": "sha512-AvHcyZ5JnSfq3ioSyjrBkH9yW4m7Ayk8/9My/DD9onKeu/94fwrMocemO2QAJFAlnnDN+ZDS+ZjAR5ua1/PV/Q==", + "dependencies": { + "imurmurhash": "^0.1.4", + "is-typedarray": "^1.0.0", + "signal-exit": "^3.0.2", + "typedarray-to-buffer": "^3.1.5" + } + }, + "node_modules/ws": { + "version": "8.19.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.19.0.tgz", + "integrity": "sha512-blAT2mjOEIi0ZzruJfIhb3nps74PRWTCz1IjglWEEpQl5XS/UNama6u2/rjFkDDouqr4L67ry+1aGIALViWjDg==", + "license": "MIT", + "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/xtend": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz", + "integrity": "sha512-LKYU1iAXJXUgAXn9URjiu+MWhyUXHsvfp7mcuYm9dSUKK0/CjtrUwFAxD82/mCWbtLsGjFIad0wIsod4zrTAEQ==", + "engines": { + "node": ">=0.4" + } + }, + "node_modules/y18n": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.3.tgz", + "integrity": "sha512-JKhqTOwSrqNA1NY5lSztJ1GrBiUodLMmIZuLiDaMRJ+itFd+ABVE8XBjOvIWL+rSqNDC74LCSFmlb/U4UZ4hJQ==" + }, + "node_modules/yallist": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-5.0.0.tgz", + "integrity": "sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw==", + "engines": { + "node": ">=18" + } + }, + "node_modules/yargs": { + "version": "15.4.1", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-15.4.1.tgz", + "integrity": "sha512-aePbxDmcYW++PaqBsJ+HYUFwCdv4LVvdnhBy78E57PIor8/OVvhMrADFFEDh8DHDFRv/O9i3lPhsENjO7QX0+A==", + "dependencies": { + "cliui": "^6.0.0", + "decamelize": "^1.2.0", + "find-up": "^4.1.0", + "get-caller-file": "^2.0.1", + "require-directory": "^2.1.1", + "require-main-filename": "^2.0.0", + "set-blocking": "^2.0.0", + "string-width": "^4.2.0", + "which-module": "^2.0.0", + "y18n": "^4.0.0", + "yargs-parser": "^18.1.2" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs-parser": { + "version": "18.1.3", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-18.1.3.tgz", + "integrity": "sha512-o50j0JeToy/4K6OZcaQmW6lyXXKhq7csREXcDwk2omFPJEwUNOVtJKvmDr9EI1fAJZUyZcRF7kxGBWmRXudrCQ==", + "dependencies": { + "camelcase": "^5.0.0", + "decamelize": "^1.2.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/yargs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/yargs/node_modules/find-up": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-4.1.0.tgz", + "integrity": "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw==", + "dependencies": { + "locate-path": "^5.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/locate-path": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-5.0.0.tgz", + "integrity": "sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g==", + "dependencies": { + "p-locate": "^4.1.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/p-limit": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-2.3.0.tgz", + "integrity": "sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w==", + "dependencies": { + "p-try": "^2.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/yargs/node_modules/p-locate": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-4.1.0.tgz", + "integrity": "sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A==", + "dependencies": { + "p-limit": "^2.2.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yoctocolors": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/yoctocolors/-/yoctocolors-2.1.2.tgz", + "integrity": "sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..44e7bd7 --- /dev/null +++ b/package.json @@ -0,0 +1,61 @@ +{ + "name": "adpanel", + "version": "1.0.0", + "main": "index.js", + "scripts": { + "start": "NODE_ENV=production node index.js", + "dev": "NODE_ENV=development node index.js", + "strip:comments": "node scripts/strip-comments.js", + "strip:comments:write": "node scripts/strip-comments.js --write" + }, + "dependencies": { + "@fortawesome/fontawesome-free": "^7.2.0", + "adm-zip": "^0.5.16", + "ansi_up": "^6.0.6", + "bcrypt": "^6.0.0", + "bcryptjs": "^3.0.3", + "busboy": "^1.6.0", + "bullmq": "^5.66.7", + "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", + "express-rate-limit": "^8.3.2", + "express-session": "^1.19.0", + "form-data": "^4.0.5", + "helmet": "^8.1.0", + "hpp": "^0.2.3", + "inquirer": "^13.3.2", + "ip-range-check": "^0.2.0", + "multer": "^1.4.5-lts.1", + "mysql2": "^3.11.5", + "nodemon": "^3.1.14", + "ora": "^9.3.0", + "pm2": "^6.0.14", + "qrcode": "^1.5.4", + "qrcode-terminal": "^0.12.0", + "rate-limit-redis": "^4.3.1", + "redis": "^5.11.0", + "session-file-store": "^1.5.0", + "socket.io": "^4.8.3", + "speakeasy": "^2.0.0", + "tar": "^7.5.13", + "ws": "^8.19.0" + }, + "description": "
\"ADPanel ", + "repository": { + "type": "git", + "url": "git+https://github.com/antonndev/ADPanel.git" + }, + "keywords": [], + "author": "", + "license": "ISC", + "bugs": { + "url": "https://github.com/antonndev/ADPanel/issues" + }, + "homepage": "https://github.com/antonndev/ADPanel#readme" +} diff --git a/panel-information.json b/panel-information.json new file mode 100644 index 0000000..17b5160 --- /dev/null +++ b/panel-information.json @@ -0,0 +1,7 @@ +[ + { + "panel-version": "v1.0.0", + "panel-architecture": "ADPanel Architecture", + "panel-auto-update": false + } +] \ No newline at end of file diff --git a/public/css-ext/all.css b/public/css-ext/all.css new file mode 100644 index 0000000..0c7695d --- /dev/null +++ b/public/css-ext/all.css @@ -0,0 +1,19 @@ +.adpanel { + display: inline-block; + width: 1em; + height: 1em; + background-color: currentColor; + mask-size: contain; + mask-repeat: no-repeat; + mask-position: center; +} + +.sidebar { + mask-image: url("/img/sidebar.png"); +} +.sidebar-modern { + mask-image: url("/img/sidebar-modern.png"); +} +.sidebar-it { + mask-image: url("/img/sidebar-it.png"); +} diff --git a/public/css/bot.css b/public/css/bot.css new file mode 100644 index 0000000..7050ac3 --- /dev/null +++ b/public/css/bot.css @@ -0,0 +1,13263 @@ +:root { + --ui-bg: url("/images/waves.png?v=1776616961314"); +} + +.ptero-flash-bar { + position: absolute; + top: 0; + left: 0; + right: 0; + height: 2px; + z-index: 100000; + pointer-events: none; + overflow: hidden; + border-radius: 20px 20px 0 0; +} + +.ptero-flash-bar .ptero-flash-fill { + position: absolute; + top: 0; + left: 0; + height: 100%; + width: 0%; + background: linear-gradient(90deg, #60a5fa, #818cf8, #60a5fa); + background-size: 200% 100%; + border-radius: 0 2px 2px 0; + transition: width 0.3s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.4s ease; + animation: pteroShimmer 1.5s linear infinite; + opacity: 1; +} + +.ptero-flash-bar .ptero-flash-fill.complete { + width: 100% !important; + opacity: 0; + transition: width 0.25s cubic-bezier(0.22, 1, 0.36, 1), opacity 0.5s ease 0.2s; +} + +@keyframes pteroShimmer { + 0% { background-position: 200% 0; } + 100% { background-position: -200% 0; } +} + +.entry-actions { + position: relative; +} + +.more-btn { + position: relative; + background: transparent; + border: none; + color: rgba(255, 255, 255, 0.4); + cursor: pointer; + font-size: 16px; + padding: 6px; + border-radius: 8px; + align-self: flex-end; + transition: all 0.15s ease; +} + +.more-btn:hover { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.8); +} + +.more-menu { + position: absolute; + left: -150px; + top: 28px; + background: rgba(18, 22, 30, 0.85); + backdrop-filter: blur(30px) saturate(160%); + -webkit-backdrop-filter: blur(30px) saturate(160%); + border: 0.5px solid rgba(255, 255, 255, 0.1); + box-shadow: 0 8px 30px rgba(0, 0, 0, 0.3); + border-radius: 12px; + overflow: hidden; + z-index: 9999; + min-width: 160px; + display: none; + pointer-events: auto; +} + +.more-menu.show { + display: block; +} + +.more-menu button { + display: block; + width: 100%; + padding: 10px 12px; + background: transparent; + border: 0; + color: #c8d1da; + text-align: left; + font-size: 14px; + cursor: pointer; +} + +.more-menu button:hover { + background: rgba(255, 255, 255, 0.02); + color: #fff; +} + +.progress-wheel { + width: 18px; + height: 18px; + border-radius: 50%; + background: rgba(255, 255, 255, 0.06); + display: inline-block; + position: relative; + overflow: hidden; + border: 0.5px solid rgba(255, 255, 255, 0.1); + margin-left: 10px; + vertical-align: middle; + cursor: pointer; + transition: transform .12s ease; +} + +.progress-wheel:hover { + transform: scale(1.08); +} + +.progress-wheel .fill { + position: absolute; + left: 0; + right: 0; + top: 0; + background: #ffffff; + height: 0%; + border-radius: 50%; + transition: height 120ms linear; + pointer-events: none; +} + +.progress-wheel.hidden { + display: none; +} + +.progress-popup { + position: fixed; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + background: rgba(12, 14, 20, 0.88); + color: #fff; + border-radius: 16px; + border: 0.5px solid rgba(255, 255, 255, 0.1); + padding: 16px 18px; + z-index: 100000; + min-width: 300px; + max-width: min(520px, calc(100vw - 32px)); + box-shadow: 0 12px 40px rgba(0, 0, 0, 0.4); + display: none; + backdrop-filter: blur(60px) saturate(150%); + -webkit-backdrop-filter: blur(60px) saturate(150%); +} + +.progress-popup .row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; +} + +.progress-popup .percent { + font-weight: 700; + font-size: 20px; + color: #ffffff; +} + +.progress-popup .close-btn { + background: transparent; + border: none; + color: #9aa3ad; + font-size: 18px; + cursor: pointer; + padding: 6px; + border-radius: 6px; +} + +.progress-popup .progress-bar { + margin-top: 12px; + width: 100%; + height: 12px; + background: rgba(255, 255, 255, 0.06); + border-radius: 8px; + overflow: hidden; + position: relative; +} + +.progress-popup .progress-bar .bar { + height: 100%; + width: 0%; + background: linear-gradient(90deg, rgba(255, 255, 255, 1), rgba(220, 220, 220, 0.85)); + transition: width 120ms linear; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.45) inset; +} + +.progress-popup .meta { + margin-top: 10px; + font-size: 12px; + color: #9aa3ad; + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.progress-file-list { + display: none; + margin-top: 12px; + max-height: min(260px, 42vh); + overflow: auto; + padding-right: 2px; +} + +.progress-file-list.visible { + display: grid; + gap: 8px; +} + +.progress-file-item { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 6px 10px; + align-items: center; + padding: 8px 10px; + border-radius: 8px; + background: rgba(255, 255, 255, 0.055); + border: 1px solid rgba(255, 255, 255, 0.075); +} + +.progress-file-name { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-size: 12px; + color: #eef3f8; +} + +.progress-file-percent { + font-size: 12px; + color: #c8d0d8; + font-variant-numeric: tabular-nums; +} + +.progress-file-track { + grid-column: 1 / -1; + height: 5px; + overflow: hidden; + border-radius: 999px; + background: rgba(255, 255, 255, 0.08); +} + +.progress-file-fill { + width: 0%; + height: 100%; + border-radius: inherit; + background: rgba(255, 255, 255, 0.9); + transition: width 120ms linear; +} + +#dropOverlay { + position: absolute; + inset: 0; + display: none; + align-items: center; + justify-content: center; + z-index: 99990; + pointer-events: none; + background: rgba(255, 255, 255, 0.02); + backdrop-filter: blur(18px) saturate(140%); + -webkit-backdrop-filter: blur(18px) saturate(140%); + transition: opacity 0.25s cubic-bezier(0.22, 1, 0.36, 1); + opacity: 0; +} + +#dropOverlay.visible { + display: flex; + pointer-events: auto; + opacity: 1; + animation: dropFadeIn 0.3s cubic-bezier(0.22, 1, 0.36, 1) forwards; +} + +@keyframes dropFadeIn { + from { opacity: 0; transform: scale(0.98); } + to { opacity: 1; transform: scale(1); } +} + +#dropOverlay .inner { + background: transparent; + border: 2px dashed rgba(96, 165, 250, 0.35); + padding: 48px 56px; + border-radius: 20px; + text-align: center; + color: #e6eef8; + position: relative; + transition: border-color 0.2s ease, transform 0.2s ease; +} + +#dropOverlay.visible .inner { + animation: dropPulse 2s ease-in-out infinite; +} + +@keyframes dropPulse { + 0%, 100% { border-color: rgba(96, 165, 250, 0.35); transform: scale(1); } + 50% { border-color: rgba(96, 165, 250, 0.55); transform: scale(1.005); } +} + +#dropOverlay .inner h3 { + margin: 0 0 8px 0; + font-size: 20px; + font-weight: 700; + letter-spacing: -0.01em; + color: #f0f4f8; +} + +#dropOverlay .inner p { + margin: 0; + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + font-weight: 400; +} + +*::-webkit-scrollbar { + width: 10px; + height: 10px; +} + +*::-webkit-scrollbar-track { + background: transparent; + margin: 6px 0; + border-radius: 999px; +} + +*::-webkit-scrollbar-thumb { + background-color: #212121; + border-radius: 999px; + border: 2px solid transparent; + background-clip: padding-box; + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.02); +} + +*::-webkit-scrollbar-thumb:hover { + background-color: #2a2a2a; +} + +*::-webkit-scrollbar-corner { + background: transparent; +} + +#console, +#entries, +.modal-body, +.modal-left, +.modal-right, +.code-area, +textarea, +.modal { + scrollbar-width: thin; + scrollbar-color: #212121 transparent; +} + +#console { + height: 375px; + overflow: auto; + padding: 12px; + border-radius: 8px; + background: #0b0c0e; + white-space: pre-wrap; + position: relative; + width: 1100px; + font-family: 'Menlo', 'Monaco', 'Consolas', 'Liberation Mono', 'Courier New', monospace; + font-size: 13px; + line-height: 1.5; + color: #d4d4d4; + word-break: break-word; +} + +#consoleContent { + font-family: inherit; + font-size: inherit; + line-height: inherit; + color: inherit; +} + +.console-link { + color: #d4d4d4; + text-decoration: none; + cursor: pointer; + transition: color 0.15s ease, text-decoration 0.15s ease; +} + +.console-link:hover { + color: #ffffff; + text-decoration: underline; +} + +#filesModal .modal { + position: relative; + width: 94vw; + max-width: 1400px; + height: 88vh; + max-height: 88vh; + display: flex; + flex-direction: column; + background: rgba(12, 14, 20, 0.82); + backdrop-filter: blur(60px) saturate(150%); + -webkit-backdrop-filter: blur(60px) saturate(150%); + color: var(--text); + border: 0.5px solid rgba(255, 255, 255, 0.1); + border-radius: 20px; + box-shadow: + 0 0 0 0.5px rgba(255, 255, 255, 0.06), + 0 24px 80px rgba(0, 0, 0, 0.35); + overflow: hidden; +} + +#filesModal .modal-body { + flex: 1; + overflow-y: auto !important; + overflow-x: hidden; + display: flex; + flex-direction: column; +} + +#filesModal .modal-left { + flex: 1; + min-height: 0 !important; + padding-bottom: 20px !important; +} + +#filesModal .modal-right { + display: none; +} + +#entries::after { + content: ""; + height: -10px; + width: 100%; + grid-column: 1 / -1; +} + +#fileUploadModal { + display: none; +} + +.file-toolbar { + display: flex; + justify-content: space-between; + align-items: center; + gap: 16px; + padding: 12px 0; + border-bottom: 0.5px solid rgba(255, 255, 255, 0.06); +} + +.file-toolbar-left { + display: flex; + align-items: center; + gap: 12px; +} + +.file-toolbar-meta { + display: flex; + flex-direction: column; + gap: 6px; +} + +.select-all-control { + display: flex; + align-items: center; + gap: 8px; + background: rgba(96, 165, 250, 0.06); + border: 0.5px solid rgba(96, 165, 250, 0.2); + padding: 6px 10px; + border-radius: 10px; + color: #dbeafe; + cursor: pointer; + user-select: none; + transition: all 0.15s ease; + align-self: flex-end; +} + +.select-all-control:hover { + background: rgba(96, 165, 250, 0.1); + border-color: rgba(96, 165, 250, 0.3); +} + +.select-all-control input { + display: none; +} + +.select-all-checkbox { + width: 18px; + height: 18px; + border-radius: 6px; + background: rgba(255, 255, 255, 0.08); + border: 1px solid rgba(255, 255, 255, 0.18); + display: flex; + align-items: center; + justify-content: center; + color: #0b0f14; + font-size: 12px; + transition: all .12s ease; +} + +.select-all-control input:checked+.select-all-checkbox { + background: linear-gradient(135deg, #38bdf8, #2563eb); + border-color: rgba(37, 99, 235, 0.65); + color: #e0f2fe; + box-shadow: 0 8px 18px rgba(37, 99, 235, 0.35); +} + +.select-all-label { + font-size: 12px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: #bfdbfe; +} + +.bulk-delete { + display: none; + align-items: center; + gap: 8px; + border: none; + outline: none; + background: rgba(239, 68, 68, 0.1); + color: #fecaca; + border-radius: 10px; + padding: 9px 14px; + font-size: 13px; + cursor: pointer; + border: 0.5px solid rgba(248, 113, 113, 0.2); + transition: all 0.15s ease; +} + +.bulk-delete.show { + border: none; + outline: none; + display: flex; +} + +.bulk-delete:hover { + border: none; + outline: none; + transform: none; +} + +.bulk-delete i { + color: #fecdd3; +} + +.bulk-archive { + display: none; + align-items: center; + gap: 8px; + border: none; + outline: none; + background: rgba(59, 130, 246, 0.1); + color: #bfdbfe; + border-radius: 10px; + padding: 9px 14px; + font-size: 13px; + cursor: pointer; + border: 0.5px solid rgba(96, 165, 250, 0.2); + transition: all 0.15s ease; +} + +.bulk-archive.show { + border: none; + outline: none; + display: flex; +} + +.bulk-archive:hover { + border: none; + outline: none; + transform: none; + box-shadow: 0 14px 32px rgba(0, 0, 0, 0.4), inset 0 0 0 1px rgba(96, 165, 250, 0.35); +} + +.bulk-archive i { + color: #93c5fd; +} + +.file-toolbar-icon { + width: 32px; + height: 32px; + border-radius: 10px; + background: rgba(96, 165, 250, 0.1); + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + color: #60a5fa; + transition: background 0.15s ease; +} + +.file-toolbar-title { + font-size: 13px; + color: var(--muted); + text-transform: uppercase; + letter-spacing: 0.2em; +} + +#storePrefModal .modal { + width: min(980px, calc(100vw - 48px)); + max-height: min(680px, calc(100dvh - 48px)); + display: flex; + flex-direction: column; + overflow: hidden; +} + +.store-pref-body { + padding: 20px 20px 22px 20px; + overflow: auto; +} + +.store-pref-grid { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; +} + +.store-pref-card { + min-height: 178px; + padding: 18px; + border: 0; + border-radius: 12px; + background: + radial-gradient(380px 200px at 20% -15%, rgba(255, 255, 255, 0.08), transparent 70%), + linear-gradient(145deg, rgba(255, 255, 255, 0.065), rgba(255, 255, 255, 0.025)); + box-shadow: none; + display: grid; + grid-template-rows: auto 1fr auto; + gap: 14px; + cursor: pointer; + transition: transform .16s ease, background .16s ease; + text-align: left; + color: var(--text); + width: 100%; + overflow: hidden; +} + +.store-pref-card .store-pref-media, +.store-pref-card .store-pref-copy, +.store-pref-card .store-pref-foot { + transition: transform .16s ease; +} + +.store-pref-card:hover { + transform: scale(1.03); + background: + radial-gradient(420px 220px at 20% -15%, rgba(255, 255, 255, 0.12), transparent 70%), + linear-gradient(145deg, rgba(255, 255, 255, 0.09), rgba(255, 255, 255, 0.035)); +} + +.store-pref-card:hover .store-pref-media, +.store-pref-card:hover .store-pref-copy, +.store-pref-card:hover .store-pref-foot { + transform: scale(0.970874); +} + +.store-pref-media { + width: 100%; + height: 74px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.075); + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; +} + +.store-pref-logo { + width: min(86%, 180px); + height: 58px; + object-fit: contain; + display: block; +} + +.store-pref-card[data-store-pref="fivem"] .store-pref-media { + background: + linear-gradient(135deg, rgba(246, 84, 64, 0.18), rgba(255, 255, 255, 0.07)), + rgba(255, 255, 255, 0.06); +} + +.store-pref-card[data-store-pref="fivem"] .store-pref-logo { + width: min(96%, 210px); + height: 66px; +} + +.store-pref-copy { + min-width: 0; +} + +.store-pref-title { + font-size: 16px; + font-weight: 800; + color: #edf4ff; + line-height: 1.2; +} + +.store-pref-desc { + color: #a8b2bf; + font-size: 13px; + line-height: 1.45; + margin-top: 8px; +} + +.store-pref-foot { + display: flex; + align-items: center; + justify-content: flex-end; + color: #cbd5e1; + font-size: 13px; +} + +#breadcrumbs { + font-size: 16px; + font-weight: 600; + color: #f3f4f6; +} + +#breadcrumbs a { + color: #60a5fa; + text-decoration: none; +} + +.file-toolbar-actions { + display: flex; + flex-direction: column; + gap: 10px; + align-items: flex-end; +} + +.file-action-row { + display: flex; + gap: 10px; + align-items: center; + flex-wrap: wrap; + justify-content: flex-end; +} + +.file-selection-row { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + flex-wrap: wrap; +} + +#filesModal .modal, +#filesModal .modal-body, +#filesModal .modal-left { + min-height: 0 !important; +} + +.ghost-btn { + border: 0.5px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.04); + color: #e6eef8; + border-radius: 10px; + padding: 9px 15px; + font-size: 13px; + display: flex; + align-items: center; + gap: 7px; + cursor: pointer; + transition: all 0.15s ease; + font-weight: 500; +} + +.ghost-btn i { + font-size: 13px; + opacity: 0.7; +} + +.ghost-btn:hover { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.15); +} + +.ghost-btn:active { + transform: scale(0.98); +} + +.file-glance { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); + gap: 12px; + margin: 18px 0; +} + +.glance-card { + display: flex; + align-items: center; + gap: 12px; + padding: 14px 16px; + height: 50px; + width: 450px; + margin-top: -95px; + margin-left: 880px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.03); + border: 0.5px solid rgba(255, 255, 255, 0.06); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + transition: background 0.15s ease; +} + +.glance-card:hover { + background: rgba(255, 255, 255, 0.05); +} + +.glance-card .icon { + width: 38px; + height: 38px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + color: #10b981; + background: rgba(16, 185, 129, 0.12); +} + +.glance-card:nth-child(2) .icon { + color: #60a5fa; + background: rgba(96, 165, 250, 0.12); +} + +.glance-card:nth-child(3) .icon { + color: #f97316; + background: rgba(249, 115, 22, 0.12); +} + +.glance-label { + font-size: 13px; + text-transform: uppercase; + letter-spacing: 0.08em; + color: #9aa3ad; +} + +.glance-desc { + font-size: 15px; + font-weight: 600; + color: #f8fafc; +} + +#entries { + flex: 1; + overflow: visible !important; + padding: 4px 0 10px; + display: grid; + box-sizing: border-box; + width: 1400px !important; + grid-template-columns: repeat(3, 1fr); + gap: 16px; + scroll-padding-bottom: 40px; + list-style: none; + margin: 0; + align-content: start; +} + +.entry { + display: grid; + grid-template-columns: auto 1fr auto; + align-items: center; + gap: 16px; + padding: 14px 16px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.03); + border: 0.5px solid rgba(255, 255, 255, 0.06); + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); + transition: all 0.18s cubic-bezier(0.22, 1, 0.36, 1); +} + +.entry.selected .entry-left { + animation: ios-tremble 0.14s ease-in-out infinite alternate; +} + +.entry.selectable .entry-left { + cursor: pointer; +} + +.entry.selectable .entry-left:active { + transform: scale(0.98); +} + +@keyframes ios-tremble { + 0% { + transform: rotate(-1.2deg) translate3d(-0.5px, 0, 0); + } + + 100% { + transform: rotate(1.2deg) translate3d(0.5px, 0, 0); + } +} + +.entry:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.12); + transform: scale(1.05); + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.15); +} + +.entry-left { + display: flex; + align-items: center; + gap: 14px; + min-width: 0; +} + +.entry-text-wrap { + min-width: 0; +} + +.entry-icon { + width: 42px; + height: 42px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(96, 165, 250, 0.1); + color: #60a5fa; + font-size: 18px; + transition: background 0.15s ease, transform 0.15s ease; +} + +.entry:hover .entry-icon { + background: rgba(96, 165, 250, 0.16); + transform: scale(1.04); +} + +.entry-icon.folder { + background: rgba(250, 204, 21, 0.1); + color: #facc15; +} + +.entry:hover .entry-icon.folder { + background: rgba(250, 204, 21, 0.16); +} + +.entry-name { + font-size: 14px; + font-weight: 600; + color: var(--text); + letter-spacing: -0.01em; + min-width: 0; +} + +.entry.renaming { + border-color: rgba(96, 165, 250, 0.3); + background: rgba(96, 165, 250, 0.08); +} + +.entry-rename-inline { + display: flex; + align-items: center; + gap: 6px; +} + +.entry-rename-input { + width: 100%; + min-width: 150px; + max-width: 320px; + height: 30px; + border-radius: 8px; + border: 0.5px solid rgba(255, 255, 255, 0.2); + background: rgba(9, 12, 18, 0.86); + color: #f8fafc; + font-size: 13px; + font-weight: 600; + letter-spacing: -0.01em; + padding: 0 10px; + box-sizing: border-box; +} + +.entry-rename-input:focus { + outline: none; + border-color: rgba(96, 165, 250, 0.8); + box-shadow: 0 0 0 2px rgba(96, 165, 250, 0.2); +} + +.entry-rename-actions { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.entry-rename-btn { + width: 28px; + height: 28px; + border: 0.5px solid rgba(255, 255, 255, 0.14); + background: rgba(255, 255, 255, 0.04); + color: #e6eef8; + border-radius: 8px; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + transition: all 0.15s ease; +} + +.entry-rename-btn:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.1); + transform: translateY(-1px); +} + +.entry-rename-btn.save { + color: #22c55e; +} + +.entry-rename-btn.cancel { + color: #fb7185; +} + +.entry-rename-btn:disabled { + opacity: 0.5; + cursor: default; + transform: none; +} + +.entry-meta { + font-size: 12px; + color: rgba(255, 255, 255, 0.35); + margin-top: 2px; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.entry-arrow { + color: #9aa3ad; + font-size: 14px; + opacity: 0; + transition: opacity .12s ease, transform .12s ease; +} + +.entry:hover .entry-arrow { + opacity: 1; + transform: translateX(4px); +} + +.entry-actions { + justify-self: end; +} + +.entry-right { + display: flex; + align-items: center; + gap: 10px; + justify-content: flex-end; +} + +#editorModal .modal { + width: 98vw; + max-width: 100vw; + max-height: 93vh; + min-height: 93vh !important; + display: flex; + flex-direction: column; + background: rgba(12, 14, 20, 0.88); + backdrop-filter: blur(60px) saturate(150%); + -webkit-backdrop-filter: blur(60px) saturate(150%); + color: var(--text); + border: 0.5px solid rgba(255, 255, 255, 0.1); + border-radius: 16px; + box-shadow: + 0 0 0 0.5px rgba(255, 255, 255, 0.06), + 0 24px 80px rgba(0, 0, 0, 0.35); + overflow: hidden; +} + +#editorModal .editor-header { + padding: 14px 18px; + border-bottom: 0.5px solid rgba(255, 255, 255, 0.06); + margin-bottom: 0; +} + +#editorModal .editor-title { + font-weight: 700; + font-size: 16px; + color: #f0f4f8; + letter-spacing: -0.01em; +} + +#bigEditor { + margin-top: 10px; + display: flex; + flex-direction: column; + gap: 10px; + flex: 1 1 0; + min-height: 0; + overflow: hidden; +} + +.code-shell { + width: 100%; + flex: 1 1 0; + min-height: 0; + display: flex; + align-items: stretch; + background: #1e1e1e; + border-radius: 12px; + box-shadow: 0 2px 12px rgba(0, 0, 0, 0.2); + overflow: hidden; + position: relative; + isolation: isolate; + -ms-overflow-style: none; + scrollbar-width: none; +} + +#monacoContainer { + background: #1e1e1e; + isolation: isolate; +} + +#aceContainer { + background: #1e1e1e; + isolation: isolate; + width: 100% !important; + height: 100% !important; + min-height: 0; + position: relative; + border-radius: 0; + overflow: hidden; +} +#aceContainer .ace_editor { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace !important; + font-size: 14px !important; + line-height: 1.6 !important; + background: #1e1e1e !important; + width: 100% !important; + height: 100% !important; +} +#aceContainer .ace_gutter { + background: #1a1d23 !important; + color: #7c8494 !important; + border-right: 1px solid rgba(255, 255, 255, 0.06) !important; +} +#aceContainer .ace_gutter-cell { + padding-left: 8px !important; + padding-right: 6px !important; +} +#aceContainer .ace_gutter-active-line { + background: rgba(255, 255, 255, 0.04) !important; +} +#aceContainer .ace_scroller { + background: #1e1e1e !important; +} +#aceContainer .ace_active-line { + background: rgba(255, 255, 255, 0.03) !important; +} +#aceContainer .ace_cursor { + color: #aeafad !important; + border-left: 2px solid #aeafad !important; +} +#aceContainer .ace_selection { + background: rgba(100, 150, 255, 0.18) !important; +} +#aceContainer .ace_bracket { + border: 1px solid rgba(255, 255, 255, 0.15) !important; +} +#aceContainer .ace_indent-guide { + border-right: 1px solid rgba(255, 255, 255, 0.05) !important; +} +#aceContainer .ace_scrollbar::-webkit-scrollbar { + width: 8px; + height: 8px; +} +#aceContainer .ace_scrollbar::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.15); + border-radius: 4px; +} +#aceContainer .ace_scrollbar::-webkit-scrollbar-thumb:hover { + background: rgba(255, 255, 255, 0.25); +} +#aceContainer .ace_scrollbar::-webkit-scrollbar-track { + background: transparent; +} + +.code-shell::-webkit-scrollbar { + width: 0; + height: 0; +} + +.line-gutter { + flex: 0 0 64px; + width: 64px; + min-width: 64px; + margin-top: -4px; + background: #1a1d23; + color: #7c8494; + padding: var(--code-pad-top) 18px var(--code-pad-bottom) 12px; + text-align: right; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: var(--code-font-size); + line-height: var(--code-line-height); + border-right: 1px solid rgba(255, 255, 255, 0.05); + display: flex; + flex-direction: column; + align-items: flex-end; + box-sizing: border-box; + overflow: hidden; + scrollbar-width: none; + -ms-overflow-style: none; +} + +.line-gutter::-webkit-scrollbar { + display: none; + width: 0; + height: 0; +} + +.line-gutter div { + padding: 0; + line-height: var(--code-line-height); + height: auto; +} + +.code-pane { + position: relative; + flex: 1; + overflow: auto; + min-height: 0; + height: 100%; + scrollbar-width: none; + -ms-overflow-style: none; +} + +.code-pane::-webkit-scrollbar { + width: 0; + height: 0; +} + +.code-overlay, +.code-input { + position: absolute; + inset: 0; + margin: 0; + padding: var(--code-pad-top) 22px var(--code-pad-bottom) 24px; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: var(--code-font-size); + line-height: var(--code-line-height); + white-space: pre; + border: 0; + outline: none; + background: transparent; + height: auto; + min-height: 100%; + box-sizing: border-box; + tab-size: 2; +} + +.code-overlay { + color: #e6eef8; + pointer-events: none; + z-index: 1; + margin: 0; + overflow: visible; +} + +.code-overlay::after { + content: ""; + display: block; + height: 0; +} + +.code-overlay .line { + min-height: calc(var(--code-line-height) * 1em); +} + +.code-input { + z-index: 2; + color: transparent; + caret-color: #e6eef8; + resize: none; + overflow: visible; +} + +.code-spacer { + position: relative; + width: 100%; + height: 0; + pointer-events: none; + visibility: hidden; +} + +textarea { + width: 100%; + max-height: 60vh; + overflow: auto; + padding: 12px; + border-radius: 12px; + border: 1px solid #2d2d2d; + background: #1e1e1e; + color: #e6eef8; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: 14px; + resize: vertical; + outline: none; +} + +#textArea:focus { + outline: none; + box-shadow: none; + border-color: transparent; +} + +.code-overlay { + color: #d4d4d4; +} + +.code-overlay [data-token="kw"], +.code-overlay [data-token="kw2"] { + color: #c586c0; +} + +.code-overlay [data-token="str"] { + color: #ce9178; +} + +.code-overlay [data-token="num"] { + color: #b5cea8; +} + +.code-overlay [data-token="com"] { + color: #6a9955; + font-style: italic; +} + +.code-overlay [data-token="fn"], +.code-overlay [data-token="call"] { + color: #dcdcaa; +} + +.code-overlay [data-token="cls"], +.code-overlay [data-token="type"] { + color: #4ec9b0; +} + +.code-overlay [data-token="prop"] { + color: #9cdcfe; +} + +.code-overlay [data-token="tag"] { + color: #569cd6; +} + +.code-overlay [data-token="attr"] { + color: #dcdcaa; +} + +.code-overlay [data-token="const"] { + color: #4fc1ff; +} + +.code-overlay [data-token="bool"] { + color: #569cd6; +} + +.dock-wrap { + position: fixed; + left: 50%; + bottom: 18px; + transform: translateX(-50%); + z-index: 99999; + width: max-content; + max-width: calc(100vw - 36px); + display: flex; + justify-content: center; +} + +.dock { + display: inline-flex; + flex-wrap: wrap; + gap: 12px; + padding: 10px 18px; + border-radius: 16px; + width: auto; + max-width: 100%; + border: none; + box-shadow: 0 8px 26px rgba(0, 0, 0, 0.45); + backdrop-filter: blur(14px) saturate(150%); + background: transparent; + align-items: center; +} + +.dock-item { + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + padding: 8px 10px; + cursor: pointer; + user-select: none; + color: #d1d8de; + text-decoration: none; +} + +.dock-item .label { + font-size: 11px; + color: #c3cad2; + margin-top: 4px; +} + +.dock-item:hover { + transform: translateY(-3px); + transition: transform .12s; +} + +.dock-item .icon { + width: 40px; + height: 40px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 12px; + position: relative; + overflow: hidden; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + + background: linear-gradient(145deg, + rgba(255, 255, 255, 0.22) 0%, + rgba(255, 255, 255, 0.1) 50%, + rgba(255, 255, 255, 0.14) 100%); + backdrop-filter: blur(40px) saturate(180%); + -webkit-backdrop-filter: blur(40px) saturate(180%); +} + +.dock-item .icon>* { + filter: drop-shadow(0 0 1px rgba(255, 255, 255, 0.3)); +} + +.dock-item .icon::before { + content: ''; + position: absolute; + inset: 0; + border-radius: 12px; + padding: 1px; + background: linear-gradient(145deg, + rgba(255, 255, 255, 0.5) 0%, + rgba(255, 255, 255, 0.12) 40%, + rgba(255, 255, 255, 0.18) 100%); + -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; + pointer-events: none; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} + +.dock-item .icon::after { + content: ''; + position: absolute; + top: 0; + left: 10%; + right: 10%; + height: 40%; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.25) 0%, transparent 100%); + border-radius: 12px 12px 50% 50%; + pointer-events: none; +} + +.dock-item .icon i { + font-size: 18px; + color: rgba(255, 255, 255, 0.9); + position: relative; + z-index: 1; + transition: all 0.3s ease; +} + +.dock-item:hover .icon { + background: linear-gradient(145deg, + rgba(255, 255, 255, 0.3) 0%, + rgba(255, 255, 255, 0.14) 50%, + rgba(255, 255, 255, 0.18) 100%); + transform: scale(1.06); +} + +.dock-item:hover .icon i { + color: rgba(255, 255, 255, 1); +} + +.dock-item:active .icon { + transform: scale(0.95); + background: linear-gradient(145deg, + rgba(255, 255, 255, 0.35) 0%, + rgba(255, 255, 255, 0.18) 50%, + rgba(255, 255, 255, 0.22) 100%); +} + +.info-grid { + display: grid; + gap: 10px; +} + +.info-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 10px 12px; + background: #0e1116; + border: 1px solid rgba(255, 255, 255, 0.05); + border-radius: 10px; +} + +.info-key { + color: #9aa3ad; + font-size: 13px; +} + +.info-val { + color: #e6eef8; + font-weight: 700; + font-size: 14px; + word-break: break-all; +} + +.addr-wrap { + display: flex; + gap: 8px; + align-items: center; +} + +.addr-input { + flex: 1; + padding: 10px 12px; + border-radius: 10px; + background: #0b0f14; + color: #e6eef8; + border: 1px solid rgba(255, 255, 255, 0.06); + outline: none; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; +} + +.copy-btn { + background: #10b981; + color: #041015; + border: 0; + border-radius: 10px; + padding: 10px 14px; + font-weight: 700; + cursor: pointer; + box-shadow: 0 6px 18px rgba(16, 185, 129, .25); +} + +.copy-btn:hover { + filter: brightness(1.06); +} + +.modal .hint { + font-size: 12px; + color: #9aa3ad; +} + +.disabled { + opacity: .5; + pointer-events: none; + filter: saturate(.3); +} + +.hidden { + display: none !important; +} + +#storeModal .modal { + width: 90vw; + max-width: 1200px; + height: 90vh; + max-height: 90vh; + display: flex; + flex-direction: column; + color: var(--text); + background: + radial-gradient(1000px 600px at 120% -10%, rgba(96, 165, 250, 0.08), transparent 60%), + radial-gradient(900px 500px at -10% 120%, rgba(16, 185, 129, 0.10), transparent 60%), + linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.02)); + backdrop-filter: blur(10px) saturate(150%); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 18px; + box-shadow: 0 30px 80px rgba(0, 0, 0, 0.6); +} + +.store-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 18px 18px 12px 18px; + border-bottom: 1px solid rgba(255, 255, 255, 0.08); + position: relative; +} + +.store-header:after { + content: ""; + position: absolute; + left: 18px; + right: 18px; + bottom: -1px; + height: 1px; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.22), transparent); + opacity: .3; +} + +.store-header-main { + display: flex; + align-items: center; + gap: 12px; +} + +.store-subtitle { + color: #b8c3cf; + font-size: 12.5px; + margin-top: 4px; +} + +.store-header-right { + display: flex; + align-items: center; + gap: 10px; +} + +.store-tabs { + display: flex; + align-items: center; + gap: 8px; + background: rgba(255, 255, 255, 0.04); + padding: 6px; + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.06); +} + +.store-tab { + border-radius: 999px; + border: 1px solid rgba(255, 255, 255, 0.1); + background: transparent; + color: #e5edf7; + font-size: 13px; + padding: 8px 14px; + cursor: pointer; + white-space: nowrap; + transition: background-color .15s ease, border-color .15s ease, color .15s ease; + transform-origin: center; + backface-visibility: hidden; +} + +.store-tab.active { + background: #ffffff; + color: #0b0f14; + border-color: #ffffff; + box-shadow: none; +} + +.store-tab:hover { + background-color: rgba(255, 255, 255, 0.08); +} + +.store-tab.active:hover { + background: #ffffff; + color: #0b0f14; +} + +.store-close { + border-radius: 999px; +} + +.store-body { + flex: 1; + display: flex; + flex-direction: column; + overflow: hidden; +} + +#storeContent { + flex: 1; + margin-top: 8px; + overflow: auto; + padding: 12px 14px 14px 14px; +} + +.store-content-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); + gap: 14px; + align-content: flex-start; +} + +.store-provider-card { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 14px; + border-radius: 16px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); + cursor: pointer; + text-align: left; + transition: transform .18s ease, border-color .18s ease, background .18s ease; + position: relative; + overflow: hidden; + transform-origin: center; + backface-visibility: hidden; + contain: layout paint style; +} + +.store-provider-card:before { + content: ""; + position: absolute; + inset: 0; + background: linear-gradient(120deg, transparent 30%, rgba(255, 255, 255, 0.05), transparent 70%); + transform: translateX(-100%); + transition: transform .6s ease; +} + +.store-provider-card:hover:before { + transform: translateX(100%); +} + +.store-provider-card:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.14); + transform: scale(1.01); + box-shadow: none; +} + +.store-provider-logo { + width: 46px; + height: 46px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.06); + display: flex; + align-items: center; + justify-content: center; + overflow: hidden; + border: 1px solid rgba(255, 255, 255, 0.08); +} + +.store-provider-logo img { + width: 36px; + height: 36px; + object-fit: contain; + filter: none; +} + +.store-provider-logo-placeholder { + font-weight: 800; + font-size: 18px; + color: #e5edf7; +} + +.store-provider-body { + flex: 1; + min-width: 0; +} + +.store-provider-name { + font-size: 15px; + font-weight: 700; + color: #e6eef8; + letter-spacing: .2px; +} + +.store-provider-desc { + font-size: 12.5px; + color: #9aa3ad; + margin-top: 3px; + opacity: .9; +} + +.store-provider-chevron { + color: #aab3bf; + font-size: 13px; +} + +.store-provider-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + margin-bottom: 20px; +} + +.store-provider-header-main { + display: flex; + align-items: center; + gap: 12px; + flex: 1; + min-width: 0; + padding: 10px 12px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); +} + +.store-provider-header-logo { + width: 40px; + height: 40px; + object-fit: contain; +} + +.store-provider-header-name { + font-size: 16px; + font-weight: 800; + color: #e6eef8; +} + +.store-provider-header-desc { + font-size: 12.5px; + color: #9aa3ad; + margin-top: 2px; +} + +.store-back-btn { + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.06); + color: #e5edf7; + font-size: 12.5px; + padding: 8px 12px; + cursor: pointer; + display: flex; + align-items: center; + gap: 6px; +} + +.store-back-btn:hover { + background: rgba(255, 255, 255, 0.1); + transform: scale(1.03); +} + +.store-note { + font-size: 12.5px; + color: #9aa3ad; + margin-bottom: 16px; + padding-left: 2px; +} + +.store-version-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.store-version-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding: 12px 14px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + cursor: pointer; + transition: transform .12s ease, background .12s ease, border-color .12s ease; + transform-origin: center; + backface-visibility: hidden; + contain: layout paint style; +} + +.store-version-row:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.12); + transform: scale(1.01); + box-shadow: none; +} + +.store-version-meta { + min-width: 0; +} + +.store-version-name { + font-size: 14px; + font-weight: 700; + color: #e6eef8; +} + +.store-version-sub { + font-size: 12px; + color: #9aa3ad; + margin-top: 2px; +} + +.store-version-tags { + display: flex; + flex-wrap: wrap; + gap: 6px; + justify-content: flex-end; +} + +.store-version-row.store-custom-version-row { + align-items: stretch; + cursor: default; +} + +.store-version-row.store-custom-version-row:hover { + transform: none; +} + +.store-custom-version-form { + display: flex; + align-items: center; + gap: 8px; + min-width: min(100%, 360px); +} + +.store-custom-version-input { + width: 210px; + min-width: 0; + height: 38px; + border: 0; + border-radius: 10px; + background: rgba(255, 255, 255, 0.075); + color: #edf4ff; + padding: 0 12px; + outline: none; + font-size: 13px; +} + +.store-custom-version-input:focus { + background: rgba(255, 255, 255, 0.11); + box-shadow: inset 0 0 0 1px rgba(148, 163, 184, 0.28); +} + +.store-custom-version-btn { + height: 38px; + border: 0; + border-radius: 10px; + background: #ffffff; + color: #0b0f14; + padding: 0 13px; + font-size: 12.5px; + font-weight: 800; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 7px; + white-space: nowrap; +} + +.store-custom-version-btn:hover { + filter: brightness(0.94); +} + +.pill { + display: inline-flex; + align-items: center; + border-radius: 999px; + padding: 4px 9px; + font-size: 11px; + font-weight: 700; + letter-spacing: .3px; +} + +.pill-green { + background: rgba(16, 185, 129, 0.16); + color: #bbf7d0; + border: 1px solid rgba(16, 185, 129, 0.4); +} + +.pill-muted { + background: rgba(148, 163, 184, 0.16); + color: #e5e7eb; + border: 1px solid rgba(148, 163, 184, 0.45); +} + +.store-placeholder, +.store-empty, +.store-loading, +.store-error { + font-size: 13px; + color: #9aa3ad; + padding: 8px; +} + +.store-error { + color: #fecaca; +} + +.mr-plugins-root { + display: flex; + flex-direction: column; + height: 100%; + min-height: 0; +} + +.mr-plugins-header { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 18px; +} + +.mr-plugins-header input { + flex: 1; + padding: 11px 14px; + border-radius: 14px; + border: 1px solid rgba(255, 255, 255, 0.12); + background: rgba(0, 0, 0, 0.38); + color: #fff; + font-size: 13px; + outline: none; + transition: border-color .15s ease, background-color .15s ease; +} + +.mr-plugins-header input:focus { + border-color: rgba(255, 255, 255, 0.28); + background: rgba(0, 0, 0, 0.52); + box-shadow: none; +} + +.mr-plugins-header input::placeholder { + color: #9aa3ad; +} + +.mr-plugin-grid { + flex: 1; + display: grid; + grid-template-columns: repeat(auto-fill, minmax(224px, 1fr)); + gap: 14px; + align-content: flex-start; + overflow: auto; + padding: 2px 8px 8px 2px; + min-height: 0; +} + +.mr-plugin-card { + display: flex; + flex-direction: column; + border-radius: 14px; + background: + linear-gradient(180deg, rgba(255, 255, 255, 0.065), rgba(255, 255, 255, 0.03)), + rgba(7, 10, 15, 0.72); + border: 1px solid rgba(255, 255, 255, 0.08); + padding: 11px; + cursor: pointer; + transition: transform .14s ease, border-color .14s ease, background-color .14s ease; + position: relative; + transform-origin: center; + backface-visibility: hidden; + contain: layout paint style; + content-visibility: auto; + contain-intrinsic-size: 248px 260px; +} + +.mr-plugin-card:hover { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.14); + transform: scale(1.01); + box-shadow: none; + z-index: 1; +} + +.mr-plugin-icon { + width: 100%; + height: 140px; + border-radius: 12px; + object-fit: cover; + margin-bottom: 10px; + background: rgba(0, 0, 0, 0.55); + border: 1px solid rgba(255, 255, 255, 0.08); + box-shadow: none; +} + +.mr-plugin-icon-placeholder { + display: flex; + align-items: center; + justify-content: center; + color: rgba(255, 255, 255, 0.72); + font-size: 34px; +} + +.mr-plugin-body { + min-width: 0; +} + +.mr-plugin-title { + font-size: 14px; + font-weight: 700; + color: var(--text); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.mr-plugin-desc { + font-size: 12px; + color: var(--muted); + margin-top: 4px; + min-height: 32px; + line-height: 1.35; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; +} + +.mr-plugin-footer { + display: flex; + align-items: center; + justify-content: space-between; + margin-top: 10px; + gap: 6px; +} + +.mr-plugin-install-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 6px; + border-radius: 12px; + border: 0; + background: linear-gradient(135deg, #18c98d, #0ea574); + color: #03130d; + font-size: 12px; + padding: 8px 12px; + cursor: pointer; + white-space: nowrap; + font-weight: 800; + transition: transform .14s ease, background .14s ease; + transform-origin: center; + backface-visibility: hidden; + box-shadow: none; +} + +.mr-plugin-install-btn:hover { + background: linear-gradient(135deg, #24d99c, #12b981); + transform: scale(1.01); + box-shadow: none; +} + +.mr-plugin-toolbar-btn, +.mr-plugin-load-more { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 7px; +} + +.mr-plugin-load-more { + align-self: flex-start; + margin-top: 12px; + border-radius: 12px; +} + +.sectionTitle { + font-size: 15px; + margin-top: 8px; + font-weight: 700; + color: var(--text); +} + +.boxGrid { + margin-top: 10px; + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 10px; +} + +.selectBox { + background: #0e1116; + border-radius: 10px; + border: 1px solid rgba(255, 255, 255, 0.06); + padding: 10px; + font-size: 13px; + text-align: center; + cursor: pointer; + color: var(--text); + transition: background .1s ease, border-color .1s ease, transform .1s ease; +} + +.selectBox:hover { + background: #10141b; + border-color: rgba(255, 255, 255, 0.16); + transform: scale(1.01); + box-shadow: none; +} + +.selectBox.selected { + background: #022c22; + border-color: #10b981; + box-shadow: none; +} + +.downloadBtnFinal { + margin-top: 18px; + border-radius: 14px; + border: 0; + padding: 10px 14px; + font-size: 14px; + font-weight: 800; + cursor: pointer; + background: #3b82f6; + color: white; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + transition: transform .14s ease, background .14s ease, opacity .14s ease; + transform-origin: center; + backface-visibility: hidden; +} + +.downloadBtnFinal:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +#mrPluginModal .mr-plugin-install-modal { + width: min(620px, calc(100vw - 28px)); + max-width: calc(100vw - 28px); + height: auto; + min-height: 0; + max-height: calc(100dvh - 32px); + display: flex; + flex-direction: column; + background: rgba(12, 14, 20, 0.48); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 24px; + color: var(--text); + box-shadow: none; + overflow: hidden; +} + +#mrPluginModal.activity-modal.show .mr-plugin-install-modal { + background: rgba(12, 14, 20, 0.48); +} + +#mrPluginModal .mr-plugin-install-modal::before { + border-radius: 24px; + background: none; +} + +#mrPluginModal .activity-header { + padding: 24px 24px 18px; + border-bottom: 1px solid rgba(255, 255, 255, 0.07); + background: linear-gradient(180deg, rgba(255, 255, 255, 0.045), transparent); +} + +#mrPluginModal .activity-header-left { + min-width: 0; + gap: 14px; +} + +#mrPluginModal .mr-plugin-title-icon { + width: 42px; + height: 42px; + display: flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + color: rgba(255, 255, 255, 0.9); + font-size: 34px; +} + +#mrPluginModal .activity-title { + font-size: 22px; + font-weight: 700; + letter-spacing: -0.03em; +} + +#mrPluginModal .activity-body { + flex: 0 0 auto; + overflow: visible; + padding: 24px 24px 24px; + mask-image: none; + -webkit-mask-image: none; +} + +.mr-plugin-install-panel { + display: grid; + gap: 24px; + padding: 0; + border-radius: 0; + background: transparent; + border: 0; + box-shadow: none; +} + +.select-control { + display: flex; + flex-direction: column; + gap: 12px; +} + +.select-control label { + font-size: 13px; + color: rgba(156, 163, 175, 0.95); + font-weight: 600; + letter-spacing: 0.02em; + text-transform: uppercase; + margin-left: 2px; +} + +.select-wrap { + position: relative; + display: block; + background: linear-gradient(145deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0.03)); + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 16px; + padding: 0; + overflow: visible; + transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); + color-scheme: dark; + box-shadow: + 0 4px 12px rgba(0, 0, 0, 0.15), + inset 0 1px 0 rgba(255, 255, 255, 0.08); +} + +.select-wrap:hover, +.select-wrap:focus-within { + background: linear-gradient(145deg, rgba(255, 255, 255, 0.09), rgba(255, 255, 255, 0.05)); + border-color: rgba(96, 165, 250, 0.35); + box-shadow: + 0 6px 20px rgba(0, 0, 0, 0.2), + 0 0 0 3px rgba(96, 165, 250, 0.08), + inset 0 1px 0 rgba(255, 255, 255, 0.12); + transform: translateY(-1px); +} + +.select-wrap select { + appearance: none; + -webkit-appearance: none; + -moz-appearance: none; + width: 100%; + border: 0; + outline: none; + background: transparent; + color: rgba(255, 255, 255, 0.95); + padding: 14px 44px 14px 16px; + font-size: 14px; + font-weight: 500; + letter-spacing: 0.01em; + cursor: pointer; + border-radius: 16px; + transition: color 0.2s ease; +} + +.select-wrap select:disabled { + color: rgba(255, 255, 255, 0.45); + cursor: not-allowed; +} + +.select-wrap select option { + background: linear-gradient(145deg, rgba(20, 24, 32, 0.98), rgba(15, 18, 25, 0.98)); + color: rgba(255, 255, 255, 0.95); + padding: 14px 18px; + border-radius: 12px; + margin: 4px 8px; + font-weight: 500; + letter-spacing: 0.01em; + transition: all 0.2s ease; + border: 1px solid rgba(255, 255, 255, 0.06); +} + +.select-wrap select option:hover { + background: linear-gradient(145deg, rgba(96, 165, 250, 0.18), rgba(59, 130, 246, 0.12)); + color: rgba(255, 255, 255, 1); + border-color: rgba(96, 165, 250, 0.3); + transform: translateX(4px); +} + +.select-wrap select option:checked, +.select-wrap select option:focus { + background: linear-gradient(135deg, rgba(96, 165, 250, 0.25), rgba(59, 130, 246, 0.18)); + color: #ffffff; + border-color: rgba(96, 165, 250, 0.4); + box-shadow: + 0 4px 12px rgba(96, 165, 250, 0.2), + inset 0 1px 0 rgba(255, 255, 255, 0.1); +} + +.select-wrap select::-webkit-scrollbar { + width: 10px; +} + +.select-wrap select::-webkit-scrollbar-track { + background: rgba(0, 0, 0, 0.4); + border-radius: 12px; + margin: 6px 4px; + border: 1px solid rgba(255, 255, 255, 0.05); +} + +.select-wrap select::-webkit-scrollbar-thumb { + background: linear-gradient(180deg, rgba(96, 165, 250, 0.7), rgba(59, 130, 246, 0.6)); + border-radius: 12px; + border: 2px solid rgba(0, 0, 0, 0.3); + box-shadow: + 0 2px 8px rgba(96, 165, 250, 0.3), + inset 0 1px 0 rgba(255, 255, 255, 0.2); + transition: all 0.2s ease; +} + +.select-wrap select::-webkit-scrollbar-thumb:hover { + background: linear-gradient(180deg, rgba(96, 165, 250, 0.9), rgba(59, 130, 246, 0.8)); + box-shadow: + 0 4px 12px rgba(96, 165, 250, 0.5), + inset 0 1px 0 rgba(255, 255, 255, 0.3); +} + +.select-wrap i { + position: absolute; + right: 14px; + top: 0; + bottom: 0; + display: flex; + align-items: center; + pointer-events: none; + color: rgba(96, 165, 250, 0.7); + font-size: 13px; + transition: all 0.25s ease; +} + +.select-wrap:hover i { + color: rgba(96, 165, 250, 0.95); + transform: translateY(1px); +} + +#mrPluginModal .mr-plugin-install-footer { + padding: 18px 24px 24px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + background: rgba(255, 255, 255, 0.01); +} + +#mrPluginModal .mr-plugin-install-action { + min-width: 166px; + justify-content: center; + color: #ffffff; + background: rgba(59, 130, 246, 0.08); + border: 0; + font-weight: 500; + box-shadow: none; +} + +#mrPluginModal .mr-plugin-install-action:hover { + background: rgba(59, 130, 246, 0.12); + box-shadow: none; +} + +#mrPluginModal .mr-plugin-install-action:disabled { + opacity: .5; + color: rgba(255, 255, 255, 0.72); + background: rgba(255, 255, 255, 0.08); + box-shadow: none; + cursor: not-allowed; +} + +#mrPluginModal .mr-plugin-install-action.is-loading { + cursor: wait; +} + +.mr-title-sub { + max-width: 390px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.modal-overlay { + position: fixed; + left: 0; + top: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.45); + backdrop-filter: blur(6px); + -webkit-backdrop-filter: blur(6px); + display: none; + align-items: center; + justify-content: center; + z-index: 10000; +} + +.modal-overlay.show { + display: flex; +} + +.icon-btn { + border-radius: 10px; + border: none; + background: rgba(255, 255, 255, 0.04); + color: #e6eef8; + backdrop-filter: blur(10px); + padding: 8px 12px; + font-weight: 400; + cursor: pointer; + transition: all .15s ease; + outline: none; + box-shadow: none; +} + +.icon-btn:hover { + background: rgba(255, 255, 255, 0.10); + transform: translateY(-1px); +} + +.modal { + background: rgba(12, 14, 20, 0.82); + border: 0.5px solid rgba(255, 255, 255, 0.08); + border-radius: 18px; + backdrop-filter: blur(60px) saturate(150%); + -webkit-backdrop-filter: blur(60px) saturate(150%); + box-shadow: + 0 0 0 0.5px rgba(255, 255, 255, 0.04), + 0 20px 60px rgba(0, 0, 0, 0.3); +} + +.modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 14px 18px; + border-bottom: 0.5px solid rgba(255, 255, 255, 0.06); +} + +.modal-title { + font-weight: 800; + font-size: 16px; +} + +.modal-close { + background: rgba(255, 255, 255, 0.05); + border: 0.5px solid rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.6); + border-radius: 10px; + padding: 7px 9px; + cursor: pointer; + transition: all 0.15s ease; + font-size: 14px; +} + +.modal-close:hover { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.9); +} + +.modal-body { + padding: 12px 14px; + min-height: 0 !important; +} + +.topbar .icon-btn { + font-weight: 400 +} + +.window-header .dot { + width: 12px; + height: 12px; + border-radius: 50%; + display: inline-block +} + +.stop-button { + background: linear-gradient(90deg, #ef4444, #7f1d1d); + color: #fff; +} + +.kill-button { + background: #ff0000; + color: #fff; +} + +.run-button, +.stop-button, +.kill-button { + transition: transform .15s ease, filter .15s ease, box-shadow .15s ease; +} + +.run-button:hover, +.stop-button:hover, +.kill-button:hover { + transform: none; + filter: brightness(1.04); + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15); +} + +.jump-btn { + position: fixed; + right: 32px; + bottom: 90px; + z-index: 20; + padding: 6px 10px; + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.12); + background: rgba(0, 0, 0, 0.45); + color: #fff; + cursor: pointer; + backdrop-filter: blur(2px); + opacity: 0; + visibility: hidden; + transform: translateY(6px); + transition: opacity .15s ease, transform .15s ease, visibility 0s linear .15s; +} + +.jump-btn:hover { + background: rgba(0, 0, 0, 0.6); +} + +.jump-btn i { + pointer-events: none; +} + +.jump-btn.show { + opacity: 1; + visibility: visible; + transform: translateY(0); + transition: opacity .15s ease, transform .15s ease, visibility 0s; +} + +.command:focus { + outline: none; + border: none; + box-shadow: none; +} + +.sidebar-toggle { + position: fixed; + left: 25px; + top: 12px; + width: 48px; + height: 48px; + display: grid; + place-items: center; + border-radius: 14px; + border: none; + outline: none; + background-color: rgba(255, 255, 255, 0.045); + backdrop-filter: blur(5px); + box-shadow: 0 12px 28px rgba(0, 0, 0, 0.45); + color: #e6eef8; + cursor: pointer; + z-index: 2300; + transition: transform .18s ease, background .18s ease, box-shadow .18s ease; + transform: scale(1); +} + +.sidebar-toggle i { + font-size: 18px; +} + +.sidebar-toggle.active { + transform: scale(0.9); + background-color: rgba(255, 255, 255, 0.045); + box-shadow: 0 8px 20px rgba(0, 0, 0, 0.42); +} + +.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; +} + +.sidebar-shell * { + box-sizing: border-box !important; +} + +#dockfiless { + color: rgba(255, 255, 255, 0.896); + background: blurred; +} + +.sidebar-shell.open { + opacity: 1; + pointer-events: auto; +} + +.sidebar-shell.open:hover { + width: 220px !important; +} + +.sidebar-top { + padding-bottom: 6px; + border-bottom: 1px solid rgba(255, 255, 255, 0.05); + margin: 0 9px; +} + +.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); +} + +.sidebar-shell.open:hover .sidebar-item:hover { + background: rgba(255, 255, 255, 0.05); + transform: translateY(-1px); +} + +.sidebar-item.active { + color: #b4f0d8; +} + +.profile-card { + width: 100%; + display: flex; + align-items: center; + gap: 10px; + padding: 9px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.05); + color: #e3e9f3; + cursor: pointer; + transition: background .15s ease, border-color .15s ease; +} + +.profile-card:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.1); +} + +.profile-card .icon { + width: 34px; + height: 34px; + border-radius: 12px; + display: grid; + place-items: center; + background: transparent; + color: #60a5fa; + box-shadow: none; + flex-shrink: 0; +} + +.profile-card img { + width: 34px !important; + height: 34px !important; + border-radius: 50% !important; + object-fit: cover; +} + +.profile-meta { + display: flex; + flex-direction: column; + gap: 4px; + text-align: left; +} + +.profile-email { + font-weight: 700; + font-size: 13px; + color: #e9eef7; + max-width: 150px; + overflow: hidden; + text-overflow: ellipsis; +} + +.profile-status { + display: flex; + align-items: center; + gap: 6px; + color: #9fb1c7; + font-size: 12px; +} + +.status-dot { + width: 10px; + height: 10px; + border-radius: 999px; + background: #22c55e; + box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.35); +} + +.status-popover { + position: absolute; + left: 70px; + bottom: 6px; + width: 220px; + background: rgba(8, 12, 18, 0.98); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 12px; + padding: 12px 12px 10px 12px; + box-shadow: 0 18px 38px rgba(0, 0, 0, 0.55); + display: none; + flex-direction: column; + gap: 10px; + z-index: 2400; +} + +.status-popover.show { + display: flex; +} + +.status-popover label { + font-size: 12px; + color: #9fb1c7; + margin-bottom: 4px; + display: block; +} + +.status-popover input { + width: 100%; + padding: 8px 10px; + border-radius: 10px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.04); + color: #e6eef8; + font-size: 13px; + box-sizing: border-box; +} + +.custom-select-wrapper { + position: relative; + user-select: none; +} + +.custom-select { + position: relative; + width: 100%; + padding: 6px 32px 6px 10px; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.04); + color: #e6eef8; + font-size: 13px; + cursor: pointer; + transition: all 0.15s ease; + display: flex; + align-items: center; + justify-content: space-between; + box-sizing: border-box; +} + +.custom-select:hover { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.15); +} + +.custom-select.open { + border-color: rgba(255, 255, 255, 0.25); + background: rgba(255, 255, 255, 0.1); + border-bottom-left-radius: 0; + border-bottom-right-radius: 0; +} + +.custom-select .arrow { + position: absolute; + right: 10px; + top: 50%; + transform: translateY(-50%); + width: 14px; + height: 14px; + background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e"); + background-repeat: no-repeat; + background-position: center; + transition: transform 0.2s ease; +} + +.custom-select.open .arrow { + transform: translateY(-50%) rotate(180deg); +} + +.custom-options { + position: absolute; + top: 100%; + left: 0; + right: 0; + background: rgba(15, 18, 25, 0.98); + border: 1px solid rgba(255, 255, 255, 0.1); + border-top: none; + border-bottom-left-radius: 12px; + border-bottom-right-radius: 12px; + box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5); + z-index: 2500; + display: none; + max-height: 200px; + overflow-y: auto; + backdrop-filter: blur(10px); + scrollbar-width: none; + -ms-overflow-style: none; +} + +.custom-options::-webkit-scrollbar { + display: none; +} + +.custom-options.show { + display: block; +} + +.custom-option, +.option { + padding: 8px 10px; + font-size: 13px; + color: #e6eef8; + cursor: pointer; + transition: background 0.1s ease; +} + +.custom-option:hover, +.option:hover { + background: rgba(255, 255, 255, 0.1); +} + +.custom-option.selected, +.option.selected { + background: rgba(99, 102, 241, 0.2); + color: #fff; + font-weight: 600; +} + +#statusDuration { + background: #000; + color: #fff; +} + +.status-actions { + display: flex; + gap: 8px; + justify-content: flex-end; +} + +.status-actions button { + padding: 8px 12px; + border-radius: 10px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.05); + color: var(--text); + cursor: pointer; + transition: background .12s ease, border-color .12s ease; +} + +.status-actions button.save { + background: rgba(0, 153, 255, 0.14); + color: #b4f0d8; +} + +.status-actions button:hover { + background: rgb(2, 94, 255) +} + +.resource-stats-popup { + position: fixed; + top: 75px; + left: 75px; + width: 300px; + background: linear-gradient(135deg, rgba(15, 20, 30, 0.92) 0%, rgba(10, 15, 25, 0.95) 100%); + -webkit-backdrop-filter: blur(12px) saturate(180%); + backdrop-filter: blur(12px) saturate(180%); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 16px; + box-shadow: + 0 20px 50px rgba(0, 0, 0, 0.5), + 0 0 0 1px rgba(255, 255, 255, 0.05), + inset 0 1px 0 rgba(255, 255, 255, 0.05); + padding: 0; + opacity: 0; + 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; + isolation: isolate; + transform: translateY(10px); +} + +.resource-stats-popup.visible { + opacity: 1; + visibility: visible; + pointer-events: auto; + transform: translateY(0); +} + +.resource-stats-popup.sidebar-expanded { + left: 245px; +} + +.resource-stats-header { + display: flex; + align-items: center; + justify-content: space-between; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.04) 0%, transparent 100%); + padding: 16px 18px; + border-bottom: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 16px 16px 0 0; +} + +.resource-stats-title { + display: flex; + align-items: center; + gap: 10px; + font-size: 14px; + font-weight: 700; + color: #f1f5f9; + text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3); + letter-spacing: 0.3px; +} + +.resource-stats-title i { + font-size: 15px; + color: #a78bfa; + filter: drop-shadow(0 0 4px rgba(167, 139, 250, 0.4)); +} + +.statusinputs:focus { + outline: none; + border: none; +} + +.resource-stats-close { + width: 28px; + height: 28px; + display: grid; + place-items: center; + background: rgba(255, 255, 255, 0.06); + border: none; + outline: none; + color: #94a3b8; + cursor: pointer; + border-radius: 8px; + transition: all 0.15s ease; + font-size: 12px; +} + +.resource-stats-close:hover { + color: #f1f5f9; + background: rgba(239, 68, 68, 0.2); + border-color: rgba(239, 68, 68, 0.4); + transform: none; +} + +.resource-stats-body { + padding: 14px 18px 18px; + display: flex; + flex-direction: column; + gap: 12px; +} + +.resource-stat-row { + display: flex; + align-items: center; + gap: 12px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.05); + padding: 12px 14px; + border-radius: 12px; + transition: background 0.15s ease, border-color 0.15s ease; +} + +.resource-stat-row:hover { + background: rgba(255, 255, 255, 0.05); + border-color: rgba(255, 255, 255, 0.08); +} + +.resource-stat-icon { + width: 40px; + height: 40px; + border-radius: 10px; + display: grid; + place-items: center; + font-size: 16px; + flex-shrink: 0; + box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); +} + +.resource-stat-icon.memory-icon { + background: linear-gradient(135deg, rgba(167, 139, 250, 0.2) 0%, rgba(139, 92, 246, 0.25) 100%); + color: #a78bfa; +} + +.resource-stat-icon.disk-icon { + background: linear-gradient(135deg, rgba(74, 222, 128, 0.2) 0%, rgba(34, 197, 94, 0.25) 100%); + color: #4ade80; +} + +.resource-stat-icon.cpu-icon { + background: linear-gradient(135deg, rgba(96, 165, 250, 0.2) 0%, rgba(59, 130, 246, 0.25) 100%); + color: #60a5fa; +} + +.resource-stat-icon.network-inbound-icon { + background: linear-gradient(135deg, rgba(34, 211, 238, 0.18) 0%, rgba(14, 165, 233, 0.24) 100%); + color: #22d3ee; +} + +.resource-stat-icon.network-outbound-icon { + background: linear-gradient(135deg, rgba(251, 113, 133, 0.18) 0%, rgba(244, 63, 94, 0.24) 100%); + color: #fb7185; +} + +.resource-stat-icon.uptime-icon { + background: linear-gradient(135deg, rgba(251, 191, 36, 0.2) 0%, rgba(245, 158, 11, 0.25) 100%); + color: #fbbf24; +} + +.resource-stat-info { + flex: 1; + min-width: 0; +} + +.resource-stat-label { + font-size: 10px; + color: #64748b; + text-transform: uppercase; + letter-spacing: 0.8px; + font-weight: 600; + margin-bottom: 4px; +} + +.resource-stat-value { + font-size: 14px; + 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; + flex-shrink: 0; +} + +.resource-stat-fill { + height: 100%; + border-radius: 3px; + transition: width 0.3s ease; +} + +.resource-stat-fill.memory-fill { + background: linear-gradient(90deg, #a78bfa, #8b5cf6); + box-shadow: 0 0 8px rgba(167, 139, 250, 0.4); +} + +.resource-stat-fill.disk-fill { + background: linear-gradient(90deg, #4ade80, #22c55e); + box-shadow: 0 0 8px rgba(74, 222, 128, 0.4); +} + +.resource-stat-fill.cpu-fill { + background: linear-gradient(90deg, #60a5fa, #3b82f6); + box-shadow: 0 0 8px rgba(96, 165, 250, 0.4); +} + + +.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; +} + +.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; +} + +.sidebar-shell.open:hover .profile-meta { + max-width: 200px; + opacity: 1; +} + +.notfound-modal { + position: fixed; + inset: 0; + display: none; + align-items: center; + justify-content: center; + z-index: 999999; +} + +.notfound-modal.show, +#offlineOverlay.show { + display: flex; +} + +.notfound-glass-layer { + position: absolute; + inset: 0; + pointer-events: none; +} + +.notfound-glass-layer-1 { + background: rgba(0, 0, 0, 0.85); + backdrop-filter: blur(40px) saturate(150%); + -webkit-backdrop-filter: blur(40px) saturate(150%); + opacity: 0; + animation: notfoundFadeIn 0.4s cubic-bezier(0.16, 1, 0.3, 1) forwards; +} + +.notfound-glass-layer-2 { + background: radial-gradient(ellipse at center, rgba(99, 102, 241, 0.08) 0%, transparent 70%); + opacity: 0; + animation: notfoundFadeIn 0.5s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +@keyframes notfoundFadeIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +.notfound-panel { + position: relative; + width: 90vw; + max-width: 480px; + background: rgba(15, 18, 25, 0.95); + border-radius: 24px; + overflow: hidden; + opacity: 0; + transform: scale(0.95); + animation: notfoundPanelIn 0.4s cubic-bezier(0.16, 1, 0.3, 1) 0.15s forwards; +} + +@keyframes notfoundPanelIn { + from { + opacity: 0; + transform: scale(0.95); + } + + to { + opacity: 1; + transform: scale(1); + } +} + +.notfound-panel:hover { + transform: scale(1.02); + transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.notfound-content { + display: flex; + flex-direction: column; + align-items: center; + padding: 48px 40px; + text-align: center; +} + +.notfound-robot { + margin-bottom: 24px; +} + +.notfound-robot-img { + width: 140px; + height: auto; + opacity: 0.9; + filter: drop-shadow(0 0 20px rgba(99, 102, 241, 0.2)); +} + +.notfound-text { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 32px; +} + +.notfound-code { + font-size: 72px; + font-weight: 800; + letter-spacing: -0.04em; + background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(255, 255, 255, 0.5) 100%); + -webkit-background-clip: text; + -webkit-text-fill-color: transparent; + background-clip: text; + line-height: 1; +} + +.notfound-title { + font-size: 24px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.02em; +} + +.notfound-desc { + font-size: 14px; + color: rgba(255, 255, 255, 0.5); + line-height: 1.5; + max-width: 320px; +} + +.notfound-actions { + display: flex; + gap: 12px; +} + +.notfound-btn-primary { + display: inline-flex; + align-items: center; + gap: 10px; + padding: 14px 28px; + background: linear-gradient(135deg, rgba(99, 102, 241, 0.9) 0%, rgba(79, 70, 229, 0.9) 100%); + color: #fff; + font-size: 14px; + font-weight: 600; + border-radius: 14px; + text-decoration: none; + transition: transform 0.2s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.2s ease; +} + +.notfound-btn-primary:hover { + transform: none; + opacity: 0.95; +} + +.notfound-btn-primary:active { + transform: scale(0.98); +} + +.notfound-btn-primary i { + font-size: 15px; +} + +body>svg:first-child { + position: absolute; + width: 0; + height: 0; + pointer-events: none; +} + +body { + background: var(--ui-bg) center/cover no-repeat fixed !important; +} + + +.activity-modal { + position: fixed; + inset: 0; + display: none; + align-items: center; + justify-content: center; + z-index: 100000; + perspective: 1200px; +} + +.activity-modal.show { + display: flex; +} + +.activity-glass-layer { + position: absolute; + inset: 0; + pointer-events: none; +} + +.activity-glass-layer-1 { + + opacity: 0; + animation: glassLayer1In 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; +} + +.activity-glass-layer-3 { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 30%, transparent 70%, rgba(255, 255, 255, 0.01) 100%); + opacity: 0; + backdrop-filter: blur(5px); + animation: glassLayer3In 0.7s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +@keyframes glassLayer1In { + from { + opacity: 0; + filter: blur(20px); + } + + to { + opacity: 1; + filter: blur(0); + } +} + +@keyframes glassLayer2In { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes glassLayer3In { + from { + opacity: 0; + filter: blur(10px); + } + + to { + opacity: 1; + filter: blur(0); + } +} + +.activity-panel { + position: relative; + width: 94vw; + max-width: 920px; + height: 88vh; + max-height: 860px; + display: flex; + flex-direction: column; + backdrop-filter: blur(80px) saturate(100%) brightness(1.05); + -webkit-backdrop-filter: blur(80px) saturate(200%) brightness(1.05); + border-radius: 28px; + overflow: hidden; + opacity: 0; + transform: scale(0.92) rotateX(8deg); + animation: panelLiquidIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.activity-panel::before { + content: ''; + position: absolute; + inset: 0; + border-radius: 28px; + padding: 1px; + -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; + pointer-events: none; + opacity: 0; + animation: borderGlowIn 0.8s cubic-bezier(0.16, 1, 0.3, 1) 0.3s forwards; +} + + +@keyframes panelLiquidIn { + from { + opacity: 0; + transform: scale(0.92) rotateX(8deg); + filter: blur(4px); + } + + to { + opacity: 1; + transform: scale(1) rotateX(0); + filter: blur(0); + } +} + +@keyframes borderGlowIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes innerGlowIn { + from { + opacity: 0; + width: 30%; + } + + to { + opacity: 1; + width: 60%; + } +} + +.activity-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 24px 28px 20px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.04), transparent); +} + +.activity-header-left { + display: flex; + align-items: center; + gap: 18px; +} + +.activity-icon-wrap { + position: relative; + width: 52px; + height: 52px; + display: flex; + align-items: center; + justify-content: center; +} + +.activity-icon-pulse { + position: absolute; + inset: 0; + border-radius: 16px; + background: linear-gradient(135deg, rgba(167, 139, 250, 0.15), rgba(139, 92, 246, 0.08)); + opacity: 0.5; + animation: iconPulse 3s ease-in-out infinite; +} + +@keyframes iconPulse { + + 0%, + 100% { + transform: scale(1); + opacity: 0.4; + filter: blur(0); + } + + 50% { + transform: scale(1.15); + opacity: 0.15; + filter: blur(4px); + } +} + +.activity-icon { + position: relative; + width: 52px; + height: 52px; + border-radius: 16px; + background: linear-gradient(135deg, rgba(167, 139, 250, 0.12), rgba(139, 92, 246, 0.06)); + display: flex; + align-items: center; + justify-content: center; + font-size: 22px; + color: rgba(255, 255, 255, 0.85); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} + +.activity-icon i { + color: white; +} + +.activity-header-text { + display: flex; + flex-direction: column; + gap: 4px; +} + +.activity-entry-icon i { + color: white; +} + +.activity-title { + font-size: 22px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.03em; + opacity: 0; + animation: textFadeIn 0.4s ease 0.2s forwards; +} + +.activity-subtitle { + font-size: 13px; + color: rgba(255, 255, 255, 0.45); + opacity: 0; + animation: textFadeIn 0.4s ease 0.3s forwards; +} + +.activity-server-name { + color: rgba(255, 255, 255, 0.75); + font-weight: 600; +} + +@keyframes textFadeIn { + from { + opacity: 0; + filter: blur(4px); + } + + to { + opacity: 1; + filter: blur(0); + } +} + +.activity-close { + width: 44px; + height: 44px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.6); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + border: none; + opacity: 0; + animation: closeButtonIn 0.4s ease 0.35s forwards; +} + +@keyframes closeButtonIn { + from { + opacity: 0; + transform: scale(0.8); + } + + to { + opacity: 1; + transform: scale(1); + } +} + +.activity-close-icon { + display: flex; + transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.activity-close:hover { + background: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.9); +} + +.activity-close:hover .activity-close-icon { + transform: rotate(90deg); +} + +.activity-close:active { + transform: scale(0.94); +} + +.activity-search-wrap { + padding: 0 28px 16px; + display: flex; + align-items: center; + gap: 12px; + opacity: 0; + animation: searchWrapIn 0.5s cubic-bezier(0.16, 1, 0.3, 1) 0.25s forwards; +} + +@keyframes searchWrapIn { + from { + opacity: 0; + filter: blur(4px); + } + + to { + opacity: 1; + filter: blur(0); + } +} + +.activity-search { + flex: 1; + position: relative; + display: flex; + align-items: center; + gap: 12px; + padding: 0 16px; + height: 46px; + background: rgba(255, 255, 255, 0.04); + border-radius: 14px; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.activity-search i { + color: rgba(255, 255, 255, 0.35); + font-size: 14px; + transition: color 0.3s ease; +} + +.activity-search:focus-within { + background: rgba(255, 255, 255, 0.08); +} + +.activity-search:focus-within i { + color: rgba(255, 255, 255, 0.6); +} + +#activitySearchInput { + flex: 1; + background: transparent !important; + background-color: transparent !important; + background-image: none !important; + border: none !important; + outline: none !important; + box-shadow: none !important; + color: rgba(255, 255, 255, 0.9) !important; + font-size: 14px; + font-weight: 500; + appearance: none !important; + -webkit-appearance: none !important; + border-radius: 0 !important; + padding: 0 !important; + margin: 0 !important; + backdrop-filter: none !important; +} + +#activitySearchInput:-webkit-autofill, +#activitySearchInput:-webkit-autofill:hover, +#activitySearchInput:-webkit-autofill:focus, +#activitySearchInput:-webkit-autofill:active { + transition: background-color 5000s ease-in-out 0s; + -webkit-text-fill-color: #e6eef8 !important; +} + +.activity-search input::placeholder { + color: rgba(255, 255, 255, 0.3); +} + +.activity-filter-pills { + display: flex; + align-items: center; + gap: 6px; +} + +.activity-pill { + padding: 10px 14px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.5); + font-size: 12px; + font-weight: 600; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + border: none; +} + +.activity-pill i { + font-size: 11px; +} + +.activity-pill:hover { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.7); +} + +.activity-pill.active { + background: linear-gradient(135deg, rgba(92, 55, 204, 0.849), rgba(139, 92, 246, 0.06)); + color: rgba(255, 255, 255, 0.8); +} + +.activity-body { + flex: 1; + overflow-y: auto; + padding: 8px 28px 16px; + min-height: 0; + mask-image: linear-gradient(to bottom, transparent, #000 16px, #000 calc(100% - 16px), transparent); + -webkit-mask-image: linear-gradient(to bottom, transparent, #000 16px, #000 calc(100% - 16px), transparent); +} + +.activity-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.activity-loading { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + padding: 60px; + color: rgba(255, 255, 255, 0.45); + font-size: 14px; + font-weight: 500; +} + +.activity-loading-spinner { + width: 36px; + height: 36px; + border-radius: 50%; + background: conic-gradient(from 0deg, transparent, rgba(255, 255, 255, 0.35)); + animation: spinnerRotate 1s linear infinite; + position: relative; +} + +.activity-loading-spinner::before { + content: ''; + position: absolute; + inset: 3px; + border-radius: 50%; + background: rgba(10, 10, 15, 0.8); +} + +@keyframes spinnerRotate { + to { + transform: rotate(360deg); + } +} + +.activity-empty { + text-align: center; + padding: 80px 20px; + color: rgba(255, 255, 255, 0.35); +} + +.activity-empty i { + font-size: 52px; + margin-bottom: 20px; + opacity: 0.4; + display: block; +} + +.activity-empty p { + font-size: 15px; + font-weight: 500; + margin: 0; +} + +.activity-entry { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 18px 20px; + background: rgba(255, 255, 255, 0.03); + border-radius: 16px; + transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1); + opacity: 0; + animation: entrySlideIn 0.5s cubic-bezier(0.16, 1, 0.3, 1) forwards; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} + +.activity-entry:nth-child(1) { + animation-delay: 0.05s; +} + +.activity-entry:nth-child(2) { + animation-delay: 0.1s; +} + +.activity-entry:nth-child(3) { + animation-delay: 0.15s; +} + +.activity-entry:nth-child(4) { + animation-delay: 0.2s; +} + +.activity-entry:nth-child(5) { + animation-delay: 0.25s; +} + +.activity-entry:nth-child(6) { + animation-delay: 0.3s; +} + +.activity-entry:nth-child(7) { + animation-delay: 0.35s; +} + +.activity-entry:nth-child(8) { + animation-delay: 0.4s; +} + +.activity-entry:nth-child(9) { + animation-delay: 0.45s; +} + +.activity-entry:nth-child(10) { + animation-delay: 0.5s; +} + +@keyframes entrySlideIn { + from { + opacity: 0; + transform: scale(0.96); + filter: blur(4px); + } + + to { + opacity: 1; + transform: scale(1); + filter: blur(0); + } +} + +.activity-entry:hover { + background: rgba(255, 255, 255, 0.06); +} + +.activity-entry-icon { + width: 42px; + height: 42px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + flex-shrink: 0; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.activity-entry:hover .activity-entry-icon { + transform: scale(1.08); +} + +.activity-entry-icon.console { + background: linear-gradient(135deg, rgba(96, 165, 250, 0.1), rgba(59, 130, 246, 0.05)); + color: rgba(147, 197, 253, 0.75); +} + +.activity-entry-icon.start { + background: linear-gradient(135deg, rgba(16, 185, 129, 0.2), rgba(5, 150, 105, 0.1)); + color: #6ee7b7; +} + +.activity-entry-icon.stop { + background: linear-gradient(135deg, rgba(249, 115, 22, 0.2), rgba(234, 88, 12, 0.1)); + color: #fdba74; +} + +.activity-entry-icon.restart { + background: linear-gradient(135deg, rgba(168, 85, 247, 0.1), rgba(147, 51, 234, 0.05)); + color: rgba(216, 180, 254, 0.75); +} + +.activity-entry-icon.kill { + background: linear-gradient(135deg, rgba(239, 68, 68, 0.2), rgba(220, 38, 38, 0.1)); + color: #fca5a5; +} + +.activity-entry-icon.file { + background: linear-gradient(135deg, rgba(251, 191, 36, 0.2), rgba(245, 158, 11, 0.1)); + color: #fde68a; +} + +.activity-entry-content { + flex: 1; + min-width: 0; +} + +.activity-entry-action { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); + margin-bottom: 6px; + letter-spacing: -0.01em; +} + +.activity-entry-details { + font-size: 12.5px; + color: rgba(255, 255, 255, 0.5); + word-break: break-word; + margin-bottom: 10px; + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Consolas', monospace; + background: rgba(0, 0, 0, 0.25); + padding: 10px 14px; + border-radius: 10px; + line-height: 1.5; +} + +.activity-entry-meta { + display: flex; + flex-wrap: wrap; + gap: 12px; + font-size: 12px; + color: rgba(255, 255, 255, 0.35); +} + +.activity-entry-meta span { + display: flex; + align-items: center; + gap: 15px; +} + +.activity-entry-meta i { + font-size: 10px; + opacity: 0.6; +} + +.activity-footer { + padding: 16px 28px 20px; + display: flex; + justify-content: center; + background: linear-gradient(0deg, rgba(0, 0, 0, 0.2), transparent); +} + +.activity-load-more { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 28px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.7); + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + border: none; +} + +.activity-load-more:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.9); +} + +.activity-load-more:hover .activity-load-more-icon { + animation: bounceDown 0.6s ease infinite; +} + +@keyframes bounceDown { + + 0%, + 100% { + transform: scale(1); + } + + 50% { + transform: scale(1.15); + } +} + +.activity-load-more:active { + transform: scale(0.97); +} + +.activity-load-more:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.activity-load-more:disabled:hover { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.7); +} + +.activity-load-more:disabled:hover .activity-load-more-icon { + animation: none; +} + +.activity-load-more-text { + letter-spacing: 0.02em; +} + +.activity-load-more-icon { + font-size: 11px; + transition: transform 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +@media (max-width: 768px) { + .activity-panel { + width: 100%; + height: 100%; + max-height: 100%; + border-radius: 0; + } + + .activity-panel::before { + border-radius: 0; + } + + .activity-header { + padding: 20px 20px 16px; + } + + .activity-search-wrap { + padding: 0 20px 14px; + flex-direction: column; + gap: 10px; + } + + .activity-search { + width: 100%; + } + + .activity-filter-pills { + width: 100%; + overflow-x: auto; + padding-bottom: 4px; + } + + .activity-body { + padding: 8px 20px 16px; + } + + .activity-footer { + padding: 14px 20px 18px; + } + + .activity-entry { + padding: 14px 16px; + } + + .activity-icon-wrap { + width: 44px; + height: 44px; + } + + .activity-icon { + width: 44px; + height: 44px; + font-size: 18px; + } + + .activity-title { + font-size: 18px; + } +} + + +.info-modal { + position: fixed; + inset: 0; + display: none; + align-items: center; + justify-content: center; + z-index: 100000; + perspective: 1200px; +} + +.info-modal.show { + display: flex; +} + +.info-glass-layer { + position: absolute; + inset: 0; + pointer-events: none; +} + +.info-glass-layer-1 { + opacity: 0; + animation: glassLayer1In 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; +} + +.info-glass-layer-2 { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.015) 0%, transparent 40%); + opacity: 0; + animation: glassLayer2In 0.5s ease 0.1s forwards; +} + +.info-glass-layer-3 { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 30%, transparent 70%, rgba(255, 255, 255, 0.01) 100%); + opacity: 0; + backdrop-filter: blur(5px); + animation: glassLayer3In 0.7s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.info-panel { + position: relative; + width: 94vw; + max-width: 580px; + max-height: 88vh; + display: flex; + flex-direction: column; + backdrop-filter: blur(80px) saturate(100%) brightness(1.05); + -webkit-backdrop-filter: blur(80px) saturate(200%) brightness(1.05); + border-radius: 28px; + overflow: hidden; + opacity: 0; + transform: scale(0.92) rotateX(8deg); + animation: panelLiquidIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.info-inner-glow { + position: absolute; + top: 0; + left: 50%; + transform: translateX(-50%); + width: 60%; + height: 1px; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent); + opacity: 0; + animation: innerGlowIn 0.8s ease 0.4s forwards; +} + +.info-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 24px 28px 20px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.04), transparent); +} + +.info-header-left { + display: flex; + align-items: center; + gap: 18px; +} + +.info-icon-wrap { + position: relative; + width: 52px; + height: 52px; + display: flex; + align-items: center; + justify-content: center; +} + +.info-icon-pulse { + position: absolute; + inset: 0; + border-radius: 16px; + background: linear-gradient(135deg, rgba(96, 165, 250, 0.15), rgba(59, 130, 246, 0.08)); + opacity: 0.5; + animation: iconPulse 3s ease-in-out infinite; +} + +.info-icon { + width: 52px; + height: 52px; + border-radius: 16px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(145deg, rgba(255, 255, 255, 0.12), rgba(255, 255, 255, 0.04)); + backdrop-filter: blur(20px); + font-size: 22px; + color: rgba(147, 197, 253, 0.9); + position: relative; + z-index: 1; +} + +.info-header-text { + display: flex; + flex-direction: column; + gap: 4px; +} + +.info-title { + font-size: 20px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.02em; +} + +.info-subtitle { + font-size: 13px; + color: rgba(255, 255, 255, 0.45); + font-weight: 500; +} + +.info-server-name { + color: rgba(255, 255, 255, 0.7); + font-weight: 600; +} + +.info-close { + width: 40px; + height: 40px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.06); + border: none; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.info-close:hover { + background: rgba(255, 255, 255, 0.12); + transform: scale(1.05); +} + +.info-close:active { + transform: scale(0.95); +} + +.info-close-icon { + font-size: 16px; + color: rgba(255, 255, 255, 0.6); + transition: color 0.2s ease; +} + +.info-close:hover .info-close-icon { + color: rgba(255, 255, 255, 0.9); +} + +.info-body { + flex: 1; + overflow-y: auto; + padding: 8px 28px 24px; + display: flex; + flex-direction: column; + gap: 20px; +} + +.info-section { + background: rgba(255, 255, 255, 0.025); + border-radius: 18px; + padding: 20px; +} + +.info-section-title { + display: flex; + align-items: center; + gap: 10px; + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); + margin-bottom: 16px; + letter-spacing: 0.02em; +} + +.info-section-title i { + font-size: 14px; + color: rgba(147, 197, 253, 0.7); +} + +.info-grid { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 12px; +} + +.info-card { + display: flex; + align-items: center; + gap: 14px; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.03); + border-radius: 14px; + transition: all 0.3s ease; + position: relative; +} + +.info-card:hover { + background: rgba(255, 255, 255, 0.06); +} + +.info-card-icon { + width: 40px; + height: 40px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, rgba(96, 165, 250, 0.12), rgba(59, 130, 246, 0.06)); + color: rgba(147, 197, 253, 0.8); + font-size: 15px; + flex-shrink: 0; +} + +.info-card-content { + flex: 1; + min-width: 0; +} + +.info-card-label { + font-size: 11px; + font-weight: 500; + color: rgba(255, 255, 255, 0.4); + text-transform: uppercase; + letter-spacing: 0.05em; + margin-bottom: 4px; +} + +.info-card-value { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); + word-break: break-all; + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Consolas', monospace; +} + +.info-card-copy { + width: 32px; + height: 32px; + border-radius: 8px; + background: rgba(255, 255, 255, 0.06); + border: none; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + color: rgba(255, 255, 255, 0.5); + font-size: 12px; + transition: all 0.2s ease; + flex-shrink: 0; +} + +.info-card-copy:hover { + background: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.9); +} + +.info-card-copy:active { + transform: scale(0.9); +} + +.info-address-row { + margin-top: 16px; + padding-top: 16px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.info-address-label { + font-size: 11px; + font-weight: 500; + color: rgba(255, 255, 255, 0.4); + text-transform: uppercase; + letter-spacing: 0.05em; + margin-bottom: 10px; +} + +.info-address-wrap { + display: flex; + gap: 10px; + align-items: center; +} + +.info-address-input { + flex: 1; + padding: 14px 16px; + border-radius: 12px; + background: rgba(0, 0, 0, 0.3); + color: rgba(255, 255, 255, 0.95); + border: 1px solid rgba(255, 255, 255, 0.06); + outline: none; + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Consolas', monospace; + font-size: 14px; + font-weight: 500; +} + +.info-address-input:focus { + border-color: rgba(96, 165, 250, 0.4); +} + +.info-copy-btn { + width: 48px; + height: 48px; + border-radius: 12px; + background: linear-gradient(135deg, rgba(16, 185, 129, 0.2), rgba(5, 150, 105, 0.15)); + border: none; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + color: #6ee7b7; + font-size: 16px; + transition: all 0.3s ease; +} + +.info-copy-btn:hover { + background: linear-gradient(135deg, rgba(16, 185, 129, 0.35), rgba(5, 150, 105, 0.25)); + transform: scale(1.05); +} + +.info-copy-btn:active { + transform: scale(0.95); +} + +.info-address-hint { + margin-top: 10px; + font-size: 12px; + color: rgba(255, 255, 255, 0.35); +} + +.info-sftp-section { + background: rgba(255, 255, 255, 0.02); +} + +.info-sftp-badge { + margin-left: auto; + padding: 4px 10px; + border-radius: 6px; + background: linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(5, 150, 105, 0.1)); + color: #6ee7b7; + font-size: 10px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.info-sftp-notice { + display: flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + background: rgba(16, 185, 129, 0.08); + border-radius: 10px; + margin-bottom: 16px; + font-size: 12px; + color: rgba(110, 231, 183, 0.9); +} + +.info-sftp-notice i { + font-size: 14px; +} + +.info-sftp-value { + font-size: 13px; +} + +.info-sftp-password { + display: flex; + align-items: center; + gap: 8px; +} + +.info-sftp-pass-mask { + letter-spacing: 2px; + color: rgba(255, 255, 255, 0.5); +} + +.info-sftp-toggle-pass { + width: 28px; + height: 28px; + border-radius: 6px; + background: rgba(255, 255, 255, 0.06); + border: none; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + color: rgba(255, 255, 255, 0.5); + font-size: 11px; + transition: all 0.2s ease; + flex-shrink: 0; +} + +.info-sftp-toggle-pass:hover { + background: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.9); +} + +.info-sftp-permissions { + display: flex; + align-items: center; + justify-content: space-between; + margin-top: 16px; + padding: 12px 16px; + background: rgba(255, 255, 255, 0.03); + border-radius: 10px; + border: 1px solid rgba(255, 255, 255, 0.06); +} + +.info-sftp-perm-label { + display: flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: rgba(255, 255, 255, 0.5); +} + +.info-sftp-perm-label i { + font-size: 14px; + color: rgba(99, 102, 241, 0.7); +} + +.info-sftp-perm-value { + font-size: 12px; + font-weight: 600; + color: rgba(255, 255, 255, 0.8); + padding: 4px 12px; + background: rgba(99, 102, 241, 0.15); + border-radius: 6px; +} + +.info-sftp-footer { + margin-top: 16px; + padding-top: 16px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + display: flex; + justify-content: flex-end; +} + +.info-sftp-regen { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 16px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.06); + border: none; + cursor: pointer; + color: rgba(255, 255, 255, 0.7); + font-size: 12px; + font-weight: 500; + transition: all 0.3s ease; +} + +.info-sftp-regen:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.95); +} + +.info-sftp-regen:hover i { + animation: spin 0.6s ease; +} + +@keyframes spin { + from { + transform: rotate(0deg); + } + + to { + transform: rotate(360deg); + } +} + +.info-no-access-message { + display: flex; + align-items: center; + gap: 12px; + padding: 20px; + background: rgba(239, 68, 68, 0.08); + border-radius: 12px; + font-size: 13px; + color: rgba(252, 165, 165, 0.9); +} + +.info-no-access-message i { + font-size: 18px; + opacity: 0.7; +} + +@media (max-width: 640px) { + .info-panel { + width: 100%; + height: 100%; + max-height: 100%; + border-radius: 0; + } + + .info-body { + padding: 8px 20px 20px; + } + + .info-grid { + grid-template-columns: 1fr; + } + + .info-header { + padding: 20px; + } + + .info-section { + padding: 16px; + } +} + + +.scheduler-modal { + position: fixed; + inset: 0; + display: none; + align-items: center; + justify-content: center; + z-index: 100000; + perspective: 1200px; +} + +.scheduler-modal.show { + display: flex; +} + +.scheduler-glass-layer { + position: absolute; + inset: 0; + pointer-events: none; +} + +.scheduler-glass-layer-1 { + opacity: 0; + animation: glassLayer1In 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; +} + +.scheduler-glass-layer-2 { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 30%, transparent 70%, rgba(255, 255, 255, 0.01) 100%); + opacity: 0; + backdrop-filter: blur(5px); + animation: glassLayer3In 0.7s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.scheduler-panel { + position: relative; + width: 94vw; + max-width: 640px; + height: auto; + max-height: 88vh; + display: flex; + flex-direction: column; + backdrop-filter: blur(80px) saturate(100%) brightness(1.05); + -webkit-backdrop-filter: blur(80px) saturate(200%) brightness(1.05); + border-radius: 28px; + overflow: hidden; + opacity: 0; + transform: scale(0.92) rotateX(8deg); + animation: panelLiquidIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.scheduler-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 24px 28px 20px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.04), transparent); +} + +.scheduler-header-left { + display: flex; + align-items: center; + gap: 18px; +} + +.scheduler-icon-wrap { + position: relative; + width: 56px; + height: 56px; + display: flex; + align-items: center; + justify-content: center; +} + +.scheduler-header-img { + width: 65px; + height: 65px; + object-fit: contain; + filter: drop-shadow(0 4px 12px rgba(0, 0, 0, 0.3)); +} + +.scheduler-icon-pulse { + display: none; +} + +.scheduler-icon { + display: none; +} + +.scheduler-header-text { + display: flex; + flex-direction: column; + gap: 2px; + opacity: 0; + animation: textFadeIn 0.4s ease 0.2s forwards; +} + +.scheduler-title { + font-size: 22px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.03em; +} + +.scheduler-subtitle { + font-size: 13px; + color: rgba(255, 255, 255, 0.4); + font-weight: 400; +} + +.scheduler-server-name { + color: rgba(96, 165, 250, 0.9); + font-weight: 600; +} + +.scheduler-close { + width: 44px; + height: 44px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.6); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + border: none; + opacity: 0; + animation: closeButtonIn 0.4s ease 0.35s forwards; +} + +.scheduler-close:hover { + background: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.9); +} + +.scheduler-close:active { + transform: scale(0.95); +} + +.scheduler-close-icon { + display: flex; + transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.scheduler-close:hover .scheduler-close-icon { + transform: rotate(90deg); +} + +.scheduler-tabs { + display: flex; + gap: 6px; + padding: 12px 20px; + background: rgba(255, 255, 255, 0.04); + margin: 0 16px; + border-radius: 14px; + margin-top: 8px; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} + +.scheduler-tab { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 12px 16px; + border-radius: 12px; + background: transparent; + color: rgba(255, 255, 255, 0.45); + font-size: 14px; + font-weight: 600; + cursor: pointer; + border: none; + transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.scheduler-tab:hover { + color: rgba(255, 255, 255, 0.7); +} + +.scheduler-tab.active { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.9); +} + +.scheduler-tab i { + font-size: 13px; +} + +.scheduler-body { + flex: 1; + overflow-y: auto; + padding: 20px 24px; + min-height: 280px; + max-height: calc(88vh - 280px); +} + +.scheduler-body::-webkit-scrollbar { + width: 4px; +} + +.scheduler-body::-webkit-scrollbar-track { + background: transparent; +} + +.scheduler-body::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.15); + border-radius: 4px; +} + +.scheduler-body::-webkit-scrollbar-thumb:hover { + background: rgba(255, 255, 255, 0.25); +} + +.scheduler-content { + display: block; +} + +.scheduler-content.hidden { + display: none; +} + +.scheduler-tasks-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 16px; +} + +.scheduler-tasks-title { + font-size: 15px; + font-weight: 600; + color: rgba(255, 255, 255, 0.6); + letter-spacing: -0.01em; +} + +.scheduler-refresh-btn { + width: 40px; + height: 40px; + border-radius: 20px; + background: rgba(255, 255, 255, 0.05); + color: rgba(255, 255, 255, 0.5); + border: none; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.scheduler-refresh-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; + transform: scale(1.05); +} + +.scheduler-refresh-btn:active { + transform: scale(0.95); +} + +.scheduler-refresh-btn.spinning i { + animation: spin 0.8s linear infinite; +} + +.scheduler-tasks-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.scheduler-loading { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 14px; + padding: 50px 20px; + color: rgba(255, 255, 255, 0.4); + font-size: 14px; +} + +.scheduler-loading-spinner { + width: 24px; + height: 24px; + border: 2px solid rgba(59, 130, 246, 0.15); + border-top-color: #3b82f6; + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +.scheduler-empty { + text-align: center; + padding: 50px 24px; + color: rgba(255, 255, 255, 0.35); +} + +.scheduler-empty i { + font-size: 52px; + margin-bottom: 18px; + color: rgba(59, 130, 246, 0.2); +} + +.scheduler-empty p { + font-size: 14px; + margin: 0; + line-height: 1.5; +} + +.scheduler-task-item { + display: flex; + align-items: center; + gap: 14px; + padding: 16px 18px; + background: rgba(255, 255, 255, 0.04); + border-radius: 16px; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.scheduler-task-item:hover { + background: rgba(255, 255, 255, 0.08); +} + +.scheduler-task-icon { + width: 44px; + height: 44px; + border-radius: 14px; + background: linear-gradient(135deg, rgba(59, 130, 246, 0.12) 0%, rgba(37, 99, 235, 0.08) 100%); + display: flex; + align-items: center; + justify-content: center; + color: #60a5fa; + font-size: 17px; + flex-shrink: 0; +} + +.scheduler-task-info { + flex: 1; + min-width: 0; +} + +.scheduler-task-name { + font-size: 15px; + font-weight: 600; + color: rgba(255, 255, 255, 0.95); + margin-bottom: 4px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.scheduler-task-meta { + display: flex; + align-items: center; + gap: 14px; + font-size: 12px; + color: rgba(255, 255, 255, 0.35); +} + +.scheduler-task-meta i { + margin-right: 5px; + font-size: 10px; + opacity: 0.7; +} + +.scheduler-task-status { + padding: 5px 12px; + border-radius: 10px; + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.scheduler-task-status.pending { + background: rgba(251, 191, 36, 0.12); + color: #fbbf24; +} + +.scheduler-task-status.running { + background: rgba(59, 130, 246, 0.12); + color: #60a5fa; +} + +.scheduler-task-status.completed { + background: rgba(34, 197, 94, 0.12); + color: #4ade80; +} + +.scheduler-task-status.failed { + background: rgba(239, 68, 68, 0.12); + color: #f87171; +} + +.scheduler-task-status.recurring { + background: rgba(139, 92, 246, 0.12); + color: #a78bfa; +} + +.scheduler-task-delete { + width: 36px; + height: 36px; + border-radius: 18px; + background: transparent; + color: rgba(255, 255, 255, 0.25); + border: none; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.scheduler-task-delete:hover { + background: rgba(239, 68, 68, 0.12); + color: #f87171; + transform: scale(1.1); +} + +.scheduler-task-delete:active { + transform: scale(0.95); +} + +.scheduler-form { + display: flex; + flex-direction: column; + gap: 20px; +} + +.scheduler-form-section { + display: flex; + flex-direction: column; + gap: 10px; +} + +.scheduler-label { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.65); + letter-spacing: -0.01em; +} + +.scheduler-label-small { + font-size: 13px; + font-weight: 500; + color: rgba(255, 255, 255, 0.45); +} + +.scheduler-input { + padding: 14px 16px; + background: rgba(255, 255, 255, 0.04); + border: none; + border-radius: 14px; + color: #fff; + font-size: 15px; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + outline: none; +} + +.scheduler-input:focus { + background: rgba(255, 255, 255, 0.08); +} + +.scheduler-input::placeholder { + color: rgba(255, 255, 255, 0.25); +} + +.scheduler-input-mono { + font-family: 'SF Mono', 'JetBrains Mono', 'Fira Code', monospace; + font-size: 14px; +} + +.scheduler-textarea { + padding: 14px 16px; + background: rgba(255, 255, 255, 0.04); + border: none; + border-radius: 14px; + color: #fff; + font-size: 14px; + resize: vertical; + min-height: 100px; + outline: none; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.scheduler-textarea:focus { + background: rgba(255, 255, 255, 0.08); +} + +.scheduler-select { + padding: 14px 16px; + background: rgba(255, 255, 255, 0.04); + border: none; + border-radius: 14px; + color: #fff; + font-size: 15px; + cursor: pointer; + outline: none; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + appearance: none; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' fill='rgba(255,255,255,0.4)' viewBox='0 0 16 16'%3E%3Cpath d='M8 11L3 6h10l-5 5z'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 16px center; + padding-right: 40px; +} + +.scheduler-select:focus { + background: rgba(255, 255, 255, 0.08); +} + +.scheduler-select option { + background: #1a1d24; + color: #fff; + padding: 12px; +} + +.scheduler-select-small { + padding: 10px 14px; + font-size: 14px; + border-radius: 12px; +} + +.scheduler-datetime-row { + display: flex; + gap: 12px; +} + +.scheduler-datetime-row .scheduler-input { + flex: 1; +} + +.scheduler-schedule-options { + display: flex; + gap: 10px; +} + +.scheduler-schedule-option { + flex: 1; + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + padding: 18px 16px; + background: rgba(255, 255, 255, 0.04); + border-radius: 14px; + color: rgba(255, 255, 255, 0.45); + font-size: 14px; + font-weight: 600; + outline: none; + border: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.scheduler-schedule-option:hover { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.7); +} + +.scheduler-schedule-option.active { + background: rgba(255, 255, 255, 0.12); + border: none; + outline: none; + color: rgba(255, 255, 255, 0.95); +} + +.scheduler-schedule-option i { + font-size: 22px; +} + +.scheduler-recurring-options { + margin-bottom: 14px; +} + +.scheduler-recurring-config { + display: flex; + align-items: center; + gap: 12px; + flex-wrap: wrap; + padding: 14px 16px; + background: rgba(0, 0, 0, 0.15); + border-radius: 14px; + margin-top: 8px; +} + +.scheduler-recurring-config.hidden { + display: none; +} + +.scheduler-or-divider { + display: flex; + align-items: center; + gap: 18px; + margin: 12px 0; +} + +.scheduler-or-divider::before, +.scheduler-or-divider::after { + content: ''; + flex: 1; + height: 1px; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.08), transparent); +} + +.scheduler-or-divider span { + font-size: 11px; + font-weight: 700; + color: rgba(255, 255, 255, 0.25); + text-transform: uppercase; + letter-spacing: 0.15em; +} + +.scheduler-action-config { + display: flex; + flex-direction: column; + gap: 14px; + padding: 18px; + background: rgba(255, 255, 255, 0.04); + border-radius: 14px; + overflow: visible; +} + +.scheduler-action-config.hidden { + display: none; +} + +.scheduler-action-info { + display: flex; + align-items: flex-start; + gap: 12px; + font-size: 13px; + color: rgba(255, 255, 255, 0.45); + line-height: 1.5; +} + +.scheduler-action-info i { + color: #3b82f6; + margin-top: 2px; +} + +.scheduler-hint { + font-size: 12px; + color: rgba(255, 255, 255, 0.35); + margin-top: -6px; +} + +.scheduler-action-config .scheduler-refresh-btn { + align-self: flex-start; +} + +.scheduler-ai-model-selector { + width: 100%; + min-width: 0; + max-width: none; + flex: 0 1 auto; + z-index: 80; +} + +.scheduler-ai-model-selector .ai-model-options-shell { + z-index: 90; +} + +.scheduler-form-footer { + display: flex; + justify-content: flex-end; + padding-top: 12px; +} + +.scheduler-create-btn { + display: flex; + align-items: center; + gap: 10px; + padding: 16px 32px; + background: linear-gradient(135deg, #3b82f6 0%, #2563eb 100%); + color: #fff; + font-size: 15px; + font-weight: 700; + border: none; + border-radius: 16px; + cursor: pointer; + transition: all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.scheduler-create-btn:hover { + transform: scale(1.03); +} + +.scheduler-create-btn:active { + transform: translateY(-1px); +} + +.scheduler-create-btn:disabled { + opacity: 0.5; + cursor: not-allowed; + transform: none; + box-shadow: none; +} + +.scheduler-status-bar { + display: flex; + align-items: center; + justify-content: center; + padding: 14px 24px; + background: rgba(255, 255, 255, 0.02); +} + +.scheduler-status-indicator { + display: flex; + align-items: center; + gap: 10px; + font-size: 13px; + color: rgba(255, 255, 255, 0.45); + font-weight: 500; +} + +.scheduler-status-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: #4ade80; +} + +.scheduler-status-dot.offline { + background: #f87171; +} + +@media (max-width: 600px) { + .scheduler-panel { + max-width: 100%; + border-radius: 28px 28px 0 0; + max-height: 95vh; + } + + .scheduler-header { + padding: 20px 20px 16px; + } + + .scheduler-body { + padding: 16px 20px; + } + + .scheduler-tabs { + margin: 8px 12px; + padding: 10px 14px; + } + + .scheduler-tab { + padding: 10px 12px; + font-size: 13px; + } + + .scheduler-schedule-option { + padding: 14px 12px; + } + + .scheduler-create-btn { + width: 100%; + justify-content: center; + } +} + + +.planner-modal { + position: fixed; + inset: 0; + display: none; + align-items: center; + justify-content: center; + z-index: 100000; + perspective: 1200px; + --planner-accent: #fb923c; + --planner-accent-strong: #f97316; +} + +.planner-modal.show { + display: flex; +} + +.planner-glass-layer { + position: absolute; + inset: 0; + pointer-events: none; +} + +.planner-glass-layer-1 { + opacity: 0; + animation: glassLayer1In 0.6s cubic-bezier(0.16, 1, 0.3, 1) forwards; +} + +.planner-glass-layer-2 { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02) 0%, transparent 30%, transparent 70%, rgba(255, 255, 255, 0.01) 100%); + opacity: 0; + backdrop-filter: blur(5px); + animation: glassLayer3In 0.7s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.planner-panel { + position: relative; + width: min(94vw, 920px); + max-height: 88vh; + display: flex; + flex-direction: column; + overflow: hidden; + border-radius: 28px; + backdrop-filter: blur(80px) saturate(100%) brightness(1.05); + -webkit-backdrop-filter: blur(80px) saturate(200%) brightness(1.05); + opacity: 0; + transform: scale(0.92) rotateX(8deg); + animation: panelLiquidIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.planner-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 24px 28px 20px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.04), transparent); +} + +.planner-header-left { + display: flex; + align-items: center; + gap: 18px; + min-width: 0; +} + +.planner-icon-wrap { + position: relative; + width: 58px; + height: 58px; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; +} + +.planner-icon-pulse { + position: absolute; + inset: 0; + border-radius: 20px; + background: linear-gradient(135deg, rgba(251, 146, 60, 0.14), rgba(249, 115, 22, 0.08)); + filter: blur(6px); +} + +.planner-icon { + position: relative; + width: 54px; + height: 54px; + border-radius: 18px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, rgba(251, 146, 60, 0.18), rgba(249, 115, 22, 0.08)); + color: var(--planner-accent); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.08); +} + +.planner-icon i { + font-size: 22px; +} + +.planner-header-text { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; + opacity: 0; + animation: textFadeIn 0.4s ease 0.2s forwards; +} + +.planner-title { + font-size: 22px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.03em; +} + +.planner-subtitle { + font-size: 13px; + color: rgba(255, 255, 255, 0.42); +} + +.planner-server-name { + color: rgba(251, 146, 60, 0.95); + font-weight: 600; +} + +.planner-header-actions { + display: flex; + align-items: center; + gap: 10px; +} + +.planner-refresh-btn, +.planner-close { + width: 42px; + height: 42px; + border-radius: 14px; + border: none; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.planner-refresh-btn { + background: rgba(255, 255, 255, 0.05); + color: rgba(255, 255, 255, 0.55); +} + +.planner-refresh-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; + transform: scale(1.05); +} + +.planner-refresh-btn.spinning i { + animation: spin 0.8s linear infinite; +} + +.planner-close { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.6); + opacity: 0; + animation: closeButtonIn 0.4s ease 0.35s forwards; +} + +.planner-close:hover { + background: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.92); +} + +.planner-close:active { + transform: scale(0.95); +} + +.planner-close-icon { + display: flex; + transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.planner-close:hover .planner-close-icon { + transform: rotate(90deg); +} + +.planner-tabs { + display: flex; + gap: 6px; + padding: 12px 20px; + margin: 0 16px; + margin-top: 8px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.04); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} + +.planner-tab { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 12px 16px; + border: none; + border-radius: 12px; + background: transparent; + color: rgba(255, 255, 255, 0.45); + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.planner-tab:hover { + color: rgba(255, 255, 255, 0.72); +} + +.planner-tab.active { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.94); +} + +.planner-body { + flex: 1; + overflow-y: auto; + padding: 22px 24px; + min-height: 320px; +} + +.planner-content.hidden { + display: none; +} + +.planner-summary { + display: grid; + grid-template-columns: repeat(3, minmax(0, 1fr)); + gap: 12px; + margin-bottom: 20px; +} + +.planner-summary-card { + padding: 18px 18px 16px; + border-radius: 18px; + background: rgba(255, 255, 255, 0.04); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04); +} + +.planner-summary-label { + display: block; + margin-bottom: 10px; + font-size: 12px; + font-weight: 700; + color: rgba(255, 255, 255, 0.42); + letter-spacing: 0.08em; + text-transform: uppercase; +} + +.planner-summary-value { + display: block; + font-size: 28px; + font-weight: 700; + letter-spacing: -0.04em; + color: rgba(255, 255, 255, 0.96); +} + +.planner-summary-note { + display: block; + margin-top: 8px; + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + line-height: 1.4; +} + +.planner-board-section { + display: flex; + flex-direction: column; + gap: 14px; +} + +.planner-completed-section { + margin-top: 22px; +} + +.planner-completed-section.hidden { + display: none; +} + +.planner-section-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; +} + +.planner-section-title { + font-size: 15px; + font-weight: 700; + color: rgba(255, 255, 255, 0.88); + letter-spacing: -0.02em; +} + +.planner-section-subtitle { + margin-top: 5px; + font-size: 13px; + line-height: 1.5; + color: rgba(255, 255, 255, 0.42); +} + +.planner-add-inline, +.planner-secondary-btn, +.planner-primary-btn { + border: none; + cursor: pointer; + transition: all 0.25s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.planner-add-inline { + display: inline-flex; + align-items: center; + gap: 9px; + padding: 12px 16px; + border-radius: 14px; + background: rgba(251, 146, 60, 0.12); + color: rgba(255, 237, 213, 0.96); + font-size: 13px; + font-weight: 700; + flex-shrink: 0; +} + +.planner-add-inline:hover { + background: rgba(251, 146, 60, 0.2); + transform: translateY(-1px); +} + +.planner-list { + display: flex; + flex-direction: column; + gap: 12px; +} + +.planner-loading, +.planner-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 14px; + padding: 46px 20px; + border-radius: 22px; + background: rgba(255, 255, 255, 0.03); + color: rgba(255, 255, 255, 0.42); + text-align: center; +} + +.planner-loading-spinner { + width: 24px; + height: 24px; + border: 2px solid rgba(251, 146, 60, 0.14); + border-top-color: var(--planner-accent); + border-radius: 50%; + animation: spin 0.8s linear infinite; +} + +.planner-empty i { + font-size: 48px; + color: rgba(251, 146, 60, 0.24); +} + +.planner-empty p { + margin: 0; + line-height: 1.5; +} + +.planner-empty-btn { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 12px 16px; + border-radius: 14px; + border: none; + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.9); + font-size: 13px; + font-weight: 600; + cursor: pointer; +} + +.planner-item { + display: flex; + align-items: stretch; + gap: 12px; + padding: 14px; + border-radius: 20px; + background: rgba(255, 255, 255, 0.04); + transition: background 0.25s ease, transform 0.25s ease; +} + +.planner-item:hover { + background: rgba(255, 255, 255, 0.08); + transform: translateY(-1px); +} + +.planner-item.dragging { + opacity: 0.5; +} + +.planner-item-main { + flex: 1; + min-width: 0; + background: none; + border: none; + padding: 0; + text-align: left; + cursor: pointer; + color: inherit; +} + +.planner-item-heading { + display: flex; + align-items: flex-start; + gap: 12px; +} + +.planner-drag-handle { + width: 38px; + height: 38px; + border-radius: 12px; + display: inline-flex; + align-items: center; + justify-content: center; + background: rgba(251, 146, 60, 0.12); + color: rgba(255, 237, 213, 0.8); + flex-shrink: 0; +} + +.planner-item-title-wrap { + min-width: 0; +} + +.planner-item-title { + font-size: 16px; + font-weight: 700; + line-height: 1.3; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.02em; +} + +.planner-item-meta { + display: flex; + flex-wrap: wrap; + gap: 10px 14px; + margin-top: 8px; + font-size: 12px; + color: rgba(255, 255, 255, 0.38); +} + +.planner-item-meta span { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.planner-priority-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 42px; + padding: 5px 10px; + border-radius: 999px; + background: rgba(251, 146, 60, 0.14); + color: rgba(255, 237, 213, 0.94); + font-size: 11px; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; +} + +.planner-priority-badge.done { + background: rgba(34, 197, 94, 0.14); + color: #86efac; +} + +.planner-item-prompt { + margin-top: 14px; + font-size: 13px; + line-height: 1.65; + color: rgba(255, 255, 255, 0.68); + display: -webkit-box; + -webkit-line-clamp: 4; + -webkit-box-orient: vertical; + overflow: hidden; + word-break: break-word; +} + +.planner-item-actions { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; +} + +.planner-item-action { + width: 40px; + height: 40px; + border-radius: 14px; + border: none; + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.52); + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: all 0.2s ease; +} + +.planner-item-action:hover { + background: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.95); +} + +.planner-item-action.send:hover { + background: rgba(251, 146, 60, 0.16); + color: #fed7aa; +} + +.planner-item-action.toggle:hover { + background: rgba(34, 197, 94, 0.14); + color: #86efac; +} + +.planner-item-action.delete:hover { + background: rgba(239, 68, 68, 0.14); + color: #fca5a5; +} + +.planner-item.is-done { + background: rgba(255, 255, 255, 0.025); +} + +.planner-item.is-done .planner-item-title, +.planner-item.is-done .planner-item-prompt { + color: rgba(255, 255, 255, 0.52); +} + +.planner-item.is-done .planner-drag-handle { + background: rgba(34, 197, 94, 0.1); + color: #86efac; +} + +.planner-form { + display: flex; + flex-direction: column; + gap: 20px; +} + +.planner-form-section { + display: flex; + flex-direction: column; + gap: 10px; +} + +.planner-label { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); +} + +.planner-input, +.planner-textarea { + width: 100%; + box-sizing: border-box; + border: none; + outline: none; + border-radius: 16px; + background: rgba(255, 255, 255, 0.04); + color: #fff; + transition: background 0.25s ease, box-shadow 0.25s ease; +} + +.planner-input { + padding: 15px 16px; + font-size: 15px; +} + +.planner-textarea { + min-height: 190px; + padding: 16px 18px; + resize: vertical; + font-size: 14px; + line-height: 1.6; +} + +.planner-input:focus, +.planner-textarea:focus { + background: rgba(255, 255, 255, 0.08); + box-shadow: 0 0 0 3px rgba(251, 146, 60, 0.08); +} + +.planner-input::placeholder, +.planner-textarea::placeholder { + color: rgba(255, 255, 255, 0.26); +} + +.planner-hint { + font-size: 12px; + line-height: 1.6; + color: rgba(255, 255, 255, 0.4); +} + +.planner-form-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 12px; + padding-top: 6px; +} + +.planner-secondary-btn { + padding: 14px 18px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.82); + font-size: 14px; + font-weight: 600; +} + +.planner-secondary-btn:hover { + background: rgba(255, 255, 255, 0.1); +} + +.planner-primary-btn { + display: inline-flex; + align-items: center; + gap: 10px; + padding: 15px 22px; + border-radius: 16px; + background: linear-gradient(135deg, var(--planner-accent), var(--planner-accent-strong)); + color: #fff; + font-size: 14px; + font-weight: 700; + box-shadow: 0 12px 32px rgba(249, 115, 22, 0.22); +} + +.planner-primary-btn:hover { + transform: translateY(-1px); +} + +.planner-primary-btn:disabled, +.planner-secondary-btn:disabled, +.planner-add-inline:disabled { + opacity: 0.55; + cursor: not-allowed; + transform: none; + box-shadow: none; +} + +.planner-status-bar { + display: flex; + align-items: center; + justify-content: center; + padding: 14px 24px; + background: rgba(255, 255, 255, 0.02); +} + +.planner-status-indicator { + display: flex; + align-items: center; + gap: 10px; + font-size: 13px; + color: rgba(255, 255, 255, 0.45); + font-weight: 500; +} + +.planner-status-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: #4ade80; +} + +.planner-status-dot.offline { + background: #f87171; +} + +@media (max-width: 860px) { + .planner-panel { + width: 96vw; + } + + .planner-summary { + grid-template-columns: 1fr; + } + + .planner-section-header, + .planner-form-footer, + .planner-item { + flex-direction: column; + } + + .planner-item-actions { + justify-content: flex-end; + } +} + +@media (max-width: 600px) { + .planner-panel { + max-height: 95vh; + border-radius: 28px 28px 0 0; + } + + .planner-header { + padding: 20px 20px 16px; + } + + .planner-tabs { + margin: 8px 12px; + padding: 10px 14px; + } + + .planner-body { + padding: 16px 20px; + } + + .planner-tab { + padding: 10px 12px; + font-size: 13px; + } + + .planner-form-footer { + align-items: stretch; + } + + .planner-primary-btn, + .planner-secondary-btn, + .planner-add-inline, + .planner-empty-btn { + width: 100%; + justify-content: center; + } +} + +#backupsModal { + --backups_header_icon_width: 42px; + --backups_header_icon_height: 42px; +} + +#backupCreateModal { + --backups_header_icon_width: 42px; + --backups_header_icon_height: 42px; +} + +#backupsModal .backups-header-icon, +#backupCreateModal .backups-header-icon { + width: var(--backups_header_icon_width); + height: var(--backups_header_icon_height); + object-fit: contain; + flex-shrink: 0; + display: block; +} + +#backupsModal .activity-body, +.backup-create-activity .activity-body { + mask-image: none; + -webkit-mask-image: none; +} + +#backupsModal .activity-pill { + font-weight: 400; +} + +#backupsModal .activity-pill:hover { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.8); +} + +#backupsModal .activity-pill.active { + background: linear-gradient(135deg, rgba(56, 189, 248, 0.18), rgba(34, 211, 238, 0.07)); + color: rgba(255, 255, 255, 0.85); +} + +#backupsModal #backupsRefreshBtn:hover i { + animation: spin 0.6s ease; +} + +#backupsModal #backupsRefreshBtn.is-loading i { + animation: spin 0.8s linear infinite; +} + +#backupsModal .backup-item-icon { + background: linear-gradient(135deg, rgba(56, 189, 248, 0.16), rgba(34, 211, 238, 0.08)); +} + +#backupsModal .backup-action-btn { + font-weight: 400; +} + +.backup-create-activity .backup-create-confirm, +.backup-create-activity .backup-create-cancel { + font-weight: 400; +} + +#backupsModal .activity-search-wrap { + justify-content: flex-end; +} + +#backupsModal .activity-filter-pills { + gap: 10px; +} + +#backupsModal .backups-loading, +#backupsModal .backups-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + padding: 60px; + color: rgba(255, 255, 255, 0.45); + font-size: 14px; + font-weight: 500; +} + +#backupsModal .backups-loading i, +#backupsModal .backups-empty i { + font-size: 36px; + margin-bottom: 4px; + opacity: 0.5; +} + +#backupsModal .backups-empty p { + font-size: 15px; + font-weight: 500; + margin: 0; + color: rgba(255, 255, 255, 0.45); +} + +#backupsModal .backups-empty .backups-empty-hint { + margin-top: 8px; + font-size: 12.5px; + color: rgba(255, 255, 255, 0.35); +} + +#backupsModal .backup-item { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 18px 20px; + background: rgba(255, 255, 255, 0.03); + border-radius: 16px; + transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + border: none; +} + +#backupsModal .backup-item:hover { + background: rgba(255, 255, 255, 0.06); +} + +#backupsModal .backup-item-main { + flex: 1; + min-width: 0; + display: flex; + align-items: flex-start; + gap: 16px; +} + +#backupsModal .backup-item-icon { + width: 42px; + height: 42px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + flex-shrink: 0; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + background: linear-gradient(135deg, rgba(251, 191, 36, 0.2), rgba(245, 158, 11, 0.1)); + color: rgba(255, 255, 255, 0.9); +} + +#backupsModal .backup-item:hover .backup-item-icon { + transform: scale(1.08); +} + +#backupsModal .backup-item-info { + flex: 1; + min-width: 0; +} + +#backupsModal .backup-item-name { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); + margin-bottom: 6px; + letter-spacing: -0.01em; +} + +#backupsModal .backup-item-desc { + font-size: 12.5px; + color: rgba(255, 255, 255, 0.5); + word-break: break-word; + margin-bottom: 8px; + line-height: 1.5; +} + +#backupsModal .backup-item-meta { + display: flex; + flex-wrap: wrap; + gap: 12px; + font-size: 11px; + color: rgba(255, 255, 255, 0.35); +} + +#backupsModal .backup-item-meta span { + display: flex; + align-items: center; + gap: 15px; +} + +#backupsModal .backup-item-meta i { + font-size: 10px; + opacity: 0.6; +} + +#backupsModal .backup-item-actions { + display: flex; + align-items: center; + gap: 10px; + flex-shrink: 0; +} + +#backupsModal .backup-action-btn { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 14px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.6); + font-size: 12px; + font-weight: 600; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + border: none; +} + +#backupsModal .backup-action-btn:hover { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.85); +} + +#backupsModal .backup-action-btn.delete { + background: rgba(239, 68, 68, 0.12); + color: rgba(255, 255, 255, 0.85); +} + +#backupsModal .backup-action-btn.delete:hover { + background: rgba(239, 68, 68, 0.18); +} + +.backup-create-activity .activity-panel { + max-width: 640px; + height: auto; + max-height: 88vh; +} + +.backup-create-activity .activity-body { + padding: 8px 28px 16px; +} + +.backup-create-activity .backup-create-footer { + padding: 16px 28px 20px; + display: flex; + justify-content: flex-end; + gap: 12px; +} + +.backups-modal { + display: none; + position: fixed; + inset: 0; + z-index: 10000; + align-items: center; + justify-content: center; + padding: 20px; +} + +.backups-modal.show { + display: flex; + animation: backupsModalIn 0.2s cubic-bezier(0.16, 1, 0.3, 1); +} + +@keyframes backupsModalIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +.backups-glass-backdrop { + position: absolute; + inset: 0; + backdrop-filter: blur(5px); +} + +.backups-panel { + position: relative; + width: 100%; + max-width: 640px; + max-height: 80vh; + display: flex; + flex-direction: column; + background: linear-gradient(165deg, rgba(17, 19, 23, 0.98), rgba(10, 12, 15, 0.99)); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 16px; + box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4); + overflow: hidden; + animation: backupsPanelIn 0.25s cubic-bezier(0.16, 1, 0.3, 1); +} + +@keyframes backupsPanelIn { + from { + opacity: 0; + transform: translateY(12px) scale(0.98); + } + + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +.backups-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 20px 24px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent); +} + +.backups-header-left { + display: flex; + align-items: center; + gap: 14px; +} + +.backups-icon { + width: 44px; + height: 44px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 12px; + color: #fbbf24; + font-size: 18px; +} + +.backups-title { + font-size: 18px; + font-weight: 700; + color: #fff; + letter-spacing: -0.02em; +} + +.backups-subtitle { + font-size: 13px; + color: #6b7280; + margin-top: 2px; +} + +.backups-close { + width: 36px; + height: 36px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 10px; + color: #9ca3af; + font-size: 14px; + cursor: pointer; + transition: all 0.15s ease; +} + +.backups-close:hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; +} + +.backups-toolbar { + display: flex; + align-items: center; + gap: 10px; + padding: 14px 24px; + border-bottom: 1px solid rgba(255, 255, 255, 0.04); +} + +.backups-create-btn { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 18px; + background: linear-gradient(135deg, rgba(245, 158, 11, 0.2), rgba(217, 119, 6, 0.15)); + border-radius: 10px; + border: none; + color: #fbbf24; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s ease; +} + +.backups-create-btn:hover { + background: linear-gradient(135deg, rgba(245, 158, 11, 0.3), rgba(217, 119, 6, 0.25)); + border-color: rgba(245, 158, 11, 0.5); + transform: translateY(-1px); +} + +.backups-refresh-btn { + width: 38px; + height: 38px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 10px; + color: #9ca3af; + font-size: 14px; + cursor: pointer; + transition: all 0.15s ease; +} + +.backups-refresh-btn:hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; +} + +.backups-body { + flex: 1; + overflow-y: auto; + padding: 16px 24px; +} + +.backups-list { + display: flex; + flex-direction: column; + gap: 10px; +} + +.backups-loading, +.backups-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 48px 24px; + color: #6b7280; + text-align: center; +} + +.backups-loading i, +.backups-empty i { + font-size: 32px; + margin-bottom: 12px; + opacity: 0.5; +} + +.backups-empty span { + font-size: 15px; + font-weight: 600; + color: #9ca3af; +} + +.backups-empty p { + font-size: 13px; + margin-top: 6px; + max-width: 280px; +} + +.backup-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.02); + border: 1px solid rgba(255, 255, 255, 0.04); + border-radius: 12px; + transition: all 0.15s ease; +} + +.backup-item:hover { + background: rgba(255, 255, 255, 0.04); + border-color: rgba(255, 255, 255, 0.08); +} + +.backup-item-main { + display: flex; + align-items: center; + gap: 14px; + flex: 1; + min-width: 0; +} + +.backup-item-icon { + width: 42px; + height: 42px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(217, 119, 6, 0.1)); + border: none; + border-radius: 10px; + color: #f59e0b; + font-size: 16px; + flex-shrink: 0; +} + +.backup-item-info { + flex: 1; + min-width: 0; +} + +.backup-item-name { + font-size: 14px; + font-weight: 600; + color: #fff; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.backup-item-meta { + display: flex; + align-items: center; + gap: 14px; + margin-top: 4px; + font-size: 12px; + color: #6b7280; +} + +.backup-item-meta span { + display: flex; + align-items: center; + gap: 5px; +} + +.backup-item-meta i { + font-size: 11px; + opacity: 0.7; +} + +.backup-item-desc { + margin-top: 6px; + font-size: 12px; + color: #6b7280; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.backup-item-actions { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; +} + +.backup-action-btn { + display: flex; + align-items: center; + gap: 6px; + padding: 8px 14px; + border-radius: 8px; + font-size: 12px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s ease; +} + +.backup-action-btn.restore { + background: linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(5, 150, 105, 0.1)); + border: 1px solid rgba(16, 185, 129, 0.25); + color: #34d399; +} + +.backup-action-btn.restore:hover { + background: linear-gradient(135deg, rgba(16, 185, 129, 0.25), rgba(5, 150, 105, 0.2)); + border-color: rgba(16, 185, 129, 0.4); +} + +.backup-action-btn.delete { + padding: 8px 10px; + background: rgba(239, 68, 68, 0.1); + border: 1px solid rgba(239, 68, 68, 0.2); + color: #f87171; +} + +.backup-action-btn.delete:hover { + background: rgba(239, 68, 68, 0.2); + border-color: rgba(239, 68, 68, 0.35); +} + +.backup-action-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.backup-create-modal { + display: none; + position: fixed; + inset: 0; + z-index: 10001; + align-items: center; + justify-content: center; + padding: 20px; + background: rgba(0, 0, 0, 0.5); + backdrop-filter: blur(4px); +} + +.backup-create-modal.show { + display: flex; + animation: backupsModalIn 0.15s ease; +} + +.backup-create-panel { + width: 100%; + max-width: 440px; + background: linear-gradient(165deg, rgba(17, 19, 23, 0.99), rgba(10, 12, 15, 1)); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 14px; + box-shadow: 0 4px 20px rgba(0, 0, 0, 0.35); + overflow: hidden; + animation: backupsPanelIn 0.2s cubic-bezier(0.16, 1, 0.3, 1); +} + +.backup-create-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 18px 20px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.backup-create-title { + font-size: 16px; + font-weight: 700; + color: #fff; +} + +.backup-create-close { + width: 32px; + height: 32px; + display: flex; + align-items: center; + justify-content: center; + background: transparent; + border: none; + color: #6b7280; + font-size: 14px; + cursor: pointer; + border-radius: 8px; + transition: all 0.15s ease; +} + +.backup-create-close:hover { + background: rgba(255, 255, 255, 0.06); + color: #fff; +} + +.backup-create-body { + padding: 20px; +} + +.backup-create-field { + margin-bottom: 16px; +} + +.backup-create-field label { + display: block; + font-size: 13px; + font-weight: 600; + color: #9ca3af; + margin-bottom: 8px; +} + +.backup-create-field input, +.backup-create-field textarea { + width: 93%; + padding: 12px 14px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 10px; + color: #fff; + font-size: 14px; + font-family: inherit; + transition: all 0.15s ease; + resize: none; +} + +.backup-create-field input:focus, +.backup-create-field textarea:focus { + outline: none; + background: rgba(255, 255, 255, 0.06); +} + +.backup-create-field input::placeholder, +.backup-create-field textarea::placeholder { + color: #4b5563; +} + +.backup-create-info { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 12px 14px; + background: rgba(59, 130, 246, 0.08); + border-radius: 10px; + font-size: 12px; + color: #93c5fd; +} + +.backup-create-info i { + margin-top: 1px; + font-size: 13px; +} + +.backup-create-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + padding: 16px 20px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + background: rgba(255, 255, 255, 0.01); +} + +.backup-create-cancel { + padding: 10px 18px; + background: transparent; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 10px; + color: #9ca3af; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s ease; +} + +.backup-create-cancel:hover { + background: rgba(255, 255, 255, 0.04); + border-color: rgba(255, 255, 255, 0.15); + color: #fff; +} + +.backup-create-confirm { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 20px; + background: rgba(59, 130, 246, 0.08); + border-radius: 10px; + border: none; + outline: none; + color: #fbbf24; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s ease; +} + +.backup-create-confirm:hover { + background: rgba(59, 130, 246, 0.1); + box-shadow: inset 0 0 0 1px rgba(59, 130, 246, 0.08); +} + +.backup-create-confirm:disabled { + opacity: 0.6; + cursor: not-allowed; +} + +.backup-btn { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 18px; + border-radius: 10px; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.15s ease; + border: 1px solid transparent; +} + +.backup-btn-secondary { + background: rgba(255, 255, 255, 0.04); + border-color: rgba(255, 255, 255, 0.1); + color: #9ca3af; +} + +.backup-btn-secondary:hover { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.15); + color: #fff; +} + +.backup-btn-danger { + background: linear-gradient(135deg, rgba(239, 68, 68, 0.25), rgba(220, 38, 38, 0.2)); + border-color: rgba(239, 68, 68, 0.35); + color: #f87171; +} + +.backup-btn-danger:hover { + background: linear-gradient(135deg, rgba(239, 68, 68, 0.35), rgba(220, 38, 38, 0.3)); + border-color: rgba(239, 68, 68, 0.5); + color: #fca5a5; +} + +.backup-btn-danger:disabled { + opacity: 0.6; + cursor: not-allowed; +} + +.backup-modal-overlay { + display: none; + position: fixed !important; + top: 0 !important; + left: 0 !important; + right: 0 !important; + bottom: 0 !important; + width: 100vw !important; + height: 100vh !important; + z-index: 99999 !important; + align-items: center; + justify-content: center; + padding: 20px; + background: rgba(0, 0, 0, 0.75) !important; + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + overflow: auto; +} + +.backup-modal-overlay.active { + display: flex !important; + animation: backupsModalIn 0.2s cubic-bezier(0.16, 1, 0.3, 1); +} + +.backup-modal-overlay>.backup-modal, +.backup-modal-overlay>.restore-confirm-modal { + position: relative !important; + max-width: 480px; + width: calc(100vw - 40px); + max-height: calc(100vh - 40px); + margin: auto; + display: flex; + flex-direction: column; + background: linear-gradient(165deg, rgba(17, 19, 23, 0.98), rgba(10, 12, 15, 0.99)) !important; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 16px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.6), 0 0 0 1px rgba(255, 255, 255, 0.05); + overflow: hidden; + animation: backupsPanelIn 0.25s cubic-bezier(0.16, 1, 0.3, 1); +} + +.backup-modal-overlay .backup-modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 16px 20px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent); + flex-shrink: 0; +} + +.backup-modal-overlay .backup-modal-header h3 { + display: flex; + align-items: center; + gap: 10px; + font-size: 16px; + font-weight: 700; + color: #fff; + margin: 0; +} + +.backup-modal-overlay .backup-modal-header h3 i { + color: #f59e0b; +} + +.backup-modal-overlay .backup-modal-close { + width: 32px; + height: 32px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 8px; + color: #9ca3af; + font-size: 14px; + cursor: pointer; + transition: all 0.15s ease; + flex-shrink: 0; +} + +.backup-modal-overlay .backup-modal-close:hover { + background: rgba(255, 255, 255, 0.08); + color: #fff; +} + +.backup-modal-overlay .backup-modal-body { + padding: 16px 20px; + overflow-y: auto; + flex: 1; +} + +.backup-modal-overlay .backup-modal-footer { + display: flex; + justify-content: flex-end; + gap: 10px; + padding: 14px 20px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + background: rgba(255, 255, 255, 0.01); + flex-shrink: 0; +} + +@media (max-width: 540px) { + .backup-modal-overlay { + padding: 10px; + } + + .backup-modal-overlay>.backup-modal, + .backup-modal-overlay>.restore-confirm-modal { + width: calc(100vw - 20px); + max-height: calc(100vh - 20px); + border-radius: 12px; + } + + .backup-modal-overlay .backup-modal-header { + padding: 14px 16px; + } + + .backup-modal-overlay .backup-modal-header h3 { + font-size: 15px; + } + + .backup-modal-overlay .backup-modal-body { + padding: 14px 16px; + } + + .backup-modal-overlay .backup-modal-footer { + padding: 12px 16px; + flex-wrap: wrap; + } + + .backup-modal-overlay .backup-btn { + flex: 1; + justify-content: center; + min-width: 100px; + } +} + + +.ai-help-trigger { + background: linear-gradient(135deg, rgba(167, 139, 250, 0.15), rgba(139, 92, 246, 0.1)) !important; + border: 1px solid rgba(167, 139, 250, 0.25) !important; + color: #c4b5fd !important; +} + +.ai-help-trigger:hover { + background: linear-gradient(135deg, rgba(167, 139, 250, 0.25), rgba(139, 92, 246, 0.2)) !important; + border-color: rgba(167, 139, 250, 0.4) !important; + transform: translateY(-1px); +} + +.ai-help-trigger i { + color: #a78bfa; +} + +.ai-help-dock { + position: relative; +} + +.ai-help-dock::before { + content: ''; + position: absolute; + inset: 0; + border-radius: inherit; + background: linear-gradient(135deg, rgba(167, 139, 250, 0.1), transparent); + opacity: 0; + transition: opacity 0.3s ease; +} + +.ai-help-dock:hover::before { + opacity: 1; +} + +.ai-help-modal { + position: fixed; + inset: 0; + display: none; + align-items: center; + justify-content: center; + z-index: 100000; + perspective: 1200px; +} + +.ai-help-modal.show { + display: flex; +} + +.ai-help-panel { + position: relative; + width: 96vw; + max-width: 1100px; + height: 92vh; + max-height: 920px; + display: flex; + flex-direction: column; + backdrop-filter: blur(80px) saturate(100%) brightness(1.05); + -webkit-backdrop-filter: blur(80px) saturate(200%) brightness(1.05); + border-radius: 28px; + overflow: hidden; + opacity: 0; + transform: scale(0.92) rotateX(8deg); + animation: panelLiquidIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.ai-avatar-wrap { + position: relative; + width: 56px; + height: 56px; + display: flex; + align-items: center; + justify-content: center; +} + +.ai-avatar-pulse { + display: none; +} + +@keyframes aiAvatarPulse { + + 0%, + 100% { + transform: scale(1); + opacity: 0.4; + } + + 50% { + transform: scale(1.2); + opacity: 0.15; + } +} + +.ai-avatar-img { + width: 52px; + height: 52px; + border-radius: 16px; + object-fit: contain; + position: relative; + z-index: 1; +} + +.ai-help-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 24px 28px 20px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.04), transparent); +} + +.ai-help-header-left { + display: flex; + align-items: center; + gap: 18px; +} + +.ai-help-header-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.ai-help-settings-btn { + width: 40px; + height: 40px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + border: none; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} + +.ai-help-settings-btn:hover { + background: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.9); + transform: rotate(45deg); +} + +.ai-help-settings-btn.hidden, +.ai-help-settings-btn[hidden] { + display: none !important; + visibility: hidden !important; + opacity: 0 !important; + pointer-events: none !important; +} + +.ai-help-modal .activity-icon { + background: linear-gradient(135deg, rgba(167, 139, 250, 0.12), rgba(139, 92, 246, 0.06)); +} + +.ai-help-modal .activity-icon i { + color: #a78bfa; +} + +.ai-help-modal .activity-icon-pulse { + background: linear-gradient(135deg, rgba(167, 139, 250, 0.15), rgba(139, 92, 246, 0.08)); +} + +.ai-help-setup { + flex: 1; + display: flex; + flex-direction: column; + padding: 20px 28px; + overflow-y: auto; +} + +@keyframes aiTextFadeIn { + from { + opacity: 0; + filter: blur(4px); + transform: translateY(10px); + } + + to { + opacity: 1; + filter: blur(0); + transform: translateY(0); + } +} + +.ai-setup-welcome { + text-align: center; + padding: 20px 0 30px; + opacity: 0; + animation: aiTextFadeIn 0.5s ease 0.2s forwards; +} + +.ai-agent-icon { + width: 72px; + height: 72px; + margin: 0 auto 20px; + border-radius: 20px; + background: linear-gradient(135deg, rgba(167, 139, 250, 0.2), rgba(139, 92, 246, 0.15)); + display: flex; + align-items: center; + justify-content: center; + position: relative; + box-shadow: + 0 8px 32px rgba(139, 92, 246, 0.25), + inset 0 1px 0 rgba(255, 255, 255, 0.1); +} + +.ai-agent-icon::before { + content: ''; + position: absolute; + inset: 0; + border-radius: 20px; + padding: 1px; + background: linear-gradient(135deg, rgba(167, 139, 250, 0.5), rgba(139, 92, 246, 0.2)); + -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; + pointer-events: none; +} + +.ai-agent-icon i { + font-size: 32px; + color: #c4b5fd; + filter: drop-shadow(0 2px 8px rgba(139, 92, 246, 0.4)); +} + +.ai-agent-icon::after { + content: ''; + position: absolute; + width: 8px; + height: 8px; + background: #4ade80; + border-radius: 50%; + bottom: 4px; + right: 4px; + box-shadow: 0 0 8px rgba(74, 222, 128, 0.6); + animation: agentPulse 2s ease-in-out infinite; +} + +@keyframes agentPulse { + + 0%, + 100% { + opacity: 1; + transform: scale(1); + } + + 50% { + opacity: 0.6; + transform: scale(1.2); + } +} + +.ai-setup-emoji { + display: none; +} + +.ai-setup-welcome h2 { + font-size: 24px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + margin: 0 0 8px; +} + +.ai-setup-welcome p { + font-size: 14px; + color: rgba(255, 255, 255, 0.5); + margin: 0; +} + +.ai-provider-grid { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 12px; + opacity: 0; + animation: aiTextFadeIn 0.5s ease 0.3s forwards; +} + +.ai-provider-grid .ai-provider-card:last-child:nth-child(odd) { + grid-column: 1 / -1; +} + +.ai-provider-card { + display: flex; + align-items: center; + gap: 14px; + padding: 16px 18px; + background: rgba(255, 255, 255, 0.03); + border-radius: 16px; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + text-align: left; + color: inherit; + border: none; +} + +.ai-provider-card:hover { + background: rgba(255, 255, 255, 0.08); + transform: scale(1.03); + border: none; +} + +.ai-provider-card.connected { + background: rgba(74, 222, 128, 0.08); +} + +.ai-provider-card.connected:hover { + background: rgba(74, 222, 128, 0.12); + transform: scale(1.03); +} + +.ai-provider-icon { + width: 44px; + height: 44px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + font-size: 20px; + flex-shrink: 0; + background: transparent; +} + +.ai-provider-icon img { + width: 32px; + height: 32px; + object-fit: contain; +} + +.ai-provider-icon.openai-icon { + background: transparent; +} + +.ai-provider-icon.anthropic-icon { + background: transparent; +} + +.ai-provider-icon.openai-compatible-icon { + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.85); +} + +.ai-provider-icon.google-icon { + background: transparent; +} + +.ai-provider-icon.groq-icon { + background: transparent; +} + +.ai-provider-icon.hf-icon { + background: transparent; + color: #ffd54f; +} + +.ai-provider-icon.together-icon { + background: transparent; + color: #3b82f6; +} + +.ai-provider-icon.cohere-icon { + background: transparent; + color: #d946ef; +} + +.ai-provider-icon.openrouter-icon { + background: transparent; + color: #22c55e; +} + +.ai-provider-info { + flex: 1; + min-width: 0; +} + +.ai-provider-name { + font-size: 15px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); + margin-bottom: 2px; +} + +.ai-provider-desc { + font-size: 12px; + color: rgba(255, 255, 255, 0.6); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; +} + +.ai-provider-status { + width: 10px; + height: 10px; + border-radius: 50%; + flex-shrink: 0; +} + +.ai-provider-status.connected { + background: #4ade80; +} + +.ai-provider-status-wrap { + display: flex; + align-items: center; + gap: 6px; + flex-shrink: 0; +} + +.ai-provider-status-label { + font-size: 10px; + color: #6ee7a0; + font-family: Inter, sans-serif !important; + font-weight: 500; + text-transform: uppercase; + letter-spacing: 0.5px; + display: none; +} + +.ai-provider-status.connected+.ai-provider-status-label { + display: inline; + font-family: sans-serif; +} + +.ai-api-key-form { + padding: 20px 0; + animation: aiSlideIn 0.3s ease forwards; +} + +.ai-config-field { + margin-bottom: 14px; +} + +.ai-config-label { + display: block; + font-size: 12px; + font-weight: 600; + letter-spacing: 0.04em; + text-transform: uppercase; + color: rgba(255, 255, 255, 0.56); + margin: 0 0 8px 4px; +} + +@keyframes aiSlideIn { + from { + opacity: 0; + transform: translateX(20px); + } + + to { + opacity: 1; + transform: translateX(0); + } +} + +.ai-key-form-header { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 24px; +} + +.ai-key-back { + width: 36px; + height: 36px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.06); + border: none; + color: rgba(255, 255, 255, 0.7); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.2s ease; +} + +.ai-key-back:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; +} + +.ai-key-form-header span { + font-size: 18px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); +} + +.ai-key-input-wrap { + position: relative; + margin-bottom: 12px; +} + +.ai-key-input-wrap input { + width: 100%; + padding: 16px 50px 16px 18px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 14px; + color: rgba(255, 255, 255, 0.9); + font-size: 15px; + outline: none; + transition: all 0.3s ease; + box-sizing: border-box; +} + +.ai-key-input-wrap input:focus { + border-color: rgba(167, 139, 250, 0.5); + background: rgba(255, 255, 255, 0.06); + box-shadow: 0 0 0 3px rgba(167, 139, 250, 0.1); +} + +.ai-key-input-wrap input::placeholder { + color: rgba(255, 255, 255, 0.3); +} + +.ai-base-url-input-wrap input { + padding-right: 18px; +} + +.ai-key-toggle { + position: absolute; + right: 12px; + top: 50%; + transform: translateY(-50%); + width: 32px; + height: 32px; + border-radius: 8px; + background: transparent; + border: none; + color: rgba(255, 255, 255, 0.4); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; +} + +.ai-key-toggle:hover { + color: rgba(255, 255, 255, 0.7); +} + +.ai-key-hint { + font-size: 12px; + color: rgba(255, 255, 255, 0.4); + margin-bottom: 20px; + padding-left: 4px; +} + +.ai-key-save { + width: 100%; + padding: 16px; + background: linear-gradient(135deg, #a78bfa, #8b5cf6); + border: none; + border-radius: 14px; + color: #fff; + font-size: 15px; + font-weight: 600; + cursor: pointer; + transition: all 0.3s ease; + box-shadow: 0 8px 30px rgba(139, 92, 246, 0.3); +} + +.ai-key-save:hover:not(:disabled) { + transform: translateY(-2px); + box-shadow: 0 12px 40px rgba(139, 92, 246, 0.4); +} + +.ai-key-save:disabled { + opacity: 0.4; + cursor: not-allowed; +} + +.ai-help-chat { + flex: 1; + display: flex; + flex-direction: row; + min-height: 0; + min-width: 0; + overflow-x: hidden; +} + +.ai-chat-sidebar { + width: 220px; + min-width: 220px; + background: rgba(0, 0, 0, 0.3); + border-right: 1px solid rgba(255, 255, 255, 0.06); + display: flex; + flex-direction: column; + position: relative; + overflow-x: hidden; + transition: all 0.3s ease; +} + +.ai-chat-sidebar.collapsed { + width: 0; + min-width: 0; + overflow: hidden; + border-right: none; +} + +.ai-sidebar-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 14px 16px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + font-size: 13px; + font-weight: 500; + color: rgba(255, 255, 255, 0.7); +} + +.ai-new-chat-btn { + width: 28px; + height: 28px; + border-radius: 8px; + background: rgba(139, 92, 246, 0.15); + border: none; + color: #a78bfa; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + transition: all 0.2s ease; +} + +.ai-new-chat-btn:hover { + background: rgba(139, 92, 246, 0.25); + color: #c4b5fd; +} + +.ai-chats-list { + flex: 1; + overflow-y: auto; + overflow-x: hidden; + padding: 8px; + display: flex; + flex-direction: column; + gap: 4px; +} + +.ai-no-chats { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 40px 16px; + color: rgba(255, 255, 255, 0.3); + text-align: center; +} + +.ai-no-chats i { + font-size: 32px; + margin-bottom: 12px; + opacity: 0.5; +} + +.ai-no-chats p { + font-size: 13px; + margin: 0; +} + +.ai-chat-item { + display: flex; + align-items: center; + padding: 10px 18px 10px 12px; + border-radius: 8px; + background: transparent; + border: none; + color: rgba(255, 255, 255, 0.7); + font-size: 13px; + cursor: pointer; + transition: all 0.2s ease; + text-align: left; + box-sizing: border-box; + width: 100%; + min-width: 0; + gap: 8px; + position: relative; +} + +.ai-chat-item:hover { + background: rgba(255, 255, 255, 0.05); + color: rgba(255, 255, 255, 0.9); +} + +.ai-chat-item.active { + background: rgba(139, 92, 246, 0.15); + color: #c4b5fd; +} + +.ai-chat-item-icon { + font-size: 12px; + opacity: 0.6; + flex-shrink: 0; +} + +.ai-chat-item-content { + flex: 1; + display: flex; + flex-direction: column; + gap: 2px; + overflow: hidden; +} + +.ai-chat-item-title { + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ai-chat-item-date { + font-size: 11px; + color: rgba(255, 255, 255, 0.35); +} + +.ai-chat-item-delete { + width: 24px; + height: 24px; + border-radius: 6px; + background: transparent; + border: none; + color: rgba(255, 255, 255, 0.3); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 11px; + opacity: 0; + transition: opacity 0.18s ease, background-color 0.18s ease, color 0.18s ease, transform 0.18s ease; + flex-shrink: 0; + margin-right: 0; + margin-left: 0; +} + +.ai-chat-item:hover .ai-chat-item-delete { + opacity: 1; +} + +.ai-chat-item-delete:hover { + background: rgba(239, 68, 68, 0.2); + color: #fca5a5; + transform: scale(1.08); +} + +.ai-sidebar-toggle { + position: absolute; + right: -28px; + top: 50%; + transform: translateY(-50%); + width: 28px; + height: 56px; + border-radius: 0 10px 10px 0; + background: rgba(15, 17, 22, 0.95); + border: 1px solid rgba(255, 255, 255, 0.1); + border-left: none; + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + transition: all 0.3s ease; + z-index: 100; +} + +.ai-sidebar-toggle:hover { + background: rgba(139, 92, 246, 0.2); + color: #a78bfa; + width: 32px; +} + +.ai-chat-sidebar.collapsed+.ai-chat-main .ai-sidebar-expand-btn { + display: flex; +} + +.ai-sidebar-expand-btn { + position: relative; + width: 36px; + height: 36px; + border-radius: 10px; + background: rgba(139, 92, 246, 0.15); + color: #a78bfa; + cursor: pointer; + display: none; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.2s ease; + border: none; + flex-shrink: 0; +} + +.ai-sidebar-expand-btn:hover { + background: rgba(139, 92, 246, 0.25); +} + +.ai-chat-sidebar.collapsed+.ai-chat-main .ai-model-selector { + margin-left: 8px; +} + +.ai-chat-sidebar.collapsed .ai-sidebar-toggle i { + transform: rotate(180deg); +} + +.ai-chat-main { + flex: 1; + display: flex; + flex-direction: column; + min-width: 0; + position: relative; + overflow-x: hidden; +} + +.ai-thinking-badge { + display: inline-flex; + align-items: center; + gap: 5px; + padding: 3px 10px; + border-radius: 20px; + background: rgba(139, 92, 246, 0.08); + border: 1px solid rgba(139, 92, 246, 0.1); + color: rgba(167, 139, 250, 0.7); + font-size: 11px; + font-weight: 500; + letter-spacing: 0.2px; + backdrop-filter: blur(6px); + -webkit-backdrop-filter: blur(6px); + cursor: pointer; + transition: background-color 0.18s ease, border-color 0.18s ease, color 0.18s ease, transform 0.18s ease; +} + +.ai-thinking-badge i { + font-size: 9px; + color: rgba(167, 139, 250, 0.6); +} + +.ai-thinking-label { + color: rgba(255, 255, 255, 0.35); +} + +.ai-thinking-shell { + display: flex; + flex-direction: column; + align-items: flex-start; + width: min(100%, 760px); +} + +.ai-thinking-toggle { + display: inline-flex; + align-items: center; + cursor: pointer; + list-style: none; + outline: none; +} + +.ai-thinking-toggle::-webkit-details-marker { + display: none; +} + +.ai-thinking-toggle::marker { + content: ''; +} + +.ai-thinking-toggle:hover .ai-thinking-badge, +.ai-thinking-toggle:focus-visible .ai-thinking-badge, +.ai-thinking-shell[open] .ai-thinking-badge { + background: rgba(139, 92, 246, 0.12); + border-color: rgba(167, 139, 250, 0.2); + color: rgba(216, 195, 255, 0.92); + transform: translateY(-1px); +} + +.ai-thinking-caret { + display: inline-flex; + align-items: center; + margin-left: 2px; + color: rgba(255, 255, 255, 0.34); +} + +.ai-thinking-caret i { + font-size: 9px; + transition: transform 0.18s ease, color 0.18s ease; +} + +.ai-thinking-shell[open] .ai-thinking-caret i { + transform: rotate(90deg); + color: rgba(216, 195, 255, 0.9); +} + +.ai-thinking-panel { + width: min(100%, 760px); + margin-top: 8px; + padding: 14px 16px; + border-radius: 16px; + background: rgba(255, 255, 255, 0.035); + border: 1px solid rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.76); + max-height: 260px; + overflow: auto; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.035); +} + +.ai-thinking-panel .ai-code-block { + margin: 6px 0; +} + +.ai-chat-toolbar { + position: relative; + z-index: 20; + display: flex; + align-items: center; + padding: 12px 20px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + gap: 12px; + overflow: visible; +} + +.ai-chat-toolbar .ai-chat-clear { + margin-left: auto; +} + +.ai-model-selector { + position: relative; + display: flex; + align-items: center; + flex: 0 0 240px; + min-width: 240px; + max-width: 240px; + z-index: 30; + border-radius: 14px; + overflow: visible; +} + +.ai-model-selector select { + position: absolute; + inset: 0; + width: 100%; + height: 100%; + opacity: 0; + pointer-events: none; +} + +.ai-model-trigger { + position: relative; + z-index: 1; + width: 100%; + min-width: 0; + padding: 13px 42px 13px 16px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 14px; + color: rgba(255, 255, 255, 0.92); + font-size: 13px; + font-weight: 500; + line-height: 1.2; + cursor: pointer; + box-sizing: border-box; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.05), + 0 8px 24px rgba(0, 0, 0, 0.14); + transition: background-color 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease, color 0.18s ease; + display: flex; + align-items: center; + text-align: left; +} + +.ai-model-trigger:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.16); +} + +.ai-model-trigger:focus-visible, +.ai-model-selector.open .ai-model-trigger { + outline: none; + background: rgba(255, 255, 255, 0.065); + border-color: rgba(167, 139, 250, 0.34); + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.06), + 0 0 0 3px rgba(167, 139, 250, 0.08), + 0 10px 28px rgba(0, 0, 0, 0.16); +} + +.ai-model-selector.is-disabled .ai-model-trigger, +.ai-model-trigger:disabled { + opacity: 0.7; + cursor: not-allowed; +} + +.ai-model-current { + display: block; + width: 100%; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ai-model-trigger i { + position: absolute; + right: 14px; + color: rgba(255, 255, 255, 0.42); + font-size: 11px; + pointer-events: none; + transition: color 0.18s ease, transform 0.18s ease; +} + +.ai-model-trigger:hover i { + color: rgba(255, 255, 255, 0.58); +} + +.ai-model-trigger:focus-visible i, +.ai-model-selector.open .ai-model-trigger i { + color: rgba(199, 178, 255, 0.88); + transform: translateY(1px); +} + +.ai-model-options-shell { + position: absolute; + top: calc(100% + 10px); + left: 0; + right: 0; + z-index: 40; + width: 100%; + box-sizing: border-box; + padding: 8px; + border-radius: 18px; + overflow: hidden; + background: + linear-gradient(180deg, rgba(26, 31, 40, 0.98), rgba(14, 18, 25, 0.97)); + border: 1px solid rgba(255, 255, 255, 0.12); + box-shadow: + 0 18px 44px rgba(0, 0, 0, 0.42), + 0 0 0 1px rgba(10, 12, 16, 0.28), + inset 0 1px 0 rgba(255, 255, 255, 0.05); + opacity: 0; + visibility: hidden; + transform: translateY(6px) scale(0.985); + pointer-events: none; + transition: opacity 0.16s ease, transform 0.16s ease; + transform-origin: top center; +} + +.ai-model-options-shell::before { + content: ''; + position: absolute; + inset: 0; + z-index: 0; + border-radius: inherit; + background: + linear-gradient(180deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0.02)), + radial-gradient(circle at top, rgba(167, 139, 250, 0.08), transparent 58%); + pointer-events: none; +} + +.ai-model-options-shell::after { + content: ''; + position: absolute; + inset: 0; + z-index: 1; + border-radius: inherit; + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.08), + inset 0 -1px 0 rgba(255, 255, 255, 0.02); + pointer-events: none; +} + +.ai-model-selector.open .ai-model-options-shell { + opacity: 1; + visibility: visible; + transform: translateY(0) scale(1); + pointer-events: auto; +} + +.ai-model-options { + position: relative; + z-index: 2; + display: flex; + flex-direction: column; + gap: 2px; + max-height: 274px; + overflow-y: auto; + overflow-x: hidden; + box-sizing: border-box; + pointer-events: auto; + scrollbar-width: thin; + scrollbar-color: rgba(255, 255, 255, 0.12) transparent; +} + +.ai-model-group { + padding: 8px 10px 6px; + color: rgba(255, 255, 255, 0.36); + font-size: 10px; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; +} + +.ai-model-option { + width: 100%; + padding: 11px 12px; + border: none; + border-radius: 12px; + background: transparent; + color: rgba(255, 255, 255, 0.82); + cursor: pointer; + box-sizing: border-box; + pointer-events: auto; + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + text-align: left; + transition: background-color 0.14s ease, color 0.14s ease, box-shadow 0.14s ease; +} + +.ai-model-option:hover, +.ai-model-option:focus-visible { + outline: none; + background: rgba(255, 255, 255, 0.07); + color: rgba(255, 255, 255, 0.96); +} + +.ai-model-option.selected { + background: linear-gradient(135deg, rgba(167, 139, 250, 0.2), rgba(124, 58, 237, 0.14)); + color: #f2ebff; + box-shadow: inset 0 0 0 1px rgba(199, 178, 255, 0.14); +} + +.ai-model-option-name { + min-width: 0; + white-space: normal; + line-height: 1.35; + word-break: break-word; +} + +.ai-model-option-check { + opacity: 0; + color: rgba(214, 198, 255, 0.9); + transition: opacity 0.14s ease; + flex-shrink: 0; +} + +.ai-model-option.selected .ai-model-option-check { + opacity: 1; +} + +.ai-model-empty { + padding: 12px; + color: rgba(255, 255, 255, 0.44); + font-size: 12px; + text-align: center; +} + +.ai-chat-clear { + width: 36px; + height: 36px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.04); + border: none; + color: rgba(255, 255, 255, 0.4); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.2s ease; +} + +.ai-chat-clear:hover { + background: rgba(239, 68, 68, 0.15); + color: #fca5a5; +} + +.ai-chat-messages { + flex: 1; + overflow-y: auto; + overflow-x: hidden; + padding: 20px 28px; + display: flex; + flex-direction: column; + gap: 16px; + mask-image: linear-gradient(to bottom, transparent, #000 16px, #000 calc(100% - 16px), transparent); + -webkit-mask-image: linear-gradient(to bottom, transparent, #000 16px, #000 calc(100% - 16px), transparent); +} + +.ai-chat-welcome { + text-align: center; + padding: 40px 20px; + opacity: 0; + animation: aiTextFadeIn 0.5s ease 0.2s forwards; +} + +.ai-welcome-emoji { + font-size: 48px; + margin-bottom: 16px; +} + +.ai-chat-welcome h3 { + font-size: 22px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + margin: 0 0 8px; +} + +.ai-chat-welcome p { + font-size: 14px; + color: rgba(255, 255, 255, 0.5); + margin: 0 0 24px; +} + +.ai-welcome-suggestions { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 8px; +} + +.ai-suggestion { + padding: 12px 20px; + background: rgba(255, 255, 255, 0.04); + border-radius: 24px; + color: rgba(255, 255, 255, 0.7); + font-size: 13px; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.16, 1, 0.3, 1); + border: none; +} + +.ai-suggestion:hover { + background: rgba(167, 139, 250, 0.2); + color: #e0d4ff; + transform: scale(1.01); +} + +.ai-message { + display: flex; + gap: 14px; + max-width: 88%; + opacity: 1; +} + +.ai-message.ai-enter, +.ai-message.ai-typing-container { + opacity: 0; + animation: aiMessageIn 0.28s cubic-bezier(0.16, 1, 0.3, 1) forwards; +} + +@keyframes aiMessageIn { + from { + opacity: 0; + transform: translateY(16px) scale(0.98); + filter: blur(4px); + } + + to { + opacity: 1; + transform: translateY(0) scale(1); + filter: blur(0); + } +} + +.ai-message.user { + align-self: flex-end; + flex-direction: row-reverse; +} + +.ai-msg-avatar { + width: 28px; + height: 28px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 13px; + flex-shrink: 0; + margin-top: 2px; + overflow: hidden; + transition: transform 0.2s ease; +} + +.ai-msg-avatar.ai { + background: rgba(167, 139, 250, 0.12); + border: 1px solid rgba(167, 139, 250, 0.15); +} + +.ai-msg-avatar.user { + background: linear-gradient(145deg, rgba(96, 165, 250, 0.15), rgba(59, 130, 246, 0.08)); + color: #60a5fa; + border: 1px solid rgba(96, 165, 250, 0.12); +} + +.ai-message:hover .ai-msg-avatar { + transform: scale(1.05); +} + +.ai-message-avatar-img { + width: 100%; + height: 100%; + object-fit: contain; + border-radius: 10px; +} + +.ai-user-avatar-img { + width: 100%; + height: 100%; + object-fit: cover; + border-radius: 10px; +} + +.user-message-avatar { + width: 28px; + height: 28px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 13px; + flex-shrink: 0; +} + +.ai-message-avatar { + width: 28px; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + overflow: hidden; + border-radius: 10px; + background: rgba(167, 139, 250, 0.12); + border: 1px solid rgba(167, 139, 250, 0.15); +} + +.ai-message-avatar .ai-message-avatar-img { + width: 100%; + height: 100%; + object-fit: contain; + border-radius: 10px; +} + +.ai-message-body { + display: flex; + flex-direction: column; + gap: 6px; +} + +.ai-message-meta { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 8px; +} + +.ai-message-content { + padding: 16px 20px; + border-radius: 20px; + font-size: 14px; + line-height: 1.6; + transition: background-color 0.18s ease, box-shadow 0.18s ease, transform 0.18s ease, opacity 0.18s ease; +} + +.ai-message.ai .ai-message-content { + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.92); + border-top-left-radius: 6px; + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); +} + +.ai-message.ai:hover .ai-message-content { + background: rgba(255, 255, 255, 0.06); +} + +.ai-message.user .ai-message-content { + background: linear-gradient(145deg, rgba(167, 139, 250, 0.18), rgba(139, 92, 246, 0.12)); + color: #f0ebff; + border-top-right-radius: 6px; + box-shadow: 0 4px 20px rgba(139, 92, 246, 0.12); +} + +.ai-message.user:hover .ai-message-content { + background: linear-gradient(145deg, rgba(167, 139, 250, 0.24), rgba(139, 92, 246, 0.18)); +} + +.ai-message-content { + user-select: text !important; + -webkit-user-select: text !important; + cursor: default; +} + +.ai-message-content * { + user-select: text !important; + -webkit-user-select: text !important; +} + +.ai-chat-messages { + user-select: text !important; + -webkit-user-select: text !important; +} + +.ai-code-block { + background: #1a1b26; + border-radius: 10px; + overflow: hidden; + margin: 8px 0; + border: 1px solid rgba(255, 255, 255, 0.06); + font-family: 'SF Mono', 'Fira Code', 'Cascadia Code', 'Consolas', monospace; +} + +.ai-code-header { + display: flex; + align-items: center; + gap: 8px; + padding: 7px 12px; + background: rgba(255, 255, 255, 0.04); + border-bottom: 1px solid rgba(255, 255, 255, 0.04); +} + +.ai-code-dots { + display: flex; + gap: 5px; + align-items: center; +} + +.ai-code-dots .dot-red, +.ai-code-dots .dot-yellow, +.ai-code-dots .dot-green { + width: 8px; + height: 8px; + border-radius: 50%; + display: inline-block; +} + +.ai-code-dots .dot-red { background: #ff5f57; } +.ai-code-dots .dot-yellow { background: #febc2e; } +.ai-code-dots .dot-green { background: #28c840; } + +.ai-code-lang { + font-size: 10px; + color: rgba(255, 255, 255, 0.3); + text-transform: uppercase; + letter-spacing: 0.5px; + flex: 1; +} + +.ai-code-copy { + background: none; + border: none; + color: rgba(255, 255, 255, 0.3); + cursor: pointer; + padding: 2px 6px; + border-radius: 4px; + font-size: 12px; + transition: all 0.2s ease; + display: flex; + align-items: center; +} + +.ai-code-copy:hover { + color: rgba(255, 255, 255, 0.8); + background: rgba(255, 255, 255, 0.06); +} + +.ai-code-copy.copied { + color: #28c840; +} + +.ai-code-pre { + margin: 0; + padding: 10px 14px; + overflow-x: auto; + font-size: 12.5px; + line-height: 1.5; + color: #c0caf5; +} + +.ai-code-pre code { + font-family: inherit; + white-space: pre; +} + +.ai-inline-code { + background: rgba(167, 139, 250, 0.15); + color: #d4bfff; + padding: 2px 6px; + border-radius: 4px; + font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace; + font-size: 0.9em; +} + +.ai-message-content strong { + color: #fff; + font-weight: 600; +} + +.ai-message-content em { + font-style: italic; + color: rgba(255, 255, 255, 0.85); +} + +.ai-message-content del { + text-decoration: line-through; + opacity: 0.6; +} + +.ai-md-h2 { + font-size: 1.3em; + font-weight: 700; + margin: 14px 0 8px; + color: #fff; +} + +.ai-md-h3 { + font-size: 1.15em; + font-weight: 600; + margin: 12px 0 6px; + color: #fff; +} + +.ai-md-h4 { + font-size: 1.05em; + font-weight: 600; + margin: 10px 0 4px; + color: rgba(255, 255, 255, 0.92); +} + +.ai-md-ul, .ai-md-ol { + margin: 8px 0; + padding-left: 22px; +} + +.ai-md-li, .ai-md-oli { + margin: 3px 0; + line-height: 1.5; +} + +.ai-md-quote { + border-left: 3px solid rgba(167, 139, 250, 0.5); + padding: 6px 14px; + margin: 8px 0; + color: rgba(255, 255, 255, 0.7); + background: rgba(167, 139, 250, 0.06); + border-radius: 0 6px 6px 0; +} + +.ai-md-hr { + border: none; + border-top: 1px solid rgba(255, 255, 255, 0.1); + margin: 12px 0; +} + +.ai-md-link { + color: #a78bfa; + text-decoration: none; + border-bottom: 1px solid rgba(167, 139, 250, 0.3); + transition: all 0.2s ease; +} + +.ai-md-link:hover { + color: #c4b5fd; + border-bottom-color: rgba(167, 139, 250, 0.6); +} + +.ai-message-attachment { + margin-top: 10px; + border-radius: 12px; + overflow: hidden; + max-width: 300px; +} + +.ai-message-attachment img { + width: 100%; + height: auto; + display: block; +} + +.ai-message-attachment-file { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 14px; + background: rgba(255, 255, 255, 0.06); + border-radius: 10px; +} + +.ai-message-attachment-file i { + font-size: 20px; + color: #a78bfa; +} + +.ai-message-attachment-file span { + font-size: 13px; + color: rgba(255, 255, 255, 0.7); +} + +.ai-typing { + display: flex; + align-items: center; + gap: 6px; + padding: 10px 2px; + min-height: 16px; +} + +.ai-typing-dot { + width: 7px; + height: 7px; + border-radius: 50%; + background: rgba(167, 139, 250, 0.62); + box-shadow: 0 0 0 1px rgba(167, 139, 250, 0.08); + animation: aiTypingDot 1.15s cubic-bezier(0.37, 0, 0.2, 1) infinite; + will-change: transform, opacity; +} + +.ai-typing-dot:nth-child(2) { + animation-delay: 0.16s; +} + +.ai-typing-dot:nth-child(3) { + animation-delay: 0.32s; +} + +@keyframes aiTypingDot { + + 0%, + 65%, + 100% { + transform: translateY(0); + opacity: 0.34; + } + + 35% { + transform: translateY(-2px) scale(1.04); + opacity: 1; + } +} + +.ai-typing-container { + transition: opacity 0.18s ease, transform 0.18s ease, filter 0.18s ease; +} + +.ai-typing-container.is-exiting { + opacity: 0; + transform: translateY(6px); + filter: blur(2px); + pointer-events: none; +} + +.ai-typing-shell { + min-width: 54px; +} + +.ai-streaming-content { + transform-origin: left center; + animation: aiStreamingReveal 0.22s ease; +} + +@keyframes aiStreamingReveal { + from { + opacity: 0.72; + transform: translateY(2px); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + +.ai-chat-input-container { + padding: 0 20px 20px; +} + +.ai-chat-input-box { + display: flex; + flex-direction: column; + background: rgba(255, 255, 255, 0.042); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 24px; + overflow: hidden; + cursor: default; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.03); + transition: background-color 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease; +} + +.ai-chat-input-box:hover { + background: rgba(255, 255, 255, 0.05); + border-color: rgba(255, 255, 255, 0.09); +} + +.ai-chat-input-box:focus-within { + background: rgba(255, 255, 255, 0.052); + border-color: rgba(167, 139, 250, 0.12); + box-shadow: + inset 0 1px 0 rgba(255, 255, 255, 0.05), + 0 0 0 1px rgba(139, 92, 246, 0.06); +} + +.ai-chat-input-row { + display: flex; + align-items: flex-end; + width: 100%; +} + +.ai-chat-input-box textarea { + flex: 1; + padding: 14px 0 14px 22px; + background: transparent !important; + border: none !important; + color: rgba(255, 255, 255, 0.92); + font-size: 14px; + font-family: inherit; + resize: none; + outline: none !important; + box-shadow: none !important; + backdrop-filter: none !important; + max-height: 120px; + min-height: 22px; + line-height: 1.5; + caret-color: #e9ddff; + cursor: text; +} + +.ai-chat-input-box textarea:hover, +.ai-chat-input-box textarea:focus, +.ai-chat-input-box textarea:focus-visible, +.ai-chat-input-box textarea:active { + background: transparent !important; + border: none !important; + outline: none !important; + box-shadow: none !important; + backdrop-filter: none !important; +} + +.ai-chat-input-box textarea::placeholder { + color: rgba(255, 255, 255, 0.28); + font-size: 14px; +} + +.ai-chat-input-actions { + display: flex; + align-items: center; + gap: 4px; + flex-shrink: 0; + padding: 8px 10px 8px 4px; +} + +.ai-chat-attach-btn { + width: 32px; + height: 32px; + border-radius: 8px; + background: transparent; + border: none; + color: rgba(255, 255, 255, 0.3); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.2s ease; +} + +.ai-chat-attach-btn:hover { + color: rgba(255, 255, 255, 0.65); + background: rgba(255, 255, 255, 0.06); +} + +.ai-chat-send-btn { + position: relative; + width: 38px; + height: 38px; + border-radius: 13px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.018)); + border: 1px solid rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.42); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 13px; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06); + -webkit-appearance: none; + appearance: none; + -webkit-tap-highlight-color: transparent; + transition: + transform 0.16s ease, + background-color 0.16s ease, + background-image 0.16s ease, + border-color 0.16s ease, + color 0.16s ease, + box-shadow 0.16s ease, + opacity 0.16s ease; +} + +.ai-chat-send-btn::before { + content: ''; + position: absolute; + inset: 0; + border-radius: inherit; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.24), rgba(255, 255, 255, 0)); + opacity: 0.12; + pointer-events: none; +} + +.ai-chat-send-btn i { + position: relative; + z-index: 1; + font-size: 13px; +} + +.ai-chat-send-btn:not(:disabled) { + background: linear-gradient(135deg, #c6a9ff 0%, #9b72fa 42%, #7c3aed 100%); + border-color: rgba(210, 188, 255, 0.28); + color: #f8f5ff; + box-shadow: + 0 8px 18px rgba(91, 54, 180, 0.18), + inset 0 1px 0 rgba(255, 255, 255, 0.18); +} + +.ai-chat-send-btn:not(:disabled):hover { + background: linear-gradient(135deg, #d0b7ff 0%, #aa83ff 42%, #8750f2 100%); + border-color: rgba(223, 205, 255, 0.34); + box-shadow: + 0 8px 18px rgba(91, 54, 180, 0.2), + inset 0 1px 0 rgba(255, 255, 255, 0.22); +} + +.ai-chat-send-btn:not(:disabled):active { + transform: translateY(0); + box-shadow: + 0 5px 12px rgba(91, 54, 180, 0.14), + inset 0 1px 0 rgba(255, 255, 255, 0.14); +} + +.ai-chat-send-btn:disabled { + cursor: not-allowed; + opacity: 0.78; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.045), rgba(255, 255, 255, 0.02)); + border-color: rgba(255, 255, 255, 0.06); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05); +} + +.ai-chat-send-btn.generating { + background: linear-gradient(135deg, #ff988a 0%, #ef5c4f 42%, #d93025 100%); + border-color: rgba(255, 214, 208, 0.22); + color: #fff6f4; + box-shadow: + 0 10px 20px rgba(220, 38, 38, 0.16), + inset 0 1px 0 rgba(255, 255, 255, 0.18); +} + +.ai-chat-send-btn:focus-visible { + outline: none; + box-shadow: + 0 0 0 1px rgba(139, 92, 246, 0.12), + inset 0 1px 0 rgba(255, 255, 255, 0.14); +} + +@media (prefers-reduced-motion: reduce) { + .ai-chat-input-box, + .ai-chat-send-btn { + transition: none; + } +} + +.ai-attached-preview { + position: relative; + padding: 12px; + display: flex; + align-items: center; + gap: 10px; + background: rgba(167, 139, 250, 0.08); + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.ai-attached-preview img { + max-width: 120px; + max-height: 80px; + border-radius: 8px; + object-fit: cover; +} + +.ai-attached-preview.ai-attached-file { + padding: 10px 16px; +} + +.ai-attached-preview.ai-attached-file i { + font-size: 24px; + color: #a78bfa; +} + +.ai-attached-name { + display: none; +} + +.ai-attached-remove { + width: 24px; + height: 24px; + border-radius: 6px; + background: rgba(239, 68, 68, 0.15); + border: none; + color: #f87171; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + transition: all 0.2s ease; + flex-shrink: 0; +} + +.ai-attached-remove:hover { + background: rgba(239, 68, 68, 0.25); +} + + + +.ai-chat-input-wrap { + display: flex; + align-items: flex-end; + gap: 12px; + padding: 16px 28px 24px; + background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.2)); +} + +.ai-chat-input-wrap textarea { + flex: 1; + padding: 14px 18px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 16px; + color: rgba(255, 255, 255, 0.9); + font-size: 14px; + font-family: inherit; + resize: none; + outline: none; + transition: all 0.3s ease; + max-height: 120px; + line-height: 1.4; +} + +.ai-chat-input-wrap textarea:focus { + border-color: rgba(167, 139, 250, 0.5); + background: rgba(255, 255, 255, 0.06); +} + +.ai-chat-input-wrap textarea::placeholder { + color: rgba(255, 255, 255, 0.3); +} + +.ai-chat-send { + width: 48px; + height: 48px; + border-radius: 14px; + background: linear-gradient(135deg, #a78bfa, #8b5cf6); + border: none; + color: #fff; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + transition: all 0.3s ease; + flex-shrink: 0; + box-shadow: 0 8px 24px rgba(139, 92, 246, 0.3); +} + +.ai-chat-send:hover:not(:disabled) { + transform: translateY(-2px); + box-shadow: 0 12px 32px rgba(139, 92, 246, 0.4); +} + +.ai-chat-send:disabled { + opacity: 0.4; + cursor: not-allowed; + box-shadow: none; +} + +.ai-file-permission { + position: absolute; + inset: 0; + background: rgba(10, 10, 18, 0.95); + backdrop-filter: blur(20px); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + text-align: center; + padding: 40px; + z-index: 10; + animation: aiPermIn 0.3s ease forwards; +} + +@keyframes aiPermIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +.ai-perm-icon { + width: 72px; + height: 72px; + border-radius: 20px; + background: linear-gradient(135deg, rgba(251, 191, 36, 0.2), rgba(245, 158, 11, 0.1)); + display: flex; + align-items: center; + justify-content: center; + font-size: 32px; + color: #fbbf24; + margin-bottom: 24px; +} + +.ai-file-permission h3 { + font-size: 22px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + margin: 0 0 12px; +} + +.ai-file-permission p { + font-size: 14px; + color: rgba(255, 255, 255, 0.6); + margin: 0 0 32px; +} + +.ai-file-permission strong { + color: #fbbf24; +} + +.ai-perm-actions { + display: flex; + gap: 12px; +} + +.ai-perm-deny, +.ai-perm-allow { + padding: 14px 28px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s ease; + border: none; +} + +.ai-perm-deny { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.7); +} + +.ai-perm-deny:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; +} + +.ai-perm-allow { + background: linear-gradient(135deg, #4ade80, #22c55e); + color: #fff; + box-shadow: 0 8px 24px rgba(74, 222, 128, 0.3); +} + +.ai-perm-allow:hover { + transform: translateY(-2px); + box-shadow: 0 12px 32px rgba(74, 222, 128, 0.4); +} + +.ai-undo-toast { + position: absolute; + bottom: 100px; + left: 50%; + transform: translateX(-50%) translateY(30px) scale(0.95); + display: flex; + align-items: center; + gap: 14px; + padding: 16px 24px; + background: rgba(15, 17, 22, 0.85); + backdrop-filter: blur(40px) saturate(180%); + -webkit-backdrop-filter: blur(40px) saturate(180%); + border-radius: 18px; + color: rgba(255, 255, 255, 0.95); + font-size: 14px; + font-weight: 500; + opacity: 0; + visibility: hidden; + pointer-events: none; + transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1); + z-index: 200; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.06) inset; +} + +.ai-undo-toast.show { + opacity: 1; + visibility: visible; + pointer-events: auto; + transform: translateX(-50%) translateY(0) scale(1); + animation: toastSlideIn 0.4s cubic-bezier(0.16, 1, 0.3, 1); +} + +@keyframes toastSlideIn { + from { + opacity: 0; + transform: translateX(-50%) translateY(30px) scale(0.95); + filter: blur(4px); + } + + to { + opacity: 1; + transform: translateX(-50%) translateY(0) scale(1); + filter: blur(0); + } +} + +.ai-undo-toast i { + color: #4ade80; + font-size: 18px; + filter: drop-shadow(0 0 8px rgba(74, 222, 128, 0.4)); +} + +.ai-undo-btn { + padding: 10px 20px; + background: linear-gradient(135deg, rgba(167, 139, 250, 0.25), rgba(139, 92, 246, 0.2)); + border-radius: 12px; + color: #e0d4ff; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: background 0.2s ease, color 0.2s ease; + border: none; + box-shadow: none; +} + +.ai-undo-btn:hover { + background: linear-gradient(135deg, rgba(167, 139, 250, 0.4), rgba(139, 92, 246, 0.35)); + box-shadow: none; +} + +.ai-undo-dismiss { + width: 32px; + height: 32px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.06); + border: none; + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.2s ease; +} + +.ai-undo-dismiss:hover { + background: rgba(239, 68, 68, 0.2); + color: #fca5a5; +} + +@media (max-width: 640px) { + .ai-help-panel { + border-radius: 20px 20px 0 0; + max-height: 95vh; + height: 95vh; + } + + .ai-provider-grid { + grid-template-columns: 1fr; + } + + .ai-help-header { + padding: 18px 20px; + } + + .ai-help-setup, + .ai-chat-messages, + .ai-chat-input-wrap, + .ai-chat-toolbar { + padding-left: 20px; + padding-right: 20px; + } + + .ai-chat-sidebar { + position: absolute; + left: 0; + top: 0; + bottom: 0; + z-index: 10; + background: rgba(15, 17, 22, 0.98); + width: 75%; + max-width: 280px; + transform: translateX(-100%); + transition: transform 0.3s ease; + } + + .ai-chat-sidebar:not(.collapsed) { + transform: translateX(0); + } + + .ai-sidebar-toggle { + right: -36px; + width: 32px; + height: 56px; + } + + .ai-chat-sidebar.collapsed .ai-sidebar-toggle { + right: -36px; + } +} + +.ai-file-changes-bar { + position: absolute; + top: clamp(118px, 16vh, 156px); + left: 50%; + right: auto; + width: min(760px, calc(100% - 40px)); + background: rgba(20, 22, 28, 0.95); + backdrop-filter: blur(20px); + -webkit-backdrop-filter: blur(20px); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 14px; + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); + overflow: hidden; + transform: translateX(-50%) translateY(-28px); + opacity: 0; + pointer-events: none; + transition: all 0.3s ease; + z-index: 100; +} + +.ai-file-changes-bar.show { + transform: translateX(-50%) translateY(0); + opacity: 1; + pointer-events: auto; +} + +.ai-file-changes-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 16px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + background: rgba(0, 0, 0, 0.2); +} + +.ai-file-changes-title { + display: flex; + align-items: center; + gap: 10px; + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); +} + +.ai-file-changes-title i { + color: #a78bfa; + font-size: 16px; +} + +.ai-file-changes-count { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 20px; + height: 20px; + padding: 0 6px; + background: rgba(139, 92, 246, 0.2); + color: #c4b5fd; + border-radius: 10px; + font-size: 11px; + font-weight: 600; +} + +.ai-file-changes-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.ai-file-changes-accept-all, +.ai-file-changes-undo-all { + display: flex; + align-items: center; + gap: 6px; + padding: 6px 12px; + border-radius: 8px; + border: none; + font-size: 12px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s ease; +} + +.ai-file-changes-accept-all { + background: rgba(34, 197, 94, 0.15); + color: #4ade80; +} + +.ai-file-changes-accept-all:hover { + background: rgba(34, 197, 94, 0.25); +} + +.ai-file-changes-undo-all { + background: rgba(239, 68, 68, 0.15); + color: #f87171; +} + +.ai-file-changes-undo-all:hover { + background: rgba(239, 68, 68, 0.25); +} + +.ai-file-changes-toggle { + width: 28px; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.05); + border: none; + border-radius: 6px; + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + transition: all 0.2s ease; +} + +.ai-file-changes-toggle:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.8); +} + +.ai-file-changes-toggle i { + transition: transform 0.2s ease; +} + +.ai-file-changes-bar.collapsed .ai-file-changes-toggle i { + transform: rotate(180deg); +} + +.ai-file-changes-list { + max-height: 200px; + overflow-y: auto; + padding: 8px; + display: flex; + flex-direction: column; + gap: 6px; +} + +.ai-file-changes-bar.collapsed .ai-file-changes-list { + display: none; +} + +.ai-file-change-item { + display: flex; + align-items: center; + gap: 12px; + padding: 10px 12px; + background: rgba(255, 255, 255, 0.03); + border-radius: 10px; + border: 1px solid rgba(255, 255, 255, 0.04); + transition: all 0.2s ease; +} + +.ai-file-change-item:hover { + background: rgba(255, 255, 255, 0.05); + border-color: rgba(255, 255, 255, 0.08); +} + +.ai-file-change-icon { + width: 32px; + height: 32px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 8px; + font-size: 14px; +} + +.ai-file-change-icon.create { + background: rgba(34, 197, 94, 0.15); + color: #4ade80; +} + +.ai-file-change-icon.modify { + background: rgba(234, 179, 8, 0.15); + color: #fbbf24; +} + +.ai-file-change-icon.delete { + background: rgba(239, 68, 68, 0.15); + color: #f87171; +} + +.ai-file-change-icon.mkdir { + background: rgba(96, 165, 250, 0.15); + color: #60a5fa; +} + +.ai-file-change-info { + flex: 1; + min-width: 0; +} + +.ai-file-change-path { + font-size: 13px; + font-weight: 500; + color: rgba(255, 255, 255, 0.9); + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.ai-file-change-action { + font-size: 11px; + color: rgba(255, 255, 255, 0.4); + text-transform: capitalize; +} + +.ai-file-change-actions { + display: flex; + align-items: center; + gap: 6px; +} + +.ai-file-change-accept, +.ai-file-change-undo { + width: 28px; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 6px; + border: none; + cursor: pointer; + font-size: 12px; + transition: all 0.2s ease; +} + +.ai-file-change-accept { + background: rgba(34, 197, 94, 0.15); + color: #4ade80; +} + +.ai-file-change-accept:hover { + background: rgba(34, 197, 94, 0.3); +} + +.ai-file-change-undo { + background: rgba(239, 68, 68, 0.15); + color: #f87171; +} + +.ai-file-change-undo:hover { + background: rgba(239, 68, 68, 0.3); +} + +@media (max-width: 640px) { + .ai-file-changes-bar { + top: 108px; + width: calc(100% - 24px); + } +} + +.ai-confirm-dialog { + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(0, 0, 0, 0.6); + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + display: flex; + align-items: center; + justify-content: center; + opacity: 0; + pointer-events: none; + transition: opacity 0.2s ease; + z-index: 200; +} + +.ai-confirm-dialog.show { + opacity: 1; + pointer-events: auto; +} + +.ai-confirm-content { + width: 90%; + max-width: 400px; + background: rgba(20, 22, 28, 0.98); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 16px; + box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5); + transform: scale(0.95); + transition: transform 0.2s ease; +} + +.ai-confirm-dialog.show .ai-confirm-content { + transform: scale(1); +} + +.ai-confirm-header { + display: flex; + align-items: center; + gap: 12px; + padding: 16px 20px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.ai-confirm-header i { + font-size: 20px; + color: #fbbf24; +} + +.ai-confirm-header span { + font-size: 16px; + font-weight: 600; + color: rgba(255, 255, 255, 0.95); +} + +.ai-confirm-body { + padding: 20px; +} + +.ai-confirm-body p { + margin: 0 0 16px 0; + font-size: 14px; + color: rgba(255, 255, 255, 0.7); +} + +.ai-confirm-operation { + padding: 14px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 10px; + margin-bottom: 12px; +} + +.ai-confirm-action { + font-size: 12px; + text-transform: uppercase; + font-weight: 600; + color: #a78bfa; + margin-bottom: 6px; +} + +.ai-confirm-path { + font-size: 14px; + font-weight: 500; + color: rgba(255, 255, 255, 0.9); + word-break: break-all; +} + +.ai-confirm-preview { + max-height: 150px; + overflow-y: auto; + padding: 12px; + background: rgba(0, 0, 0, 0.3); + border-radius: 8px; + font-family: 'JetBrains Mono', 'Fira Code', monospace; + font-size: 12px; + color: rgba(255, 255, 255, 0.7); + white-space: pre-wrap; + word-break: break-word; +} + +.ai-confirm-preview:empty { + display: none; +} + +.ai-confirm-footer { + display: flex; + gap: 10px; + padding: 16px 20px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.ai-confirm-deny, +.ai-confirm-allow { + flex: 1; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 12px 16px; + border-radius: 10px; + border: none; + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s ease; +} + +.ai-confirm-deny { + background: rgba(239, 68, 68, 0.15); + color: #f87171; +} + +.ai-confirm-deny:hover { + background: rgba(239, 68, 68, 0.25); +} + +.ai-confirm-allow { + background: linear-gradient(135deg, rgba(34, 197, 94, 0.2), rgba(34, 197, 94, 0.15)); + color: #4ade80; +} + +.ai-confirm-allow:hover { + background: linear-gradient(135deg, rgba(34, 197, 94, 0.3), rgba(34, 197, 94, 0.25)); +} + + +.access-denied-container { + position: fixed; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, #0a0a0f 0%, #12121a 50%, #0d0d14 100%); + overflow: hidden; + z-index: 10000; +} + +.access-denied-container::before { + content: ''; + position: absolute; + inset: 0; + background: + radial-gradient(ellipse 80% 50% at 50% -20%, rgba(99, 102, 241, 0.15), transparent), + radial-gradient(ellipse 60% 40% at 80% 100%, rgba(239, 68, 68, 0.08), transparent), + radial-gradient(ellipse 50% 30% at 10% 80%, rgba(168, 85, 247, 0.06), transparent); + pointer-events: none; +} + +.access-denied-particles { + position: absolute; + inset: 0; + overflow: hidden; + pointer-events: none; +} + +.access-denied-particle { + position: absolute; + width: 4px; + height: 4px; + background: rgba(255, 255, 255, 0.1); + border-radius: 50%; + animation: access-denied-float 20s infinite linear; +} + +.access-denied-particle:nth-child(1) { + left: 10%; + animation-delay: 0s; + animation-duration: 25s; +} + +.access-denied-particle:nth-child(2) { + left: 20%; + animation-delay: -5s; + animation-duration: 20s; +} + +.access-denied-particle:nth-child(3) { + left: 30%; + animation-delay: -10s; + animation-duration: 28s; +} + +.access-denied-particle:nth-child(4) { + left: 40%; + animation-delay: -2s; + animation-duration: 22s; +} + +.access-denied-particle:nth-child(5) { + left: 50%; + animation-delay: -7s; + animation-duration: 26s; +} + +.access-denied-particle:nth-child(6) { + left: 60%; + animation-delay: -12s; + animation-duration: 24s; +} + +.access-denied-particle:nth-child(7) { + left: 70%; + animation-delay: -3s; + animation-duration: 27s; +} + +.access-denied-particle:nth-child(8) { + left: 80%; + animation-delay: -8s; + animation-duration: 21s; +} + +.access-denied-particle:nth-child(9) { + left: 90%; + animation-delay: -15s; + animation-duration: 23s; +} + +@keyframes access-denied-float { + 0% { + transform: translateY(100vh) scale(0); + opacity: 0; + } + + 10% { + opacity: 0.6; + } + + 90% { + opacity: 0.6; + } + + 100% { + transform: translateY(-100vh) scale(1); + opacity: 0; + } +} + +.access-denied-card { + position: relative; + max-width: 520px; + width: 90%; + padding: 48px 40px; + background: linear-gradient(145deg, + rgba(255, 255, 255, 0.05) 0%, + rgba(255, 255, 255, 0.02) 100%); + backdrop-filter: blur(40px); + -webkit-backdrop-filter: blur(40px); + border-radius: 32px; + border: 1px solid rgba(255, 255, 255, 0.08); + box-shadow: + 0 4px 24px rgba(0, 0, 0, 0.4), + 0 8px 48px rgba(0, 0, 0, 0.2), + inset 0 1px 0 rgba(255, 255, 255, 0.06); + text-align: center; + animation: access-denied-card-enter 0.8s cubic-bezier(0.16, 1, 0.3, 1) forwards; + transform: translateY(30px); + opacity: 0; +} + +@keyframes access-denied-card-enter { + to { + transform: translateY(0); + opacity: 1; + } +} + +.access-denied-card::before { + content: ''; + position: absolute; + inset: -1px; + border-radius: 32px; + padding: 1px; + background: linear-gradient(145deg, + rgba(239, 68, 68, 0.3), + rgba(168, 85, 247, 0.1), + transparent); + -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; + pointer-events: none; +} + +.sad-robot-container { + position: relative; + width: 160px; + height: 160px; + margin: 0 auto 32px; +} + +.sad-robot { + width: 100%; + height: 100%; + animation: sad-robot-hover 3s ease-in-out infinite; +} + +@keyframes sad-robot-hover { + + 0%, + 100% { + transform: translateY(0); + } + + 50% { + transform: translateY(-8px); + } +} + +.sad-robot-body { + fill: linear-gradient(180deg, #374151 0%, #1f2937 100%); +} + +.sad-robot-head { + fill: url(#robot-head-gradient); + filter: drop-shadow(0 4px 12px rgba(0, 0, 0, 0.3)); +} + +.sad-robot-eye { + fill: #1e293b; + animation: sad-robot-blink 4s ease-in-out infinite; +} + +.sad-robot-eye-glow { + fill: #ef4444; + animation: sad-robot-eye-pulse 2s ease-in-out infinite; +} + +@keyframes sad-robot-blink { + + 0%, + 90%, + 100% { + transform: scaleY(1); + } + + 95% { + transform: scaleY(0.1); + } +} + +@keyframes sad-robot-eye-pulse { + + 0%, + 100% { + opacity: 0.6; + } + + 50% { + opacity: 1; + } +} + +.sad-robot-mouth { + stroke: #374151; + stroke-width: 3; + stroke-linecap: round; + fill: none; + animation: sad-robot-mouth-wobble 4s ease-in-out infinite; +} + +@keyframes sad-robot-mouth-wobble { + + 0%, + 100% { + d: path("M 50 95 Q 65 85 80 95"); + } + + 50% { + d: path("M 50 95 Q 65 83 80 95"); + } +} + +.sad-robot-tear { + fill: #60a5fa; + opacity: 0; + animation: sad-robot-tear-fall 3s ease-in-out infinite; +} + +.sad-robot-tear:nth-child(2) { + animation-delay: 1.5s; +} + +@keyframes sad-robot-tear-fall { + 0% { + opacity: 0; + transform: translateY(0); + } + + 10% { + opacity: 0.8; + } + + 100% { + opacity: 0; + transform: translateY(40px); + } +} + +.sad-robot-antenna { + fill: #4b5563; +} + +.sad-robot-antenna-ball { + fill: #ef4444; + animation: sad-robot-antenna-pulse 1.5s ease-in-out infinite; +} + +@keyframes sad-robot-antenna-pulse { + + 0%, + 100% { + fill: #ef4444; + filter: drop-shadow(0 0 8px rgba(239, 68, 68, 0.6)); + } + + 50% { + fill: #f87171; + filter: drop-shadow(0 0 16px rgba(239, 68, 68, 0.9)); + } +} + +.sad-robot-shadow { + fill: rgba(0, 0, 0, 0.2); + animation: sad-robot-shadow-pulse 3s ease-in-out infinite; +} + +@keyframes sad-robot-shadow-pulse { + + 0%, + 100% { + transform: scale(1); + opacity: 0.3; + } + + 50% { + transform: scale(0.9); + opacity: 0.2; + } +} + +.access-denied-code { + font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace; + font-size: 72px; + font-weight: 800; + letter-spacing: -2px; + background: linear-gradient(135deg, + #f87171 0%, + #ef4444 50%, + #dc2626 100%); + -webkit-background-clip: text; + background-clip: text; + -webkit-text-fill-color: transparent; + margin: 0 0 8px; + animation: access-denied-code-glow 3s ease-in-out infinite; +} + +@keyframes access-denied-code-glow { + + 0%, + 100% { + filter: drop-shadow(0 0 20px rgba(239, 68, 68, 0.3)); + } + + 50% { + filter: drop-shadow(0 0 40px rgba(239, 68, 68, 0.5)); + } +} + +.access-denied-title { + font-size: 28px; + font-weight: 700; + color: #f8fafc; + margin: 0 0 24px; + letter-spacing: -0.5px; +} + +.access-denied-divider { + width: 60px; + height: 3px; + background: linear-gradient(90deg, transparent, rgba(239, 68, 68, 0.5), transparent); + margin: 0 auto 24px; + border-radius: 2px; +} + +.access-denied-message { + font-size: 16px; + color: #94a3b8; + line-height: 1.7; + margin: 0 0 12px; +} + +.access-denied-server { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 8px 16px; + background: rgba(239, 68, 68, 0.1); + border: 1px solid rgba(239, 68, 68, 0.2); + border-radius: 8px; + font-family: 'SF Mono', 'Fira Code', monospace; + font-size: 14px; + color: #f87171; + margin-bottom: 32px; +} + +.access-denied-server i { + font-size: 12px; + opacity: 0.7; +} + +.access-denied-btn { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 10px; + padding: 14px 32px; + background: linear-gradient(135deg, + rgba(99, 102, 241, 0.2) 0%, + rgba(139, 92, 246, 0.15) 100%); + border: 1px solid rgba(139, 92, 246, 0.3); + border-radius: 14px; + color: #c4b5fd; + font-size: 15px; + font-weight: 600; + text-decoration: none; + cursor: pointer; + transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); + position: relative; + overflow: hidden; +} + +.access-denied-btn::before { + content: ''; + position: absolute; + inset: 0; + background: linear-gradient(135deg, + rgba(139, 92, 246, 0.3) 0%, + rgba(99, 102, 241, 0.2) 100%); + opacity: 0; + transition: opacity 0.3s ease; +} + +.access-denied-btn:hover { + transform: translateY(-2px); + border-color: rgba(139, 92, 246, 0.5); + box-shadow: + 0 8px 24px rgba(139, 92, 246, 0.25), + 0 0 0 1px rgba(139, 92, 246, 0.1); +} + +.access-denied-btn:hover::before { + opacity: 1; +} + +.access-denied-btn i { + position: relative; + z-index: 1; + transition: transform 0.3s ease; +} + +.access-denied-btn span { + position: relative; + z-index: 1; +} + +.access-denied-btn:hover i { + transform: translateX(-3px); +} + +.access-denied-decor { + position: absolute; + border-radius: 50%; + filter: blur(60px); + pointer-events: none; + opacity: 0.4; +} + +.access-denied-decor-1 { + width: 300px; + height: 300px; + background: radial-gradient(circle, rgba(239, 68, 68, 0.3), transparent); + top: -150px; + right: -100px; +} + +.access-denied-decor-2 { + width: 200px; + height: 200px; + background: radial-gradient(circle, rgba(168, 85, 247, 0.25), transparent); + bottom: -100px; + left: -50px; +} + +.access-denied-footer { + margin-top: 32px; + padding-top: 24px; + border-top: 1px solid rgba(255, 255, 255, 0.05); +} + +.access-denied-footer-text { + font-size: 13px; + color: #64748b; + display: flex; + align-items: center; + justify-content: center; + gap: 6px; +} + +.access-denied-footer-text i { + color: #475569; +} + + +input[type="text"], +input[type="search"], +input[type="number"], +input[type="password"], +input[type="email"], +textarea, +select { + border: 0.5px solid rgba(255, 255, 255, 0.1) !important; + outline: none !important; + background: rgba(10, 12, 16, 0.5); + transition: border-color 0.2s, background 0.2s; + backdrop-filter: blur(4px); +} + +input:focus, +textarea:focus, +select:focus { + border-color: rgba(255, 255, 255, 0.25) !important; + background: rgba(14, 18, 24, 0.8); +} + +button, +.btn { + outline: none !important; +} + +.tooltip, +.popover { + backdrop-filter: blur(12px); + border: 0.5px solid rgba(255, 255, 255, 0.08); +} + +.monaco-editor, +.monaco-editor .overflow-guard, +.monaco-editor .inputarea { + background: transparent !important; + border: none !important; + outline: none !important; + box-shadow: none !important; +} + +.monaco-editor input[type="text"], +.monaco-editor input[type="search"], +.monaco-editor input[type="number"], +.monaco-editor input[type="password"], +.monaco-editor input[type="email"], +.monaco-editor textarea, +.monaco-editor select { + border: none !important; + outline: none !important; + background: transparent !important; + border-radius: 0 !important; + box-shadow: none !important; + transition: none !important; + backdrop-filter: none !important; +} + +.monaco-editor input:focus, +.monaco-editor textarea:focus, +.monaco-editor select:focus { + border-color: transparent !important; + background: transparent !important; +} + +.monaco-editor textarea.inputarea, +.monaco-editor .inputarea { + resize: none !important; + width: 1px !important; + height: 1px !important; + opacity: 0 !important; +} + +.monaco-editor .overflow-guard { + border-radius: 8px; +} + +.monaco-editor .find-widget .monaco-inputbox, +.monaco-editor .find-widget .monaco-inputbox > .wrapper { + backdrop-filter: none !important; + box-shadow: none !important; +} + +.monaco-editor .find-widget .monaco-inputbox > .wrapper > .input, +.monaco-editor .find-widget .monaco-inputbox > .wrapper > input.input, +.monaco-editor .find-widget .monaco-inputbox > .wrapper > textarea.input { + margin: 0 !important; + padding: 2px 4px !important; + border: none !important; + border-radius: 0 !important; + background: transparent !important; + min-height: 0 !important; + height: 100% !important; + line-height: inherit !important; + font-family: inherit !important; + font-size: inherit !important; + box-sizing: border-box !important; + resize: none !important; +} + +.monaco-editor .find-widget .monaco-inputbox > .wrapper > .mirror { + padding: 2px 4px !important; + box-sizing: border-box !important; +} + +.topbar { + display: flex !important; + align-items: center; + justify-content: space-between !important; + width: 100% !important; + max-width: 100vw !important; + padding-right: 20px; +} + +.top-actions { + display: flex !important; + align-items: center; + gap: 10px; + margin-left: auto !important; + padding-right: 20px; +} + +.brands { + margin-right: auto; + flex-shrink: 0; +} + + +#subdomainsModal .activity-panel, +#subdomainCreateModal .activity-panel { + border: none !important; + box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.6) !important; +} + +#subdomainsModal .activity-icon-wrap .activity-icon, +#subdomainCreateModal .activity-icon-wrap .activity-icon { + background: transparent !important; + box-shadow: none !important; + border: none !important; + font-size: 50px !important; + width: 50px !important; + height: 50px !important; + display: flex; + align-items: center; + justify-content: center; + color: #e6eef8; +} + +#subdomainsModal .activity-icon-pulse, +#subdomainCreateModal .activity-icon-pulse { + display: none !important; +} + +#subdomainsModal .activity-icon-wrap, +#subdomainCreateModal .activity-icon-wrap { + background: transparent !important; + box-shadow: none !important; +} + + +.subdomain-card { + position: relative; + background: rgba(255, 255, 255, 0.02); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 12px; + padding: 16px; + display: flex; + flex-direction: column; + gap: 12px; + transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1); + overflow: hidden; + margin-bottom: 12px; +} + +.subdomain-card::before { + display: none; +} + +.subdomain-card:hover { + transform: scale(1.02); + background: rgba(255, 255, 255, 0.04); + border-color: rgba(255, 255, 255, 0.12); + box-shadow: 0 10px 30px -10px rgba(0, 0, 0, 0.5); +} + +.sub-card-header { + display: flex; + align-items: center; + gap: 14px; +} + +.sub-icon { + display: none !important; +} + +.sub-info { + flex: 1; +} + +.sub-domain { + font-size: 16px; + font-weight: 600; + color: #f1f5f9; + letter-spacing: 0.01em; + padding-bottom: 8px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + margin-bottom: 8px; + width: 100%; +} + +.sub-meta { + font-size: 11px; + color: #64748b; + text-transform: uppercase; + letter-spacing: 0.05em; +} + +.sub-status-badge { + padding: 4px 10px; + border-radius: 6px; + font-size: 11px; + font-weight: 600; + display: flex; + align-items: center; + gap: 6px; + text-transform: uppercase; + letter-spacing: 0.04em; +} + +.sub-status-badge.approved { + background: rgba(74, 222, 128, 0.08); + color: #4ade80; + border: 1px solid rgba(74, 222, 128, 0.15); +} + +.sub-status-badge.pending { + background: rgba(251, 191, 36, 0.08); + color: #fbbf24; + border: 1px solid rgba(251, 191, 36, 0.15); +} + +.sub-status-badge.canceled { + background: rgba(248, 113, 113, 0.08); + color: #f87171; + border: 1px solid rgba(248, 113, 113, 0.15); +} + +.sub-card-footer { + display: flex; + align-items: center; + justify-content: space-between; + padding-top: 4px; + border-top: none; +} + +.sub-dns-hint { + font-size: 12px; + color: #475569; + display: flex; + align-items: center; + gap: 6px; +} + +.sub-actions { + display: flex; + gap: 8px; +} + +.sub-btn { + width: 28px; + height: 28px; + display: flex; + align-items: center; + justify-content: center; + border-radius: 6px; + border: 1px solid transparent; + background: transparent; + color: #64748b; + cursor: pointer; + transition: all 0.2s; +} + +.sub-btn:hover { + background: rgba(255, 255, 255, 0.05); + color: #fff; + border-color: rgba(255, 255, 255, 0.1); +} + +.sub-btn.delete:hover { + background: rgba(239, 68, 68, 0.1); + color: #ef4444; + border-color: rgba(239, 68, 68, 0.2); +} + +.sub-btn.verify:hover { + background: rgba(59, 130, 246, 0.1); + color: #3b82f6; + border-color: rgba(59, 130, 246, 0.2); +} + +.activity-empty-state { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 48px 24px; + text-align: center; + height: 100%; + min-height: 250px; + animation: fadeIn 0.3s ease; +} + +.activity-empty-state i { + font-size: 42px; + color: rgba(255, 255, 255, 0.08); + margin-bottom: 16px; + filter: drop-shadow(0 4px 12px rgba(0, 0, 0, 0.2)); +} + +.activity-empty-state span { + font-size: 15px; + font-weight: 500; + color: var(--muted); + letter-spacing: -0.01em; +} + +@keyframes fadeIn { + from { + opacity: 0; + transform: scale(0.98); + } + + to { + opacity: 1; + transform: scale(1); + } +} + +@keyframes modalClose { + from { + opacity: 1; + transform: scale(1); + filter: blur(0px); + } + + to { + opacity: 0; + transform: scale(0.95); + filter: blur(4px); + } +} + +.modal-overlay.closing, +.activity-modal.closing, +.info-modal.closing, +.ai-help-modal.closing, +.notfound-modal.closing, +.store-pref-modal.closing, +#storePrefModal.closing, +.scheduler-modal.closing, +.planner-modal.closing, +.progress-popup.closing { + animation: modalClose 0.25s forwards cubic-bezier(0.4, 0, 0.2, 1); + pointer-events: none; +} + +.clear-console-modal { + position: fixed; + top: 0; + left: 0; + width: 100%; + height: 100%; + background: rgba(0, 0, 0, 0.6); + backdrop-filter: blur(5px); + display: flex; + align-items: center; + justify-content: center; + z-index: 10000; + animation: fadeIn 0.2s ease-out; +} + +.clear-console-content { + background: #1e1e2e; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 16px; + padding: 24px; + width: 90%; + max-width: 400px; + box-shadow: 0 10px 40px rgba(0, 0, 0, 0.5); + animation: scaleIn 0.2s ease-out; + display: flex; + flex-direction: column; + gap: 16px; +} + +.clear-console-title { + font-size: 18px; + font-weight: 600; + color: #fff; + margin: 0; + text-align: center; +} + +.clear-console-desc { + font-size: 14px; + color: rgba(255, 255, 255, 0.6); + text-align: center; + margin: 0; +} + +.clear-console-checkbox-wrapper { + display: flex; + justify-content: center; + margin-top: 8px; +} + +.clear-console-label { + display: flex; + align-items: center; + gap: 8px; + font-size: 14px; + color: rgba(255, 255, 255, 0.8); + cursor: pointer; +} + +.clear-console-checkbox { + width: 16px; + height: 16px; + accent-color: #8b5cf6; + cursor: pointer; +} + +.clear-console-actions { + display: flex; + gap: 12px; + margin-top: 8px; +} + +.btn-cancel { + flex: 1; + padding: 12px; + border-radius: 10px; + border: none; + background: linear-gradient(135deg, #374151, #1f2937); + color: #e5e7eb; + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s ease; +} + +.btn-cancel:hover { + background: linear-gradient(135deg, #4b5563, #374151); + color: #fff; + transform: translateY(-1px); +} + +.btn-clear { + flex: 1; + padding: 12px; + border-radius: 10px; + border: none; + background: linear-gradient(135deg, #a78bfa, #8b5cf6); + color: #fff; + font-size: 14px; + font-weight: 500; + cursor: pointer; + transition: all 0.2s ease; + box-shadow: 0 4px 15px rgba(139, 92, 246, 0.3); +} + +.btn-clear:hover { + transform: translateY(-1px); + box-shadow: 0 6px 20px rgba(139, 92, 246, 0.4); +} + +@keyframes fadeIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes scaleIn { + from { + transform: scale(0.95); + opacity: 0; + } + + to { + transform: scale(1); + opacity: 1; + } +} + +.clear-console-modal { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.4); + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + display: flex; + align-items: center; + justify-content: center; + z-index: 10000; + animation: modalFadeIn 0.3s cubic-bezier(0.16, 1, 0.3, 1); +} + +.clear-console-content { + background: rgba(30, 30, 40, 0.65); + backdrop-filter: blur(24px) saturate(180%); + -webkit-backdrop-filter: blur(24px) saturate(180%); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 28px; + padding: 32px; + width: 90%; + max-width: 380px; + box-shadow: + 0 20px 50px -12px rgba(0, 0, 0, 0.5), + 0 0 0 1px rgba(255, 255, 255, 0.05) inset; + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + animation: modalScaleIn 0.35s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.clear-console-icon { + width: 64px; + height: 64px; + background: linear-gradient(135deg, rgba(239, 68, 68, 0.2), rgba(239, 68, 68, 0.1)); + border-radius: 20px; + display: flex; + align-items: center; + justify-content: center; + font-size: 28px; + color: #ef4444; + margin-bottom: 20px; + box-shadow: 0 8px 24px rgba(239, 68, 68, 0.15); +} + +.clear-console-title { + font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + font-size: 22px; + font-weight: 700; + color: #fff; + margin: 0 0 8px 0; + letter-spacing: -0.01em; +} + +.clear-console-desc { + font-family: 'SF Pro Text', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + font-size: 15px; + color: rgba(255, 255, 255, 0.6); + margin: 0 0 24px 0; + line-height: 1.5; +} + +.clear-console-toggle-wrapper { + width: 100%; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.05); + border-radius: 16px; + padding: 12px 16px; + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 24px; + transition: background 0.2s; +} + +.clear-console-toggle-wrapper:hover { + background: rgba(255, 255, 255, 0.05); +} + +.clear-console-label-text { + font-size: 14px; + font-weight: 500; + color: rgba(255, 255, 255, 0.9); +} + +.switch { + position: relative; + display: inline-block; + width: 44px; + height: 24px; +} + +.switch input { + opacity: 0; + width: 0; + height: 0; +} + +.slider { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(255, 255, 255, 0.15); + transition: .3s cubic-bezier(0.4, 0.0, 0.2, 1); + border-radius: 34px; +} + +.slider:before { + position: absolute; + content: ""; + height: 20px; + width: 20px; + left: 2px; + bottom: 2px; + background-color: white; + transition: .3s cubic-bezier(0.4, 0.0, 0.2, 1); + border-radius: 50%; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); +} + +.switch input:checked+.slider { + background: #34c759; +} + +.switch input:focus+.slider { + box-shadow: 0 0 0 2px rgba(52, 199, 89, 0.3); +} + +.switch input:checked+.slider:before { + transform: translateX(20px); +} + +.clear-console-actions { + display: flex; + gap: 12px; + width: 100%; +} + +.btn-cancel, +.btn-clear { + flex: 1; + padding: 14px; + border-radius: 14px; + font-family: 'SF Pro Text', sans-serif; + font-size: 15px; + font-weight: 600; + border: none; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.4, 0, 0.2, 1); + outline: none; + position: relative; + overflow: hidden; +} + +.btn-cancel { + background: rgba(255, 255, 255, 0.08); + color: #fff; + border: 1px solid rgba(255, 255, 255, 0.05); +} + +.btn-cancel:hover { + background: rgba(255, 255, 255, 0.12); + transform: scale(1.01); +} + +.btn-clear { + background: linear-gradient(135deg, #ef4444, #dc2626); + color: white; + box-shadow: none; +} + +.btn-clear:hover { + transform: scale(1.01); + background: linear-gradient(135deg, #f87171, #ef4444); +} + +.btn-cancel:active, +.btn-clear:active { + transform: scale(0.98); +} + +@keyframes modalFadeIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes modalScaleIn { + from { + opacity: 0; + transform: scale(0.9) translateY(10px); + } + + to { + opacity: 1; + transform: scale(1) translateY(0); + } +} + +.clear-console-modal { + position: fixed; + inset: 0; + display: flex; + align-items: center; + justify-content: center; + z-index: 10000; + opacity: 0; + pointer-events: none; + transition: opacity 0.3s ease; +} + +.clear-console-modal.show { + opacity: 1; + pointer-events: auto; +} + +.clear-console-glass-layer { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.1); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + z-index: 1; +} + +.clear-console-content { + position: relative; + z-index: 2; + background: rgba(20, 20, 25, 0.5); + backdrop-filter: blur(30px) saturate(180%); + -webkit-backdrop-filter: blur(30px) saturate(180%); + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 24px; + padding: 32px; + width: 90%; + max-width: 360px; + box-shadow: + 0 25px 50px -12px rgba(0, 0, 0, 0.5), + 0 0 0 1px rgba(255, 255, 255, 0.05) inset; + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + transform: scale(0.95) translateY(10px); + transition: transform 0.35s cubic-bezier(0.34, 1.56, 0.64, 1); +} + +.clear-console-modal.show .clear-console-content { + transform: scale(1) translateY(0); +} + +.clear-console-title { + font-family: 'SF Pro Display', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + font-size: 20px; + font-weight: 600; + color: #fff; + margin: 0 0 8px 0; + letter-spacing: -0.01em; +} + +.clear-console-desc { + font-family: 'SF Pro Text', -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; + font-size: 14px; + color: rgba(255, 255, 255, 0.6); + margin: 0 0 24px 0; + line-height: 1.5; +} + +.clear-console-toggle-wrapper { + width: 100%; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 14px; + padding: 12px 16px; + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 24px; + transition: background 0.2s; + cursor: pointer; +} + +.clear-console-toggle-wrapper:hover { + background: rgba(255, 255, 255, 0.08); +} + +.clear-console-label-text { + font-size: 14px; + font-weight: 500; + color: rgba(255, 255, 255, 0.9); + cursor: pointer; +} + +.switch { + position: relative; + display: inline-block; + width: 40px; + height: 22px; +} + +.switch input { + cursor: pointer; +} + +.switch input { + opacity: 0; + width: 0; + height: 0; +} + +.slider { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background-color: rgba(255, 255, 255, 0.2); + transition: .3s cubic-bezier(0.4, 0.0, 0.2, 1); + border-radius: 34px; +} + +.slider:before { + position: absolute; + content: ""; + height: 18px; + width: 18px; + left: 2px; + bottom: 2px; + background-color: white; + transition: .3s cubic-bezier(0.4, 0.0, 0.2, 1); + border-radius: 50%; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); +} + +.switch input:checked+.slider { + background: #32d74b; +} + +.switch input:checked+.slider:before { + transform: translateX(18px); +} + +.clear-console-actions { + display: flex; + gap: 10px; + width: 100%; +} + +.btn-cancel, +.btn-clear { + flex: 1; + padding: 12px; + border-radius: 12px; + font-family: 'SF Pro Text', sans-serif; + font-size: 14px; + font-weight: 600; + border: none; + cursor: pointer; + transition: transform 0.1s cubic-bezier(0.4, 0, 0.2, 1), background 0.2s; + outline: none; + position: relative; + box-shadow: none !important; +} + +.btn-cancel { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.9); + border: 1px solid rgba(255, 255, 255, 0.05); +} + +.btn-cancel:hover { + background: rgba(255, 255, 255, 0.1); + transform: scale(1.01); +} + +.btn-clear { + background: #ff3b30; + color: white; +} + +.btn-clear:hover { + background: #ff453a; + transform: scale(1.01); +} + +.btn-cancel:active, +.btn-clear:active { + transform: scale(0.98); +} + +.dock-wrap.dock-hidden { + opacity: 0; + pointer-events: none; + transform: translateY(20px); + transition: all 0.3s ease; +} + +.dock-wrap { + transition: all 0.3s ease; +} + + +.reinstall-panel { + position: relative; + width: 94vw; + max-width: 600px; + max-height: 88vh; + display: flex; + flex-direction: column; + backdrop-filter: blur(80px) saturate(100%) brightness(1.05); + -webkit-backdrop-filter: blur(80px) saturate(200%) brightness(1.05); + border-radius: 28px; + overflow: hidden; + opacity: 0; + transform: scale(0.92) rotateX(8deg); + animation: panelLiquidIn 0.6s cubic-bezier(0.16, 1, 0.3, 1) 0.1s forwards; +} + +.reinstall-panel::before { + content: ''; + position: absolute; + inset: 0; + border-radius: 28px; + padding: 1px; + -webkit-mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + mask: linear-gradient(#fff 0 0) content-box, linear-gradient(#fff 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; + pointer-events: none; + opacity: 0; + animation: borderGlowIn 0.8s cubic-bezier(0.16, 1, 0.3, 1) 0.3s forwards; +} + +.reinstall-icon-accent { + color: #f59e0b; +} + +.reinstall-body { + flex: 1; + overflow-y: auto; + padding: 28px 32px 32px; +} + +.reinstall-content { + display: flex; + flex-direction: column; + align-items: center; + gap: 24px; +} + +.reinstall-warning-card { + display: flex; + align-items: flex-start; + gap: 16px; + padding: 20px; + border-radius: 16px; + background: rgba(245, 158, 11, 0.08); + border: 1px solid rgba(245, 158, 11, 0.15); + width: 100%; +} + +.reinstall-warning-icon { + font-size: 28px; + color: #f59e0b; + flex-shrink: 0; + margin-top: 2px; +} + +.reinstall-warning-text { + flex: 1; +} + +.reinstall-warning-title { + font-size: 16px; + font-weight: 700; + color: #fbbf24; + margin-bottom: 6px; +} + +.reinstall-warning-desc { + font-size: 13.5px; + color: rgba(255, 255, 255, 0.75); + line-height: 1.6; +} + +.reinstall-info-cards { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 12px; + width: 100%; +} + +.reinstall-info-card { + display: flex; + flex-direction: column; + align-items: center; + gap: 10px; + padding: 18px 12px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); + text-align: center; + transition: background 0.2s, border-color 0.2s; +} + +.reinstall-info-card:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.1); +} + +.reinstall-info-icon { + font-size: 22px; + color: rgba(255, 255, 255, 0.5); +} + +.reinstall-info-label { + font-size: 12.5px; + color: rgba(255, 255, 255, 0.65); + line-height: 1.4; +} + +.reinstall-actions, +.reinstall-confirm-actions, +.reinstall-success-actions, +.reinstall-error-actions { + display: flex; + gap: 12px; + width: 100%; + justify-content: flex-end; +} + +.reinstall-cancel-btn { + padding: 12px 24px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.9); + cursor: pointer; + transition: background 0.2s, transform 0.1s; +} + +.reinstall-cancel-btn:hover { + background: rgba(255, 255, 255, 0.1); +} + +.reinstall-cancel-btn:active { + transform: scale(0.98); +} + +.reinstall-confirm-btn { + padding: 12px 24px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + border: none; + background: linear-gradient(135deg, #f59e0b, #d97706); + color: #000; + cursor: pointer; + transition: opacity 0.2s, transform 0.1s; + display: flex; + align-items: center; + gap: 8px; +} + +.reinstall-confirm-btn:hover { + opacity: 0.9; +} + +.reinstall-confirm-btn:active { + transform: scale(0.98); +} + +.reinstall-danger-btn { + padding: 12px 24px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + border: none; + background: linear-gradient(135deg, #ef4444, #dc2626); + color: #fff; + cursor: pointer; + transition: opacity 0.2s, transform 0.1s; + display: flex; + align-items: center; + gap: 8px; +} + +.reinstall-danger-btn:hover { + opacity: 0.9; +} + +.reinstall-danger-btn:active { + transform: scale(0.98); +} + +.reinstall-done-btn { + padding: 12px 24px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + border: none; + background: linear-gradient(135deg, #22c55e, #16a34a); + color: #fff; + cursor: pointer; + transition: opacity 0.2s, transform 0.1s; + display: flex; + align-items: center; + gap: 8px; +} + +.reinstall-done-btn:hover { + opacity: 0.9; +} + +.reinstall-done-btn:active { + transform: scale(0.98); +} + +.reinstall-confirm-icon-wrap { + width: 72px; + height: 72px; + border-radius: 50%; + background: rgba(245, 158, 11, 0.12); + display: flex; + align-items: center; + justify-content: center; + margin-top: 8px; +} + +.reinstall-confirm-big-icon { + font-size: 32px; + color: #f59e0b; +} + +.reinstall-confirm-title { + font-size: 20px; + font-weight: 700; + color: #fff; + text-align: center; +} + +.reinstall-confirm-desc { + font-size: 14px; + color: rgba(255, 255, 255, 0.65); + text-align: center; + max-width: 400px; + line-height: 1.6; +} + +.reinstall-progress-spinner { + width: 64px; + height: 64px; + display: flex; + align-items: center; + justify-content: center; + margin-top: 12px; +} + +.reinstall-spinner { + width: 48px; + height: 48px; + border: 3px solid rgba(255, 255, 255, 0.1); + border-top-color: #f59e0b; + border-radius: 50%; + animation: reinstallSpin 0.8s linear infinite; +} + +@keyframes reinstallSpin { + to { transform: rotate(360deg); } +} + +.reinstall-progress-title { + font-size: 18px; + font-weight: 700; + color: #fff; + text-align: center; +} + +.reinstall-progress-desc { + font-size: 13.5px; + color: rgba(255, 255, 255, 0.6); + text-align: center; + max-width: 380px; + line-height: 1.6; +} + +.reinstall-success-icon-wrap { + width: 72px; + height: 72px; + border-radius: 50%; + background: rgba(34, 197, 94, 0.12); + display: flex; + align-items: center; + justify-content: center; + margin-top: 8px; +} + +.reinstall-success-big-icon { + font-size: 32px; + color: #22c55e; +} + +.reinstall-success-title { + font-size: 20px; + font-weight: 700; + color: #fff; + text-align: center; +} + +.reinstall-success-desc { + font-size: 14px; + color: rgba(255, 255, 255, 0.65); + text-align: center; + max-width: 400px; + line-height: 1.6; +} + +.reinstall-error-icon-wrap { + width: 72px; + height: 72px; + border-radius: 50%; + background: rgba(239, 68, 68, 0.12); + display: flex; + align-items: center; + justify-content: center; + margin-top: 8px; +} + +.reinstall-error-big-icon { + font-size: 32px; + color: #ef4444; +} + +.reinstall-error-title { + font-size: 20px; + font-weight: 700; + color: #fff; + text-align: center; +} + +.reinstall-error-desc { + font-size: 14px; + color: rgba(255, 255, 255, 0.65); + text-align: center; + max-width: 400px; + line-height: 1.6; +} + +@media (max-width: 600px) { + .reinstall-info-cards { + grid-template-columns: 1fr; + } + .reinstall-body { + padding: 20px 18px 24px; + } + .reinstall-panel { + max-width: 95vw; + border-radius: 20px; + } + .reinstall-actions, + .reinstall-confirm-actions, + .reinstall-success-actions, + .reinstall-error-actions { + flex-direction: column; + } + .reinstall-cancel-btn, + .reinstall-confirm-btn, + .reinstall-danger-btn, + .reinstall-done-btn { + width: 100%; + justify-content: center; + } +} + +/* ============= URL Uploader Modal ============= */ +.url-uploader-btn i { + opacity: 0.85; +} + +.url-uploader-btn { + min-height: 32px; + background: rgba(56, 189, 248, 0.08); + border-color: rgba(56, 189, 248, 0.22); + color: #dbeafe; +} + +.url-uploader-btn:hover { + border-color: rgba(96, 165, 250, 0.35); + background: rgba(96, 165, 250, 0.08); + color: #93c5fd; +} + +.url-uploader-btn:disabled, +.url-uploader-btn.disabled { + opacity: 0.55; + cursor: not-allowed; + filter: saturate(0.55); +} + +.url-uploader-activity .activity-icon { + background: linear-gradient(135deg, rgba(96, 165, 250, 0.18), rgba(59, 130, 246, 0.10)); + color: #93c5fd; +} + +.url-uploader-body { + padding: 20px; +} + +.url-uploader-desc { + display: flex; + align-items: flex-start; + gap: 10px; + padding: 12px 14px; + background: rgba(59, 130, 246, 0.08); + border-radius: 10px; + font-size: 12.5px; + color: #93c5fd; + margin-bottom: 18px; + line-height: 1.5; +} + +.url-uploader-desc i { + margin-top: 2px; + font-size: 13px; +} + +.url-uploader-field { + margin-bottom: 14px; +} + +.url-uploader-field label { + display: block; + font-size: 13px; + font-weight: 600; + color: #9ca3af; + margin-bottom: 8px; +} + +.url-uploader-field input { + width: 93%; + padding: 12px 14px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 10px; + color: #fff; + font-size: 14px; + font-family: inherit; + transition: all 0.15s ease; +} + +.url-uploader-field input:focus { + outline: none; + background: rgba(255, 255, 255, 0.06); + border-color: rgba(96, 165, 250, 0.35); +} + +.url-uploader-field input::placeholder { + color: #4b5563; +} + +.url-uploader-hint { + margin-top: 8px; + font-size: 12px; + color: #6b7280; + word-break: break-all; +} + +.url-uploader-target { + color: #cbd5e1; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace; + font-size: 12px; + background: rgba(255, 255, 255, 0.04); + padding: 2px 6px; + border-radius: 4px; +} + +.url-uploader-error { + margin-top: 6px; + padding: 10px 12px; + background: rgba(239, 68, 68, 0.10); + border: 1px solid rgba(239, 68, 68, 0.25); + color: #fca5a5; + border-radius: 10px; + font-size: 12.5px; + word-break: break-word; +} + +.url-uploader-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + padding: 16px 20px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + background: rgba(255, 255, 255, 0.01); +} + +.url-uploader-activity .backup-create-confirm, +.url-uploader-activity .backup-create-cancel { + font-weight: 500; +} + +.url-uploader-activity .backup-create-confirm:disabled { + opacity: 0.55; + cursor: not-allowed; +} + +/* Files and editor refresh */ +#filesModal.modal-overlay, +#editorModal.modal-overlay { + background: rgba(5, 8, 13, 0.72); + backdrop-filter: blur(18px) saturate(120%); + -webkit-backdrop-filter: blur(18px) saturate(120%); +} + +#filesModal .modal { + width: min(1180px, 94vw); + height: min(86vh, 860px); + max-height: 86vh; + padding: 0; + border-radius: 22px; + background: rgba(11, 14, 20, 0.96); + border: 1px solid rgba(255, 255, 255, 0.09); + box-shadow: 0 28px 90px rgba(0, 0, 0, 0.48), inset 0 1px 0 rgba(255, 255, 255, 0.05); +} + +#filesModal .modal-header { + min-height: 72px; + padding: 18px 22px; + margin: 0; + border-bottom: 1px solid rgba(255, 255, 255, 0.07); + background: rgba(255, 255, 255, 0.025); +} + +#filesModal .modal-title { + font-size: 17px; + line-height: 1.25; + letter-spacing: 0; + color: #eef3f8; +} + +.files-modal-server-name { + color: #fff; + font-weight: 700; +} + +.files-modal-subtitle { + margin-top: 3px; + color: #8f9aa8; + font-size: 12.5px; +} + +#filesModal .modal-body { + flex: 1; + min-height: 0; + display: block; + padding: 12px 20px 20px; + overflow: hidden !important; +} + +#filesModal .modal-left { + width: 100%; + height: 100%; + min-height: 0 !important; + padding: 0 !important; + display: flex; + flex-direction: column; +} + +#filesModal .modal-right { + display: none; +} + +#filesModal .ptero-flash-bar, +#editorModal .ptero-flash-bar { + height: 3px; + border-radius: 22px 22px 0 0; +} + +#filesModal .ptero-flash-bar .ptero-flash-fill, +#editorModal .ptero-flash-bar .ptero-flash-fill { + background: linear-gradient(90deg, #38bdf8, #22c55e, #a3e635); +} + +#filesModal .file-toolbar { + flex: 0 0 auto; + padding: 12px; + margin: 0 0 12px; + gap: 14px; + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 12px; + background: rgba(255, 255, 255, 0.035); + box-shadow: none; +} + +#filesModal .file-toolbar-left { + min-width: 0; +} + +#filesModal .file-toolbar-icon { + width: 38px; + height: 38px; + border-radius: 9px; + background: rgba(56, 189, 248, 0.09); + color: #7dd3fc; +} + +#filesModal .file-toolbar-title, +#filesModal .glance-label, +#filesModal .select-all-label { + letter-spacing: 0; + text-transform: none; +} + +#filesModal .file-toolbar-title { + color: #8f9aa8; + font-size: 12px; +} + +#breadcrumbs { + font-size: 14px; + font-weight: 600; + color: #f3f6fa; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + max-width: min(46vw, 520px); +} + +#breadcrumbs a { + color: #7dd3fc; +} + +#filesModal .file-toolbar-actions { + flex-direction: row; + align-items: center; + justify-content: flex-end; + gap: 10px; +} + +#filesModal .file-action-row, +#filesModal .file-selection-row { + gap: 8px; + flex-wrap: wrap; +} + +#filesModal .ghost-btn, +#filesModal .bulk-delete, +#filesModal .bulk-archive, +#filesModal .select-all-control { + min-height: 36px; + border-radius: 9px; + padding: 8px 12px; + font-size: 13px; + letter-spacing: 0; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.045); + color: #e7edf5; + box-shadow: none; +} + +#filesModal .ghost-btn:hover, +#filesModal .select-all-control:hover { + background: rgba(255, 255, 255, 0.075); + border-color: rgba(255, 255, 255, 0.14); +} + +#filesModal .bulk-delete { + background: rgba(239, 68, 68, 0.10); + border-color: rgba(248, 113, 113, 0.22); + color: #fecaca; +} + +#filesModal .bulk-archive { + background: rgba(34, 197, 94, 0.09); + border-color: rgba(74, 222, 128, 0.20); + color: #bbf7d0; +} + +#filesModal .bulk-delete:hover, +#filesModal .bulk-archive:hover { + transform: none; + box-shadow: none; +} + +#filesModal .select-all-checkbox { + width: 17px; + height: 17px; + border-radius: 5px; +} + +#filesModal .select-all-control input:checked+.select-all-checkbox { + background: #22c55e; + border-color: rgba(34, 197, 94, 0.8); + box-shadow: none; +} + +#filesModal .file-glance { + flex: 0 0 auto; + display: grid; + grid-template-columns: 1fr; + gap: 0; + margin: 0 0 12px; +} + +#filesModal .glance-card { + width: auto; + height: auto; + margin: 0; + padding: 10px 12px; + border-radius: 10px; + background: rgba(34, 197, 94, 0.06); + border: 1px solid rgba(74, 222, 128, 0.12); + box-shadow: none; +} + +#filesModal .glance-card:hover { + background: rgba(34, 197, 94, 0.075); +} + +#filesModal .glance-card .icon { + width: 32px; + height: 32px; + border-radius: 8px; + color: #86efac; + background: rgba(34, 197, 94, 0.12); +} + +#filesModal .glance-desc { + font-size: 13px; + color: #dce4ee; +} + +#entries { + flex: 1; + min-height: 0; + width: 100% !important; + display: grid; + grid-template-columns: 1fr; + align-content: start; + gap: 7px; + padding: 2px 4px 10px; + margin: 0; + overflow-y: auto !important; + overflow-x: hidden !important; + scroll-padding: 12px; +} + +#entries::after { + height: 4px; +} + +#filesModal .entry { + min-height: 58px; + grid-template-columns: minmax(0, 1fr) auto; + gap: 12px; + padding: 9px 12px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.026); + border: 1px solid rgba(255, 255, 255, 0.055); + box-shadow: none; + transition: background 0.14s ease, border-color 0.14s ease; +} + +#filesModal .entry:hover { + transform: none; + background: rgba(255, 255, 255, 0.052); + border-color: rgba(255, 255, 255, 0.12); + box-shadow: none; +} + +#filesModal .entry.selected { + background: rgba(56, 189, 248, 0.08); + border-color: rgba(56, 189, 248, 0.22); +} + +#filesModal .entry.selected .entry-left { + animation: none; +} + +#filesModal .entry-left { + min-width: 0; + gap: 12px; +} + +#filesModal .entry-text-wrap { + min-width: 0; +} + +#filesModal .entry-icon { + width: 36px; + height: 36px; + flex: 0 0 36px; + border-radius: 8px; + font-size: 15px; + background: rgba(125, 211, 252, 0.09); + color: #7dd3fc; + transition: none; +} + +#filesModal .entry:hover .entry-icon { + transform: none; + background: rgba(125, 211, 252, 0.13); +} + +#filesModal .entry-icon.folder { + background: rgba(250, 204, 21, 0.10); + color: #fde68a; +} + +#filesModal .entry:hover .entry-icon.folder { + background: rgba(250, 204, 21, 0.14); +} + +#filesModal .entry-name { + max-width: 100%; + color: #edf3f9; + font-size: 14px; + font-weight: 600; + letter-spacing: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +#filesModal .entry-meta { + margin-top: 3px; + color: #7d8897; + font-size: 12px; + letter-spacing: 0; + text-transform: none; +} + +#filesModal .entry-right { + gap: 6px; +} + +#filesModal .entry-arrow { + display: none; +} + +#filesModal .more-btn { + width: 34px; + height: 34px; + padding: 0; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 8px; + color: #8f9aa8; +} + +#filesModal .more-btn:hover { + color: #fff; + background: rgba(255, 255, 255, 0.08); +} + +#filesModal .more-menu { + left: auto; + right: 0; + top: 38px; + min-width: 170px; + border-radius: 10px; + background: rgba(13, 17, 24, 0.96); + border: 1px solid rgba(255, 255, 255, 0.10); + box-shadow: 0 18px 48px rgba(0, 0, 0, 0.45); +} + +#filesModal .more-menu button { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 12px; + color: #d6dee8; + font-size: 13px; +} + +#filesModal .more-menu button:hover { + background: rgba(255, 255, 255, 0.07); + color: #fff; +} + +#filesModal .entry-rename-inline { + width: min(440px, 100%); +} + +#filesModal .entry-rename-input { + min-width: 0; + max-width: none; + height: 32px; + letter-spacing: 0; +} + +#filesModal #dropOverlay { + background: rgba(5, 8, 13, 0.62); + backdrop-filter: blur(18px) saturate(125%); + -webkit-backdrop-filter: blur(18px) saturate(125%); +} + +#filesModal #dropOverlay .inner { + border: 1px dashed rgba(125, 211, 252, 0.46); + border-radius: 16px; + padding: 42px 52px; + background: rgba(11, 14, 20, 0.72); +} + +#filesModal #dropOverlay.visible .inner { + animation: none; +} + +#filesModal .progress-wheel { + width: 22px; + height: 22px; + margin-left: 6px; + background: rgba(255, 255, 255, 0.055); + border-color: rgba(255, 255, 255, 0.12); +} + +#filesModal .progress-wheel .fill { + background: #7dd3fc; +} + +#editorModal .modal { + width: min(1280px, 96vw); + height: min(90vh, 900px); + min-height: 0 !important; + max-height: 90vh; + padding: 0; + border-radius: 22px; + background: rgba(10, 13, 18, 0.97); + border: 1px solid rgba(255, 255, 255, 0.09); + box-shadow: 0 30px 96px rgba(0, 0, 0, 0.52), inset 0 1px 0 rgba(255, 255, 255, 0.05); +} + +#editorModal .editor-header { + min-height: 66px; + padding: 16px 20px; + margin: 0; + border-bottom: 1px solid rgba(255, 255, 255, 0.075); + background: rgba(255, 255, 255, 0.025); +} + +#editorModal .editor-title { + color: #f2f6fb; + font-size: 16px; + font-weight: 700; + letter-spacing: 0; +} + +#editorPath { + max-width: min(70vw, 900px); + margin-top: 4px; + color: #8f9aa8 !important; + font-size: 12px !important; + line-height: 1.35; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +#editorModal .modal-close, +#filesModal .modal-close { + width: 36px; + height: 36px; + border-radius: 9px; + background: rgba(255, 255, 255, 0.045); + border: 1px solid rgba(255, 255, 255, 0.08); +} + +#editorModal .modal-close:hover, +#filesModal .modal-close:hover { + background: rgba(255, 255, 255, 0.085); +} + +#bigEditor { + flex: 1 1 auto; + min-height: 0; + gap: 12px; + margin: 0; + padding: 14px; + background: transparent; +} + +#editorModal .code-shell { + border-radius: 12px; + background: #11151c; + border: 1px solid rgba(255, 255, 255, 0.075); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.025); +} + +#editorModal #monacoContainer, +#editorModal #aceContainer, +#editorModal #aceContainer .ace_editor, +#editorModal #aceContainer .ace_scroller { + background: #11151c !important; +} + +#editorModal #aceContainer .ace_gutter { + background: #0d1118 !important; + color: #778293 !important; +} + +#textArea { + flex: 1 1 auto; + min-height: 0; + max-height: none; + resize: none; + border-radius: 12px; + background: #11151c; + border: 1px solid rgba(255, 255, 255, 0.075); + color: #e7edf5; +} + +#textArea:focus { + border-color: rgba(125, 211, 252, 0.34); + box-shadow: 0 0 0 3px rgba(125, 211, 252, 0.08); +} + +.editor-footer-actions { + flex: 0 0 auto; + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + padding-top: 0; +} + +#editorModal .editor-footer-actions .icon-btn { + min-height: 38px; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + border-radius: 9px; + padding: 0 14px; + font-size: 13px; + letter-spacing: 0; + border: 1px solid rgba(255, 255, 255, 0.085); + box-shadow: none; +} + +#editorModal .editor-discard-btn { + background: rgba(255, 255, 255, 0.045); + color: #d6dee8; +} + +#editorModal .editor-save-btn { + background: rgba(34, 197, 94, 0.15); + border-color: rgba(74, 222, 128, 0.28); + color: #dcfce7; +} + +#editorModal .editor-footer-actions .icon-btn:hover { + transform: none; + box-shadow: none; + filter: brightness(1.08); +} + +#editorModal .editor-footer-actions .icon-btn.disabled, +#editorModal .editor-footer-actions .icon-btn:disabled { + opacity: 0.55; + cursor: not-allowed; + filter: none; +} + +@media (max-width: 860px) { + #filesModal .modal, + #editorModal .modal { + width: 100vw; + height: 100dvh; + max-height: 100dvh; + border-radius: 0; + } + + #filesModal .modal-header, + #editorModal .editor-header { + padding: 14px 16px; + } + + #filesModal .modal-body { + padding: 12px; + } + + #filesModal .file-toolbar { + align-items: stretch; + flex-direction: column; + } + + #filesModal .file-toolbar-actions { + align-items: stretch; + justify-content: flex-start; + flex-direction: column; + } + + #filesModal .file-action-row, + #filesModal .file-selection-row { + justify-content: flex-start; + } + + #breadcrumbs { + max-width: 70vw; + } + + #filesModal .entry { + min-height: 56px; + padding: 9px 10px; + } + + #bigEditor { + padding: 10px; + } + + .editor-footer-actions { + justify-content: stretch; + } + + #editorModal .editor-footer-actions .icon-btn { + flex: 1 1 0; + } +} + +/* Enterprise files/editor tuning */ +#filesModal .modal { + width: min(1440px, 96vw); + height: min(92vh, 980px); + max-height: 92vh; + border-radius: 24px; +} + +#filesModal .modal-header { + min-height: 56px; + padding: 12px 20px; +} + +#filesModal .modal-body { + padding: 12px 20px 20px; +} + +#filesModal .file-toolbar { + min-height: 54px; + padding: 8px 12px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.032); +} + +#filesModal .file-toolbar-left { + flex: 1 1 auto; +} + +#filesModal .file-toolbar-meta { + min-width: 0; +} + +#filesModal .file-toolbar-actions { + flex: 0 0 auto; + flex-direction: row; + align-items: center; + gap: 6px; + padding: 4px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.032); + border: 1px solid rgba(255, 255, 255, 0.055); +} + +#filesModal .file-action-row, +#filesModal .file-selection-row { + gap: 8px; + flex-wrap: nowrap; +} + +#filesModal .ghost-btn, +#filesModal .bulk-delete, +#filesModal .bulk-archive, +#filesModal .select-all-control { + position: relative; + isolation: isolate; + width: 44px; + height: 44px; + min-width: 44px; + min-height: 44px; + padding: 0; + border: 0; + border-radius: 13px; + display: inline-flex; + align-items: center; + justify-content: center; + overflow: visible; + background: transparent; + color: #dfe7ef; + box-shadow: none; + transform: none; +} + +#filesModal .bulk-delete, +#filesModal .bulk-archive { + display: none; +} + +#filesModal .bulk-delete.show, +#filesModal .bulk-archive.show { + display: inline-flex; +} + +#filesModal .ghost-btn::before, +#filesModal .bulk-delete::before, +#filesModal .bulk-archive::before, +#filesModal .select-all-control::before { + content: ""; + position: absolute; + inset: 0; + z-index: 0; + pointer-events: none; + border-radius: inherit; + box-sizing: border-box; + background: rgba(255, 255, 255, 0.052); + border: 1px solid rgba(255, 255, 255, 0.082); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.052); + transform: scale(1); + transition: transform 150ms ease, background 150ms ease, border-color 150ms ease, box-shadow 150ms ease; +} + +#filesModal .ghost-btn:hover, +#filesModal .bulk-delete:hover, +#filesModal .bulk-archive:hover, +#filesModal .select-all-control:hover { + background: transparent; + border-color: transparent; + transform: none; +} + +#filesModal .ghost-btn:hover::before, +#filesModal .bulk-delete:hover::before, +#filesModal .bulk-archive:hover::before, +#filesModal .select-all-control:hover::before { + transform: scale(1.03); + background: rgba(255, 255, 255, 0.082); + border-color: rgba(255, 255, 255, 0.15); + box-shadow: 0 10px 26px rgba(0, 0, 0, 0.22), inset 0 1px 0 rgba(255, 255, 255, 0.075); +} + +#filesModal .ghost-btn:active::before, +#filesModal .bulk-delete:active::before, +#filesModal .bulk-archive:active::before, +#filesModal .select-all-control:active::before { + transform: scale(0.98); +} + +#filesModal .ghost-btn i, +#filesModal .bulk-delete i, +#filesModal .bulk-archive i, +#filesModal .select-all-checkbox { + position: relative; + z-index: 1; + font-size: 15px; + line-height: 1; + opacity: 1; +} + +#filesModal #uploadLabel { + color: #93c5fd; +} + +#filesModal #newBtn { + color: #d8b4fe; +} + +#filesModal .url-uploader-btn { + color: #67e8f9; +} + +#filesModal .bulk-delete { + color: #fca5a5; +} + +#filesModal .bulk-delete::before { + background: rgba(239, 68, 68, 0.11); + border-color: rgba(248, 113, 113, 0.22); +} + +#filesModal .bulk-archive { + color: #bbf7d0; +} + +#filesModal .bulk-archive::before { + background: rgba(34, 197, 94, 0.10); + border-color: rgba(74, 222, 128, 0.20); +} + +#filesModal .select-all-control { + cursor: pointer; + user-select: none; +} + +#filesModal .select-all-checkbox { + width: auto; + height: auto; + border: 0; + border-radius: 0; + background: transparent; + color: #9aa6b2; +} + +#filesModal .select-all-control input:checked+.select-all-checkbox { + background: transparent; + border-color: transparent; + color: #86efac; + box-shadow: none; +} + +#filesModal .select-all-control:has(input:checked)::before { + background: rgba(34, 197, 94, 0.13); + border-color: rgba(74, 222, 128, 0.28); +} + +#breadcrumbs { + max-width: min(56vw, 760px); +} + +.file-breadcrumbs { + display: flex; + align-items: center; + min-width: 0; + gap: 6px; + overflow: hidden; + white-space: nowrap; +} + +.file-crumb, +.file-crumb:visited { + min-width: 0; + max-width: 220px; + display: inline-flex; + align-items: center; + height: 26px; + padding: 0 9px; + border-radius: 8px; + color: #dbeafe; + background: rgba(125, 211, 252, 0.075); + border: 1px solid rgba(125, 211, 252, 0.10); + text-decoration: none; + overflow: hidden; + text-overflow: ellipsis; +} + +.file-crumb:hover { + color: #fff; + background: rgba(125, 211, 252, 0.12); + border-color: rgba(125, 211, 252, 0.18); + text-decoration: none; +} + +.file-crumb-server { + color: #eef6ff; + background: rgba(255, 255, 255, 0.055); + border-color: rgba(255, 255, 255, 0.09); +} + +.file-crumb-separator { + flex: 0 0 auto; + color: #667080; + font-weight: 700; +} + +#filesModal .file-glance { + margin-bottom: 10px; +} + +#filesModal .glance-card { + padding: 9px 12px; +} + +#filesModal #entries { + gap: 8px; + padding-right: 6px; +} + +#filesModal .entry { + min-height: 60px; + border-radius: 12px; +} + +#editorModal .modal { + width: 98vw; + max-width: 100vw; + height: 94vh; + max-height: 94vh; + border-radius: 18px; +} + +#editorModal .editor-header { + min-height: 58px; + padding: 12px 16px; +} + +#bigEditor { + gap: 8px; + padding: 10px; +} + +#editorModal .code-shell { + border-radius: 10px; +} + +#editorModal .editor-footer-actions .icon-btn { + min-height: 36px; +} + +@media (max-width: 860px) { + #filesModal .modal, + #editorModal .modal { + width: 100vw; + height: 100dvh; + max-height: 100dvh; + border-radius: 0; + } + + #filesModal .file-toolbar-actions { + width: fit-content; + max-width: 100%; + overflow-x: auto; + } + + #filesModal .file-action-row, + #filesModal .file-selection-row { + flex-wrap: nowrap; + } + + #breadcrumbs { + max-width: calc(100vw - 112px); + } + + .file-crumb { + max-width: 140px; + } +} + +/* Neutral toolbar correction */ +#filesModal .file-toolbar-actions { + gap: 8px; + background: rgba(255, 255, 255, 0.026); + border-color: rgba(255, 255, 255, 0.07); +} + +#filesModal .file-action-row, +#filesModal .file-selection-row { + gap: 8px; +} + +#filesModal .ghost-btn, +#filesModal .bulk-delete, +#filesModal .bulk-archive, +#filesModal .select-all-control { + width: auto; + min-width: 112px; + height: 42px; + min-height: 42px; + padding: 0 14px; + gap: 8px; + color: #d8e0ea; + font-weight: 600; +} + +#filesModal .bulk-delete, +#filesModal .bulk-archive { + display: none; +} + +#filesModal .bulk-delete.show, +#filesModal .bulk-archive.show { + display: inline-flex; +} + +#filesModal .ghost-btn::before, +#filesModal .bulk-delete::before, +#filesModal .bulk-archive::before, +#filesModal .select-all-control::before { + background: rgba(255, 255, 255, 0.048); + border-color: rgba(255, 255, 255, 0.09); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.045); +} + +#filesModal .ghost-btn:hover::before, +#filesModal .bulk-delete:hover::before, +#filesModal .bulk-archive:hover::before, +#filesModal .select-all-control:hover::before { + transform: scale(1.03); + background: rgba(255, 255, 255, 0.072); + border-color: rgba(255, 255, 255, 0.16); + box-shadow: 0 10px 24px rgba(0, 0, 0, 0.20), inset 0 1px 0 rgba(255, 255, 255, 0.065); +} + +#filesModal #uploadLabel, +#filesModal #newBtn, +#filesModal .url-uploader-btn, +#filesModal .bulk-delete, +#filesModal .bulk-archive { + color: #d8e0ea; +} + +#filesModal .bulk-delete::before, +#filesModal .bulk-archive::before, +#filesModal .select-all-control:has(input:checked)::before { + background: rgba(255, 255, 255, 0.048); + border-color: rgba(255, 255, 255, 0.09); +} + +#filesModal .ghost-btn i, +#filesModal .bulk-delete i, +#filesModal .bulk-archive i { + color: #aeb8c5; + font-size: 14px; +} + +#filesModal .ghost-btn span, +#filesModal .bulk-delete span, +#filesModal .bulk-archive span, +#filesModal .select-all-label { + position: relative; + z-index: 1; + color: inherit; + font-size: 13px; + line-height: 1; + letter-spacing: 0; + text-transform: none; +} + +#filesModal .select-all-control { + cursor: pointer; + user-select: none; +} + +#filesModal .select-all-checkbox { + width: 17px; + height: 17px; + border-radius: 6px; + background: rgba(255, 255, 255, 0.06); + border: 1px solid rgba(255, 255, 255, 0.18); + color: transparent; + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 11px; + transition: background 0.14s ease, border-color 0.14s ease, color 0.14s ease, transform 0.14s ease; +} + +#filesModal .select-all-checkbox i { + font-size: 10px; +} + +#filesModal .select-all-control input:checked+.select-all-checkbox { + background: rgba(255, 255, 255, 0.18); + border-color: rgba(255, 255, 255, 0.35); + color: #f4f7fb; + box-shadow: none; + transform: scale(1.02); +} + +#breadcrumbs { + color: #d8e0ea; +} + +.file-crumb, +.file-crumb:visited, +.file-crumb-server { + color: #d8e0ea; + background: rgba(255, 255, 255, 0.045); + border-color: rgba(255, 255, 255, 0.08); +} + +.file-crumb:hover { + color: #fff; + background: rgba(255, 255, 255, 0.075); + border-color: rgba(255, 255, 255, 0.15); +} + +.file-crumb-separator { + color: #687281; +} + +@media (max-width: 860px) { + #filesModal .ghost-btn, + #filesModal .bulk-delete, + #filesModal .bulk-archive, + #filesModal .select-all-control { + min-width: 104px; + } +} + +/* Enterprise modal performance pass + Keep the same glass language, but animate only composited properties. */ +:root { + --adp-modal-enter-duration: 420ms; + --adp-modal-exit-duration: 220ms; + --adp-modal-ease: cubic-bezier(0.16, 1, 0.3, 1); +} + +.modal-overlay, +.activity-modal, +.info-modal, +.ai-help-modal, +.notfound-modal, +.scheduler-modal, +.planner-modal { + opacity: 0; +} + +.modal-overlay.show, +.activity-modal.show, +.info-modal.show, +.ai-help-modal.show, +.notfound-modal.show, +.scheduler-modal.show, +.planner-modal.show, +#offlineOverlay.show { + opacity: 1; + animation: adpOverlayIn 180ms ease-out both; +} + +.modal-overlay.show { + backdrop-filter: blur(18px) saturate(125%); + -webkit-backdrop-filter: blur(18px) saturate(125%); +} + +.activity-modal.show, +.info-modal.show, +.ai-help-modal.show, +.scheduler-modal.show, +.planner-modal.show { + background: rgba(5, 8, 13, 0.34); + backdrop-filter: blur(16px) saturate(135%); + -webkit-backdrop-filter: blur(16px) saturate(135%); +} + +.modal-overlay.show > .modal, +.activity-modal.show .activity-panel, +.activity-modal.show .reinstall-panel, +.info-modal.show .info-panel, +.ai-help-modal.show .ai-help-panel, +.scheduler-modal.show .scheduler-panel, +.planner-modal.show .planner-panel, +.notfound-modal.show .notfound-panel, +#offlineOverlay.show .notfound-panel { + animation: panelLiquidIn var(--adp-modal-enter-duration) var(--adp-modal-ease) both; + backface-visibility: hidden; + isolation: isolate; + transform-origin: center center; + will-change: opacity, transform; +} + +.modal-overlay.show > .modal, +.activity-modal.show .activity-panel, +.activity-modal.show .reinstall-panel, +.info-modal.show .info-panel, +.ai-help-modal.show .ai-help-panel, +.scheduler-modal.show .scheduler-panel, +.planner-modal.show .planner-panel { + backdrop-filter: blur(72px) saturate(150%) brightness(1.05); + -webkit-backdrop-filter: blur(72px) saturate(180%) brightness(1.05); +} + +.activity-modal.show .activity-panel, +.activity-modal.show .reinstall-panel, +.info-modal.show .info-panel, +.ai-help-modal.show .ai-help-panel, +.scheduler-modal.show .scheduler-panel, +.planner-modal.show .planner-panel { + background: rgba(12, 14, 20, 0.48); +} + +.activity-modal.show .activity-glass-layer-1, +.activity-modal.show .activity-glass-layer-3, +.info-modal.show .info-glass-layer-1, +.info-modal.show .info-glass-layer-2, +.info-modal.show .info-glass-layer-3, +.scheduler-modal.show .scheduler-glass-layer-1, +.scheduler-modal.show .scheduler-glass-layer-2, +.planner-modal.show .planner-glass-layer-1, +.planner-modal.show .planner-glass-layer-2, +.notfound-modal.show .notfound-glass-layer-1, +.notfound-modal.show .notfound-glass-layer-2, +#offlineOverlay.show .notfound-glass-layer-1, +#offlineOverlay.show .notfound-glass-layer-2 { + animation-duration: 260ms; + animation-timing-function: ease-out; + will-change: opacity; +} + +.modal-overlay.closing, +.activity-modal.closing, +.info-modal.closing, +.ai-help-modal.closing, +.notfound-modal.closing, +.store-pref-modal.closing, +#storePrefModal.closing, +.scheduler-modal.closing, +.planner-modal.closing, +.progress-popup.closing { + animation: modalClose var(--adp-modal-exit-duration) cubic-bezier(0.4, 0, 0.2, 1) both; +} + +.dock-wrap { + transform: translate3d(-50%, 0, 0); + transition: opacity 0.22s ease, transform 0.22s ease; + will-change: opacity, transform; +} + +.dock-wrap.dock-hidden { + transform: translate3d(-50%, 20px, 0); + transition: opacity 0.22s ease, transform 0.22s ease; +} + +.dock-item { + transition: transform 0.12s ease; +} + +.dock-item .icon { + transition: transform 0.22s var(--adp-modal-ease), background 0.22s ease; + will-change: transform; +} + +.dock-item .icon i, +.modal-close, +.activity-close, +.activity-close-icon, +.activity-pill, +.activity-load-more, +.icon-btn { + transition-property: background, background-color, border-color, color, opacity, transform, box-shadow; +} + +@keyframes adpOverlayIn { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes modalClose { + from { + opacity: 1; + transform: scale(1); + } + + to { + opacity: 0; + transform: scale(0.965); + } +} + +@keyframes glassLayer1In { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes glassLayer3In { + from { + opacity: 0; + } + + to { + opacity: 1; + } +} + +@keyframes panelLiquidIn { + from { + opacity: 0; + transform: translate3d(0, 10px, 0) scale(0.94) rotateX(6deg); + } + + to { + opacity: 1; + transform: translate3d(0, 0, 0) scale(1) rotateX(0); + } +} + +@keyframes textFadeIn { + from { + opacity: 0; + transform: translate3d(0, 3px, 0); + } + + to { + opacity: 1; + transform: translate3d(0, 0, 0); + } +} + +@keyframes searchWrapIn { + from { + opacity: 0; + transform: translate3d(0, 4px, 0); + } + + to { + opacity: 1; + transform: translate3d(0, 0, 0); + } +} + +@keyframes entrySlideIn { + from { + opacity: 0; + transform: translate3d(0, 4px, 0) scale(0.985); + } + + to { + opacity: 1; + transform: translate3d(0, 0, 0) scale(1); + } +} + +@keyframes iconPulse { + 0%, + 100% { + transform: scale(1); + opacity: 0.4; + } + + 50% { + transform: scale(1.12); + opacity: 0.15; + } +} + +@keyframes aiMessageIn { + from { + opacity: 0; + transform: translate3d(0, 12px, 0) scale(0.98); + } + + to { + opacity: 1; + transform: translate3d(0, 0, 0) scale(1); + } +} + +#storeModal.modal-overlay.show, +#storePrefModal.modal-overlay.show { + backdrop-filter: blur(12px) saturate(120%); + -webkit-backdrop-filter: blur(12px) saturate(120%); +} + +#storeModal.modal-overlay.show > .modal, +#storePrefModal.modal-overlay.show > .modal { + animation-name: storePanelScaleIn; + animation-duration: 260ms; + 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; +} + +@keyframes storePanelScaleIn { + from { + opacity: 0; + transform: scale(0.96); + } + + to { + opacity: 1; + transform: scale(1); + } +} + +@media (max-width: 680px) { + #storePrefModal .modal { + width: calc(100vw - 18px); + max-height: calc(100dvh - 18px); + } + + .store-pref-body { + padding: 14px; + } + + .store-pref-grid { + grid-template-columns: 1fr; + } + + .store-pref-card { + min-height: 150px; + } + + #storeModal .modal { + width: calc(100vw - 18px); + height: calc(100dvh - 18px); + max-height: calc(100dvh - 18px); + border-radius: 18px; + } + + .store-header { + align-items: flex-start; + flex-direction: column; + } + + .store-header-right, + .store-tabs { + width: 100%; + } + + .store-tabs { + justify-content: space-between; + } + + .store-tab { + flex: 1 1 auto; + padding-inline: 10px; + } + + .store-version-row.store-custom-version-row { + flex-direction: column; + } + + .store-custom-version-form { + width: 100%; + min-width: 0; + flex-direction: column; + align-items: stretch; + } + + .store-custom-version-input { + width: 100%; + } + + .mr-plugins-header { + align-items: stretch; + flex-direction: column; + } + + .mr-plugin-grid { + grid-template-columns: repeat(auto-fill, minmax(172px, 1fr)); + gap: 10px; + padding-right: 2px; + } + + .mr-plugin-icon { + height: 112px; + } + + #mrPluginModal .mr-plugin-install-modal { + width: calc(100vw - 20px); + max-height: calc(100dvh - 20px); + border-radius: 20px; + } + + #mrPluginModal .mr-plugin-install-modal::before { + border-radius: 20px; + } + + #mrPluginModal .activity-header, + #mrPluginModal .activity-body { + padding-left: 16px; + padding-right: 16px; + } + + #mrPluginModal .mr-plugin-install-footer { + padding-left: 16px; + padding-right: 16px; + } + + #mrPluginModal .mr-plugin-install-action, + #mrPluginModal .backup-create-cancel { + width: 100%; + justify-content: center; + } + + #mrPluginModal .mr-plugin-install-footer { + flex-direction: column-reverse; + } +} + +/* URL uploader: compact, aligned, same visual language. */ +.url-uploader-activity .activity-panel { + width: min(560px, calc(100vw - 32px)); + max-width: min(560px, calc(100vw - 32px)); + height: auto; + min-height: 0; + max-height: calc(100dvh - 40px); + border-radius: 24px; +} + +.url-uploader-activity .activity-header { + padding: 22px 24px 16px; +} + +.url-uploader-activity .activity-body { + flex: 0 0 auto; + overflow: visible; + padding: 0 24px 16px; + mask-image: none; + -webkit-mask-image: none; +} + +.url-uploader-body { + display: grid; + gap: 16px; + padding: 0; +} + +.url-uploader-desc { + margin: 0; +} + +.url-uploader-field { + margin: 0; +} + +.url-uploader-field input { + width: 100%; + box-sizing: border-box; + transition: background-color 0.15s ease, border-color 0.15s ease, box-shadow 0.15s ease; +} + +.url-uploader-error { + margin-top: 0; +} + +.url-uploader-footer { + padding: 16px 24px 22px; +} + +@media (max-width: 640px) { + .url-uploader-activity .activity-panel { + width: calc(100vw - 20px); + max-height: calc(100dvh - 20px); + border-radius: 20px; + } + + .url-uploader-activity .activity-header { + padding: 20px 18px 14px; + } + + .url-uploader-activity .activity-body { + padding: 0 18px 14px; + } + + .url-uploader-footer { + padding: 14px 18px 18px; + } +} + +@media (prefers-reduced-motion: reduce) { + .modal-overlay.show, + .activity-modal.show, + .info-modal.show, + .ai-help-modal.show, + .notfound-modal.show, + .scheduler-modal.show, + .planner-modal.show, + #offlineOverlay.show, + .modal-overlay.show > .modal, + .activity-modal.show .activity-panel, + .activity-modal.show .reinstall-panel, + .info-modal.show .info-panel, + .ai-help-modal.show .ai-help-panel, + .scheduler-modal.show .scheduler-panel, + .planner-modal.show .planner-panel, + .notfound-modal.show .notfound-panel, + #offlineOverlay.show .notfound-panel, + .activity-entry, + .activity-title, + .activity-subtitle, + .activity-search-wrap, + .activity-close, + .ai-message.ai-enter, + .ai-message.ai-typing-container { + animation-duration: 1ms !important; + animation-delay: 0ms !important; + transition-duration: 1ms !important; + } +} diff --git a/public/css/dashboard-assistant.css b/public/css/dashboard-assistant.css new file mode 100644 index 0000000..a7176ab --- /dev/null +++ b/public/css/dashboard-assistant.css @@ -0,0 +1,855 @@ +.toolbar-assistant { + position: relative; +} + +.dashboard-assistant-trigger { + position: relative; +} + +.dashboard-assistant-trigger::after { + content: ""; + position: absolute; + inset: -1px; + border-radius: inherit; + background: linear-gradient(135deg, rgba(34, 211, 238, 0.2), rgba(59, 130, 246, 0.18)); + opacity: 0; + transition: opacity 0.2s ease; + pointer-events: none; +} + +.dashboard-assistant-trigger:hover::after, +.dashboard-assistant-trigger[aria-expanded="true"]::after { + opacity: 1; +} + +.dashboard-assistant-menu { + position: fixed; + top: 105px; + right: clamp(12px, 5vw, 100px); + left: auto; + width: min(580px, calc(100vw - 24px)); + max-height: 85vh; + display: none; + flex-direction: column; + z-index: 1500; + border-radius: 24px; + background: linear-gradient(165deg, rgba(30,32,38,0.95) 0%, rgba(22,24,28,0.98) 100%); + backdrop-filter: blur(40px) saturate(180%); + -webkit-backdrop-filter: blur(40px) saturate(180%); + border: none; + box-shadow: 0 0 0 1px rgba(255, 255, 255, 0.06), 0 25px 80px -12px rgba(0, 0, 0, 0.5), 0 0 100px rgba(0, 0, 0, 0.3); + overflow: hidden; +} + +.dashboard-assistant-menu.dashboard-assistant-menu--setup { + width: min(430px, calc(100vw - 24px)); + max-height: min(520px, calc(100vh - 96px)); +} + +.dashboard-assistant-menu.is-open { + display: flex; + animation: modalReveal 0.35s cubic-bezier(0.32, 0.72, 0, 1) forwards; +} + +@keyframes modalReveal { + 0% { + opacity: 0; + transform: scale(0.96) translateY(10px); + filter: blur(8px); + } + + 100% { + opacity: 1; + transform: scale(1) translateY(0); + filter: blur(0); + } +} + +.dashboard-assistant-head { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 24px 28px 20px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.03), transparent); +} + +.dashboard-assistant-icon { + width: 64px; + height: 64px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + background: transparent; +} + +.dashboard-assistant-icon i { + display: block; + font-size: 24px; + color: #fff; +} + +.dashboard-assistant-title { + margin: 0; + font-size: 20px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.02em; +} + +.dashboard-assistant-subtitle { + margin: 6px 0 0; + font-size: 14px; + color: rgba(255, 255, 255, 0.5); +} + +.dashboard-assistant-head-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.dashboard-assistant-head-btn { + width: 36px; + height: 36px; + border-radius: 10px; + border: none; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + flex-shrink: 0; +} + +.dashboard-assistant-head-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.8); +} + +.dashboard-assistant-head-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.dashboard-assistant-status { + margin: 0 28px 14px; + padding: 11px 16px; + display: flex; + align-items: center; + gap: 10px; + border-radius: 12px; + background: rgba(20, 28, 49, 0.5); + color: rgba(255, 255, 255, 0.85); + font-size: 13px; + border: 1px solid rgba(255, 255, 255, 0.04); +} + +.dashboard-assistant-status::before { + content: ""; + width: 10px; + height: 10px; + border-radius: 999px; + background: #22c55e; + box-shadow: 0 0 0 6px rgba(34, 197, 94, 0.16); + flex: 0 0 auto; +} + +.dashboard-assistant-status[data-state="working"]::before, +.dashboard-assistant-status[data-state="transcribing"]::before { + background: #38bdf8; + box-shadow: 0 0 0 6px rgba(56, 189, 248, 0.18); +} + +.dashboard-assistant-status[data-state="recording"]::before { + background: #fb7185; + box-shadow: 0 0 0 6px rgba(251, 113, 133, 0.18); +} + +.dashboard-assistant-status[data-state="warning"]::before, +.dashboard-assistant-status[data-state="error"]::before { + background: #f59e0b; + box-shadow: 0 0 0 6px rgba(245, 158, 11, 0.18); +} + +.dashboard-assistant-config, +.dashboard-assistant-notice { + margin: 0 28px 14px; + border-radius: 12px; + background: rgba(0, 0, 0, 0.2); + border: 1px solid rgba(255, 255, 255, 0.04); +} + +.dashboard-assistant-config[hidden], +.dashboard-assistant-notice[hidden] { + display: none; +} + +.dashboard-assistant-config { + padding: 14px; +} + +.dashboard-assistant-menu.dashboard-assistant-menu--setup .dashboard-assistant-head { + padding-bottom: 16px; +} + +.dashboard-assistant-menu.dashboard-assistant-menu--setup .dashboard-assistant-config, +.dashboard-assistant-menu.dashboard-assistant-menu--setup .dashboard-assistant-notice { + margin-bottom: 22px; +} + +.dashboard-assistant-config-title { + margin: 0; + font-size: 14px; + font-weight: 700; + color: #ecf5ff; +} + +.dashboard-assistant-config-text, +.dashboard-assistant-notice { + font-size: 13px; + line-height: 1.55; + color: rgba(204, 216, 236, 0.84); +} + +.dashboard-assistant-config-text { + margin: 6px 0 0; +} + +.dashboard-assistant-token-form { + margin-top: 14px; + display: grid; + gap: 10px; +} + +.dashboard-assistant-token-label { + font-size: 12px; + font-weight: 700; + color: rgba(171, 189, 219, 0.88); +} + +.dashboard-assistant-token-input { + width: 100%; + min-height: 42px; + padding: 0 14px; + border-radius: 14px; + border: 1px solid rgba(120, 146, 190, 0.26); + background: rgba(8, 13, 24, 0.88); + color: #edf4ff; + font-size: 14px; +} + +select.dashboard-assistant-token-input { + appearance: none; + -webkit-appearance: none; + background-image: + linear-gradient(45deg, transparent 50%, rgba(212, 228, 255, 0.9) 50%), + linear-gradient(135deg, rgba(212, 228, 255, 0.9) 50%, transparent 50%); + background-position: + calc(100% - 18px) calc(50% - 3px), + calc(100% - 12px) calc(50% - 3px); + background-size: 6px 6px, 6px 6px; + background-repeat: no-repeat; + padding-right: 42px; +} + +.dashboard-assistant-token-input::placeholder, +.dashboard-assistant-transcript::placeholder { + color: rgba(141, 156, 183, 0.78); +} + +.dashboard-assistant-token-foot { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; +} + +.dashboard-assistant-token-state { + font-size: 12px; + color: rgba(164, 180, 207, 0.8); +} + +.dashboard-assistant-access-row { + margin-top: 14px; + padding-top: 14px; + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.dashboard-assistant-access-copy { + flex: 1; + min-width: 0; +} + +.dashboard-assistant-access-title { + margin: 0; + font-size: 13px; + font-weight: 700; + color: #ecf5ff; +} + +.dashboard-assistant-access-text { + margin: 5px 0 0; + font-size: 12px; + line-height: 1.5; + color: rgba(164, 180, 207, 0.8); +} + +.dashboard-assistant-switch { + position: relative; + width: 48px; + height: 28px; + display: inline-block; + flex: 0 0 auto; +} + +.dashboard-assistant-switch input { + position: absolute; + width: 0; + height: 0; + opacity: 0; +} + +.dashboard-assistant-switch-slider { + position: absolute; + inset: 0; + border-radius: 999px; + background: rgba(71, 85, 105, 0.85); + cursor: pointer; + transition: background 0.2s ease, opacity 0.2s ease; + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08); +} + +.dashboard-assistant-switch-slider::before { + content: ""; + position: absolute; + top: 3px; + left: 3px; + width: 22px; + height: 22px; + border-radius: 999px; + background: #f8fbff; + transition: transform 0.2s ease; + box-shadow: 0 1px 8px rgba(0, 0, 0, 0.28); +} + +.dashboard-assistant-switch input:checked + .dashboard-assistant-switch-slider { + background: linear-gradient(135deg, #0ea5e9, #2563eb); +} + +.dashboard-assistant-switch input:checked + .dashboard-assistant-switch-slider::before { + transform: translateX(20px); +} + +.dashboard-assistant-switch input:focus + .dashboard-assistant-switch-slider { + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08), 0 0 0 3px rgba(56, 189, 248, 0.2); +} + +.dashboard-assistant-switch input:disabled + .dashboard-assistant-switch-slider { + opacity: 0.55; + cursor: not-allowed; +} + +.dashboard-assistant-save { + min-height: 40px; + padding: 0 16px; + border: none; + border-radius: 12px; + background: linear-gradient(135deg, #0ea5e9, #2563eb); + color: #eff8ff; + font-weight: 800; + cursor: pointer; + transition: filter 0.2s ease, transform 0.2s ease; +} + +.dashboard-assistant-save:hover { + filter: brightness(1.05); + transform: translateY(-1px); +} + +.dashboard-assistant-save:disabled { + opacity: 0.6; + cursor: not-allowed; + transform: none; +} + +.dashboard-assistant-notice { + padding: 14px; +} + +.dashboard-assistant-messages[hidden], +.dashboard-assistant-composer[hidden] { + display: none; +} + +.dashboard-assistant-messages { + flex: 1; + min-height: 220px; + padding: 4px 28px 20px; + overflow-y: auto; + display: flex; + flex-direction: column; + gap: 12px; +} + +.dashboard-assistant-messages::-webkit-scrollbar { + width: 8px; +} + +.dashboard-assistant-messages::-webkit-scrollbar-thumb { + background: rgba(114, 136, 179, 0.3); + border-radius: 999px; +} + +.dashboard-assistant-empty { + min-height: 220px; + border: 1px dashed rgba(139, 161, 203, 0.16); + border-radius: 18px; + background: rgba(11, 17, 31, 0.46); + display: flex; + align-items: center; + justify-content: center; + text-align: center; + padding: 24px; + font-size: 13px; + line-height: 1.6; + color: rgba(176, 191, 216, 0.8); +} + +.dashboard-assistant-message { + max-width: 88%; + display: flex; + flex-direction: column; + gap: 6px; + align-self: flex-start; + user-select: text; + -webkit-user-select: text; +} + +.dashboard-assistant-message--user { + align-self: flex-end; +} + +.dashboard-assistant-message-bubble { + padding: 12px 14px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.9); + font-size: 13px; + line-height: 1.65; + white-space: pre-wrap; + word-break: break-word; + user-select: text; + -webkit-user-select: text; +} + +.dashboard-assistant-message-bubble::selection { + background: rgba(96, 165, 250, 0.35); + color: #fff; +} + +.dashboard-assistant-message-link { + color: #8ec5ff; + word-break: break-all; +} + +.dashboard-assistant-message-link:hover { + color: #b7daff; +} + +.dashboard-assistant-message--user .dashboard-assistant-message-bubble { + background: linear-gradient(135deg, rgba(99, 102, 241, 0.2), rgba(79, 70, 229, 0.15)); + border: 1px solid rgba(99, 102, 241, 0.3); +} + +.dashboard-assistant-message-meta-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; + padding-inline: 2px; +} + +.dashboard-assistant-message-meta { + font-size: 11px; + color: rgba(145, 160, 187, 0.76); + user-select: text; + -webkit-user-select: text; +} + +.dashboard-assistant-message-copy { + border: 1px solid rgba(148, 163, 184, 0.16); + border-radius: 999px; + background: rgba(255, 255, 255, 0.05); + color: rgba(223, 233, 249, 0.9); + min-height: 28px; + padding: 0 10px; + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 11px; + font-weight: 700; + cursor: pointer; + transition: background 0.2s ease, border-color 0.2s ease, color 0.2s ease, transform 0.2s ease; + user-select: none; + -webkit-user-select: none; +} + +.dashboard-assistant-message-copy:hover { + background: rgba(96, 165, 250, 0.14); + border-color: rgba(96, 165, 250, 0.28); + color: #f8fbff; +} + +.dashboard-assistant-message-copy:active { + transform: translateY(1px); +} + +.dashboard-assistant-message-copy.is-copied { + background: rgba(34, 197, 94, 0.14); + border-color: rgba(34, 197, 94, 0.28); + color: rgba(220, 252, 231, 0.96); +} + +.dashboard-assistant-message-copy i { + font-size: 11px; +} + +.dashboard-assistant-composer { + padding: 16px 28px 24px; + background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.15)); + border-top: 1px solid rgba(255, 255, 255, 0.03); +} + +.dashboard-assistant-text-form { + display: grid; + gap: 8px; + margin-bottom: 12px; +} + +.dashboard-assistant-text-label { + font-size: 12px; + font-weight: 700; + color: rgba(171, 189, 219, 0.88); +} + +.dashboard-assistant-text-row { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 10px; + align-items: stretch; +} + +.dashboard-assistant-text-input { + width: 100%; + min-height: 52px; + resize: vertical; + padding: 12px 14px; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(0, 0, 0, 0.2); + color: rgba(255, 255, 255, 0.9); + font-size: 14px; + line-height: 1.45; + transition: all 0.2s ease; +} + +.dashboard-assistant-text-input:focus { + outline: none; + background: rgba(0, 0, 0, 0.3); + border-color: rgba(99, 102, 241, 0.5); + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15); +} + +.dashboard-assistant-send-btn { + width: 52px; + min-height: 52px; + border: none; + border-radius: 12px; + background: linear-gradient(135deg, rgba(99, 102, 241, 0.9), rgba(79, 70, 229, 0.85)); + color: #fff; + font-size: 17px; + cursor: pointer; + transition: all 0.2s ease; +} + +.dashboard-assistant-send-btn:hover { + filter: brightness(1.04); +} + +.dashboard-assistant-send-btn:disabled { + opacity: 0.5; + cursor: not-allowed; + filter: none; +} + +.dashboard-assistant-voicepad { + display: grid; + grid-template-columns: minmax(0, 1fr) auto; + gap: 10px; + align-items: stretch; +} + +.dashboard-assistant-voice-btn, +.dashboard-assistant-replay-btn { + border: none; + cursor: pointer; + transition: transform 0.2s ease, filter 0.2s ease, opacity 0.2s ease; +} + +.dashboard-assistant-voice-btn:hover, +.dashboard-assistant-replay-btn:hover { + filter: brightness(1.04); +} + +.dashboard-assistant-voice-btn:disabled, +.dashboard-assistant-replay-btn:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.dashboard-assistant-voice-btn { + min-height: 52px; + padding: 0 18px; + border-radius: 12px; + background: linear-gradient(135deg, rgba(16, 185, 129, 0.15), rgba(5, 150, 105, 0.12)); + border: 1px solid rgba(16, 185, 129, 0.3); + color: rgba(255, 255, 255, 0.9); + display: inline-flex; + align-items: center; + justify-content: center; + gap: 12px; + font-size: 14px; + font-weight: 600; + box-shadow: none; +} + +.dashboard-assistant-voice-btn--recording { + background: linear-gradient(135deg, rgba(190, 24, 93, 0.95), rgba(225, 29, 72, 0.95)); + color: #fff3f6; +} + +.dashboard-assistant-voice-icon { + width: 34px; + height: 34px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.14); + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; +} + +.dashboard-assistant-voice-copy { + white-space: nowrap; +} + +.dashboard-assistant-replay-btn { + width: 52px; + min-height: 52px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.05); + color: rgba(255, 255, 255, 0.7); + border: 1px solid rgba(255, 255, 255, 0.08); + display: inline-flex; + align-items: center; + justify-content: center; + font-size: 16px; +} + +.dashboard-assistant-voice-meta { + margin-top: 10px; + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + min-height: 24px; +} + +.dashboard-assistant-voice-state { + font-size: 12px; + color: rgba(171, 187, 214, 0.82); +} + +.dashboard-assistant-speaking { + display: inline-flex; + align-items: center; + gap: 4px; +} + +.dashboard-assistant-speaking-wave { + width: 4px; + height: 16px; + border-radius: 999px; + background: linear-gradient(180deg, #7dd3fc, #2563eb); + animation: dashboardAssistantSpeak 0.9s ease-in-out infinite; +} + +.dashboard-assistant-speaking-wave:nth-child(2) { + animation-delay: 0.15s; +} + +.dashboard-assistant-speaking-wave:nth-child(3) { + animation-delay: 0.3s; +} + +@keyframes dashboardAssistantSpeak { + 0%, + 100% { + transform: scaleY(0.45); + opacity: 0.5; + } + + 50% { + transform: scaleY(1); + opacity: 1; + } +} + +.dashboard-assistant-transcript { + margin-top: 10px; + padding: 12px 14px; + border-radius: 16px; + background: rgba(9, 14, 27, 0.8); + border: 1px solid rgba(126, 147, 189, 0.14); + color: #dce8fb; + font-size: 13px; + line-height: 1.55; +} + +.dashboard-assistant-transcript[hidden] { + display: none; +} + +.dashboard-assistant-composer-note { + margin-top: 10px; + font-size: 12px; + color: rgba(144, 160, 187, 0.78); +} + +.dashboard-assistant-confirm-overlay { + z-index: 2200; +} + +.dashboard-assistant-confirm-modal { + width: min(620px, calc(100vw - 28px)); + max-height: min(78vh, 560px); +} + +/* Responsive fixes to keep paddings aligned */ +@media (max-width: 640px) { + .dashboard-assistant-menu { + top: 70px; + right: 10px; + left: auto; + width: calc(100vw - 20px); + max-height: calc(100vh - 80px); + border-radius: 20px; + } + + .dashboard-assistant-head, + .dashboard-assistant-messages, + .dashboard-assistant-composer { + padding-left: 20px; + padding-right: 20px; + } + + .dashboard-assistant-status, + .dashboard-assistant-config, + .dashboard-assistant-notice { + margin-left: 20px; + margin-right: 20px; + } +} + +.dashboard-assistant-confirm-copy { + display: grid; + gap: 10px; +} + +.dashboard-assistant-confirm-lead { + margin: 0; + font-size: 17px; + line-height: 1.5; + color: #eef6ff; +} + +.dashboard-assistant-confirm-text { + margin: 0; + font-size: 14px; + line-height: 1.65; + color: rgba(194, 209, 233, 0.82); +} + +.dashboard-assistant-confirm-footer { + justify-content: space-between; + flex-wrap: wrap; +} + +.dashboard-assistant-confirm-footer .enterprise-btn-secondary, +.dashboard-assistant-confirm-footer .enterprise-btn-primary { + flex: 1 1 220px; + justify-content: center; +} + +.dashboard-assistant-status.is-hidden, +.dashboard-assistant-token-state.is-hidden, +.dashboard-assistant-notice.is-hidden { + display: none; +} + +@media (max-width: 640px) { + .dashboard-assistant-menu { + width: calc(100vw - 20px); + max-height: calc(100vh - 112px); + border-radius: 20px; + } + + .dashboard-assistant-head, + .dashboard-assistant-messages, + .dashboard-assistant-composer { + padding-left: 14px; + padding-right: 14px; + } + + .dashboard-assistant-status, + .dashboard-assistant-config, + .dashboard-assistant-notice { + margin-left: 14px; + margin-right: 14px; + } + + .dashboard-assistant-message { + max-width: 94%; + } + + .dashboard-assistant-voicepad { + grid-template-columns: minmax(0, 1fr); + } + + .dashboard-assistant-text-row { + grid-template-columns: minmax(0, 1fr); + } + + .dashboard-assistant-replay-btn { + width: 100%; + } + + .dashboard-assistant-voice-copy { + white-space: normal; + } + + .dashboard-assistant-confirm-modal { + width: calc(100vw - 20px); + } +} diff --git a/public/css/dashboard.css b/public/css/dashboard.css new file mode 100644 index 0000000..851b9a4 --- /dev/null +++ b/public/css/dashboard.css @@ -0,0 +1,1147 @@ + :root { + --ui-bg: url("/images/waves.png?v=1776616961314"); + } + + .btn-primary { + display: inline-flex; + gap: 8px; + align-items: center; + background: linear-gradient(135deg, rgba(14, 165, 233, 0.8), rgba(29, 78, 216, 0.8)); + backdrop-filter: blur(12px) saturate(180%); + -webkit-backdrop-filter: blur(12px) saturate(180%); + color: #e5f4ff; + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 10px; + padding: 10px 14px; + font-weight: 700; + cursor: pointer; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.2); + transition: + transform 0.22s cubic-bezier(0.22, 0.61, 0.36, 1), + filter 0.18s ease-out, + background 0.28s ease-out; + } + + .btn-primary:hover { + filter: brightness(1.06); + transform: translateY(-1px); + } + + .btn-primary:active { + transform: translateY(0); + filter: brightness(0.96); + } + + .btn-ghost { + background: rgba(15, 23, 42, 0.85); + border: none; + color: #c8d3df; + padding: 9px 13px; + border-radius: 10px; + cursor: pointer; + box-shadow: none; + font-size: 13px; + display: inline-flex; + align-items: center; + gap: 6px; + transition: + background 0.2s ease-out, + transform 0.2s ease-out, + opacity 0.18s ease-out; + } + + .btn-ghost:hover { + background: rgba(15, 23, 42, 1); + transform: translateY(-1px); + } + + .btn-ghost:active { + transform: translateY(0); + opacity: .9; + } + + .modal-overlay { + position: fixed; + inset: 0; + background: radial-gradient(circle at top, rgba(15, 23, 42, .9), rgba(2, 6, 23, .96)); + display: none; + align-items: center; + justify-content: center; + z-index: 9999; + backdrop-filter: blur(10px); + padding: 12px; + } + + .modal-overlay.show { + display: flex; + } + + @keyframes modalEnter { + from { + opacity: 0; + transform: translateY(16px) scale(.97); + } + + to { + opacity: 1; + transform: translateY(0) scale(1); + } + } + + .modal-card { + width: min(780px, 96vw); + max-height: 92vh; + background: linear-gradient(145deg, var(--panel-bg), #02091a); + border-radius: 18px; + color: #e7eef7; + display: flex; + flex-direction: column; + box-shadow: none; + animation: modalEnter .22s ease-out; + overflow: hidden; + } + + .modal-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + padding: 14px 18px 10px; + flex-shrink: 0; + } + + .modal-title-group { + display: flex; + gap: 12px; + align-items: flex-start; + } + + .modal-avatar { + width: 40px; + height: 40px; + border-radius: 999px; + background: radial-gradient(circle at 25% 0, #38bdf8, #1e40af 45%, #020617 100%); + display: flex; + align-items: center; + justify-content: center; + color: #e5f4ff; + flex-shrink: 0; + } + + .modal-eyebrow { + font-size: 11px; + letter-spacing: 0.14em; + text-transform: uppercase; + color: var(--panel-text-soft); + margin-bottom: 2px; + } + + .modal-title { + font-size: 18px; + font-weight: 800; + } + + .modal-subtitle { + font-size: 13px; + color: var(--panel-text-soft); + margin-top: 4px; + } + + .modal-body { + padding: 12px 18px 14px; + display: flex; + flex-direction: column; + gap: 14px; + flex: 1 1 auto; + overflow: auto; + } + + .modal-body--split { + display: grid; + grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); + gap: 16px; + align-items: flex-start; + } + + .modal-main { + display: grid; + gap: 12px; + } + + .modal-aside { + display: flex; + flex-direction: column; + gap: 10px; + } + + @media (max-width: 720px) { + .modal-card { + width: 100%; + max-height: 96vh; + } + + .modal-head { + padding: 12px 14px 6px; + } + + .modal-body { + padding: 10px 12px 12px; + } + + .modal-body--split { + grid-template-columns: minmax(0, 1fr); + } + } + + .modal-foot { + display: flex; + justify-content: flex-end; + gap: 10px; + padding: 10px 18px 12px; + background: #020617; + flex-shrink: 0; + } + + .field { + display: grid; + gap: 6px; + } + + .field label { + font-size: 13px; + color: #a9b4c2; + } + + .field input, + .field select, + .field textarea { + background: #020617; + border: none; + border-radius: 10px; + color: #eaf1fb; + padding: 9px 11px; + outline: none; + font-family: inherit; + font-size: 14px; + transition: + background 0.18s ease-out, + transform 0.14s ease-out; + } + + .field input:focus, + .field select:focus, + .field textarea:focus { + background: #020b1f; + transform: translateY(-1px); + } + + .inline-hint { + font-size: 12px; + color: #9eb0c5; + } + + .summary-card { + border-radius: 12px; + background: var(--panel-bg-soft); + font-size: 13px; + padding: 9px 10px 8px; + position: relative; + overflow: hidden; + } + + .summary-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 4px; + } + + .summary-title { + font-size: 11px; + letter-spacing: 0.16em; + text-transform: uppercase; + color: var(--panel-text-soft); + } + + .summary-badge { + font-size: 11px; + padding: 2px 8px; + border-radius: 999px; + background: rgba(15, 23, 42, .95); + color: #cbd5f5; + } + + .summary-row { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 2px; + } + + .summary-label { + color: var(--panel-text-soft); + font-size: 12px; + } + + .summary-value { + color: #e5edf9; + font-weight: 600; + font-size: 13px; + margin-left: 8px; + } + + .summary-footer { + font-size: 11px; + color: var(--panel-text-muted); + margin-top: 5px; + } + + .template-grid, + .node-grid { + display: grid; + gap: 10px; + grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); + } + + /* Base flat card */ + .template-card, + .node-card, + .fork-card { + border: none; + border-radius: 12px; + padding: 9px 9px 8px; + cursor: pointer; + background: var(--panel-bg-soft); + text-align: left; + display: flex; + flex-direction: column; + gap: 6px; + box-shadow: none; + position: relative; + overflow: hidden; + transform: translateY(0) scale(1); + transition: + transform .26s cubic-bezier(0.22, 0.61, 0.36, 1), + background .26s ease-out; + --mouse-x: 50%; + --mouse-y: 50%; + } + + /* Aqua “cursor follow” aura */ + .template-card::before, + .node-card::before, + .fork-card::before { + content: ""; + position: absolute; + top: var(--mouse-y); + left: var(--mouse-x); + transform: translate(-50%, -50%); + width: 220%; + height: 220%; + background: + radial-gradient(circle at center, + rgba(34, 211, 238, 0.25) 0%, + rgba(37, 99, 235, 0.18) 35%, + transparent 60%); + opacity: 0; + pointer-events: none; + transition: + opacity .35s ease-out, + transform .35s ease-out; + } + + .template-card:hover, + .node-card:hover, + .fork-card:hover { + transform: translateY(-2px) scale(1.01); + background: var(--panel-bg-soft-alt); + } + + .template-card:hover::before, + .node-card:hover::before, + .fork-card:hover::before { + opacity: 1; + transform: translate(-50%, -50%) scale(1.03); + } + + .template-card[aria-selected="true"], + .node-card[aria-selected="true"], + .fork-card[aria-selected="true"] { + background: var(--panel-bg-soft-alt); + } + + .template-card__header, + .node-card__header { + display: flex; + gap: 10px; + align-items: center; + } + + .template-card__icon, + .node-card__icon, + .fork-card__icon { + width: 30px; + height: 30px; + border-radius: 999px; + display: flex; + align-items: center; + justify-content: center; + background: #020617; + flex-shrink: 0; + font-size: 14px; + } + + .template-card__title-group h4, + .node-card__title-group h4 { + margin: 0; + font-size: 14px; + } + + .template-card__badge { + display: inline-flex; + align-items: center; + margin-top: 2px; + padding: 2px 8px; + border-radius: 999px; + font-size: 11px; + text-transform: uppercase; + letter-spacing: .12em; + color: #cbd5f5; + background: rgba(15, 23, 42, .95); + } + + .template-card__description, + .node-card__description { + margin: 2px 0 0 0; + font-size: 12px; + color: #a9b4c2; + min-height: 32px; + } + + .template-card__meta { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 11px; + color: var(--panel-text-soft); + } + + .node-status { + display: inline-flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: #9eb0c5; + } + + .dot { + width: 8px; + height: 8px; + border-radius: 999px; + background: #64748b; + display: inline-block; + } + + .dot.ok { + background: var(--panel-aqua); + } + + .dot.down { + background: #ef4444; + } + + .spinner { + width: 16px; + height: 16px; + border-radius: 999px; + border: 2px solid rgba(255, 255, 255, .28); + border-top-color: #e5f4ff; + animation: spin .9s linear infinite; + display: none; + } + + .spinner.show { + display: inline-block; + } + + @keyframes spin { + to { + transform: rotate(360deg); + } + } + + .fork-grid { + display: grid; + gap: 10px; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + } + + .fork-title { + font-weight: 700; + font-size: 14px; + } + + .muted { + color: #a9b4c2; + font-size: 12px; + } + + .port-layout { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); + gap: 16px; + align-items: flex-start; + } + + @media (max-width: 640px) { + .port-layout { + grid-template-columns: minmax(0, 1fr); + } + } + + .connection-chip { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 7px 9px; + border-radius: 999px; + background: #020617; + font-size: 12px; + color: #e5edf9; + box-shadow: none; + position: relative; + overflow: hidden; + } + + .connection-chip i { + font-size: 13px; + } + + .connection-chip__divider { + margin: 0 2px; + opacity: .6; + } + + .connection-chip code { + background: none; + padding: 0; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: 12px; + color: #e5edf9; + } + + /* Resources Modal Styles */ + .resources-layout { + display: flex; + flex-direction: column; + gap: 24px; + } + + .resources-info { + background: rgba(124, 92, 255, 0.06); + border: 1px solid rgba(124, 92, 255, 0.15); + border-radius: 16px; + padding: 16px 20px; + } + + .resources-info__header { + display: flex; + align-items: center; + gap: 10px; + font-size: 13px; + font-weight: 600; + color: var(--color-accent); + margin-bottom: 12px; + } + + .resources-info__header i { + font-size: 14px; + } + + .resources-info__grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 16px; + } + + @media (max-width: 640px) { + .resources-info__grid { + grid-template-columns: 1fr; + gap: 12px; + } + } + + .resources-info__item { + display: flex; + flex-direction: column; + gap: 4px; + } + + .resources-info__label { + font-size: 11px; + color: var(--color-text-muted); + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .resources-info__value { + font-size: 15px; + font-weight: 600; + color: var(--color-text); + font-variant-numeric: tabular-nums; + } + + .resources-fields { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 16px; + } + + @media (max-width: 640px) { + .resources-fields { + grid-template-columns: 1fr; + } + } + + .resources-fields .field { + display: flex; + flex-direction: column; + gap: 6px; + } + + .resources-fields input::-webkit-outer-spin-button, + .resources-fields input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; + } + + .resources-fields input[type=number] { + -moz-appearance: textfield; + } + + .ssh-terminal-btn { + border-color: rgba(45, 212, 191, 0.35); + box-shadow: 0 0 0 1px rgba(45, 212, 191, 0.12) inset; + } + + .ssh-terminal-btn:hover { + border-color: rgba(45, 212, 191, 0.65); + box-shadow: 0 0 14px rgba(45, 212, 191, 0.2); + } + + .ssh-terminal-overlay { + position: fixed; + inset: 0; + display: none; + align-items: center; + justify-content: center; + overflow: hidden; + z-index: 100050; + background: rgba(2, 6, 23, 0.76); + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + } + + .ssh-terminal-overlay.show { + display: flex; + } + + .ssh-terminal-modal { + width: 95vw; + height: 95vh; + border-radius: 10px; + overflow: hidden; + border: 1px solid rgba(255, 255, 255, 0.08); + background: #000; + box-shadow: 0 20px 65px rgba(0, 0, 0, 0.45); + display: block; + animation: sshTermIn .18s ease-out; + position: relative; + } + + @keyframes sshTermIn { + from { + opacity: 0; + transform: translateY(12px) scale(0.985); + } + + to { + opacity: 1; + transform: translateY(0) scale(1); + } + } + + .ssh-terminal-close { + position: absolute; + top: 8px; + right: 8px; + z-index: 2; + width: 30px; + height: 30px; + border-radius: 6px; + border: 1px solid rgba(255, 255, 255, 0.14); + background: rgba(0, 0, 0, 0.5); + color: #d1d5db; + cursor: pointer; + } + + .ssh-terminal-close:hover { + background: rgba(255, 255, 255, 0.14); + } + + .ssh-terminal-frame-wrap { + min-height: 0; + height: 100%; + background: #000; + overflow: hidden; + } + + #sshTerminalFrame { + width: 100%; + height: 100%; + border: 0; + display: block; + background: #020817; + } + + .bot-card { + position: relative; + } + + .bot-card__body { + position: relative; + transition: opacity 0.2s ease; + height: 100%; + display: flex; + flex-direction: column; + } + + .bot-card.is-offline .bot-card__body { + filter: none; + opacity: 1; + } + + .bot-card__offline { + display: none; + position: absolute; + top: 50%; + left: 50%; + transform: translate(-50%, -50%); + padding: 8px 12px; + backdrop-filter: blur(10px); + border: none; + border-radius: 999px; + align-items: center; + justify-content: center; + flex-direction: row; + gap: 8px; + z-index: 3; + pointer-events: none; + box-shadow: none; + width: max-content; + } + + .bot-card.is-offline .bot-card__offline { + display: flex; + } + + .bot-card__offline .offline-ring { + width: 20px; + height: 20px; + border-radius: 999px; + border: 3px solid rgba(255, 255, 255, 0.28); + border-top-color: #60a5fa; + animation: dashboard-offline-ring 0.95s linear infinite; + flex-shrink: 0; + } + + .bot-card__offline .offline-text { + color: #fff; + font-weight: 500; + font-size: 14px; + line-height: 1.2; + text-align: center; + } + + @keyframes dashboard-offline-ring { + to { + transform: rotate(360deg); + } + } + + .mysvg { + position: absolute; + width: 0; + height: 0; + pointer-events: none; + } + + .toolbar-actions { + gap: 10px; + display: flex; + align-items: center; + } + + .faplusbutton { + margin-right: 6px; + } + + .footer-inner { + align-items: center; + gap: 16px; + } + + .manageaccount { + font-family: "Segoe UI", "SF Pro Display", system-ui, sans-serif; + font-size: 15px; + line-height: 1.4; + } + + .manageserversv2 { + font-family: "Segoe UI", "SF Pro Display", system-ui, sans-serif; + font-size: 15px; + line-height: 1.4; + } + + .adpanelsite { + font-family: "Segoe UI", "SF Pro Display", system-ui, sans-serif; + font-size: 15px; + line-height: 1.4; + } + + body { + background: var(--ui-bg) center/cover no-repeat fixed !important; + } + + /* Quick Action Custom Scale Animation - Independent Element Scaling */ + .quick-action.qa-anim-scale { + position: relative; + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); + transform-origin: center center; + isolation: isolate; + } + + .quick-action.qa-anim-scale:hover { + transform: scale(var(--hover-scale, 1.05)); + } + + /* Create wrapper for content that doesn't scale */ + .quick-action.qa-anim-scale > i, + .quick-action.qa-anim-scale > p { + display: inline-block; + transform-style: preserve-3d; + transform: translateZ(100px) scale(1); + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); + } + + /* Counter-scale on hover */ + .quick-action.qa-anim-scale:hover > i, + .quick-action.qa-anim-scale:hover > p { + transform: translateZ(100px) scale(calc(1 / var(--hover-scale, 1.05))); + } + + /* Preview Card */ + .quick-action-preview-card.qa-anim-scale { + position: relative; + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); + transform-origin: center center; + isolation: isolate; + } + + .quick-action-preview-card.qa-anim-scale:hover { + transform: scale(var(--hover-scale, 1.05)); + } + + /* Preview card children with 3D transform */ + .quick-action-preview-card.qa-anim-scale > i, + .quick-action-preview-card.qa-anim-scale > p { + display: inline-block; + transform-style: preserve-3d; + transform: translateZ(100px) scale(1); + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); + } + + /* Counter-scale on hover */ + .quick-action-preview-card.qa-anim-scale:hover > i, + .quick-action-preview-card.qa-anim-scale:hover > p { + transform: translateZ(100px) scale(calc(1 / var(--hover-scale, 1.05))); + } + + /* Hide scrollbar for modals */ + .enterprise-modal, + .enterprise-modal-body, + .email-modal, + .email-modal-body, + .recovery-modal, + .recovery-modal-body, + .password-modal, + .password-modal-body, + .twofa-modal, + .twofa-modal-body, + .modal, + .modal-body { + scrollbar-width: none; + /* Firefox */ + -ms-overflow-style: none; + /* IE and Edge */ + } + + .enterprise-modal::-webkit-scrollbar, + .enterprise-modal-body::-webkit-scrollbar, + .email-modal::-webkit-scrollbar, + .email-modal-body::-webkit-scrollbar, + .recovery-modal::-webkit-scrollbar, + .recovery-modal-body::-webkit-scrollbar, + .password-modal::-webkit-scrollbar, + .password-modal-body::-webkit-scrollbar, + .twofa-modal::-webkit-scrollbar, + .twofa-modal-body::-webkit-scrollbar, + .modal::-webkit-scrollbar, + .modal-body::-webkit-scrollbar { + display: none; + } + + /* ===== Navbar + Scroll Animation Override (kept from redesign) ===== */ + :root { + --nav-radius: 24px; + --nav-border: rgba(255, 255, 255, 0.1); + --nav-bg: linear-gradient(145deg, rgba(16, 24, 43, 0.78), rgba(11, 17, 32, 0.76)); + --nav-bg-compact: linear-gradient(145deg, rgba(16, 24, 43, 0.9), rgba(10, 16, 30, 0.9)); + } + + #topbar-spacer { + height: 104px; + } + + .dashboard { + margin-top: 46px; + } + + .top-bar { + position: fixed; + top: clamp(12px, 2vw, 22px); + left: clamp(12px, 4vw, 72px); + right: clamp(12px, 4vw, 72px); + z-index: 120; + border-radius: var(--nav-radius); + border: 1px solid var(--nav-border); + background: var(--nav-bg); + backdrop-filter: blur(20px) saturate(130%); + -webkit-backdrop-filter: blur(20px) saturate(130%); + box-shadow: none; + transition: + padding 0.28s ease, + background 0.28s ease, + transform 0.28s ease, + opacity 0.28s ease, + filter 0.28s ease; + will-change: transform, opacity, filter; + transform: translate3d(0, 0, 0); + -webkit-backface-visibility: hidden; + backface-visibility: hidden; + perspective: 1000px; + } + + .top-bar--compact { + padding-block: 10px; + background: var(--nav-bg-compact); + } + + .top-bar--hidden { + transform: translate3d(0, -8px, 0) scale(0.98); + opacity: 0; + filter: blur(8px); + pointer-events: none; + } + + .top-bar--pinned { + transform: translate3d(0, 0, 0) scale(1); + opacity: 1; + filter: blur(0); + } + + .brand { + gap: 14px; + } + + .brand-logo { + width: 52px; + height: 52px; + border-radius: 14px; + object-fit: contain; + filter: none; + } + + .brand-title { + letter-spacing: -0.012em; + } + + .brand-subtitle { + color: rgba(184, 199, 228, 0.7); + } + + .toolbar-actions { + gap: 10px; + } + + .icon-button, + .icon-butt { + width: 42px; + height: 42px; + border-radius: 50%; + border: 1px solid rgba(174, 196, 237, 0.22); + background: rgba(117, 141, 188, 0.12); + box-shadow: none; + transition: background 0.22s ease, border-color 0.22s ease, color 0.22s ease; + } + + .icon-button:hover:not(:disabled), + .icon-butt:hover:not(:disabled) { + transform: none; + box-shadow: none; + border-color: rgba(204, 218, 245, 0.38); + background: rgba(141, 166, 214, 0.22); + } + + .icon-butt:hover:not(:disabled) { + background: rgba(255, 107, 123, 0.2); + border-color: rgba(255, 170, 182, 0.36); + color: #ffdbe0; + } + + .account-avatar-btn { + padding: 0; + overflow: hidden; + } + + .account-btn-avatar { + width: 100%; + height: 100%; + 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 { + outline: none !important; + box-shadow: none !important; + border: none !important; + } + + .top-bar .btn-primary.create-btn::-moz-focus-inner { + border: 0; + } + + @media (max-width: 860px) { + .top-bar { + left: 14px; + right: 14px; + } + + #topbar-spacer { + height: 136px; + } + + .dashboard { + margin-top: 38px; + } + } + + @media (max-width: 640px) { + .top-bar { + top: 10px; + left: 10px; + right: 10px; + border-radius: 20px; + } + + .brand-logo { + width: 42px; + height: 42px; + } + + .toolbar-actions { + width: 100%; + justify-content: flex-end; + } + + .btn-primary.create-btn span { + display: none; + } + + .btn-primary.create-btn { + width: 42px; + padding: 0; + border-radius: 50%; + } + + #topbar-spacer { + height: 150px; + } + + .dashboard { + margin-top: 34px; + } + } + + .bot-grid>.empty-state { + grid-column: 1 / -1; + text-align: center; + padding: 60px 20px; + border-radius: 24px; + border: 1px dashed rgba(255, 255, 255, 0.14); + background: rgba(6, 10, 20, 0.28) !important; + color: #aab3d5; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05), 0 18px 40px rgba(2, 6, 23, 0.22); + backdrop-filter: blur(24px) saturate(140%); + -webkit-backdrop-filter: blur(24px) saturate(140%); + } + + .bot-grid>.empty-state::before, + .bot-grid>.empty-state::after { + content: none; + } + + .bot-grid>.empty-state>* { + position: static; + z-index: auto; + } + + .bot-grid>.empty-state .empty-state__icon { + display: block; + width: auto; + height: auto; + margin-bottom: 12px; + font-size: 2rem; + color: rgba(124, 92, 255, 0.6); + border: 0; + background: none; + box-shadow: none; + backdrop-filter: none; + -webkit-backdrop-filter: none; + } + + .bot-grid>.empty-state h4 { + color: #edf1ff; + font-size: 1rem; + font-weight: 700; + letter-spacing: normal; + } + + .bot-grid>.empty-state p { + max-width: none; + margin: 8px 0 0; + padding: 0; + border-radius: 0; + color: #aab3d5; + background: none; + border: 0; + backdrop-filter: none; + -webkit-backdrop-filter: none; + } diff --git a/public/css/dock-hider.css b/public/css/dock-hider.css new file mode 100644 index 0000000..bf52598 --- /dev/null +++ b/public/css/dock-hider.css @@ -0,0 +1,10 @@ +.dock-wrap.dock-hidden { + opacity: 0; + pointer-events: none; + transform: translateY(20px); + transition: all 0.3s ease; +} + +.dock-wrap { + transition: all 0.3s ease; +} \ No newline at end of file diff --git a/public/dashboard.css b/public/dashboard.css new file mode 100644 index 0000000..3833fb2 --- /dev/null +++ b/public/dashboard.css @@ -0,0 +1,4208 @@ +:root { + color-scheme: dark light; + font-size: 16px; + --color-bg: #05060c; + --color-surface: rgba(19, 21, 29, 0.72); + --color-surface-solid: #141622; + --color-accent: #7c5cff; + --color-accent-soft: rgba(124, 92, 255, 0.16); + --color-text: #edf1ff; + --color-text-muted: #aab3d5; + --color-border: rgba(255, 255, 255, 0.08); + --shadow-lg: 0 24px 48px rgba(10, 12, 20, 0.38); + --shadow-md: 0 14px 30px rgba(10, 12, 20, 0.28); + --radius-lg: 24px; + --radius-md: 18px; + --radius-sm: 12px; + --transition-base: 180ms ease; + + --panel-bg: #020617; + --panel-bg-soft: #050816; + --panel-bg-soft-alt: #050b1a; + --panel-aqua: #22d3ee; + --panel-blue: #1d4ed8; + --panel-text-soft: #9caad0; + --panel-text-muted: #7e8ba4; +} + +* { + margin: 0; + padding: 0; + box-sizing: border-box; +} + +body { + font-family: 'Manrope', system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; + min-height: 100vh; + color: var(--color-text); + 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; +} + +::-webkit-scrollbar { + display: none; +} + +html { + -ms-overflow-style: none; + scrollbar-width: none; + scroll-behavior: smooth; +} + +#splash-screen { + position: fixed; + inset: 0; + width: 100vw; + height: 100vh; + background: url('/images/hello.webp') center/cover no-repeat, #07080f; + z-index: 9999; + opacity: 1; + transition: opacity 0.6s ease; +} + +html.skip-dashboard-splash #splash-screen { + display: none; +} + +#splash-screen.hidden { + opacity: 0; + pointer-events: none; +} + +.top-bar { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 24px; + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-lg); + padding: 20px clamp(20px, 4vw, 36px); + box-shadow: var(--shadow-md); + backdrop-filter: blur(18px); + transition: transform 0.28s ease, opacity 0.28s ease, filter 0.28s ease, background 0.28s ease, padding 0.28s ease; + will-change: transform, opacity, filter; + transform: translate3d(0, 0, 0); + -webkit-backface-visibility: hidden; + backface-visibility: hidden; + perspective: 1000px; +} + +.brand { + display: flex; + align-items: center; + gap: 16px; +} + +.brand-logo { + width: 58px; + height: 58px; + object-fit: contain; + filter: drop-shadow(0 10px 15px rgba(0, 0, 0, 0.4)); +} + +.brand-title { + font-size: clamp(1.5rem, 2vw, 1.8rem); + font-weight: 800; + letter-spacing: 0.02em; +} + +.brand-subtitle { + font-size: 0.95rem; + color: var(--color-text-muted); +} + +.toolbar { + display: flex; + align-items: center; + gap: clamp(16px, 3vw, 32px); +} + +.upload-form { + display: flex; +} + +.upload-form__form, +.footer-upload { + display: flex; + align-items: center; + gap: 12px; + background: rgba(10, 12, 20, 0.45); + border: 1px solid var(--color-border); + border-radius: var(--radius-md); + padding: 8px 14px; + position: relative; + box-shadow: inset 0 0 0 1px rgba(140, 114, 242, 0.038); +} + +.upload-form__label, +.footer-upload__label { + display: flex; + align-items: center; + gap: 8px; + font-weight: 600; + font-size: 0.9rem; + background: var(--color-accent-soft); + color: var(--color-accent); + padding: 10px 14px; + border-radius: var(--radius-sm); + cursor: pointer; + transition: transform var(--transition-base), box-shadow var(--transition-base); +} + +.upload-form__label:hover, +.footer-upload__label:hover { + transform: translateY(-1px); + box-shadow: rgba(140, 114, 242, 0.115); +} + +.upload-form__form input[type="file"], +.footer-upload input[type="file"] { + display: none; +} + +.upload-form__submit, +.footer-upload__submit { + border: none; + border-radius: var(--radius-sm); + background: linear-gradient(135deg, #7c5cff, #4f46e5); + color: white; + padding: 10px 18px; + font-weight: 600; + cursor: pointer; + transition: transform var(--transition-base), box-shadow var(--transition-base); +} + +.upload-form__submit:hover, +.footer-upload__submit:hover { + transform: translateY(-1px); + box-shadow: rgba(140, 114, 242, 0.115); +} + +.toolbar-actions { + display: flex; + align-items: center; + gap: 12px; +} + +.icon-button { + width: 44px; + height: 44px; + border-radius: 50%; + border: none; + outline: none; + 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); +} + +.icon-button:hover { + border: none !important; + outline: none !important; +} + +.icon-button i { + font-size: 1rem; +} + +.icon-button:hover:not(:disabled) { + transform: none; + background: rgb(0, 140, 254); +} + +.icon-button:disabled { + cursor: not-allowed; + opacity: 0.6; +} + +.dynamic-quick-actions { + display: flex; + align-items: center; + gap: 8px; +} + +.quick-action-btn { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 16px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.9); + text-decoration: none; + font-size: 14px; + font-weight: 600; + transition: all 0.25s ease; + border: 1px solid rgba(255, 255, 255, 0.08); +} + +.quick-action-btn:hover { + background: rgba(99, 102, 241, 0.2); + border-color: rgba(99, 102, 241, 0.3); + transform: translateY(-2px); +} + +.quick-action-btn i { + font-size: 14px; +} + +.account-avatar-btn { + padding: 0; + overflow: hidden; +} + +.account-btn-avatar { + width: 100%; + height: 100%; + object-fit: cover; + border-radius: 50%; +} + +.account-avatar-btn:hover { + transform: none; + background: transparent; + border: none; +} + +.icon-butt { + width: 44px; + height: 44px; + border-radius: 50%; + 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); +} + +.icon-butt { + border: none; + outline: none; +} + +.icon-butt i { + font-size: 1rem; +} + +.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); +} + +.icon-butt:disabled { + cursor: not-allowed; + opacity: 0.6; +} + +.dashboard { + margin-top: 32px; + display: grid; + gap: clamp(28px, 4vw, 48px); +} + +.hero { + display: grid; + 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); + border-radius: var(--radius-lg); + padding: clamp(28px, 4vw, 40px); + box-shadow: var(--shadow-lg); + backdrop-filter: blur(18px); +} + +.hero-copy h2 { + font-size: clamp(1.8rem, 3vw, 2.3rem); + margin-bottom: 12px; +} + +.hero-copy p { + color: var(--color-text-muted); + line-height: 1.65; + margin-bottom: 24px; + max-width: 560px; +} + +.hero-actions { + display: flex; + flex-wrap: wrap; + gap: 12px; +} + +.pill { + border-top: 20px solid black; + border-right: 5px solid black; + border-bottom: 20px solid black; + border-left: 5px solid black; + border-radius: 5px; + padding: 10px 22px; + font-weight: 600; + cursor: pointer; + background: linear-gradient(135deg, #7c5cff, #4f46e5); + color: white; + transition: transform var(--transition-base), box-shadow var(--transition-base); +} + +.pill--outline { + background: transparent; + color: var(--color-text); + border: 2px solid rgba(255, 255, 255, 0.088); +} + +.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); +} + +.pills { + border: none; + border-radius: 999px; + padding: 10px 22px; + font-weight: 600; + cursor: pointer; + background: linear-gradient(135deg, #7c5cff, #4f46e5); + color: white; + transition: transform var(--transition-base), box-shadow var(--transition-base); +} + +.pills--outline { + background: transparent; + color: var(--color-text); + border: 1px solid rgba(255, 255, 255, 0.2); +} + +.pills:hover { + transform: translateY(-1px); + box-shadow: 0 12px 24px rgba(79, 70, 229, 0.28); +} + +.hero-stats { + display: grid; + gap: 18px; +} + +.stat-card { + display: flex; + align-items: center; + gap: 18px; + background: var(--color-surface); + border-radius: var(--radius-lg); + padding: 20px; + box-shadow: var(--shadow-md); + backdrop-filter: blur(20px); +} + +.stat-card__icon { + width: 56px; + height: 56px; + border-radius: 18px; + display: grid; + place-items: center; + font-size: 1.3rem; + color: white; +} + +.stat-card__icon--active { + background: linear-gradient(135deg, #34d399, #059669); +} + +.stat-card__icon--uptime { + background: linear-gradient(135deg, #38bdf8, #1d4ed8); +} + +.stat-card__icon--deploy { + background: linear-gradient(135deg, #ffa600, #da4500); +} + +.stat-card__label { + font-size: 0.9rem; + color: var(--color-text-muted); +} + +.stat-card__value { + font-size: 1.7rem; + font-weight: 700; +} + +.quick-actions { + background: var(--color-surface); + border-radius: var(--radius-lg); + border: 1px solid var(--color-border); + box-shadow: var(--shadow-md); + padding: clamp(24px, 4vw, 36px); + backdrop-filter: blur(14px); +} + +.quick-actions h3 { + font-size: 1.2rem; + margin-bottom: 18px; +} + +.quick-actions__grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 16px; +} + +.quick-action { + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: var(--radius-md); + background: rgba(255, 255, 255, 0.04); + color: inherit; + padding: 18px 16px; + display: grid; + justify-items: center; + gap: 10px; + font-weight: 600; + cursor: pointer; + transition: transform var(--transition-base), border var(--transition-base), background var(--transition-base); +} + +.quick-action i { + font-size: 1.3rem; +} + +.quick-action:hover { + transform: translateY(-4px); + background: rgba(124, 92, 255, 0.16); +} + +.quick-action.qa-anim-pulse:hover { + transform: none; + animation: qaAnimPulse 0.6s ease-in-out; +} + +.quick-action.qa-anim-shake:hover { + transform: none; + animation: qaAnimShake 0.5s ease-in-out; +} + +.quick-action.qa-anim-bounce:hover { + transform: none; + animation: qaAnimBounce 0.5s ease; +} + +.quick-action.qa-anim-glow:hover { + transform: translateY(-4px); + box-shadow: 0 0 25px rgba(124, 92, 255, 0.5); +} + +.quick-action.qa-anim-scale:hover { + transform: scale(1.08); +} + +.quick-action.qa-anim-rotate:hover i { + animation: qaAnimRotate 0.5s ease; +} + +@keyframes qaAnimPulse { + + 0%, + 100% { + transform: scale(1); + } + + 50% { + transform: scale(1.06); + } +} + +@keyframes qaAnimShake { + + 0%, + 100% { + transform: translateX(0); + } + + 20% { + transform: translateX(-5px); + } + + 40% { + transform: translateX(5px); + } + + 60% { + transform: translateX(-5px); + } + + 80% { + transform: translateX(5px); + } +} + +@keyframes qaAnimBounce { + + 0%, + 100% { + transform: translateY(0); + } + + 40% { + transform: translateY(-10px); + } + + 60% { + transform: translateY(-5px); + } +} + +@keyframes qaAnimRotate { + from { + transform: rotate(0deg); + } + + to { + transform: rotate(360deg); + } +} + +.section-heading { + display: flex; + flex-wrap: wrap; + align-items: flex-end; + justify-content: space-between; + gap: 16px; + margin-bottom: 20px; +} + +.section-heading h3 { + font-size: 1.2rem; + margin-bottom: 6px; +} + +.section-heading p { + color: var(--color-text-muted); + font-size: 0.95rem; +} + +.section-actions { + display: flex; + align-items: center; +} + +.search-field { + display: flex; + align-items: center; + gap: 10px; + padding: 10px 16px; + backdrop-filter: blur(8px); + border-radius: var(--radius-md); + border: 1px solid rgba(255, 255, 255, 0.12); + background: rgba(255, 255, 255, 0.085); + color: var(--color-text-muted); +} + +.search-field:hover { + border-color: rgba(255, 255, 255, 0.199); +} + +.search-servers::placeholder { + color: rgba(255, 255, 255, 0.636); +} + +.search-field input { + background: transparent; + border: none; + color: inherit; + font-size: 0.95rem; + outline: none; +} + +.bot-grid { + display: grid; + gap: 18px; + grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); +} + +.bots .bot-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); + gap: 16px; + + justify-items: center; +} + +.bots, +.quick-actions { + scroll-snap-align: start; + scroll-margin-top: 20px; +} + +.bot-card { + position: relative; + display: flex; + 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)); + 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; +} + +.bot-card:hover { + transform: translateY(-1px) scale(1.005); + 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; + padding: 22px 20px 18px; +} + +.bot-card__hero-bg { + position: absolute; + inset: 0; + background: var(--bot-cover); + background-size: cover; + background-position: center; + filter: saturate(1.5) brightness(1); + -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%); +} + +.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; +} + +.bot-card__hero-content { + position: relative; + display: flex; + flex-direction: column; + gap: 14px; + color: #ecf3ff; + z-index: 1; +} + +.bot-card__eyebrow { + text-transform: uppercase; + letter-spacing: 0.14em; + font-size: 12px; + color: rgba(255, 255, 255, 0.75); +} + +.bot-card__title-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; +} + +.bot-card__title-row h4 { + margin: 0; + font-size: 1.32rem; + letter-spacing: -0.01em; + text-shadow: 0 6px 18px rgba(0, 0, 0, 0.4); +} + +.bot-card__title-row p { + margin: 4px 0 0; + color: rgba(255, 255, 255, 0.85); + font-weight: 600; +} + +.bot-card__status { + display: inline-flex; + align-items: center; + justify-content: center; + width: 42px; + height: 42px; + border-radius: 14px; + background: radial-gradient(circle at 40% 30%, rgba(255, 255, 255, 0.12), transparent 50%), rgba(0, 0, 0, 0.55); + border: 1px solid rgba(255, 255, 255, 0.2); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.06), 0 16px 28px rgba(0, 0, 0, 0.35); + backdrop-filter: blur(8px); +} + +.bot-card__status-dot { + position: relative; + width: 14px; + height: 14px; + border-radius: 50%; + background: #34d399; +} + +.bot-card__status-dot::before, +.bot-card__status-dot::after { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + background: #34d399; + opacity: 0.18; + transform: scale(1); + animation: softRing 2.4s ease-out infinite; +} + +.bot-card__status-dot::after { + animation-delay: 1.2s; +} + +@keyframes softRing { + 0% { + transform: scale(1); + opacity: 0.18; + } + + 70% { + transform: scale(2.2); + opacity: 0; + } + + 100% { + transform: scale(2.2); + opacity: 0; + } +} + +.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); +} + +.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); +} + +.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); +} + +.bot-card.status-unknown .bot-card__status-dot::before, +.bot-card.status-unknown .bot-card__status-dot::after { + background: #f59e0b; +} + +.bot-card__meta-row { + display: flex; + flex-wrap: wrap; + gap: 10px; + padding: 10px 12px; + color: #d3def3; + font-size: 0.95rem; + 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 { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 8px 11px; + background: rgba(0, 0, 0, 0.35); + border-radius: 11px; + border: 1px solid rgba(255, 255, 255, 0.12); + box-shadow: 0 10px 16px rgba(0, 0, 0, 0.26); +} + +.bot-card__stats { + display: grid; + gap: 14px; + padding: 18px 18px 20px; + 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 { + position: relative; + display: grid; + gap: 10px; + padding: 12px 14px; + border-radius: 14px; + background: linear-gradient(120deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.01)); + border: 1px solid rgba(255, 255, 255, 0.06); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.06), 0 14px 30px rgba(0, 0, 0, 0.35); +} + +.bot-card__stat::before { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + background: radial-gradient(circle at 20% 20%, rgba(34, 211, 238, 0.08), transparent 45%); + pointer-events: none; +} + +.bot-card__stat-label { + display: grid; + grid-template-columns: auto 1fr auto; + align-items: center; + gap: 10px; + color: #e5edfb; + font-size: 0.98rem; + letter-spacing: -0.01em; +} + +.bot-card__stat-icon { + display: inline-flex; + align-items: center; + justify-content: center; + width: 32px; + height: 32px; + border-radius: 12px; + background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.02)); + box-shadow: inset 0 0 0 1px rgba(255, 255, 255, 0.08), 0 12px 22px rgba(0, 0, 0, 0.26); + color: #cde0ff; + font-size: 14px; +} + +.bot-card__stat-icon--memory { + color: #22d3ee; +} + +.bot-card__stat-icon--disk { + color: #60a5fa; +} + +.bot-card__stat-icon--cpu { + color: #a855f7; +} + +.bot-card__stat-title { + font-weight: 800; + text-transform: uppercase; + letter-spacing: 0.08em; + color: #dfe9ff; + opacity: 0.9; +} + +.bot-card__stat-chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 7px 10px; + border-radius: 999px; + background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.04)); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.12), 0 10px 20px rgba(0, 0, 0, 0.25); + color: #c6d6f7; + font-weight: 700; + font-size: 0.9rem; + letter-spacing: 0.01em; +} + +.bot-card__stat-chip i { + color: inherit; + opacity: 0.9; +} + +.bot-card__progress { + position: relative; + width: 100%; + height: 12px; + border-radius: 999px; + background: linear-gradient(90deg, rgba(255, 255, 255, 0.08), rgba(255, 255, 255, 0.02)); + overflow: hidden; + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.12); +} + +.bot-card__progress span { + position: absolute; + inset: 0; + width: 0; + background: linear-gradient(90deg, #22d3ee 0%, #60a5fa 35%, #7c5cff 70%, #22d3ee 100%); + border-radius: 999px; + box-shadow: 0 10px 18px rgba(34, 211, 238, 0.32); + transition: width 0.28s ease, filter 0.28s ease; + background-size: 200% 100%; + animation: progressSheen 2.4s linear infinite; +} + +.bot-card__footer { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 16px 14px; + color: #c1cce3; + background: rgba(0, 0, 0, 0.841); + border-top: 1px solid rgba(255, 255, 255, 0.06); + backdrop-filter: blur(15px); +} + +.bot-card__footer-text { + font-size: 0.95rem; +} + +.bot-card__chevron { + color: rgba(255, 255, 255, 0.6); + transition: transform 0.25s ease, color 0.25s ease; +} + +.bot-card:hover .bot-card__chevron { + transform: translateX(4px); + color: #22d3ee; +} + +.bot-card.is-hidden { + display: none; +} + +.empty-state { + grid-column: 1 / -1; + text-align: center; + padding: 60px 20px; + border-radius: var(--radius-lg); + border: 1px dashed rgba(255, 255, 255, 0.14); + background: rgba(6, 10, 20, 0.28); + color: var(--color-text-muted); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05), 0 18px 40px rgba(2, 6, 23, 0.22); + backdrop-filter: blur(24px) saturate(140%); + -webkit-backdrop-filter: blur(24px) saturate(140%); +} + +.empty-state::before, +.empty-state::after { + content: none; +} + +.empty-state>* { + position: static; + z-index: auto; +} + +.empty-state__icon { + display: block; + width: auto; + height: auto; + font-size: 2rem; + margin-bottom: 12px; + color: rgba(124, 92, 255, 0.6); + border-radius: 0; + border: 0; + background: none; + box-shadow: none; + backdrop-filter: none; + -webkit-backdrop-filter: none; +} + +.empty-state h4 { + font-size: 1rem; + font-weight: 700; + color: var(--color-text); + letter-spacing: normal; + text-shadow: none; +} + +.empty-state p { + max-width: none; + margin: 8px 0 0; + padding: 0; + border-radius: 0; + border: 0; + background: none; + color: var(--color-text-muted); + line-height: 1.6; + box-shadow: none; + backdrop-filter: none; + -webkit-backdrop-filter: none; +} + +.footer { + margin-top: 40px; + background: var(--color-surface); + border: 1px solid var(--color-border); + border-radius: var(--radius-lg); + box-shadow: var(--shadow-md); + backdrop-filter: blur(14px); +} + +.footer-inner { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 24px; + padding: clamp(24px, 5vw, 40px); +} + +.footer-copy h3 { + font-size: 1.3rem; + margin-bottom: 8px; +} + +.footer-copy p { + color: var(--color-text-muted); + max-width: 420px; + line-height: 1.6; +} + +@keyframes statusPulse { + 0% { + transform: scale(0.96); + filter: drop-shadow(0 0 0 rgba(255, 255, 255, 0)); + } + + 50% { + transform: scale(1.06); + filter: drop-shadow(0 0 12px rgba(255, 255, 255, 0.26)); + } + + 100% { + transform: scale(0.96); + filter: drop-shadow(0 0 0 rgba(255, 255, 255, 0)); + } +} + +@keyframes statusWaveRing { + 0% { + transform: scale(0.9); + opacity: 0.36; + } + + 70% { + transform: scale(1.9); + opacity: 0; + } + + 100% { + transform: scale(1.9); + opacity: 0; + } +} + +@keyframes statusOrbit { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } +} + +@keyframes progressSheen { + 0% { + background-position: 0% 50%; + } + + 100% { + background-position: -200% 50%; + } +} + +@media (max-width: 960px) { + body { + padding: 24px; + } + + .hero { + grid-template-columns: 1fr; + } + + .hero-stats { + grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); + } +} + +@media (max-width: 640px) { + .top-bar { + flex-direction: column; + align-items: stretch; + } + + .toolbar { + width: 100%; + flex-direction: column; + align-items: stretch; + } + + .toolbar-actions { + justify-content: flex-start; + } + + .upload-form__form, + .footer-upload { + width: 100%; + justify-content: space-between; + } + + .bot-grid { + grid-template-columns: 1fr; + } +} + +::-webkit-scrollbar { + width: 6px; + height: 6px; +} + +::-webkit-scrollbar-track { + background: rgba(255, 255, 255, 0.04); + border-radius: 10px; +} + +::-webkit-scrollbar-thumb { + background: rgba(124, 92, 255, 0.5); + border-radius: 10px; + transition: background 0.2s ease; +} + +::-webkit-scrollbar-thumb:hover { + background: rgba(124, 92, 255, 0.8); +} + +* { + scrollbar-width: thin; + scrollbar-color: rgba(124, 92, 255, 0.5) rgba(255, 255, 255, 0.04); +} + +.btn-primary { + display: inline-flex; + gap: 8px; + align-items: center; + background: linear-gradient(135deg, #0ea5e9, #1d4ed8); + color: #e5f4ff; + border: none; + border-radius: 10px; + padding: 10px 14px; + font-weight: 700; + cursor: pointer; + box-shadow: none; + transition: + transform 0.22s cubic-bezier(0.22, 0.61, 0.36, 1), + filter 0.18s ease-out, + background 0.28s ease-out; +} + +.btn-primary:hover { + filter: brightness(1.06); + transform: none; +} + +.btn-primary.create-btn:hover { + transform: none; +} + +.btn-primary:active { + transform: translateY(0); + filter: brightness(0.96); +} + +.btn-ghost { + background: rgba(15, 23, 42, 0.85); + border: none; + color: #c8d3df; + padding: 9px 13px; + border-radius: 10px; + cursor: pointer; + box-shadow: none; + font-size: 13px; + display: inline-flex; + align-items: center; + gap: 6px; + transition: + background 0.2s ease-out, + transform 0.2s ease-out, + opacity 0.18s ease-out; +} + +.btn-ghost:hover { + background: rgba(15, 23, 42, 1); + transform: translateY(-1px); +} + +.btn-ghost:active { + transform: translateY(0); + opacity: .9; +} + +.modal-overlay { + position: fixed; + inset: 0; + background: radial-gradient(circle at top, rgba(15, 23, 42, .9), rgba(2, 6, 23, .96)); + display: none; + align-items: center; + justify-content: center; + z-index: 9999; + backdrop-filter: blur(10px); + padding: 12px; +} + +.modal-overlay.show { + display: flex; +} + +@keyframes modalEnter { + from { + opacity: 0; + transform: translateY(16px) scale(.97); + } + + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +.modal-card { + width: min(780px, 96vw); + max-height: 92vh; + background: linear-gradient(145deg, var(--panel-bg), #02091a); + border-radius: 18px; + color: #e7eef7; + display: flex; + flex-direction: column; + box-shadow: none; + animation: modalEnter .22s ease-out; + overflow: hidden; +} + +.modal-head { + display: flex; + align-items: flex-start; + justify-content: space-between; + padding: 14px 18px 10px; + flex-shrink: 0; +} + +.modal-title-group { + display: flex; + gap: 12px; + align-items: flex-start; +} + +.modal-avatar { + width: 40px; + height: 40px; + border-radius: 999px; + background: radial-gradient(circle at 25% 0, #38bdf8, #1e40af 45%, #020617 100%); + display: flex; + align-items: center; + justify-content: center; + color: #e5f4ff; + flex-shrink: 0; +} + +.modal-eyebrow { + font-size: 11px; + letter-spacing: 0.14em; + text-transform: uppercase; + color: var(--panel-text-soft); + margin-bottom: 2px; +} + +.modal-title { + font-size: 18px; + font-weight: 800; +} + +.modal-subtitle { + font-size: 13px; + color: var(--panel-text-soft); + margin-top: 4px; +} + +.modal-body { + padding: 12px 18px 14px; + display: flex; + flex-direction: column; + gap: 14px; + flex: 1 1 auto; + overflow: auto; +} + +.modal-body--split { + display: grid; + grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); + gap: 16px; + align-items: flex-start; +} + +.modal-main { + display: grid; + gap: 12px; +} + +.modal-aside { + display: flex; + flex-direction: column; + gap: 10px; +} + +@media (max-width: 720px) { + .modal-card { + width: 100%; + max-height: 96vh; + } + + .modal-head { + padding: 12px 14px 6px; + } + + .modal-body { + padding: 10px 12px 12px; + } + + .modal-body--split { + grid-template-columns: minmax(0, 1fr); + } +} + +.modal-foot { + display: flex; + justify-content: flex-end; + gap: 10px; + padding: 10px 18px 12px; + background: #020617; + flex-shrink: 0; +} + +.field { + display: grid; + gap: 6px; +} + +.field label { + font-size: 13px; + color: #a9b4c2; +} + +.field input, +.field select, +.field textarea { + background: #020617; + border: none; + border-radius: 10px; + color: #eaf1fb; + padding: 9px 11px; + outline: none; + font-family: inherit; + font-size: 14px; + transition: + background 0.18s ease-out, + transform 0.14s ease-out; +} + +.field input:focus, +.field select:focus, +.field textarea:focus { + background: #020b1f; + transform: translateY(-1px); +} + +.inline-hint { + font-size: 12px; + color: #9eb0c5; +} + +.summary-card { + border-radius: 12px; + background: var(--panel-bg-soft); + font-size: 13px; + padding: 9px 10px 8px; + position: relative; + overflow: hidden; +} + +.summary-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 4px; +} + +.summary-title { + font-size: 11px; + letter-spacing: 0.16em; + text-transform: uppercase; + color: var(--panel-text-soft); +} + +.summary-badge { + font-size: 11px; + padding: 2px 8px; + border-radius: 999px; + background: rgba(15, 23, 42, .95); + color: #cbd5f5; +} + +.summary-row { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 2px; +} + +.summary-label { + color: var(--panel-text-soft); + font-size: 12px; +} + +.summary-value { + color: #e5edf9; + font-weight: 600; + font-size: 13px; + margin-left: 8px; +} + +.summary-footer { + font-size: 11px; + color: var(--panel-text-muted); + margin-top: 5px; +} + +.template-grid, +.node-grid { + display: grid; + gap: 10px; + grid-template-columns: repeat(auto-fill, minmax(190px, 1fr)); +} + +.template-card, +.node-card, +.fork-card { + border: none; + border-radius: 12px; + padding: 9px 9px 8px; + cursor: pointer; + background: var(--panel-bg-soft); + text-align: left; + display: flex; + flex-direction: column; + gap: 6px; + box-shadow: none; + position: relative; + overflow: hidden; + transform: translateY(0) scale(1); + transition: + transform .26s cubic-bezier(0.22, 0.61, 0.36, 1), + background .26s ease-out; + --mouse-x: 50%; + --mouse-y: 50%; +} + +.template-card::before, +.node-card::before, +.fork-card::before { + content: ""; + position: absolute; + top: var(--mouse-y); + left: var(--mouse-x); + transform: translate(-50%, -50%); + width: 220%; + height: 220%; + background: + radial-gradient(circle at center, + rgba(34, 211, 238, 0.25) 0%, + rgba(37, 99, 235, 0.18) 35%, + transparent 60%); + opacity: 0; + pointer-events: none; + transition: + opacity .35s ease-out, + transform .35s ease-out; +} + +.template-card:hover, +.node-card:hover, +.fork-card:hover { + transform: translateY(-2px) scale(1.01); + background: var(--panel-bg-soft-alt); +} + +.template-card:hover::before, +.node-card:hover::before, +.fork-card:hover::before { + opacity: 1; + transform: translate(-50%, -50%) scale(1.03); +} + +.template-card[aria-selected="true"], +.node-card[aria-selected="true"], +.fork-card[aria-selected="true"] { + background: var(--panel-bg-soft-alt); +} + +.template-card__header, +.node-card__header { + display: flex; + gap: 10px; + align-items: center; +} + +.template-card__icon, +.node-card__icon, +.fork-card__icon { + width: 30px; + height: 30px; + border-radius: 999px; + display: flex; + align-items: center; + justify-content: center; + background: #020617; + flex-shrink: 0; + font-size: 14px; +} + +.template-card__title-group h4, +.node-card__title-group h4 { + margin: 0; + font-size: 14px; +} + +.template-card__badge { + display: inline-flex; + align-items: center; + margin-top: 2px; + padding: 2px 8px; + border-radius: 999px; + font-size: 11px; + text-transform: uppercase; + letter-spacing: .12em; + color: #cbd5f5; + background: rgba(15, 23, 42, .95); +} + +.template-card__description, +.node-card__description { + margin: 2px 0 0 0; + font-size: 12px; + color: #a9b4c2; + min-height: 32px; +} + +.template-card__meta { + display: flex; + justify-content: space-between; + align-items: center; + font-size: 11px; + color: var(--panel-text-soft); +} + +.node-status { + display: inline-flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: #9eb0c5; +} + +.dot { + width: 8px; + height: 8px; + border-radius: 999px; + background: #64748b; + display: inline-block; +} + +.dot.ok { + background: var(--panel-aqua); +} + +.dot.down { + background: #ef4444; +} + +.spinner { + width: 16px; + height: 16px; + border-radius: 999px; + border: 2px solid rgba(255, 255, 255, .28); + border-top-color: #e5f4ff; + animation: spin .9s linear infinite; + display: none; +} + +.spinner.show { + display: inline-block; +} + +@keyframes spin { + to { + transform: rotate(360deg); + } +} + +.fork-grid { + display: grid; + gap: 10px; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); +} + +.fork-title { + font-weight: 700; + font-size: 14px; +} + +.muted { + color: #a9b4c2; + font-size: 12px; +} + +.port-layout { + display: grid; + grid-template-columns: minmax(0, 1.4fr) minmax(0, 1fr); + gap: 16px; + align-items: flex-start; +} + +@media (max-width: 640px) { + .port-layout { + grid-template-columns: minmax(0, 1fr); + } +} + +.connection-chip { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 7px 9px; + border-radius: 999px; + background: #020617; + font-size: 12px; + color: #e5edf9; + box-shadow: none; + position: relative; + overflow: hidden; +} + +.connection-chip i { + font-size: 13px; +} + +.connection-chip__divider { + margin: 0 2px; + opacity: .6; +} + +.connection-chip code { + background: none; + padding: 0; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + font-size: 12px; + color: #e5edf9; +} + +.resources-layout { + display: flex; + flex-direction: column; + gap: 24px; +} + +.resources-info { + background: rgba(124, 92, 255, 0.06); + border: 1px solid rgba(124, 92, 255, 0.15); + border-radius: 16px; + padding: 16px 20px; +} + +.resources-info__header { + display: flex; + align-items: center; + gap: 10px; + font-size: 13px; + font-weight: 600; + color: var(--color-accent); + margin-bottom: 12px; +} + +.resources-info__header i { + font-size: 14px; +} + +.resources-info__grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 16px; +} + +@media (max-width: 640px) { + .resources-info__grid { + grid-template-columns: 1fr; + gap: 12px; + } +} + +.resources-info__item { + display: flex; + flex-direction: column; + gap: 4px; +} + +.resources-info__label { + font-size: 11px; + color: var(--color-text-muted); + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.resources-info__value { + font-size: 15px; + font-weight: 600; + color: var(--color-text); + font-variant-numeric: tabular-nums; +} + +.resources-fields { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 16px; +} + +@media (max-width: 640px) { + .resources-fields { + grid-template-columns: 1fr; + } +} + +.resources-fields .field { + display: flex; + flex-direction: column; + gap: 6px; +} + +.resources-fields input::-webkit-outer-spin-button, +.resources-fields input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; +} + +.resources-fields input[type=number] { + -moz-appearance: textfield; +} + +.enterprise-modal-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.65); + backdrop-filter: blur(24px) saturate(180%); + -webkit-backdrop-filter: blur(24px) saturate(180%); + display: none; + align-items: center; + justify-content: center; + z-index: 10000; + padding: 16px; +} + +.enterprise-modal-overlay.show { + display: flex; + animation: enterpriseOverlayReveal 0.35s cubic-bezier(0.32, 0.72, 0, 1) forwards; +} + +@keyframes enterpriseOverlayReveal { + 0% { + opacity: 0; + backdrop-filter: blur(0) saturate(100%); + } + + 100% { + opacity: 1; + backdrop-filter: blur(24px) saturate(180%); + } +} + +.enterprise-modal { + position: relative; + width: min(680px, 96vw); + max-height: 90vh; + display: flex; + flex-direction: column; + background: linear-gradient(165deg, rgba(30, 32, 38, 0.95) 0%, rgba(22, 24, 28, 0.98) 100%); + backdrop-filter: blur(40px) saturate(180%); + -webkit-backdrop-filter: blur(40px) saturate(180%); + border-radius: 24px; + overflow: hidden; + animation: enterpriseModalReveal 0.5s cubic-bezier(0.32, 0.72, 0, 1) forwards; + box-shadow: + 0 0 0 1px rgba(255, 255, 255, 0.06), + 0 25px 80px -12px rgba(0, 0, 0, 0.5), + 0 0 100px rgba(0, 0, 0, 0.3); +} + +@keyframes enterpriseModalReveal { + 0% { + opacity: 0; + transform: scale(0.96); + filter: blur(8px); + } + + 100% { + opacity: 1; + transform: scale(1); + filter: blur(0); + } +} + +.enterprise-modal-header { + display: flex; + align-items: center; + gap: 16px; + padding: 24px 28px 20px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.03), transparent); + flex-shrink: 0; +} + +.enterprise-modal-icon { + width: 56px; + height: 56px; + border-radius: 16px; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + font-size: 22px; + color: #fff; +} + +.enterprise-modal-icon.icon-rocket { + background: linear-gradient(135deg, rgba(56, 189, 248, 0.25), rgba(30, 64, 175, 0.35)); +} + +.enterprise-modal-icon.icon-cube { + background: linear-gradient(135deg, rgba(65, 65, 65, 0.25), rgba(63, 63, 63, 0.35)); +} + +.enterprise-modal-icon.icon-ethernet { + background: linear-gradient(135deg, rgba(32, 32, 32, 0.25), rgba(36, 36, 36, 0.35)); +} + +.enterprise-modal-icon.icon-chip { + background: linear-gradient(135deg, rgba(32, 32, 32, 0.25), rgba(36, 36, 36, 0.35)); +} + +.enterprise-modal-icon.icon-terminal { + background: linear-gradient(135deg, rgba(99, 102, 241, 0.25), rgba(67, 56, 202, 0.35)); +} + +.enterprise-modal-titles { + flex: 1; + min-width: 0; +} + +.enterprise-modal-eyebrow { + font-size: 11px; + letter-spacing: 0.12em; + text-transform: uppercase; + color: rgba(255, 255, 255, 0.4); + margin-bottom: 4px; +} + +.enterprise-modal-title { + margin: 0; + font-size: 20px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.02em; +} + +.enterprise-modal-subtitle { + margin: 6px 0 0; + font-size: 14px; + color: rgba(255, 255, 255, 0.5); +} + +.enterprise-modal-close { + width: 36px; + height: 36px; + border-radius: 10px; + border: none; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + flex-shrink: 0; +} + +.enterprise-modal-close:hover { + background: rgba(239, 68, 68, 0.2); + color: rgba(255, 255, 255, 0.9); +} + +.enterprise-modal-body { + flex: 1; + padding: 4px 28px 20px; + overflow-y: auto; + min-height: 0; +} + +.enterprise-modal-body::-webkit-scrollbar { + width: 6px; +} + +.enterprise-modal-body::-webkit-scrollbar-track { + background: transparent; +} + +.enterprise-modal-body::-webkit-scrollbar-thumb { + background: rgba(255, 255, 255, 0.1); + border-radius: 3px; +} + +.enterprise-modal-body--split { + display: grid; + grid-template-columns: minmax(0, 1.6fr) minmax(0, 1fr); + gap: 20px; + align-items: flex-start; +} + +@media (max-width: 720px) { + .enterprise-modal-body--split { + grid-template-columns: 1fr; + } +} + +.enterprise-modal-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + padding: 16px 28px 24px; + background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.15)); + flex-shrink: 0; +} + +.enterprise-btn-primary { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + border-radius: 12px; + border: none; + background: linear-gradient(135deg, rgba(7, 48, 230, 0.9), rgba(8, 93, 230, 0.85)); + color: #fff; + font-weight: 600; + font-size: 14px; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); +} + +.enterprise-btn-primary:hover { + background: linear-gradient(135deg, rgb(24, 88, 206), rgba(11, 76, 218, 0.95)); + filter: brightness(1.1); + transform: none; +} + +.enterprise-btn-secondary { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.7); + font-weight: 600; + font-size: 14px; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); +} + +.enterprise-btn-secondary:hover { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.15); + color: rgba(255, 255, 255, 0.9); +} + +.enterprise-modal-icon.icon-download { + background: linear-gradient(135deg, rgba(16, 185, 129, 0.25), rgba(5, 150, 105, 0.35)); +} + +.enterprise-import-progress { + background: rgba(255, 255, 255, 0.03); + border-radius: 14px; + padding: 16px; + margin-top: 16px; + border: 1px solid rgba(255, 255, 255, 0.06); +} + +.enterprise-import-progress-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 10px; +} + +.enterprise-import-progress-label { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.8); +} + +.enterprise-import-progress-percent { + font-size: 13px; + font-weight: 700; + color: #10b981; +} + +.enterprise-import-progress-bar { + width: 100%; + height: 8px; + background: rgba(255, 255, 255, 0.1); + border-radius: 4px; + overflow: hidden; +} + +.enterprise-import-progress-fill { + height: 100%; + background: linear-gradient(90deg, #10b981, #34d399); + border-radius: 4px; + transition: width 0.3s ease; +} + +.enterprise-import-progress-info { + margin-top: 8px; + font-size: 12px; + color: rgba(255, 255, 255, 0.5); + text-align: center; +} + +.enterprise-btn-primary:disabled, +.enterprise-btn-secondary:disabled { + opacity: 0.5; + cursor: not-allowed; + pointer-events: none; +} + +.enterprise-field { + display: flex; + flex-direction: column; + gap: 8px; + margin-bottom: 16px; +} + +.enterprise-field label { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.8); +} + +.enterprise-field label .hint { + font-weight: 400; + color: rgba(255, 255, 255, 0.4); + font-size: 12px; +} + +.enterprise-field input, +.enterprise-field select, +.enterprise-field textarea { + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 12px; + color: rgba(255, 255, 255, 0.9); + padding: 12px 14px; + outline: none; + font-family: inherit; + font-size: 14px; + transition: all 0.2s ease; +} + +.enterprise-field input:focus, +.enterprise-field select:focus, +.enterprise-field textarea:focus { + background: rgba(255, 255, 255, 0.06); + box-shadow: 0 0 0 3px rgba(0, 0, 0, 0.1); +} + +.enterprise-field input::placeholder { + color: rgba(255, 255, 255, 0.3); +} + +.enterprise-hint { + font-size: 12px; + color: rgba(255, 255, 255, 0.4); + line-height: 1.5; + margin-top: 4px; +} + +.enterprise-hint--spacious { + margin-top: 16px; +} + +.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: absolute; + bottom: calc(100% + 8px); + left: 50%; + transform: translateX(-50%); + background: rgba(30, 30, 40, 0.95); + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 12px; + padding: 12px 16px; + min-width: 220px; + max-width: 280px; + z-index: 1000; + backdrop-filter: blur(20px); + box-shadow: 0 8px 32px rgba(0, 0, 0, 0.4); +} + +.enterprise-field-tooltip-card::after { + content: ''; + position: absolute; + top: 100%; + left: 50%; + transform: translateX(-50%); + border: 6px solid transparent; + border-top-color: rgba(30, 30, 40, 0.95); +} + +.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.85); + line-height: 1.5; +} + +.enterprise-modal-body--spacious { + gap: 20px; +} + +.enterprise-variables-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); + gap: 8px; +} + +.enterprise-variables-grid--spacious { + gap: 12px; +} + +.enterprise-variable-chip { + display: flex; + align-items: center; + gap: 6px; + padding: 8px 12px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 8px; + font-size: 12px; +} + +.enterprise-variable-chip code { + font-size: 11px; + color: rgba(255, 255, 255, 0.7); +} + +.enterprise-resources-fields--spacious { + gap: 20px; +} + +.enterprise-resources-section-title { + grid-column: 1 / -1; + display: flex; + align-items: center; + gap: 10px; + min-height: 34px; + padding: 10px 14px; + font-size: 13px; + font-weight: 800; + color: rgba(255, 255, 255, 0.86); + letter-spacing: 0; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 10px; + margin-top: 4px; +} + +.enterprise-resources-section-title--spaced { + margin-top: 12px; +} + +.enterprise-resources-section-title i { + width: 26px; + height: 26px; + display: inline-flex; + align-items: center; + justify-content: center; + border-radius: 8px; + background: rgba(99, 102, 241, 0.14); + color: rgba(165, 180, 252, 0.95); + font-size: 12px; +} + +.enterprise-resources-section-title .enterprise-field-tooltip i { + width: auto; + height: auto; + border-radius: 0; + background: transparent; + color: rgba(255, 255, 255, 0.42); +} + +.enterprise-input-with-suffix { + position: relative; + display: flex; + align-items: center; +} + +.enterprise-input-with-suffix input { + padding-right: 54px; + width: 100%; + box-sizing: border-box; +} + +.enterprise-input-with-suffix span { + position: absolute; + right: 14px; + font-size: 12px; + font-weight: 700; + color: rgba(255, 255, 255, 0.42); + pointer-events: none; + white-space: nowrap; +} + +.enterprise-hint.enterprise-hint-error { + color: rgba(248, 113, 113, 0.96); +} + +.enterprise-template-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); + gap: 15px; + margin-top: 4px; +} + +.enterprise-template-item { + display: flex; + flex-direction: column; + align-items: center; + gap: 8px; + padding: 14px 10px; + border-radius: 14px; + border: none; + outline: none; + background: rgba(255, 255, 255, 0.03); + cursor: pointer; + transition: all 0.2s ease; +} + +.enterprise-template-item:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.1); + transform: none; +} + +.enterprise-template-item.selected { + background: rgba(0, 128, 255, 0.137); + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1); + border: none; +} + +.enterprise-template-icon { + width: 44px; + height: 44px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + font-size: 18px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.8); + overflow: hidden; +} + +.enterprise-template-icon img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.enterprise-template-name { + font-size: 12px; + font-weight: 600; + color: rgba(255, 255, 255, 0.8); + text-align: center; + line-height: 1.3; +} + +.enterprise-node-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 10px; + margin-top: 4px; +} + +.enterprise-node-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 14px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + cursor: pointer; + transition: all 0.2s ease; +} + +.enterprise-node-item:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.1); +} + +.enterprise-node-item.selected { + background: rgba(33, 33, 33, 0.15); +} + +.enterprise-node-icon { + width: 36px; + height: 36px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.7); + flex-shrink: 0; +} + +.enterprise-node-info { + flex: 1; + min-width: 0; +} + +.enterprise-node-name { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); +} + +.enterprise-node-meta { + font-size: 11px; + color: rgba(255, 255, 255, 0.4); + margin-top: 2px; +} + +.enterprise-summary { + border-radius: 14px; + background: linear-gradient(145deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.02)); + border: 1px solid rgba(255, 255, 255, 0.06); + padding: 16px; +} + +.enterprise-summary-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 12px; + padding-bottom: 10px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.enterprise-summary-title { + font-size: 13px; + font-weight: 700; + color: rgba(255, 255, 255, 0.9); +} + +.enterprise-summary-badge { + font-size: 10px; + padding: 4px 8px; + border-radius: 6px; + background: rgba(74, 222, 128, 0.15); + color: #4ade80; + font-weight: 600; + letter-spacing: 0.02em; +} + +.enterprise-summary-row { + display: flex; + justify-content: space-between; + align-items: center; + padding: 8px 0; +} + +.enterprise-summary-row:not(:last-child) { + border-bottom: 1px solid rgba(255, 255, 255, 0.04); +} + +.enterprise-summary-label { + font-size: 12px; + color: rgba(255, 255, 255, 0.5); +} + +.enterprise-summary-value { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); +} + +.enterprise-summary-footer { + margin-top: 12px; + font-size: 11px; + color: rgba(255, 255, 255, 0.35); + text-align: center; +} + +.enterprise-fork-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 16px; +} + +.enterprise-fork-grid--spacious { + gap: 20px; +} + +.enterprise-fork-item { + display: flex; + flex-direction: column; + align-items: center; + gap: 14px; + padding: 24px 18px; + border-radius: 16px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + cursor: pointer; + transition: all 0.2s ease; + text-align: center; +} + +.enterprise-fork-item:hover { + background: rgba(255, 255, 255, 0.06); + border-color: rgba(255, 255, 255, 0.12); + outline: none; + transform: translateY(-2px); +} + +.enterprise-fork-item.selected { + background: rgba(0, 128, 255, 0.137); + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1); + outline: none; + border-color: rgba(99, 102, 241, 0.3); +} + +.enterprise-fork-icon { + width: 56px; + height: 56px; + border-radius: 14px; + display: flex; + align-items: center; + justify-content: center; + font-size: 22px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.8); + overflow: hidden; +} + +.enterprise-fork-icon img { + width: 100%; + height: 100%; + object-fit: cover; +} + +.enterprise-fork-name { + font-size: 13px; + font-weight: 700; + color: rgba(255, 255, 255, 0.9); +} + +.enterprise-fork-desc { + font-size: 11px; + color: rgba(255, 255, 255, 0.4); + line-height: 1.4; +} + +.enterprise-port-layout { + display: grid; + gap: 20px; +} + +.enterprise-connection-chip { + display: inline-flex; + align-items: center; + gap: 10px; + padding: 12px 16px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.08); + font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace; +} + +.enterprise-connection-chip i { + color: rgba(74, 222, 128, 0.8); +} + +.enterprise-connection-chip code { + color: rgba(255, 255, 255, 0.9); + font-size: 14px; + background: transparent; + padding: 0; +} + +.enterprise-connection-chip__divider { + color: rgba(255, 255, 255, 0.3); +} + +.enterprise-resources-layout { + display: grid; + gap: 20px; +} + +.enterprise-resources-info { + padding: 16px; + border-radius: 14px; + background: linear-gradient(145deg, rgba(99, 102, 241, 0.08), rgba(99, 102, 241, 0.04)); +} + +.enterprise-resources-info__header { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 14px; + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); +} + +.enterprise-resources-info__header i { + color: rgba(99, 102, 241, 0.8); +} + +.enterprise-resources-info__grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 12px; +} + +.enterprise-resources-info__item { + display: flex; + flex-direction: column; + gap: 4px; +} + +.enterprise-resources-info__label { + font-size: 10px; + color: rgba(255, 255, 255, 0.4); + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.enterprise-resources-info__value { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); +} + +.enterprise-resources-fields { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 16px; +} + +@media (max-width: 640px) { + .enterprise-resources-fields { + grid-template-columns: 1fr; + } + + .enterprise-resources-info__grid { + grid-template-columns: 1fr; + } +} + +.enterprise-spinner { + width: 18px; + height: 18px; + border: 2px solid rgba(255, 255, 255, 0.1); + border-top-color: rgba(99, 102, 241, 0.8); + border-radius: 50%; + animation: enterpriseSpin 0.8s linear infinite; + display: none; +} + +.enterprise-spinner.visible { + display: inline-block; +} + +@keyframes enterpriseSpin { + to { + transform: rotate(360deg); + } +} + +.enterprise-variables-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 8px; + margin-top: 8px; +} + +.enterprise-variable-chip { + display: flex; + align-items: center; + gap: 6px; + padding: 8px 12px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 8px; + font-size: 12px; + color: rgba(255, 255, 255, 0.7); + line-height: 1.4; +} + +.enterprise-variable-chip code { + font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace; + font-size: 11px; + font-weight: 600; + color: var(--color-accent, #7c5cff); + background: rgba(124, 92, 255, 0.15); + padding: 2px 6px; + border-radius: 4px; + white-space: nowrap; +} + +@media (max-width: 640px) { + .enterprise-variables-grid { + grid-template-columns: 1fr; + } +} + +.account-page { + max-width: 800px; + margin: 0 auto; + padding: 40px 24px; + animation: fadeInUp 0.4s ease; +} + +@keyframes fadeInUp { + from { + opacity: 0; + transform: translateY(20px); + } + + to { + opacity: 1; + transform: translateY(0); + } +} + +.account-header { + margin-bottom: 32px; +} + +.account-header h2 { + font-size: 28px; + font-weight: 700; + color: #fff; + margin: 0 0 8px; +} + +.account-header p { + color: rgba(255, 255, 255, 0.6); + font-size: 15px; + margin: 0; +} + +.account-back-btn { + display: inline-flex; + align-items: center; + gap: 10px; + padding: 10px 18px; + margin-bottom: 24px; + border: none; + border-radius: 12px; + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.85); + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s ease; +} + +.account-back-btn:hover { + background: rgba(255, 255, 255, 0.12); + transform: translateX(-4px); +} + +.account-back-btn i { + font-size: 14px; +} + +.account-card { + background: var(--color-surface, rgba(19, 21, 29, 0.72)); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 20px; + padding: 24px; + margin-bottom: 20px; + backdrop-filter: blur(18px); + box-shadow: var(--shadow-md, 0 14px 30px rgba(10, 12, 20, 0.28)); +} + +.account-card-header { + display: flex; + align-items: center; + gap: 16px; + margin-bottom: 24px; + padding-bottom: 20px; + border-bottom: 1px solid rgba(255, 255, 255, 0.08); +} + +.account-avatar { + width: 64px; + height: 64px; + border-radius: 50%; + background: transparent; + display: flex; + align-items: center; + justify-content: center; + font-size: 24px; + color: #a5b4fc; +} + +.account-info h3 { + font-size: 20px; + font-weight: 700; + color: #fff; + margin: 0 0 4px; +} + +.account-info p { + font-size: 14px; + color: rgba(255, 255, 255, 0.6); + margin: 0; +} + +.account-badge { + display: inline-block; + padding: 4px 10px; + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.5px; + border-radius: 6px; + margin-left: 10px; + vertical-align: middle; +} + +.account-badge.admin { + background: linear-gradient(145deg, rgba(16, 185, 129, 0.25), rgba(5, 150, 105, 0.2)); + color: #10b981; +} + +.account-badge.user { + background: linear-gradient(145deg, rgba(99, 102, 241, 0.25), rgba(79, 70, 229, 0.2)); + color: #a5b4fc; +} + +.account-section-title { + font-size: 15px; + font-weight: 700; + color: #fff; + margin: 0 0 16px; + display: flex; + align-items: center; + gap: 10px; +} + +.account-section-title i { + font-size: 16px; + opacity: 0.7; + color: var(--color-accent, #7c5cff); +} + +.account-row { + display: flex; + justify-content: space-between; + align-items: center; + padding: 14px 0; + border-bottom: 1px solid rgba(255, 255, 255, 0.05); +} + +.account-row:last-child { + border-bottom: none; +} + +.account-row-label { + font-size: 14px; + color: rgba(255, 255, 255, 0.6); +} + +.account-row-value { + font-size: 14px; + font-weight: 600; + color: #fff; +} + +.account-row-editable { + flex-wrap: wrap; +} + +.account-row-value-wrap { + display: flex; + align-items: center; + gap: 10px; +} + +.account-row-input { + padding: 8px 14px; + background: rgba(255, 255, 255, 0.08); + border: 1px solid rgba(255, 255, 255, 0.12); + border-radius: 8px; + color: #fff; + font-size: 14px; + font-weight: 600; + width: 180px; + transition: all 0.2s ease; +} + +.account-row-input:focus { + outline: none; + border-color: rgba(99, 102, 241, 0.5); + background: rgba(255, 255, 255, 0.1); +} + +.account-row-edit-btn, +.account-row-save-btn, +.account-row-cancel-btn { + width: 32px; + height: 32px; + border-radius: 8px; + border: none; + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + transition: all 0.2s ease; +} + +.account-row-edit-btn { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.6); +} + +.account-row-edit-btn:hover { + background: rgba(99, 102, 241, 0.2); + color: #a5b4fc; +} + +.account-row-save-btn { + background: rgba(74, 222, 128, 0.2); + color: #4ade80; +} + +.account-row-save-btn:hover { + background: rgba(74, 222, 128, 0.3); +} + +.account-row-cancel-btn { + background: rgba(239, 68, 68, 0.15); + color: #f87171; +} + +.account-row-cancel-btn:hover { + background: rgba(239, 68, 68, 0.25); +} + +.account-row-cooldown { + width: 100%; + font-size: 12px; + color: rgba(251, 191, 36, 0.9); + margin-top: 8px; + padding-left: 0; +} + +.account-status-value { + display: flex; + align-items: center; + gap: 8px; +} + +.account-status-value .status-dot { + width: 8px; + height: 8px; + border-radius: 50%; + background: #4ade80; + box-shadow: 0 0 8px rgba(74, 222, 128, 0.5); +} + +.account-placeholder { + text-align: center; + padding: 48px 20px; + color: rgba(255, 255, 255, 0.5); +} + +.account-placeholder i { + font-size: 42px; + margin-bottom: 16px; + opacity: 0.5; +} + +.account-placeholder h4 { + font-size: 17px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); + margin: 0 0 8px; +} + +.account-placeholder p { + font-size: 14px; + margin: 0; +} + +.account-card { + background: rgba(10, 12, 20, 0.55); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 20px; + padding: 24px; + margin-bottom: 20px; + backdrop-filter: blur(24px); + -webkit-backdrop-filter: blur(24px); + box-shadow: 0 20px 50px rgba(0, 0, 0, 0.35); +} + +.account-avatar { + width: 72px; + height: 72px; + border-radius: 50%; + background: transparent; + display: flex; + align-items: center; + justify-content: center; + font-size: 28px; + color: #a5b4fc; + position: relative; + cursor: pointer; + overflow: hidden; + transition: all 0.25s ease; +} + +.account-avatar img { + width: 100%; + height: 100%; + object-fit: cover; + border-radius: 50%; +} + +.account-avatar-overlay { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.65); + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + opacity: 0; + transition: opacity 0.25s ease; + border-radius: 50%; +} + +.account-avatar:hover .account-avatar-overlay { + opacity: 1; +} + +.account-avatar-overlay i { + font-size: 20px; + color: #fff; + margin-bottom: 4px; +} + +.account-avatar-overlay span { + font-size: 10px; + color: rgba(255, 255, 255, 0.9); + font-weight: 600; + text-transform: uppercase; + letter-spacing: 0.5px; +} + +.account-avatar:hover { + transform: scale(1.05); +} + +.account-avatar-input { + display: none; +} + +.account-tabs { + display: flex; + gap: 10px; + margin-bottom: 24px; +} + +.account-tab { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 22px; + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + border: none; + border-radius: 12px; + color: rgba(255, 255, 255, 0.6); + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: all 0.25s ease; +} + +.account-tab:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.9); +} + +.account-tab.active { + background: rgba(99, 102, 241, 0.2); + backdrop-filter: blur(20px); + color: #a5b4fc; +} + +.account-tab i { + font-size: 15px; +} + +.account-tab-content { + display: none; +} + +.account-tab-content.active { + display: block; + animation: fadeInUp 0.3s ease; +} + +.credentials-card { + display: flex; + align-items: center; + justify-content: space-between; + padding: 20px; + background: rgba(255, 255, 255, 0.03); + border-radius: 14px; +} + +.credentials-info { + display: flex; + align-items: center; + gap: 16px; +} + +.credentials-icon { + width: 50px; + height: 50px; + border-radius: 14px; + background: transparent; + display: flex; + align-items: center; + justify-content: center; +} + +.credentials-icon img { + width: 60px; + height: 60px; + object-fit: contain; +} + +.credentials-text h4 { + font-size: 15px; + font-weight: 600; + color: #fff; + margin: 0 0 4px; +} + +.credentials-text p { + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + margin: 0; +} + +.credentials-btn { + display: flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + background: rgba(99, 102, 241, 0.18); + backdrop-filter: blur(16px); + -webkit-backdrop-filter: blur(16px); + border: none; + border-radius: 12px; + color: #a5b4fc; + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.25s ease; +} + +.credentials-btn:hover { + background: rgba(99, 102, 241, 0.28); + transform: scale(1.02); +} + +.twofa-modal-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.65); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + display: none; + align-items: center; + justify-content: center; + z-index: 10000; +} + +.twofa-modal-overlay.show { + display: flex; +} + +.twofa-modal { + background: rgba(15, 17, 25, 0.95); + backdrop-filter: blur(24px); + -webkit-backdrop-filter: blur(24px); + border-radius: 20px; + width: 100%; + max-width: 420px; + box-shadow: 0 30px 70px rgba(0, 0, 0, 0.5); + overflow: hidden; + animation: modalSlideIn 0.3s ease; +} + +@keyframes modalSlideIn { + from { + opacity: 0; + transform: translateY(20px) scale(0.97); + } + + to { + opacity: 1; + transform: translateY(0) scale(1); + } +} + +.twofa-modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 20px 24px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.twofa-modal-header-left { + display: flex; + align-items: center; + gap: 14px; +} + +.twofa-modal-icon { + width: 44px; + height: 44px; + border-radius: 12px; + background: transparent; + display: flex; + align-items: center; + justify-content: center; +} + +.twofa-modal-icon img { + width: 60px; + height: 60px; + object-fit: contain; +} + +.twofa-modal-title { + font-size: 17px; + font-weight: 700; + color: #fff; + margin: 0; +} + +.twofa-modal-subtitle { + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + margin: 4px 0 0; +} + +.twofa-modal-close { + width: 36px; + height: 36px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(12px); + border: none; + color: rgba(255, 255, 255, 0.6); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; +} + +.twofa-modal-close:hover { + background: rgba(239, 68, 68, 0.2); + color: #ef4444; +} + +.twofa-modal-body { + padding: 24px; +} + +.twofa-step { + margin-bottom: 24px; +} + +.twofa-step-label { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); + margin-bottom: 12px; + display: flex; + align-items: center; + gap: 10px; +} + +.twofa-step-num { + width: 24px; + height: 24px; + border-radius: 50%; + background: rgba(99, 102, 241, 0.25); + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + font-weight: 700; + color: #a5b4fc; +} + +.twofa-input { + width: 100%; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.04); + border: none; + border-radius: 12px; + color: #fff; + font-size: 18px; + font-family: 'SF Mono', Monaco, monospace; + letter-spacing: 6px; + text-align: center; + outline: none; + transition: background 0.2s ease; + box-sizing: border-box; +} + +.twofa-input:focus { + background: rgba(99, 102, 241, 0.12); +} + +.twofa-input::placeholder { + letter-spacing: 4px; + color: rgba(255, 255, 255, 0.25); +} + +.twofa-qr-wrap { + display: flex; + flex-direction: column; + align-items: center; + padding: 20px; + background: rgba(255, 255, 255, 0.03); + border-radius: 14px; + margin-bottom: 12px; +} + +.twofa-qr-wrap img { + width: 170px; + height: 170px; + border-radius: 10px; + background: #fff; + padding: 10px; +} + +.twofa-qr-hint { + font-size: 12px; + color: rgba(255, 255, 255, 0.45); + text-align: center; + margin-top: 14px; +} + +.twofa-secret-display { + display: flex; + align-items: center; + justify-content: center; + padding: 12px; + background: rgba(255, 255, 255, 0.04); + border-radius: 10px; +} + +.twofa-secret-code { + font-family: 'SF Mono', Monaco, monospace; + font-size: 13px; + font-weight: 600; + color: #a5b4fc; + letter-spacing: 2px; +} + +.twofa-modal-footer { + display: flex; + gap: 12px; + padding: 20px 24px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.twofa-btn { + flex: 1; + padding: 14px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: all 0.25s ease; + border: none; +} + +.twofa-btn-cancel { + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(12px); + color: rgba(255, 255, 255, 0.7); +} + +.twofa-btn-cancel:hover { + background: rgba(255, 255, 255, 0.1); +} + +.twofa-btn-confirm { + background: rgba(99, 102, 241, 0.85); + backdrop-filter: blur(12px); + color: #fff; +} + +.twofa-btn-confirm:hover { + background: rgba(99, 102, 241, 1); + transform: scale(1.02); +} + +.twofa-btn-confirm:disabled { + opacity: 0.5; + cursor: not-allowed; + transform: none; + box-shadow: none; +} + +.twofa-error { + padding: 12px 16px; + background: rgba(239, 68, 68, 0.12); + border-radius: 10px; + color: #ef4444; + font-size: 13px; + margin-top: 16px; + display: none; +} + +.twofa-error.show { + display: block; +} + +.twofa-success { + padding: 14px 16px; + background: rgba(16, 185, 129, 0.12); + border-radius: 10px; + color: #10b981; + font-size: 13px; + text-align: center; + display: none; +} + +.twofa-success.show { + display: block; +} + +.password-modal-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.65); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + display: none; + align-items: center; + justify-content: center; + z-index: 10000; +} + +.password-modal-overlay.show { + display: flex; +} + +.password-modal { + background: rgba(15, 17, 25, 0.95); + backdrop-filter: blur(24px); + -webkit-backdrop-filter: blur(24px); + border-radius: 20px; + width: 100%; + max-width: 420px; + box-shadow: 0 30px 70px rgba(0, 0, 0, 0.5); + overflow: hidden; + animation: modalSlideIn 0.3s ease; +} + +.password-modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 20px 24px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.password-modal-header-left { + display: flex; + align-items: center; + gap: 14px; +} + +.password-modal-icon { + width: 100px; + height: 100px; + border-radius: 12px; + background: transparent; + display: flex; + align-items: center; + justify-content: center; +} + +.password-modal-icon img { + width: 100px; + height: 100px; + object-fit: contain; + border-radius: 12px; +} + +.password-modal-title { + font-size: 17px; + font-weight: 700; + color: #fff; + margin: 0; +} + +.password-modal-subtitle { + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + margin: 4px 0 0; +} + +.password-modal-close { + width: 36px; + height: 36px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(12px); + border: none; + color: rgba(255, 255, 255, 0.6); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; +} + +.password-modal-close:hover { + background: rgba(239, 68, 68, 0.2); + color: #ef4444; +} + +.password-modal-body { + padding: 24px; +} + +.password-step { + margin-bottom: 20px; +} + +.password-step-label { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); + margin-bottom: 12px; + display: flex; + align-items: center; + gap: 10px; +} + +.password-step-num { + width: 24px; + height: 24px; + border-radius: 50%; + background: rgba(99, 102, 241, 0.25); + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + font-weight: 700; + color: #a5b4fc; +} + +.password-input { + width: 100%; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.04); + border: none; + border-radius: 12px; + color: #fff; + font-size: 15px; + outline: none; + transition: background 0.2s ease; + box-sizing: border-box; +} + +.password-input:focus { + background: rgba(99, 102, 241, 0.12); +} + +.password-input::placeholder { + color: rgba(255, 255, 255, 0.25); +} + +.password-code-input { + font-family: 'SF Mono', Monaco, monospace; + font-size: 18px; + letter-spacing: 6px; + text-align: center; +} + +.password-modal-footer { + display: flex; + gap: 12px; + padding: 20px 24px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.password-btn { + flex: 1; + padding: 14px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: all 0.25s ease; + border: none; +} + +.password-btn-cancel { + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(12px); + color: rgba(255, 255, 255, 0.7); +} + +.password-btn-cancel:hover { + background: rgba(255, 255, 255, 0.1); +} + +.password-btn-confirm { + background: rgba(99, 102, 241, 0.85); + backdrop-filter: blur(12px); + color: #fff; +} + +.password-btn-confirm:hover { + background: rgba(99, 102, 241, 1); + transform: scale(1.02); +} + +.password-btn-confirm:disabled { + opacity: 0.5; + cursor: not-allowed; + transform: none; +} + +.password-error { + padding: 12px 16px; + background: rgba(239, 68, 68, 0.12); + border-radius: 10px; + color: #ef4444; + font-size: 13px; + margin-top: 16px; + display: none; +} + +.password-error.show { + display: block; +} + +.password-success { + padding: 14px 16px; + background: rgba(16, 185, 129, 0.12); + border-radius: 10px; + color: #10b981; + font-size: 13px; + text-align: center; + display: none; +} + +.password-success.show { + display: block; +} + +.password-input-wrap { + position: relative; + width: 100%; +} + +.password-input-wrap .password-input { + padding-right: 48px; +} + +.password-toggle-eye { + position: absolute; + right: 12px; + top: 50%; + transform: translateY(-50%); + background: transparent; + border: none; + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + padding: 6px; + font-size: 16px; + transition: color 0.2s ease; +} + +.password-toggle-eye:hover { + color: #a5b4fc; +} + +.email-modal-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.65); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + display: none; + align-items: center; + justify-content: center; + z-index: 10000; +} + +.email-modal-overlay.show { + display: flex; +} + +.email-modal { + background: rgba(15, 17, 25, 0.95); + backdrop-filter: blur(24px); + -webkit-backdrop-filter: blur(24px); + border-radius: 20px; + width: 100%; + max-width: 420px; + box-shadow: 0 30px 70px rgba(0, 0, 0, 0.5); + overflow: hidden; + animation: modalSlideIn 0.3s ease; +} + +.email-modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 20px 24px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.email-modal-header-left { + display: flex; + align-items: center; + gap: 14px; +} + +.email-modal-icon { + width: 100px; + height: 100px; + border-radius: 12px; + background: transparent; + display: flex; + align-items: center; + justify-content: center; +} + +.email-modal-icon img { + width: 100px; + height: 100px; + object-fit: contain; + border-radius: 12px; +} + +.email-modal-title { + font-size: 17px; + font-weight: 700; + color: #fff; + margin: 0; +} + +.email-modal-subtitle { + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + margin: 4px 0 0; +} + +.email-modal-close { + width: 36px; + height: 36px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(12px); + border: none; + color: rgba(255, 255, 255, 0.6); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; +} + +.email-modal-close:hover { + background: rgba(239, 68, 68, 0.2); + color: #ef4444; +} + +.email-modal-body { + padding: 24px; +} + +.email-step { + margin-bottom: 20px; +} + +.email-step-label { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); + margin-bottom: 12px; + display: flex; + align-items: center; + gap: 10px; +} + +.email-step-num { + width: 24px; + height: 24px; + border-radius: 50%; + background: rgba(99, 102, 241, 0.25); + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + font-weight: 700; + color: #a5b4fc; +} + +.email-input { + width: 100%; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.04); + border: none; + border-radius: 12px; + color: #fff; + font-size: 15px; + outline: none; + transition: background 0.2s ease; + box-sizing: border-box; +} + +.email-input:focus { + background: rgba(99, 102, 241, 0.12); +} + +.email-input::placeholder { + color: rgba(255, 255, 255, 0.25); +} + +.email-code-input { + font-family: 'SF Mono', Monaco, monospace; + font-size: 18px; + letter-spacing: 6px; + text-align: center; +} + +.email-input-wrap { + position: relative; + width: 100%; +} + +.email-input-wrap .email-input { + padding-right: 48px; +} + +.email-toggle-eye { + position: absolute; + right: 12px; + top: 50%; + transform: translateY(-50%); + background: transparent; + border: none; + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + padding: 6px; + font-size: 16px; + transition: color 0.2s ease; +} + +.email-toggle-eye:hover { + color: #a5b4fc; +} + +.email-modal-footer { + display: flex; + gap: 12px; + padding: 20px 24px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.email-btn { + flex: 1; + padding: 14px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: all 0.25s ease; + border: none; +} + +.email-btn-cancel { + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(12px); + color: rgba(255, 255, 255, 0.7); +} + +.email-btn-cancel:hover { + background: rgba(255, 255, 255, 0.1); +} + +.email-btn-confirm { + background: rgba(99, 102, 241, 0.85); + backdrop-filter: blur(12px); + color: #fff; +} + +.email-btn-confirm:hover { + background: rgba(99, 102, 241, 1); + transform: scale(1.02); +} + +.email-btn-confirm:disabled { + opacity: 0.5; + cursor: not-allowed; + transform: none; +} + +.email-error { + padding: 12px 16px; + background: rgba(239, 68, 68, 0.12); + border-radius: 10px; + color: #ef4444; + font-size: 13px; + margin-top: 16px; + display: none; +} + +.email-error.show { + display: block; +} + +.email-success { + padding: 14px 16px; + background: rgba(16, 185, 129, 0.12); + border-radius: 10px; + color: #10b981; + font-size: 13px; + text-align: center; + display: none; +} + +.email-success.show { + display: block; +} + +.forgot-code-link { + text-align: center; + margin-top: 12px; + font-size: 13px; + color: rgba(255, 255, 255, 0.5); +} + +.forgot-code-click { + color: #a5b4fc; + cursor: pointer; + text-decoration: underline; + transition: color 0.2s ease; +} + +.forgot-code-click:hover { + color: #818cf8; +} + +.recovery-modal-overlay { + position: fixed; + inset: 0; + background: rgba(0, 0, 0, 0.65); + backdrop-filter: blur(10px); + -webkit-backdrop-filter: blur(10px); + display: none; + align-items: center; + justify-content: center; + z-index: 10001; +} + +.recovery-modal-overlay.show { + display: flex; +} + +.recovery-modal { + background: rgba(15, 17, 25, 0.95); + backdrop-filter: blur(24px); + -webkit-backdrop-filter: blur(24px); + border-radius: 20px; + width: 100%; + max-width: 420px; + box-shadow: 0 30px 70px rgba(0, 0, 0, 0.5); + overflow: hidden; + animation: modalSlideIn 0.3s ease; +} + +.recovery-modal-header { + display: flex; + align-items: center; + justify-content: space-between; + padding: 20px 24px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); +} + +.recovery-modal-header-left { + display: flex; + align-items: center; + gap: 14px; +} + +.recovery-modal-icon { + width: 100px; + height: 100px; + border-radius: 12px; + background: transparent; + display: flex; + align-items: center; + justify-content: center; +} + +.recovery-modal-icon img { + width: 100px; + height: 100px; + object-fit: contain; + border-radius: 12px; +} + +.recovery-modal-title { + font-size: 17px; + font-weight: 700; + color: #fff; + margin: 0; +} + +.recovery-modal-subtitle { + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + margin: 4px 0 0; +} + +.recovery-modal-close { + width: 36px; + height: 36px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(12px); + border: none; + color: rgba(255, 255, 255, 0.6); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; +} + +.recovery-modal-close:hover { + background: rgba(239, 68, 68, 0.2); + color: #ef4444; +} + +.recovery-modal-body { + padding: 24px; +} + +.recovery-step { + margin-bottom: 20px; +} + +.recovery-step-label { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); + margin-bottom: 12px; + display: flex; + align-items: center; + gap: 10px; +} + +.recovery-step-num { + width: 24px; + height: 24px; + border-radius: 50%; + background: rgba(99, 102, 241, 0.25); + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + font-weight: 700; + color: #a5b4fc; +} + +.recovery-input { + width: 100%; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.04); + border: none; + border-radius: 12px; + color: #fff; + font-size: 15px; + outline: none; + transition: background 0.2s ease; + box-sizing: border-box; +} + +.recovery-input:focus { + background: rgba(99, 102, 241, 0.12); +} + +.recovery-input::placeholder { + color: rgba(255, 255, 255, 0.25); +} + +.recovery-hint { + padding: 12px 16px; + background: rgba(99, 102, 241, 0.1); + border-radius: 10px; + color: rgba(255, 255, 255, 0.6); + font-size: 12px; + line-height: 1.5; + margin-bottom: 16px; +} + +.recovery-modal-footer { + display: flex; + gap: 12px; + padding: 20px 24px; + border-top: 1px solid rgba(255, 255, 255, 0.06); +} + +.recovery-btn { + flex: 1; + padding: 14px; + border-radius: 12px; + font-size: 14px; + font-weight: 600; + cursor: pointer; + transition: all 0.25s ease; + border: none; +} + +.recovery-btn-cancel { + background: rgba(255, 255, 255, 0.06); + backdrop-filter: blur(12px); + color: rgba(255, 255, 255, 0.7); +} + +.recovery-btn-cancel:hover { + background: rgba(255, 255, 255, 0.1); +} + +.recovery-btn-confirm { + background: rgba(99, 102, 241, 0.85); + backdrop-filter: blur(12px); + color: #fff; +} + +.recovery-btn-confirm:hover { + background: rgba(99, 102, 241, 1); + transform: scale(1.02); +} + +.recovery-btn-confirm:disabled { + opacity: 0.5; + cursor: not-allowed; + transform: none; +} + +.recovery-error { + padding: 12px 16px; + background: rgba(239, 68, 68, 0.12); + border-radius: 10px; + color: #ef4444; + font-size: 13px; + display: none; +} + +.recovery-error.show { + display: block; +} diff --git a/public/images/ADPanel-christmas.webp b/public/images/ADPanel-christmas.webp new file mode 100644 index 0000000..375ff1c Binary files /dev/null and b/public/images/ADPanel-christmas.webp differ diff --git a/public/images/ADPanel.webp b/public/images/ADPanel.webp new file mode 100644 index 0000000..a21c527 Binary files /dev/null and b/public/images/ADPanel.webp differ diff --git a/public/images/Dax-dark.png b/public/images/Dax-dark.png new file mode 100644 index 0000000..d82f0d7 Binary files /dev/null and b/public/images/Dax-dark.png differ diff --git a/public/images/Dax-dark.webp b/public/images/Dax-dark.webp new file mode 100644 index 0000000..f98cd91 Binary files /dev/null and b/public/images/Dax-dark.webp differ diff --git a/public/images/Scheduler.webp b/public/images/Scheduler.webp new file mode 100644 index 0000000..84f8944 Binary files /dev/null and b/public/images/Scheduler.webp differ diff --git a/public/images/adpanel-dark.webp b/public/images/adpanel-dark.webp new file mode 100644 index 0000000..a5b967f Binary files /dev/null and b/public/images/adpanel-dark.webp differ diff --git a/public/images/backup.webp b/public/images/backup.webp new file mode 100644 index 0000000..546b3a3 Binary files /dev/null and b/public/images/backup.webp differ diff --git a/public/images/bgvid.webm b/public/images/bgvid.webm new file mode 100644 index 0000000..2df258c Binary files /dev/null and b/public/images/bgvid.webm differ diff --git a/public/images/captcha.webp b/public/images/captcha.webp new file mode 100644 index 0000000..4d9c8ff Binary files /dev/null and b/public/images/captcha.webp differ diff --git a/public/images/favicon.ico b/public/images/favicon.ico new file mode 100644 index 0000000..d82f0d7 Binary files /dev/null and b/public/images/favicon.ico differ diff --git a/public/images/hello.webp b/public/images/hello.webp new file mode 100644 index 0000000..49ee207 Binary files /dev/null and b/public/images/hello.webp differ diff --git a/public/images/login-background-remote-80a53467cc608e86.png b/public/images/login-background-remote-80a53467cc608e86.png new file mode 100644 index 0000000..3685b30 Binary files /dev/null and b/public/images/login-background-remote-80a53467cc608e86.png differ diff --git a/public/images/logo.webp b/public/images/logo.webp new file mode 100644 index 0000000..f98cd91 Binary files /dev/null and b/public/images/logo.webp differ diff --git a/public/images/minecraft.webp b/public/images/minecraft.webp new file mode 100644 index 0000000..1851412 Binary files /dev/null and b/public/images/minecraft.webp differ diff --git a/public/images/mountains.webp b/public/images/mountains.webp new file mode 100644 index 0000000..bcb56e1 Binary files /dev/null and b/public/images/mountains.webp differ diff --git a/public/images/node-status.avif b/public/images/node-status.avif new file mode 100644 index 0000000..5b4d227 Binary files /dev/null and b/public/images/node-status.avif differ diff --git a/public/images/nodejs.webp b/public/images/nodejs.webp new file mode 100644 index 0000000..352787e Binary files /dev/null and b/public/images/nodejs.webp differ diff --git a/public/images/quick-actions.webp b/public/images/quick-actions.webp new file mode 100644 index 0000000..2368088 Binary files /dev/null and b/public/images/quick-actions.webp differ diff --git a/public/images/rate-limiter.webp b/public/images/rate-limiter.webp new file mode 100644 index 0000000..7d8af90 Binary files /dev/null and b/public/images/rate-limiter.webp differ diff --git a/public/images/server.webp b/public/images/server.webp new file mode 100644 index 0000000..36142ed Binary files /dev/null and b/public/images/server.webp differ diff --git a/public/images/sunset.webp b/public/images/sunset.webp new file mode 100644 index 0000000..6fb5a7a Binary files /dev/null and b/public/images/sunset.webp differ diff --git a/public/images/waves-digital.webp b/public/images/waves-digital.webp new file mode 100644 index 0000000..653b3d5 Binary files /dev/null and b/public/images/waves-digital.webp differ diff --git a/public/images/waves.png b/public/images/waves.png new file mode 100644 index 0000000..3685b30 Binary files /dev/null and b/public/images/waves.png differ diff --git a/public/js/bot.js b/public/js/bot.js new file mode 100644 index 0000000..3988338 --- /dev/null +++ b/public/js/bot.js @@ -0,0 +1,11325 @@ +(() => { + const bot = document.documentElement?.dataset?.bot; + if (!bot) { + console.error("BOT not injected (data-bot missing)"); + return; + } + function escapeHtml(s) { + return String(s).replace(/[&<>"']/g, function (m) { + return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]); + }); + } + let htmlEntityDecoder = null; + function decodeHtmlEntities(raw) { + const value = String(raw || ''); + if (!value || !/[&](?:[a-z]+|#\d+|#x[0-9a-f]+);/i.test(value)) return value; + if (!htmlEntityDecoder) htmlEntityDecoder = document.createElement('textarea'); + htmlEntityDecoder.innerHTML = value; + return htmlEntityDecoder.value; + } + + const ANSI_SGR_RE = /\x1B\[[0-9:;]*m/g; + + function skipAnsiOscSequence(str, idx) { + let i = idx; + while (i < str.length) { + const code = str.charCodeAt(i); + if (code === 0x07) return i + 1; + if (code === 0x1b && str.charCodeAt(i + 1) === 0x5c) return i + 2; + i += 1; + } + return str.length; + } + + function skipAnsiEscTerminatedSequence(str, idx) { + let i = idx; + while (i < str.length) { + if (str.charCodeAt(i) === 0x1b && str.charCodeAt(i + 1) === 0x5c) return i + 2; + i += 1; + } + return str.length; + } + + function skipAnsiCsiSequence(str, idx) { + let i = idx; + while (i < str.length) { + const code = str.charCodeAt(i); + if (code >= 0x40 && code <= 0x7e) { + return { next: i + 1, keep: str[i] === 'm' }; + } + i += 1; + } + return { next: str.length, keep: false }; + } + + function sanitizeAnsiForConsole(input) { + const str = String(input || ''); + if (!str) return ''; + let out = ''; + for (let i = 0; i < str.length;) { + const code = str.charCodeAt(i); + if (code === 0x1b || code === 0x9b) { + const start = i; + if (code === 0x9b) { + const parsed = skipAnsiCsiSequence(str, i + 1); + if (parsed.keep) out += str.slice(start, parsed.next); + i = parsed.next; + continue; + } + const next = str.charCodeAt(i + 1); + if (next === 0x5b) { + const parsed = skipAnsiCsiSequence(str, i + 2); + if (parsed.keep) out += str.slice(start, parsed.next); + i = parsed.next; + continue; + } + if (next === 0x5d) { + i = skipAnsiOscSequence(str, i + 2); + continue; + } + if (next === 0x50 || next === 0x58 || next === 0x5e || next === 0x5f) { + i = skipAnsiEscTerminatedSequence(str, i + 2); + continue; + } + if (next >= 0x40 && next <= 0x5f) { + i += 2; + continue; + } + i += 1; + continue; + } + if ((code < 32 || code === 127) && code !== 10 && code !== 13 && code !== 9) { + i += 1; + continue; + } + out += str[i]; + i += 1; + } + return out; + } + + function stripRenderableAnsi(text) { + return String(text || '').replace(ANSI_SGR_RE, ''); + } + + function visibleConsoleText(text) { + return stripRenderableAnsi(text).replace(/…+/g, ''); + } + + function stripDockerStreamFrames(raw) { + const value = String(raw || ''); + if (value.length < 8) return value; + let out = ''; + let usedFrames = false; + for (let i = 0; i < value.length;) { + const c0 = value.charCodeAt(i); + if ( + (c0 === 1 || c0 === 2 || c0 === 3) && + value.charCodeAt(i + 1) === 0 && + value.charCodeAt(i + 2) === 0 && + value.charCodeAt(i + 3) === 0 && + i + 8 <= value.length + ) { + const frameLen = ( + ((value.charCodeAt(i + 4) & 0xff) << 24) | + ((value.charCodeAt(i + 5) & 0xff) << 16) | + ((value.charCodeAt(i + 6) & 0xff) << 8) | + (value.charCodeAt(i + 7) & 0xff) + ) >>> 0; + if (frameLen === 0) { + usedFrames = true; + i += 8; + continue; + } + if (i + 8 + frameLen <= value.length) { + out += value.slice(i + 8, i + 8 + frameLen); + i += 8 + frameLen; + usedFrames = true; + continue; + } + } + out += value[i]; + i += 1; + } + return usedFrames ? out : value; + } + + function normalizeAiServerNameCandidate(raw) { + let name = String(raw || '').trim(); + if (!name) return ''; + if (name.includes('..') || /[\/\\]/.test(name) || name.length > 120) return ''; + name = name.replace(/\s+/g, '-').replace(/[^\w\-_.]/g, '').replace(/^-+|-+$/g, ''); + return name; + } + + function formatFileSize(bytes) { + const size = Number(bytes); + if (!Number.isFinite(size) || size < 0) return 'Unknown size'; + if (size < 1024) return `${size} B`; + const units = ['KB', 'MB', 'GB', 'TB']; + let value = size / 1024; + let unitIndex = 0; + while (value >= 1024 && unitIndex < units.length - 1) { + value /= 1024; + unitIndex += 1; + } + const precision = value >= 100 ? 0 : value >= 10 ? 1 : 2; + return `${value.toFixed(precision).replace(/\.0+$|(\.\d*[1-9])0+$/, '$1')} ${units[unitIndex]}`; + } + + function flashBar(barId) { + const fill = document.getElementById(barId); + if (!fill) return; + fill.classList.remove('complete'); + fill.style.width = '0%'; + void fill.offsetWidth; + fill.style.width = '70%'; + setTimeout(() => { fill.style.width = '90%'; }, 150); + setTimeout(() => { fill.classList.add('complete'); }, 300); + setTimeout(() => { fill.classList.remove('complete'); fill.style.width = '0%'; }, 1100); + } + function flashFilesBar() { flashBar('filesFlashFill'); } + function flashEditorBar() { flashBar('editorFlashFill'); } + + const sio = window.io; + let socket; + + if (typeof sio !== "function") { + console.error("Socket.IO client not loaded. Console features will be disabled."); + socket = { + on: () => { }, + off: () => { }, + emit: () => { }, + connected: false + }; + } else { + try { + socket = sio(); + } catch (err) { + console.error("Failed to initialize Socket.IO:", err); + socket = { + on: () => { }, + off: () => { }, + emit: () => { }, + connected: false + }; + } + } + const bootstrapUser = window.__ADPANEL_BOOTSTRAP__ && window.__ADPANEL_BOOTSTRAP__.currentUser + ? window.__ADPANEL_BOOTSTRAP__.currentUser + : null; + const currentUser = bootstrapUser || null; + + function getRequestedAssistantBotAction() { + const params = new URLSearchParams(window.location.search || ""); + return String(params.get("assistantAction") || "").trim(); + } + + let assistantActionHandlers = null; + let assistantRequestedActionConsumed = false; + + function clearRequestedAssistantBotAction() { + const url = new URL(window.location.href); + if (!url.searchParams.has("assistantAction")) return; + url.searchParams.delete("assistantAction"); + const nextSearch = url.searchParams.toString(); + const nextUrl = `${url.pathname}${nextSearch ? `?${nextSearch}` : ""}${url.hash || ""}`; + try { + window.history.replaceState({}, "", nextUrl); + } catch { + } + } + + function runRequestedAssistantBotAction(actionHandlers) { + if (assistantRequestedActionConsumed) return; + const requestedAction = getRequestedAssistantBotAction(); + if (!requestedAction) return; + const handler = actionHandlers?.[requestedAction]; + if (typeof handler !== "function") return; + assistantRequestedActionConsumed = true; + + window.setTimeout(() => { + try { + handler(); + clearRequestedAssistantBotAction(); + } catch (error) { + console.error("[assistant-bot-action] failed:", error); + } + }, 160); + } + + const sidebarToggle = document.getElementById('sidebarToggle'); + const floatingSidebar = document.getElementById('floatingSidebar'); + const profileCard = document.getElementById('profileCard'); + const statusPopover = document.getElementById('statusPopover'); + const statusInput = document.getElementById('statusInput'); + const statusDuration = document.getElementById('statusDuration'); + const saveStatus = document.getElementById('saveStatus'); + const cancelStatus = document.getElementById('cancelStatus'); + const profileStatusLabel = document.getElementById('profileStatusLabel'); + const statusDot = document.querySelector('.status-dot'); + let profileEmailEl = null; + const STATUS_KEY = 'adpanel-profile-status'; + function bindUiActions() { + function setupCustomSelect(wrapper) { + const select = wrapper.querySelector('select'); + const customSelect = wrapper.querySelector('.custom-select'); + const customOptions = wrapper.querySelector('.custom-options'); + const currentSpan = customSelect.querySelector('.current'); + + if (!select || !customSelect || !customOptions) return; + + if (customOptions.children.length === 0 && select.options.length > 0) { + Array.from(select.options).forEach(opt => { + const div = document.createElement('div'); + div.className = 'option'; + div.dataset.value = opt.value; + div.textContent = opt.textContent; + if (opt.selected) div.classList.add('selected'); + customOptions.appendChild(div); + }); + if (select.selectedIndex >= 0) { + currentSpan.textContent = select.options[select.selectedIndex].textContent; + } + } + + customSelect.addEventListener('click', (e) => { + e.stopPropagation(); + document.querySelectorAll('.custom-select').forEach(el => { + if (el !== customSelect) { + el.classList.remove('open'); + const otherWrapper = el.closest('.custom-select-wrapper'); + if (otherWrapper) otherWrapper.querySelector('.custom-options')?.classList.remove('show'); + } + }); + + customSelect.classList.toggle('open'); + customOptions.classList.toggle('show'); + }); + + customOptions.addEventListener('click', (e) => { + if (!e.target.classList.contains('option') && !e.target.classList.contains('custom-option')) return; + const value = e.target.dataset.value; + const text = e.target.textContent; + + currentSpan.textContent = text; + wrapper.querySelectorAll('.option, .custom-option').forEach(el => el.classList.remove('selected')); + e.target.classList.add('selected'); + + select.value = value; + select.dispatchEvent(new Event('change')); + + customSelect.classList.remove('open'); + customOptions.classList.remove('show'); + }); + } + + document.querySelectorAll('.custom-select-wrapper').forEach(setupCustomSelect); + + document.addEventListener('click', (e) => { + if (!e.target.closest('.custom-select-wrapper')) { + document.querySelectorAll('.custom-select').forEach(el => el.classList.remove('open')); + document.querySelectorAll('.custom-options').forEach(el => el.classList.remove('show')); + } + }); + + const actionHandlers = { + "open-files": () => openFilesModal(), + + "open-task": () => openTaskModal(), + "open-store": () => openStoreModal(), + "open-info": () => openInfoModal(), + "open-activity": () => openActivityModal(), + "open-backups": () => openBackupsModal(), + "open-scheduler": () => openSchedulerModal(), + "open-planner": () => openPlannerModal(), + "open-resource-stats": () => openResourceStatsPopup(), + "open-ai-help": () => openAiHelpModal(), + "open-reinstall": () => openReinstallModal(), + "run": () => run(), + "stop": () => stop(), + "kill": () => killServer(), + "send": () => sendCommand(), + "clear": () => clearConsole(), + "create-new": () => createNew(), + "go-home": () => { window.location = "/"; }, + "open-subdomains": () => openSubdomainsModal(), + }; + + document.querySelectorAll('[data-action]').forEach((el) => { + if (el.dataset.actionBound) return; + const action = actionHandlers[el.dataset.action]; + if (!action) return; + el.dataset.actionBound = "1"; + el.addEventListener('click', (e) => { + e.preventDefault(); + if ( + el.classList.contains('disabled') || + el.getAttribute('aria-disabled') === 'true' || + (typeof el.disabled === 'boolean' && el.disabled) + ) return; + action(); + }); + }); + assistantActionHandlers = actionHandlers; + + const listEl = document.getElementById("list"); + if (listEl && !listEl.dataset.versionBound) { + listEl.dataset.versionBound = "1"; + listEl.addEventListener("click", (e) => { + const btn = e.target.closest("button[data-version]"); + if (!btn) return; + e.preventDefault(); + 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)); + }); + } + + const breadcrumbsEl = document.getElementById("breadcrumbs"); + if (breadcrumbsEl && !breadcrumbsEl.dataset.bound) { + breadcrumbsEl.dataset.bound = "1"; + breadcrumbsEl.addEventListener("click", (e) => { + const link = e.target.closest("a[data-path]"); + if (!link) return; + e.preventDefault(); + const path = link.getAttribute("data-path") || ""; + loadExplorer(path); + }); + } + } + if (document.readyState === "loading") { + document.addEventListener("DOMContentLoaded", bindUiActions); + } else { + bindUiActions(); + } + function applyStatus(statusObj) { + if (!statusObj || (statusObj.expiresAt && Date.now() > statusObj.expiresAt)) { + profileStatusLabel.textContent = 'Available'; + if (statusDot) statusDot.style.background = '#22c55e'; + localStorage.removeItem(STATUS_KEY); + return; + } + profileStatusLabel.textContent = statusObj.text || 'Available'; + if (statusDot) statusDot.style.background = '#38bdf8'; + } + function loadStatus() { + fetch('/api/me/status') + .then(res => res.json()) + .then(data => { + if (data.ok && data.status) { + applyStatus(data.status); + } else { + applyStatus(null); + } + }) + .catch(() => applyStatus(null)); + } + function persistStatus(text, duration) { + let expiresAt = null; + if (duration !== 'never') { + const ms = parseInt(duration, 10); + if (!Number.isNaN(ms)) expiresAt = Date.now() + ms; + } + const payload = { text: text || 'Available', expiresAt }; + fetch('/api/me/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }) + .then(res => res.json()) + .then(data => { + if (data.ok) { + applyStatus(payload); + } + }) + .catch(err => console.error('Failed to save status:', err)); + } + function setSidebar(open) { + if (!floatingSidebar || !sidebarToggle) return; + if (open) { + floatingSidebar.classList.add('open'); + sidebarToggle.classList.add('active'); + return; + } + floatingSidebar.classList.remove('open'); + sidebarToggle.classList.remove('active'); + if (statusPopover) statusPopover.classList.remove('show'); + } + function toggleSidebar() { + const isOpen = floatingSidebar && floatingSidebar.classList.contains('open'); + setSidebar(!isOpen); + } + setSidebar(true); + if (sidebarToggle) { + sidebarToggle.addEventListener('click', (e) => { + e.stopPropagation(); + toggleSidebar(); + }); + } + if (profileCard) { + profileCard.addEventListener('click', (e) => { + e.stopPropagation(); + if (!floatingSidebar || !floatingSidebar.classList.contains('open')) return; + if (statusPopover) { + const showing = statusPopover.classList.toggle('show'); + if (showing && statusInput) statusInput.focus(); + } + }); + } + if (saveStatus) { + saveStatus.addEventListener('click', () => { + const text = statusInput ? statusInput.value.trim() : ''; + const duration = statusDuration ? statusDuration.value : 'never'; + persistStatus(text, duration); + if (statusPopover) statusPopover.classList.remove('show'); + }); + } + if (cancelStatus) { + cancelStatus.addEventListener('click', () => { + if (statusPopover) statusPopover.classList.remove('show'); + }); + } + document.addEventListener('click', (e) => { + if (statusPopover && statusPopover.classList.contains('show')) { + const clickInsidePopover = statusPopover.contains(e.target); + const clickOnProfile = profileCard && profileCard.contains(e.target); + if (!clickInsidePopover && !clickOnProfile) statusPopover.classList.remove('show'); + } + }); + window.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + setSidebar(false); + if (statusPopover) statusPopover.classList.remove('show'); + } + }); + loadStatus(); + let REMOTE_MODE = false; + let NODE_ONLINE = true; + function setNodeOnline(isOnline) { + NODE_ONLINE = !!isOnline; + updateOfflineState(!NODE_ONLINE); + } + let NODE_ID = null; + let NODE_API_BASE = `/api/nodes/server/${encodeURIComponent(bot)}`; + let NODE_MAX_UPLOAD_MB = 0; + let NODE_MAX_UPLOAD_BYTES = 0; + 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; + function clearRemoteLogFallbackTimer() { + if (remoteLogFallbackTimer) { + clearTimeout(remoteLogFallbackTimer); + remoteLogFallbackTimer = null; + } + } + function ensureSocketConsoleJoin() { + if (!socket || !socket.connected) return; + socket.emit("join", bot); + } + function enableRemoteSocketLogFallback() { + remoteLogTransport = 'socket'; + clearRemoteLogFallbackTimer(); + try { + if (logSource) { + logSource.close(); + logSource = null; + } + } catch { } + activeRemoteLogUrl = ''; + ensureSocketConsoleJoin(); + } + function closeRemoteLogEventSource() { + clearRemoteLogFallbackTimer(); + try { + if (logSource) { + logSource.close(); + logSource = null; + } + } catch { } + activeRemoteLogUrl = ''; + } + function getRemoteLogTailCount(preferredTail = null) { + const explicitTail = Number(preferredTail); + if (Number.isFinite(explicitTail) && explicitTail >= 0) { + return Math.max(0, Math.trunc(explicitTail)); + } + return 0; + } + function buildRemoteLogsUrl(tailCount = null) { + const params = new URLSearchParams(); + params.set('tail', String(getRemoteLogTailCount(tailCount))); + return `${NODE_API_BASE}/logs?${params.toString()}`; + } + function attachLogStreamIfRemote(options = {}) { + const { forceReconnect = false, tail = null } = options || {}; + if (!REMOTE_MODE || !hasConsoleReadAccess()) { + remoteLogTransport = 'none'; + 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; + } + remoteLogTransport = 'eventsource'; + closeRemoteLogEventSource(); + 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.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 }); + } + } catch { + appendToConsole(ev.data || "", { live: true }); + } + }; + es.onerror = () => { + if (remoteLogTransport === 'eventsource') { + console.warn('[remote-logs] SSE stream failed, falling back to socket transport'); + enableRemoteSocketLogFallback(); + } + }; + } + window.addEventListener('beforeunload', () => { + closeRemoteLogEventSource(); + }); + function updateOfflineState(isOffline) { + const overlay = document.getElementById('offlineOverlay'); + if (!overlay) return; + if (isOffline) overlay.classList.add('show'); + else overlay.classList.remove('show'); + } + + function finiteUploadNumber(value) { + const num = Number(value); + return Number.isFinite(num) ? num : null; + } + + function setServerDiskSnapshot(snapshot) { + if (!snapshot || typeof snapshot !== 'object') return; + const usedBytes = finiteUploadNumber(snapshot.usedBytes); + const limitBytes = finiteUploadNumber(snapshot.limitBytes); + if (usedBytes != null) SERVER_DISK_USED_BYTES = Math.max(0, usedBytes); + if (limitBytes != null) SERVER_DISK_LIMIT_BYTES = limitBytes > 0 ? Math.max(0, limitBytes) : 0; + } + + function updateUploadLimitsFromInfo(info) { + if (!info || typeof info !== 'object') return; + const maxUploadBytes = finiteUploadNumber(info.maxUploadBytes); + const maxUploadMb = finiteUploadNumber(info.maxUploadMb ?? info.max_upload_mb); + if (maxUploadBytes && maxUploadBytes > 0) { + NODE_MAX_UPLOAD_BYTES = maxUploadBytes; + NODE_MAX_UPLOAD_MB = maxUploadBytes / (1024 * 1024); + } else if (maxUploadMb && maxUploadMb > 0) { + NODE_MAX_UPLOAD_MB = maxUploadMb; + NODE_MAX_UPLOAD_BYTES = maxUploadMb * 1024 * 1024; + } + if (info.disk) setServerDiskSnapshot(info.disk); + } + + async function topoInfo() { + try { + const r = await fetch(`${NODE_API_BASE}/info`); + if (r.status === 429 || r.status === 401 || r.status === 403) { + return null; + } + if (!r.ok) throw new Error('nodes info not ok'); + const j = await r.json(); + REMOTE_MODE = !!j.remote; NODE_ID = j.nodeId || null; + updateUploadLimitsFromInfo(j); + return j; + } catch (e) { + REMOTE_MODE = false; NODE_ID = null; + return null; + } + } + topoInfoPromise = topoInfo(); + + async function ensureUploadLimitsReady() { + if (topoInfoPromise) { + await topoInfoPromise.catch(() => null); + } + if (!NODE_MAX_UPLOAD_BYTES || SERVER_DISK_LIMIT_BYTES === null) { + await topoInfo().catch(() => null); + } + } + + function getKnownReplacementBytes(file) { + const name = String(file?.name || ''); + if (!name || !currentExplorerEntryMeta.has(name)) return 0; + const known = currentExplorerEntryMeta.get(name); + if (!known || known.isDir) return 0; + const size = finiteUploadNumber(known.size); + return size && size > 0 ? size : 0; + } + + function validateUploadCandidate(file) { + const size = Math.max(0, finiteUploadNumber(file?.size) || 0); + const name = String(file?.name || 'file'); + if (NODE_MAX_UPLOAD_BYTES > 0 && size > NODE_MAX_UPLOAD_BYTES) { + throw new Error(`"${name}" is ${formatBytes(size)}, above this node's max single-file upload size of ${formatBytes(NODE_MAX_UPLOAD_BYTES)}.`); + } + if (SERVER_DISK_LIMIT_BYTES && SERVER_DISK_LIMIT_BYTES > 0 && SERVER_DISK_USED_BYTES != null) { + const replacedBytes = getKnownReplacementBytes(file); + const extraBytes = Math.max(0, size - replacedBytes); + const remainingBytes = Math.max(0, SERVER_DISK_LIMIT_BYTES - SERVER_DISK_USED_BYTES); + if (extraBytes > remainingBytes) { + throw new Error(`"${name}" would exceed this server's disk limit. Remaining: ${formatBytes(remainingBytes)}; file: ${formatBytes(size)}.`); + } + } + } + + function accountForSuccessfulUpload(file) { + const name = String(file?.name || ''); + if (!name) return; + const size = Math.max(0, finiteUploadNumber(file?.size) || 0); + if (SERVER_DISK_LIMIT_BYTES && SERVER_DISK_LIMIT_BYTES > 0 && SERVER_DISK_USED_BYTES != null) { + SERVER_DISK_USED_BYTES += Math.max(0, size - getKnownReplacementBytes(file)); + } + currentExplorerEntryMeta.set(name, { isDir: false, size }); + } + + async function apiExplore(path = "") { + const url = REMOTE_MODE + ? `${NODE_API_BASE}/entries?path=${encodeURIComponent(path)}` + : `/api/servers/${encodeURIComponent(bot)}/files/list?path=${encodeURIComponent(path)}`; + const r = await fetch(url); + if (!r.ok) throw new Error('explore failed'); + return await r.json(); + } + async function apiReadFile(relPath) { + if (!REMOTE_MODE) { + socket.emit("readFile", { bot, path: relPath }); + return null; + } + const r = await fetch(`${NODE_API_BASE}/file?path=${encodeURIComponent(relPath)}`); + if (!r.ok) throw new Error('read file failed'); + const j = await r.json(); + return j && typeof j.content === 'string' ? j.content : ''; + } + async function apiWriteFile(relPath, content) { + if (!REMOTE_MODE) { + socket.emit("writeFile", { bot, path: relPath, content }); + return true; + } + const r = await fetch(`${NODE_API_BASE}/file`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ path: relPath, content }) + }); + if (r.status === 507) { + const j = await r.json().catch(() => null); + throw new Error((j && j.message) || 'Disk space limit exceeded. Free up space or increase the storage limit.'); + } + if (!r.ok) throw new Error('write file failed'); + return true; + } + async function apiDelete(relPath, isDir) { + if (!REMOTE_MODE) { + socket.emit("deleteFile", { bot, path: relPath, isDir }); + return true; + } + const r = await fetch(`${NODE_API_BASE}/delete`, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ path: relPath, isDir: !!isDir }) + }); + if (!r.ok) throw new Error('delete failed'); + return true; + } + async function apiRename(oldPath, newName) { + const url = REMOTE_MODE ? `${NODE_API_BASE}/rename` : '/rename'; + const payload = REMOTE_MODE + ? { path: oldPath, newName } + : { bot, oldPath, newName }; + const r = await fetch(url, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + if (!r.ok) throw new Error(await r.text().catch(() => r.statusText)); + return true; + } + async function apiExtract(relPath) { + const url = REMOTE_MODE ? `${NODE_API_BASE}/extract` : '/extract'; + const payload = REMOTE_MODE ? { path: relPath } : { bot, path: relPath }; + const requestOptions = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }; + const r = REMOTE_MODE + ? await fetch(url, requestOptions) + : await fetchWithServerActionToken(url, requestOptions, 'fileExtract'); + const j = await r.json().catch(() => ({})); + if (r.status === 507 || (j && j.error === 'disk_limit_exceeded')) { + throw new Error(j.message || 'This server has exceeded its disk space limit. Delete files to free space before extracting.'); + } + if (!r.ok || !j.ok) throw new Error((j && j.error) ? j.error : 'extract failed'); + return j; + } + async function apiArchive(paths, destDir) { + const url = REMOTE_MODE ? `${NODE_API_BASE}/archive` : '/archive'; + const payload = REMOTE_MODE ? { paths, destDir } : { bot, paths, destDir }; + const requestOptions = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }; + const r = REMOTE_MODE + ? await fetch(url, requestOptions) + : await fetchWithServerActionToken(url, requestOptions, 'fileArchive'); + const j = await r.json().catch(() => ({})); + if (r.status === 507 || (j && j.error === 'disk_limit_exceeded')) { + throw new Error(j.message || 'This server has exceeded its disk space limit. Delete files to free space before archiving.'); + } + if (!r.ok || !j.ok) throw new Error((j && j.error) ? j.error : 'archive failed'); + return j; + } + function apiDownloadFile(relPath) { + const url = REMOTE_MODE + ? `${NODE_API_BASE}/download?path=${encodeURIComponent(relPath)}` + : `/api/servers/${encodeURIComponent(bot)}/files/download?path=${encodeURIComponent(relPath)}`; + const a = document.createElement('a'); + a.href = url; + a.download = relPath.split('/').pop() || 'download'; + a.style.display = 'none'; + document.body.appendChild(a); + a.click(); + setTimeout(() => a.remove(), 500); + } + const FILE_SIZE_EDITOR_LIMIT = 5000 * 1024; + const explorerEntryCollator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); + + function normalizeExplorerEntry(rawEntry) { + return { + name: String(rawEntry?.name ?? ''), + isDir: !!(rawEntry?.isDir || rawEntry?.type === "dir"), + size: rawEntry?.size + }; + } + + function compareExplorerEntries(a, b) { + if (a.isDir !== b.isDir) return a.isDir ? -1 : 1; + return explorerEntryCollator.compare(a.name, b.name); + } + + let currentUserPreferences = {}; + const CLEAR_CONSOLE_NO_ASK_STORAGE_KEY = `adpanel:clear-console-no-ask:${String(currentUser?.email || 'browser').toLowerCase()}`; + const FILE_BACKUPS_STORAGE_KEY = `adpanel:file-backups:${bot}`; + const fileBackupDrafts = new Map(); + + function loadClearConsoleNoAskFromStorage() { + try { + const raw = localStorage.getItem(CLEAR_CONSOLE_NO_ASK_STORAGE_KEY); + return raw === '1' || raw === 'true'; + } catch { + return false; + } + } + + function saveClearConsoleNoAskToStorage(value) { + try { + if (value) localStorage.setItem(CLEAR_CONSOLE_NO_ASK_STORAGE_KEY, '1'); + else localStorage.removeItem(CLEAR_CONSOLE_NO_ASK_STORAGE_KEY); + } catch { } + } + + function mergeCurrentUserPreferences(preferences) { + const incoming = preferences && typeof preferences === 'object' ? preferences : {}; + currentUserPreferences = { ...currentUserPreferences, ...incoming }; + if (loadClearConsoleNoAskFromStorage()) { + currentUserPreferences.clear_console_no_ask = true; + } + } + + mergeCurrentUserPreferences({}); + + function normalizeFileBackupPath(filePath) { + return String(filePath || '').replace(/\\/g, '/').trim(); + } + + function loadFileBackupsFromStorage() { + fileBackupDrafts.clear(); + try { + const raw = localStorage.getItem(FILE_BACKUPS_STORAGE_KEY); + if (!raw) return fileBackupDrafts; + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return fileBackupDrafts; + for (const [path, value] of Object.entries(parsed)) { + const cleanPath = normalizeFileBackupPath(path); + if (!cleanPath) continue; + if (typeof value === 'string') { + fileBackupDrafts.set(cleanPath, value); + continue; + } + if (value && typeof value === 'object' && typeof value.content === 'string') { + fileBackupDrafts.set(cleanPath, value.content); + } + } + } catch (err) { + console.warn('[FileBackups] Failed to load draft backups from storage:', err); + try { localStorage.removeItem(FILE_BACKUPS_STORAGE_KEY); } catch { } + } + return fileBackupDrafts; + } + + async function loadMeIntoProfileEmail() { + if (!profileEmailEl) profileEmailEl = document.getElementById('profileEmail'); + + if (currentUser && typeof currentUser === 'object') { + const email = String(currentUser.email || '').trim(); + if (email && profileEmailEl) profileEmailEl.textContent = email; + if (currentUser.preferences && typeof currentUser.preferences === 'object') { + mergeCurrentUserPreferences(currentUser.preferences); + } + if (email) return; + } + + try { + const res = await fetch('/api/me', { credentials: 'include' }); + if (!res.ok) return; + + const data = await res.json().catch(() => null); + if (data && data.user) { + const email = data.user.email; + if (email && profileEmailEl) profileEmailEl.textContent = email; + if (data.user.preferences) mergeCurrentUserPreferences(data.user.preferences); + } + } catch (err) { + console.warn('Fetch error in /api/me:', err); + } + } + function apiUploadWithProgress(file, currentPath, onProgress, baseMsg) { + return new Promise((resolve, reject) => { + (async () => { + try { + await ensureUploadLimitsReady(); + validateUploadCandidate(file); + const fd = new FormData(); + if (!REMOTE_MODE) { fd.append('bot', bot); } + fd.append('path', currentPath || ''); + fd.append('file', file); + + const xhr = new XMLHttpRequest(); + xhr.open('POST', REMOTE_MODE ? `${NODE_API_BASE}/upload` : '/upload'); + + if (!REMOTE_MODE) { + const uploadToken = await ensureServerActionToken('fileUpload', { refresh: true }); + if (uploadToken) { + xhr.setRequestHeader('x-action-token', uploadToken); + } + } + + xhr.upload.onprogress = (e) => { if (e.lengthComputable) { const pct = Math.round((e.loaded / e.total) * 100); onProgress(pct, `${baseMsg} (${pct}%)`); } else onProgress(6, `${baseMsg}...`); }; + xhr.onload = () => { + if (xhr.status >= 200 && xhr.status < 300) { + try { const j = JSON.parse(xhr.responseText || "{}"); onProgress(100, j && j.msg ? j.msg : "Finalizing..."); } catch { } + accountForSuccessfulUpload(file); + resolve(); + } else if (xhr.status === 413) { + try { + const j = JSON.parse(xhr.responseText || "{}"); + reject(new Error(j.message || `File too large. Maximum upload size for this node is ${j.limit_mb ? j.limit_mb + ' MB' : 'exceeded'}.`)); + return; + } catch { } + reject(new Error('File too large for this node. Increase the upload limit in node settings.')); + } else if (xhr.status === 507) { + try { + const j = JSON.parse(xhr.responseText || "{}"); + if (j.error === 'disk_limit_exceeded') { + reject(new Error(j.message || 'Disk space limit exceeded. Free up space or increase the storage limit.')); + return; + } + } catch { } + reject(new Error('Disk space limit exceeded')); + } else { + reject(new Error(xhr.responseText || xhr.statusText || ('status ' + xhr.status))); + } + }; + xhr.onerror = () => reject(new Error('Network error')); + xhr.send(fd); + } catch (error) { + reject(error); + } + })(); + }); + } + async function apiCreate(type, name, currentPath) { + const url = REMOTE_MODE ? `${NODE_API_BASE}/create` : '/create'; + const payload = REMOTE_MODE + ? { type, name, path: currentPath || '' } + : { bot, type, name, path: currentPath || '' }; + const r = await fetch(url, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + if (r.status === 507) { + const j = await r.json().catch(() => null); + throw new Error((j && j.message) || 'Disk space limit exceeded. Free up space or increase the storage limit.'); + } + if (!r.ok) throw new Error(await r.text().catch(() => r.statusText)); + return true; + } + function normalizeServerPowerAction(value) { + const action = String(value || '').trim().toLowerCase(); + if (!action) return ''; + if (action === 'run') return 'start'; + if (action === 'shutdown') return 'stop'; + return action; + } + function createServerActionError(code, message, extra = {}) { + const err = new Error(message || 'Server action failed.'); + err.code = code || 'server_action_failed'; + Object.assign(err, extra); + return err; + } + function buildServerActionError(action, serverName, payload = null, status = null) { + const target = normalizeAiServerNameCandidate(serverName) || normalizeAiServerNameCandidate(bot) || 'server'; + const info = payload && typeof payload === 'object' ? payload : {}; + const errorCode = String(info.error || '').trim().toLowerCase(); + const detail = String(info.detail || info.message || '').trim(); + if (errorCode === 'permission denied') { + return createServerActionError('permission_denied', `You do not have permission to ${action} ${target}.`, { + action, + serverName: target, + permission: info.permission || null, + status + }); + } + if (errorCode === 'no access to server') { + return createServerActionError('access_denied', `You do not have access to ${target}.`, { + action, + serverName: target, + status + }); + } + if (errorCode === 'server not found') { + return createServerActionError('server_not_found', `${target} was not found.`, { + action, + serverName: target, + status + }); + } + if (errorCode === 'not_remote') { + return createServerActionError('not_remote', `${target} is not attached to a node.`, { + action, + serverName: target, + status + }); + } + if (status === 403) { + return createServerActionError('permission_denied', `You do not have permission to ${action} ${target}.`, { + action, + serverName: target, + permission: info.permission || null, + status + }); + } + return createServerActionError(errorCode || 'server_action_failed', detail || info.error || `Request failed${status ? ` (HTTP ${status})` : '.'}`, { + action, + serverName: target, + status + }); + } + function socketRequest(eventName, payload, timeoutMs = 12000) { + return new Promise((resolve, reject) => { + if (!socket || typeof socket.emit !== 'function') { + reject(createServerActionError('socket_unavailable', 'Realtime connection unavailable.')); + return; + } + let settled = false; + const timer = setTimeout(() => { + if (settled) return; + settled = true; + reject(createServerActionError('timeout', 'No reply from the panel.')); + }, timeoutMs); + try { + socket.emit(eventName, payload, (response) => { + if (settled) return; + settled = true; + clearTimeout(timer); + resolve(response || {}); + }); + } catch (err) { + if (settled) return; + settled = true; + clearTimeout(timer); + reject(err instanceof Error ? err : createServerActionError('socket_emit_failed', String(err || 'Socket request failed.'))); + } + }); + } + async function requestSocketServerAction(serverName, action, hostPort = null) { + const target = normalizeAiServerNameCandidate(serverName) || normalizeAiServerNameCandidate(bot); + const normalizedAction = normalizeServerPowerAction(action); + if (!target) throw createServerActionError('missing_server', 'No server selected.'); + if (!normalizedAction) throw createServerActionError('invalid_action', 'Invalid server action.'); + const ack = await socketRequest('action', { + bot: target, + cmd: normalizedAction === 'start' ? 'run' : normalizedAction, + ...(hostPort != null ? { port: hostPort } : {}) + }); + if (!ack || ack.ok === false) { + throw buildServerActionError(normalizedAction, target, ack); + } + return { confirmed: true, via: 'socket' }; + } + async function requestHttpServerAction(serverName, action, hostPort = null) { + const target = normalizeAiServerNameCandidate(serverName) || normalizeAiServerNameCandidate(bot); + const normalizedAction = normalizeServerPowerAction(action); + if (!target) throw createServerActionError('missing_server', 'No server selected.'); + if (!normalizedAction) throw createServerActionError('invalid_action', 'Invalid server action.'); + try { + const response = await fetch(`/api/nodes/server/${encodeURIComponent(target)}/action`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + cmd: normalizedAction, + ...(hostPort != null ? { hostPort } : {}) + }) + }); + const data = await response.json().catch(() => null); + if (!response.ok) { + if (response.status === 400 && data && data.error === 'not_remote') { + return requestSocketServerAction(target, normalizedAction, hostPort); + } + throw buildServerActionError(normalizedAction, target, data, response.status); + } + if (data && data.ok === false) { + throw buildServerActionError(normalizedAction, target, data, response.status); + } + return { confirmed: true, via: 'http' }; + } catch (err) { + if (err && err.code) throw err; + const message = String((err && err.message) || ''); + if (/Failed to fetch|NetworkError|Load failed/i.test(message)) { + return requestSocketServerAction(target, normalizedAction, hostPort); + } + throw createServerActionError('server_action_failed', message || 'Server action failed.', { + action: normalizedAction, + serverName: target + }); + } + } + async function apiAction(data) { + const target = normalizeAiServerNameCandidate(data && data.bot) || normalizeAiServerNameCandidate(bot); + const action = normalizeServerPowerAction(data && data.cmd); + const rawHostPort = data && (data.hostPort ?? data.port); + const hostPort = rawHostPort == null || rawHostPort === '' ? null : Number(rawHostPort); + if (REMOTE_MODE) { + await requestHttpServerAction(target, action, Number.isFinite(hostPort) ? hostPort : null); + return true; + } + await requestSocketServerAction(target, action, Number.isFinite(hostPort) ? hostPort : null); + return true; + } + async function apiCommand(command, sentAt = Date.now(), requestId = "") { + const trimmed = String(command || '').trim(); + if (!trimmed) throw new Error('empty_command'); + const commandRequestId = String(requestId || '').trim(); + const commandPayload = commandRequestId + ? { bot, command: trimmed, requestId: commandRequestId } + : { bot, command: trimmed }; + + if (!REMOTE_MODE) { + const ack = await socketRequest('command', commandPayload); + if (!ack || ack.ok === false) { + const msg = String((ack && (ack.error || ack.detail)) || 'command_failed'); + throw new Error(msg); + } + scheduleConsoleHistoryResync(trimmed, sentAt); + return true; + } + + 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 }) + }); + + const payload = await r.json().catch(async () => { + const text = await r.text().catch(() => ''); + return text ? { error: text } : {}; + }); + + if (!r.ok || (payload && payload.ok === false)) { + const message = String((payload && (payload.detail || payload.error)) || r.statusText || 'Command failed'); + throw new Error(message); + } + scheduleConsoleHistoryResync(trimmed, sentAt); + return true; + } + let IS_ADMIN = false; + let AGENT_ACCESS = false; + let SERVER_ACTION_TOKENS = {}; + let serverActionTokensLoadedAt = 0; + const SERVER_ACTION_TOKEN_REFRESH_MS = 4 * 60 * 1000; + const INVALID_ACTION_TOKEN_ERROR = 'invalid or missing action token'; + const ONE_TIME_SERVER_ACTION_TOKENS = new Set(['fileDelete', 'fileRename', 'changeTemplate', 'applyVersion']); + let PERMS = { + files_read: false, files_delete: false, files_rename: false, files_archive: false, console_read: false, console_write: false, + server_stop: false, server_start: false, files_upload: false, files_create: false, + activity_logs: false, backups_view: false, backups_create: false, backups_delete: false, + scheduler_access: false, scheduler_create: false, scheduler_delete: false, store_access: false, + server_reinstall: false, agent_settings: false + }; + function hasPerm(k) { return IS_ADMIN || !!PERMS[k]; } + function hasConsoleReadAccess() { return hasPerm('console_read'); } + function hasAgentAccess() { return IS_ADMIN || AGENT_ACCESS; } + function getServerActionToken(tokenKey) { + return String(SERVER_ACTION_TOKENS?.[tokenKey] || '').trim(); + } + function shouldRefreshServerActionToken(tokenKey) { + if (!tokenKey) return false; + if (ONE_TIME_SERVER_ACTION_TOKENS.has(tokenKey)) return true; + if (!serverActionTokensLoadedAt) return true; + return (Date.now() - serverActionTokensLoadedAt) >= SERVER_ACTION_TOKEN_REFRESH_MS; + } + async function readJsonResponseSafe(response) { + try { + return await response.json(); + } catch { + return {}; + } + } + function isInvalidActionTokenErrorPayload(payload) { + return String(payload?.error || '').trim().toLowerCase() === INVALID_ACTION_TOKEN_ERROR; + } + async function ensureServerActionToken(tokenKey, opts = {}) { + const { refresh = false } = opts; + if (!tokenKey) return ''; + + const existingToken = getServerActionToken(tokenKey); + if (!refresh && existingToken && !shouldRefreshServerActionToken(tokenKey)) { + return existingToken; + } + + const refreshed = await fetchPerms({ preserveCurrentState: true }); + if (refreshed && refreshed.actionTokens && typeof refreshed.actionTokens === 'object') { + return String(refreshed.actionTokens[tokenKey] || '').trim(); + } + + return getServerActionToken(tokenKey); + } + async function fetchWithServerActionToken(url, options = {}, tokenKey, opts = {}) { + const { refreshBefore = false, retryOnInvalidToken = true } = opts; + + const runRequest = async (refreshToken) => { + const headers = new Headers(options.headers || {}); + const token = await ensureServerActionToken(tokenKey, { refresh: refreshToken }); + if (token) headers.set('x-action-token', token); + return fetch(url, { ...options, headers }); + }; + + let response = await runRequest(refreshBefore); + if (retryOnInvalidToken && response.status === 403) { + const errData = await readJsonResponseSafe(response.clone()); + if (isInvalidActionTokenErrorPayload(errData)) { + response = await runRequest(true); + } + } + + if (response.ok && ONE_TIME_SERVER_ACTION_TOKENS.has(tokenKey)) { + delete SERVER_ACTION_TOKENS[tokenKey]; + } + + return response; + } + async function writeServerFileWithActionToken(serverName, relPath, content) { + return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/files/write`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ path: relPath, content }) + }, 'fileWrite'); + } + async function createServerFolderWithActionToken(serverName, relPath) { + return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/files/mkdir`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ path: relPath }) + }, 'fileMkdir'); + } + async function deleteServerPathWithActionToken(serverName, relPath, isDir = false) { + return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/files/delete`, { + method: 'DELETE', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ path: relPath, isDir: isDir ? '1' : '0' }) + }, 'fileDelete', { refreshBefore: true }); + } + async function changeServerTemplateWithActionToken(serverName, templateId) { + return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/template`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ template: templateId }) + }, 'changeTemplate', { refreshBefore: true }); + } + async function applyServerVersionWithActionToken(serverName, payload) { + return fetchWithServerActionToken(`/api/servers/${encodeURIComponent(serverName)}/versions/apply`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload || {}) + }, 'applyVersion', { refreshBefore: true }); + } + const consoleEl = document.getElementById("console"); + let consoleContentEl = document.getElementById('consoleContent'); + if (!consoleContentEl) { + consoleContentEl = document.createElement('div'); + consoleContentEl.id = 'consoleContent'; + consoleEl.appendChild(consoleContentEl); + } + const cmdRow = document.getElementById("cmdRow"); + const cmdInput = document.getElementById("cmdInput"); + const sendBtn = document.getElementById("sendBtn"); + const entriesEl = document.getElementById("entries"); + const breadcrumbs = document.getElementById("breadcrumbs"); + const filesModal = document.getElementById("filesModal"); + const filesModalClose = document.getElementById("filesModalClose"); + const fileUploadModal = document.getElementById("fileUploadModal"); + const uploadLabel = document.getElementById("uploadLabel"); + const newBtn = document.getElementById("newBtn"); + const selectAllToggle = document.getElementById("selectAllToggle"); + const bulkDeleteBtn = document.getElementById("bulkDeleteBtn"); + const bulkArchiveBtn = document.getElementById("bulkArchiveBtn"); + const taskModal = document.getElementById("taskModal"); + const taskModalClose = document.getElementById("taskModalClose"); + const taskStartupSelect = document.getElementById("taskStartupSelect"); + const statusLabel = document.getElementById("statusLabel"); + const editorModalClose = document.getElementById("editorModalClose"); + const editorPath = document.getElementById("editorPath"); + const codeShell = document.getElementById("codeShell"); + let editorOriginalContent = ""; + const codePane = document.querySelector('.code-pane'); + const codeOverlay = document.getElementById("codeOverlay"); + const codeInput = document.getElementById("codeInput"); + const lineGutter = document.getElementById("lineGutter"); + const codeSpacer = document.getElementById("codeSpacer"); + const textArea = document.getElementById("textArea"); + const editorSave = document.getElementById("editorSave"); + const editorDiscard = document.getElementById("editorDiscard"); + const editorModal = document.getElementById("editorModal"); + let editorSaving = false; + const monacoContainer = document.getElementById("monacoContainer"); + const aceContainer = document.getElementById("aceContainer"); + let aceEditor = null; + let useAceFallback = null; + let monacoEditor = null; + let monacoLoaderPromise = null; + let monacoFindWidgetObserver = null; + const progressWheel = document.getElementById("progressWheel"); + const progressFill = document.getElementById("progressFill"); + const progressPopup = document.getElementById("progressPopup"); + const popupPercent = document.getElementById("popupPercent"); + const popupBar = document.getElementById("popupBar"); + const popupMsg = document.getElementById("popupMsg"); + const popupTime = document.getElementById("popupTime"); + const popupClose = document.getElementById("popupClose"); + const popupFileList = document.getElementById("popupFileList"); + const dropOverlay = document.getElementById("dropOverlay"); + const dropTitle = document.getElementById("dropTitle"); + const dropSubtitle = document.getElementById("dropSubtitle"); + const infoModal = document.getElementById("infoModal"); + const infoModalClose = document.getElementById("infoModalClose"); + const infoIp = document.getElementById("infoIp"); + const infoPort = document.getElementById("infoPort"); + const infoAddress = document.getElementById("infoAddress"); + const copyAddressBtn = document.getElementById("copyAddressBtn"); + + const infoSftpSection = document.getElementById("infoSftpSection"); + const infoSftpNoAccess = document.getElementById("infoSftpNoAccess"); + const infoSftpHost = document.getElementById("infoSftpHost"); + const infoSftpPort = document.getElementById("infoSftpPort"); + const infoSftpUser = document.getElementById("infoSftpUser"); + const infoSftpPass = document.getElementById("infoSftpPass"); + const infoSftpPassMask = infoSftpPass?.querySelector(".info-sftp-pass-mask"); + const infoSftpPassText = infoSftpPass?.querySelector(".info-sftp-pass-text"); + const infoSftpTogglePass = document.getElementById("infoSftpTogglePass"); + const infoSftpRegenBtn = document.getElementById("infoSftpRegenBtn"); + let currentSftpPassword = null; + let sftpPasswordVisible = false; + + const filesBtn = document.getElementById("filesBtn"); + const taskBtn = document.getElementById("taskBtn"); + const runBtn = document.getElementById("runBtn"); + const stopBtn = document.getElementById("stopBtn"); + const miniRunBtn = document.getElementById("miniRunBtn"); + const miniStopBtn = document.getElementById("miniStopBtn"); + const miniKillBtn = document.getElementById("miniKillBtn"); + const storeBtn = document.getElementById("storeBtn"); + let monacoIdleSuggestTimer = null; + const storeModal = document.getElementById("storeModal"); + const storeModalClose = document.getElementById("storeModalClose"); + const storeContent = document.getElementById("storeContent"); + const storeTabs = document.getElementById("storeTabs"); + const storeTabVersions = document.getElementById("storeTabVersions"); + const storeTabPlugins = document.getElementById("storeTabPlugins"); + const storeSubtitle = document.getElementById("storeSubtitle"); + const storePrefModal = document.getElementById("storePrefModal"); + const storePrefOptions = document.getElementById("storePrefOptions"); + const storePrefClose = document.getElementById("storePrefClose"); + const dockFiles = document.getElementById("dockFiles"); + const dockTask = document.getElementById("dockTask"); + const dockRun = document.getElementById("dockRun"); + const dockStop = document.getElementById("dockStop"); + const dockNew = document.getElementById("dockNew"); + const dockStore = document.getElementById("dockStore"); + const mrPluginModal = document.getElementById("mrPluginModal"); + const mrPluginModalClose = document.getElementById("mrPluginModalClose"); + const mrPluginCancel = document.getElementById("mrPluginCancel"); + const mrPluginName = document.getElementById("mrPluginName"); + const mrPlatformGrid = document.getElementById("mrPlatformGrid"); + const mrVersionGrid = document.getElementById("mrVersionGrid"); + const mrPluginInstallBtn = document.getElementById("mrPluginInstallBtn"); + let currentEditorPath = ""; + let selectedEntries = new Set(); + let serverInfo = null; + let SERVER_NODE_ID = null; + let currentStoreTab = 'versions'; + let storeProvidersCache = null; + let storeCurrentProvider = null; + let papermcVersionsCache = null; + const STORE_PREF_STORAGE_KEY = 'store-preference-map'; + const STORE_PREF_OPTIONS = [ + { + id: 'discord-bot', + title: 'Node.js & Bots', + description: 'Show Node.js runtimes and container versions optimized for Discord or generic bots.', + logo: 'https://nodejs.org/static/images/logo.svg' + }, + { + 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' + }, + { + id: 'fivem', + title: 'FiveM', + description: 'Install Linux FXServer artifacts using the recommended, optional, or a custom build.', + logo: 'https://cdn.jsdelivr.net/gh/antonndev/ADCDn/FiveM-Logo.webp' + } + ]; + let pendingStoreOpen = false; + const JUMP_THRESHOLD = 8; + const MR_PLUGIN_LOADERS = ["paper", "purpur", "spigot", "bukkit", "velocity", "waterfall", "folia"]; + const MR_MOD_LOADERS = ["fabric", "forge", "neoforge", "quilt"]; + const MR_VALID_LOADERS = Array.from(new Set([...MR_PLUGIN_LOADERS, ...MR_MOD_LOADERS])); + let mrPluginsState = { + offset: 0, + limit: 24, + query: "", + loading: false, + more: true + }; + let mrAllProjectVersions = []; + let mrCurrentProjectId = null; + let mrSelectedPlatform = null; + let mrSelectedMcVersion = null; + const POWER_STATE = Object.freeze({ + UNKNOWN: "unknown", + STOPPED: "stopped", + RUNNING: "running", + STARTING: "starting", + STOPPING: "stopping" + }); + const POWER_STATE_LABEL = Object.freeze({ + [POWER_STATE.UNKNOWN]: "idle", + [POWER_STATE.STOPPED]: "stopped", + [POWER_STATE.RUNNING]: "running", + [POWER_STATE.STARTING]: "running", + [POWER_STATE.STOPPING]: "stopped" + }); + const POWER_POLL_IDLE_MS = 6000; + const POWER_POLL_TRANSITION_MS = 2000; + const POWER_TRANSITION_TIMEOUT_MS = 30000; + const powerRunControls = Array.from(document.querySelectorAll('[data-action="run"]')); + const powerStopControls = Array.from(document.querySelectorAll('[data-action="stop"]')); + const powerKillControls = Array.from(document.querySelectorAll('[data-action="kill"]')); + let powerState = POWER_STATE.UNKNOWN; + let powerTransition = null; + let powerTransitionSince = 0; + let powerNodeOnline = true; + let powerPollTimer = null; + let powerPollInFlight = false; + function normalizePowerState(raw) { + const v = String(raw || "").trim().toLowerCase(); + if (!v) return POWER_STATE.UNKNOWN; + if (v.includes("starting")) return POWER_STATE.STARTING; + if (v.includes("stopping")) return POWER_STATE.STOPPING; + if (v.includes("running") || v.includes("online") || v.includes("up") || v.includes("healthy")) return POWER_STATE.RUNNING; + if (v.includes("stopped") || v.includes("offline") || v.includes("down") || v.includes("exit") || v.includes("dead")) return POWER_STATE.STOPPED; + return POWER_STATE.UNKNOWN; + } + function isTransitionPowerState(state) { + return state === POWER_STATE.STARTING || state === POWER_STATE.STOPPING; + } + function setPowerControlDisabled(el, disabled) { + if (!el) return; + el.classList.toggle("disabled", disabled); + el.setAttribute("aria-disabled", disabled ? "true" : "false"); + if (typeof el.disabled === "boolean") { + el.disabled = disabled; + } + } + function canRunNow() { + return hasPerm("server_start") && powerNodeOnline && powerState === POWER_STATE.STOPPED; + } + function canStopNow() { + return hasPerm("server_stop") && powerNodeOnline && powerState === POWER_STATE.RUNNING; + } + function isPowerActionAllowed(action) { + if (action === "run") return canRunNow(); + if (action === "stop") return canStopNow(); + if (action === "kill") return canStopNow(); + return false; + } + function updatePowerStatusLabel() { + if (!statusLabel) return; + statusLabel.textContent = POWER_STATE_LABEL[powerState] || "idle"; + } + function updatePowerControlsInteractivity() { + const enableRun = canRunNow(); + const enableStop = canStopNow(); + powerRunControls.forEach((el) => setPowerControlDisabled(el, !enableRun)); + powerStopControls.forEach((el) => setPowerControlDisabled(el, !enableStop)); + powerKillControls.forEach((el) => setPowerControlDisabled(el, !enableStop)); + } + function setPowerState(nextState, opts = {}) { + const normalized = normalizePowerState(nextState); + const now = Date.now(); + if (normalized === POWER_STATE.STARTING || normalized === POWER_STATE.STOPPING) { + if (powerTransition !== normalized) { + powerTransition = normalized; + powerTransitionSince = now; + } + } else if (normalized === POWER_STATE.RUNNING || normalized === POWER_STATE.STOPPED) { + powerTransition = null; + powerTransitionSince = 0; + } else if (!opts.keepTransition) { + powerTransition = null; + powerTransitionSince = 0; + } + if (powerState !== normalized || opts.force) { + powerState = normalized; + updatePowerStatusLabel(); + } + updatePowerControlsInteractivity(); + } + function applyPolledPowerState(rawState, nodeOnline) { + powerNodeOnline = nodeOnline !== false; + const polled = normalizePowerState(rawState); + const now = Date.now(); + if (polled === POWER_STATE.UNKNOWN && !powerTransition) { + if (powerState === POWER_STATE.RUNNING || powerState === POWER_STATE.STOPPED) { + updatePowerControlsInteractivity(); + return; + } + const seeded = normalizePowerState(serverInfo && serverInfo.status ? serverInfo.status : ""); + if (seeded === POWER_STATE.RUNNING || seeded === POWER_STATE.STOPPED) { + setPowerState(seeded, { force: true }); + return; + } + } + if (powerTransition === POWER_STATE.STARTING) { + if (polled === POWER_STATE.RUNNING) { + setPowerState(POWER_STATE.RUNNING, { force: true }); + return; + } + if (polled === POWER_STATE.STOPPED && now - powerTransitionSince > 5000) { + setPowerState(POWER_STATE.STOPPED, { force: true }); + return; + } + if (now - powerTransitionSince > POWER_TRANSITION_TIMEOUT_MS) { + setPowerState(polled === POWER_STATE.UNKNOWN ? POWER_STATE.STOPPED : polled, { force: true }); + return; + } + setPowerState(POWER_STATE.STARTING, { force: true, keepTransition: true }); + return; + } + if (powerTransition === POWER_STATE.STOPPING) { + if (polled === POWER_STATE.STOPPED) { + setPowerState(POWER_STATE.STOPPED, { force: true }); + return; + } + if (now - powerTransitionSince > POWER_TRANSITION_TIMEOUT_MS) { + setPowerState(polled === POWER_STATE.UNKNOWN ? POWER_STATE.RUNNING : polled, { force: true }); + return; + } + setPowerState(POWER_STATE.STOPPING, { force: true, keepTransition: true }); + return; + } + setPowerState(polled, { force: true }); + } + async function fetchPowerSnapshot() { + const r = await fetch(`/api/server/${encodeURIComponent(bot)}/node-status`, { cache: "no-store" }); + if (!r.ok) throw new Error(`power-status-${r.status}`); + const j = await r.json().catch(() => ({})); + return { + state: (j && (j.status || j.state)) || "", + nodeOnline: j && typeof j.nodeOnline !== "undefined" ? j.nodeOnline !== false : true + }; + } + function nextPowerPollDelay() { + return isTransitionPowerState(powerState) ? POWER_POLL_TRANSITION_MS : POWER_POLL_IDLE_MS; + } + function schedulePowerStatePoll(delayMs = nextPowerPollDelay()) { + if (powerPollTimer) clearTimeout(powerPollTimer); + powerPollTimer = setTimeout(() => { + refreshPowerState().catch(() => { }); + }, delayMs); + } + async function refreshPowerState(opts = {}) { + const { force = false } = opts; + if (powerPollInFlight && !force) return; + powerPollInFlight = true; + try { + const snapshot = await fetchPowerSnapshot(); + applyPolledPowerState(snapshot.state, snapshot.nodeOnline); + } catch { + if (powerTransition && (Date.now() - powerTransitionSince > POWER_TRANSITION_TIMEOUT_MS)) { + powerTransition = null; + powerTransitionSince = 0; + } + updatePowerControlsInteractivity(); + } finally { + powerPollInFlight = false; + schedulePowerStatePoll(); + } + } + function startPowerStatePolling() { + schedulePowerStatePoll(120); + } + function stopPowerStatePolling() { + if (powerPollTimer) { + clearTimeout(powerPollTimer); + powerPollTimer = null; + } + } + function syncPowerStateFromPanelMessage(rawOutput) { + const msg = String(rawOutput || "").toLowerCase(); + if (!msg.includes("[adpanel]")) return; + if (msg.includes("server starting")) setPowerState(POWER_STATE.STARTING); + else if (msg.includes("server stopping")) setPowerState(POWER_STATE.STOPPING); + else if (msg.includes("server killing")) setPowerState(POWER_STATE.STOPPING); + else if (msg.includes("server started")) setPowerState(POWER_STATE.RUNNING); + else if (msg.includes("server stopped")) setPowerState(POWER_STATE.STOPPED); + else if (msg.includes("server killed")) setPowerState(POWER_STATE.STOPPED); + } + updatePowerControlsInteractivity(); + window.addEventListener('load', () => { + ensureJumpBtn(); + updateJumpBtnVisibility(); + }); + window.addEventListener('beforeunload', stopPowerStatePolling); + window.addEventListener('resize', updateJumpBtnVisibility); + async function fetchPerms(opts = {}) { + const { preserveCurrentState = false } = opts; + try { + const r = await fetch(`/api/servers/${encodeURIComponent(bot)}/permissions`, { cache: 'no-store' }); + if (!r.ok) { + const status = r.status; + if (status === 401 || status === 403) { + const offlineOverlay = document.getElementById('offlineOverlay'); + const offlineText = document.querySelector('#offlineOverlay .offline-text'); + if (offlineOverlay && offlineText) { + offlineText.textContent = status === 401 ? "Not authenticated" : "No Access"; + offlineOverlay.classList.add('show'); + } + } + throw new Error('perm fetch failed'); + } + const j = await r.json(); + IS_ADMIN = !!j.isAdmin; + AGENT_ACCESS = !!j.agent_access; + SERVER_ACTION_TOKENS = (j && j.actionTokens && typeof j.actionTokens === 'object') ? { ...j.actionTokens } : {}; + serverActionTokensLoadedAt = Date.now(); + if (j && j.perms && typeof j.perms === 'object') { + PERMS = Object.assign(PERMS, j.perms); + } + if (profileEmailEl && j) { + const emailFromApi = + (j.user && j.user.email) ? j.user.email : + (j.email || null); + if (emailFromApi) { + profileEmailEl.textContent = emailFromApi; + } + } + return j; + } catch (e) { + if (!preserveCurrentState) { + IS_ADMIN = false; + AGENT_ACCESS = false; + SERVER_ACTION_TOKENS = {}; + serverActionTokensLoadedAt = 0; + PERMS = { + files_read: false, files_delete: false, files_rename: false, files_archive: false, console_read: false, console_write: false, + server_stop: false, server_start: false, files_upload: false, files_create: false, + activity_logs: false, backups_view: false, backups_create: false, backups_delete: false, + scheduler_access: false, scheduler_create: false, scheduler_delete: false, store_access: false, + server_reinstall: false, agent_settings: false + }; + } + return null; + } + } + function clientClean(raw) { + if (!raw) return ""; + let s = decodeHtmlEntities(raw); + s = stripDockerStreamFrames(s); + s = s.replace(/\r\n/g, "\n").replace(/\r/g, "\n"); + s = sanitizeAnsiForConsole(s); + s = s.replace(/…+/g, ""); + s = s.replace(/^\s*(?:stdout|stderr)\s*:\s*/gmi, ""); + const out = []; + for (let line of s.split("\n")) { + line = line.replace(/…+/g, ""); + line = line.replace(/^((?:\x1B\[[0-9:;]*m)*)(?:\s*>\.{2,}\s*)/, '$1'); + line = line.replace(/^((?:\x1B\[[0-9:;]*m)*)(?:[>=. ]+)/, '$1'); + line = line.replace(/\s+$/, ""); + const visible = visibleConsoleText(line); + const t = visible.trim(); + if (!t) continue; + if (/^[\s>.=…-]+$/.test(t)) continue; + if (/^\[ADPanel\]\s+Connected\s*$/i.test(t)) continue; + if (/^>\s*$/.test(t)) continue; + if (/^>\s*\.{2,}\s*$/.test(t)) continue; + if (/^>\s+[^@\s]+@[^\s]+\s+\S+/i.test(t)) continue; + if (/^>\s+(?:node|npm|pnpm|yarn)\b/i.test(t)) continue; + if (t.includes("Usage: docker")) continue; + if (t.includes("Run 'docker COMMAND --help'")) continue; + if (t.includes("For more help on how to use Docker")) continue; + if (/^\s*Container started\s*$/i.test(t)) continue; + if (/^[0-9a-f]{64}(?:\s*Container started)?\s*$/i.test(t)) continue; + if (/^\s*\[?waiting\]?\s+/i.test(t)) continue; + if (/container\s+".*"\s+not\s+found\s+yet/i.test(t)) continue; + 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; + out.push(line); + } + let joined = out.join("\n"); + joined = joined + .replace(/([^\n])(?=20\d{2}-\d{2}-\d{2}T)/g, "$1\n"); + joined = joined.replace(/\n{2,}/g, "\n"); + if (joined && !joined.endsWith("\n")) joined += "\n"; + return joined; + } + + let ansiUp = null; + function getAnsiUp() { + if (!ansiUp) { + if (typeof AnsiUp !== 'undefined') { + ansiUp = new AnsiUp(); + ansiUp.use_classes = false; + } else { + return { ansi_to_html: (t) => t }; + } + } + return ansiUp; + } + + function ansiToHtml(text) { + if (!text) return ""; + + let result = getAnsiUp().ansi_to_html(text); + + result = result.replace( + /(https?:\/\/[^\s<>"']+)/gi, + '$1' + ); + + return result; + } + let userPinnedBottom = true; + let suppressAutoScroll = false; + const COMMAND_SUBMIT_DEDUPE_MS = 1200; + let commandSendInFlight = false; + let lastSubmittedCommand = ""; + let lastSubmittedAt = 0; + 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 { + const parsed = JSON.parse(localStorage.getItem(consoleCommandHistoryKey) || '[]'); + if (!Array.isArray(parsed)) return []; + return parsed + .map((entry) => String(entry || '').trim()) + .filter(Boolean) + .slice(0, CONSOLE_COMMAND_HISTORY_LIMIT); + } catch { + return []; + } + } + + function persistConsoleCommandHistory() { + try { + localStorage.setItem(consoleCommandHistoryKey, JSON.stringify(consoleCommandHistory.slice(0, CONSOLE_COMMAND_HISTORY_LIMIT))); + } catch { } + } + + function rememberConsoleCommandForInput(commandText) { + const command = String(commandText || '').trim(); + if (!command) return; + consoleCommandHistory = [ + command, + ...consoleCommandHistory.filter((entry) => entry !== command) + ].slice(0, CONSOLE_COMMAND_HISTORY_LIMIT); + consoleCommandHistoryIndex = -1; + persistConsoleCommandHistory(); + } + + function recallConsoleCommand(direction) { + if (!cmdInput || !consoleCommandHistory.length) return; + if (direction < 0) { + consoleCommandHistoryIndex = Math.min(consoleCommandHistoryIndex + 1, consoleCommandHistory.length - 1); + } else { + consoleCommandHistoryIndex = Math.max(consoleCommandHistoryIndex - 1, -1); + } + cmdInput.value = consoleCommandHistory[consoleCommandHistoryIndex] || ''; + const cursor = cmdInput.value.length; + try { cmdInput.setSelectionRange(cursor, cursor); } catch { } + } + + function isNearBottom(el) { + return (el.scrollHeight - el.scrollTop - el.clientHeight) < JUMP_THRESHOLD; + } + function canScroll(el) { + return el && (el.scrollHeight - el.clientHeight) > 2; + } + let jumpBtn = null; + function ensureJumpBtn() { + if (jumpBtn) return jumpBtn; + try { + if (getComputedStyle(consoleEl).position === 'static') { + consoleEl.style.position = 'relative'; + } + } catch { } + jumpBtn = document.createElement('button'); + jumpBtn.type = 'button'; + jumpBtn.className = 'jump-btn'; + jumpBtn.setAttribute('aria-label', 'Jump to bottom'); + jumpBtn.innerHTML = ''; + consoleEl.appendChild(jumpBtn); + jumpBtn.addEventListener('click', () => { + scrollConsoleToBottom(true); + suppressAutoScroll = false; + userPinnedBottom = true; + jumpBtn.classList.remove('show'); + }); + return jumpBtn; + } + function updateJumpBtnVisibility() { + const btn = ensureJumpBtn(); + const show = canScroll(consoleEl) && !isNearBottom(consoleEl); + btn.classList.toggle('show', show); + } + function scrollConsoleToBottom(smooth = true) { + try { + if (smooth) { + const start = consoleEl.scrollTop; + const end = consoleEl.scrollHeight - consoleEl.clientHeight; + const distance = end - start; + const duration = Math.min(600, Math.max(200, Math.abs(distance) * 0.5)); + let startTime = null; + + const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3); + + function animateScroll(currentTime) { + if (!startTime) startTime = currentTime; + const elapsed = currentTime - startTime; + const progress = Math.min(elapsed / duration, 1); + const easedProgress = easeOutCubic(progress); + + consoleEl.scrollTop = start + (distance * easedProgress); + + if (progress < 1) { + requestAnimationFrame(animateScroll); + } + } + + requestAnimationFrame(animateScroll); + } else { + consoleEl.scrollTop = consoleEl.scrollHeight; + } + } catch { } + } + const MAX_CONSOLE_CHARS = 400_000; + const RECENT_CONSOLE_DEDUPE_MS = 5000; + let _pendingConsoleText = ""; + let _flushRaf = 0; + let _consoleRawChunks = []; + let _consoleVisibleChars = 0; + let lastConsoleAppendText = ""; + let lastConsoleAppendAt = 0; + let lastConsoleHistorySyncTs = 0; + const seenConsoleHistoryEntries = new Set(); + const recentConsoleLineFingerprints = new Map(); + + function consoleDedupeFingerprint(text) { + return String(text || '') + .replace(ANSI_SGR_RE, '') + .replace(/\s+$/g, '') + .trim(); + } + + function pruneRecentConsoleLineFingerprints(now = Date.now()) { + for (const [key, ts] of recentConsoleLineFingerprints.entries()) { + if ((now - ts) > RECENT_CONSOLE_DEDUPE_MS) { + recentConsoleLineFingerprints.delete(key); + } + } + } + + function rememberRecentConsoleChunk(cleaned, now = Date.now()) { + const lines = String(cleaned || '').split('\n'); + for (const line of lines) { + const key = consoleDedupeFingerprint(line); + if (key) recentConsoleLineFingerprints.set(key, now); + } + if (recentConsoleLineFingerprints.size > 600) { + pruneRecentConsoleLineFingerprints(now); + } + } + + function recentlySawConsoleLine(line, sinceTs = 0) { + const cleaned = clientClean(line); + const key = consoleDedupeFingerprint(cleaned); + if (!key) return false; + const seenAt = recentConsoleLineFingerprints.get(key) || 0; + return seenAt >= sinceTs && (Date.now() - seenAt) <= RECENT_CONSOLE_DEDUPE_MS; + } + + function getConsoleVisibleLength(text) { + return visibleConsoleText(text).length; + } + + function resetConsoleBuffer() { + if (_flushRaf) { + cancelAnimationFrame(_flushRaf); + _flushRaf = 0; + } + if (pendingConsoleHistoryResyncTimer) { + clearTimeout(pendingConsoleHistoryResyncTimer); + pendingConsoleHistoryResyncTimer = null; + } + _pendingConsoleText = ""; + _consoleRawChunks = []; + _consoleVisibleChars = 0; + lastConsoleAppendText = ""; + lastConsoleAppendAt = 0; + lastConsoleHistorySyncTs = 0; + lastConsoleLiveAt = 0; + seenConsoleHistoryEntries.clear(); + recentConsoleLineFingerprints.clear(); + if (consoleContentEl) { + consoleContentEl.innerHTML = ''; + } + updateJumpBtnVisibility(); + } + + function formatConsoleClock(ts = Date.now()) { + const d = new Date(ts); + const hh = String(d.getHours()).padStart(2, '0'); + const mm = String(d.getMinutes()).padStart(2, '0'); + const ss = String(d.getSeconds()).padStart(2, '0'); + return `${hh}:${mm}:${ss}`; + } + + function appendCommandEcho(commandText, sentAt = Date.now()) { + const safe = String(commandText || '').replace(/[\r\n]+/g, ' ').trim(); + if (!safe) return; + appendToConsole(`[${formatConsoleClock(sentAt)} CMD] ${safe}\n`); + } + + function createCommandRequestId() { + try { + if (window.crypto && typeof window.crypto.randomUUID === 'function') { + return window.crypto.randomUUID(); + } + } catch { } + return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`; + } + + function setCommandSendingState(isSending) { + if (sendBtn) { + sendBtn.disabled = !!isSending; + sendBtn.classList.toggle('disabled', !!isSending); + sendBtn.setAttribute('aria-disabled', isSending ? 'true' : 'false'); + } + } + + function _flushConsole() { + _flushRaf = 0; + if (!_pendingConsoleText) return; + + const wasNearBottom = isNearBottom(consoleEl); + const rawChunk = _pendingConsoleText; + const htmlContent = ansiToHtml(rawChunk); + consoleContentEl.innerHTML += htmlContent; + _pendingConsoleText = ""; + + _consoleRawChunks.push(rawChunk); + _consoleVisibleChars += getConsoleVisibleLength(rawChunk); + + if (_consoleVisibleChars > MAX_CONSOLE_CHARS) { + while (_consoleVisibleChars > MAX_CONSOLE_CHARS && _consoleRawChunks.length > 1) { + const dropped = _consoleRawChunks.shift(); + _consoleVisibleChars -= getConsoleVisibleLength(dropped); + } + consoleContentEl.innerHTML = ansiToHtml(_consoleRawChunks.join('')); + } + + if (!suppressAutoScroll && wasNearBottom) { + scrollConsoleToBottom(false); + } + updateJumpBtnVisibility(); + } + + function appendToConsole(rawChunk, options = {}) { + const cleaned = clientClean(rawChunk); + if (!cleaned) return; + if (options && options.live) { + lastConsoleLiveAt = Date.now(); + } + const now = Date.now(); + if (cleaned === lastConsoleAppendText && now - lastConsoleAppendAt < 400) { + return; + } + lastConsoleAppendText = cleaned; + lastConsoleAppendAt = now; + rememberRecentConsoleChunk(cleaned, now); + + _pendingConsoleText += cleaned; + + if (!_flushRaf) { + _flushRaf = requestAnimationFrame(_flushConsole); + } + } + async function fetchConsoleHistory(limit = 80) { + const r = await fetch(`/api/servers/${encodeURIComponent(bot)}/console-history?limit=${encodeURIComponent(limit)}`); + 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; + } + async function resetServerConsoleHistorySession() { + try { + const response = await fetch(`/api/servers/${encodeURIComponent(bot)}/console-history/reset`, { method: 'POST' }); + return response.ok; + } catch { + return false; + } + } + async function hydrateInitialConsoleHistory(limit = 120) { + if (!hasConsoleReadAccess()) return 0; + if (_consoleVisibleChars > 0 || _pendingConsoleText || (consoleContentEl && consoleContentEl.textContent.trim())) return 0; + let appendedCount = 0; + try { + const lines = await fetchConsoleHistory(limit); + 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; + const key = `${ts}:${source}:${line}`; + if (seenConsoleHistoryEntries.has(key)) continue; + seenConsoleHistoryEntries.add(key); + if (seenConsoleHistoryEntries.size > 1500) { + const first = seenConsoleHistoryEntries.values().next().value; + if (first) seenConsoleHistoryEntries.delete(first); + } + appendToConsole(line.endsWith('\n') ? line : `${line}\n`); + if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; + appendedCount += 1; + } + } catch { } + return appendedCount; + } + function scheduleConsoleHistoryResync(commandText, sentAt = Date.now()) { + if (!hasConsoleReadAccess()) return; + const baselineTs = sentAt - 250; + if (pendingConsoleHistoryResyncTimer) { + clearTimeout(pendingConsoleHistoryResyncTimer); + pendingConsoleHistoryResyncTimer = null; + } + pendingConsoleHistoryResyncTimer = window.setTimeout(async () => { + pendingConsoleHistoryResyncTimer = null; + if (remoteLogTransport === 'eventsource' && lastConsoleLiveAt >= sentAt) return; + try { + const lines = await fetchConsoleHistory(120); + 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); + if (seenConsoleHistoryEntries.size > 1500) { + const first = seenConsoleHistoryEntries.values().next().value; + if (first) seenConsoleHistoryEntries.delete(first); + } + if (source === 'command' && line.trim() === String(commandText || '').trim()) continue; + const historyLine = line.endsWith('\n') ? line : `${line}\n`; + if (source !== 'command' && recentlySawConsoleLine(historyLine, baselineTs)) { + if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; + continue; + } + appendToConsole(historyLine); + if (ts > lastConsoleHistorySyncTs) lastConsoleHistorySyncTs = ts; + } + } catch { } + }, remoteLogTransport === 'eventsource' ? 1200 : 400); + } + consoleEl.addEventListener('scroll', () => { + userPinnedBottom = isNearBottom(consoleEl); + suppressAutoScroll = !userPinnedBottom; + updateJumpBtnVisibility(); + }); + function updateUrlUploaderButtonState() { + const btn = document.getElementById('urlUploaderBtn'); + if (!btn) return; + const canSeeFiles = hasPerm('files_read'); + const canUploadFiles = hasPerm('files_upload'); + btn.classList.toggle('hidden', !canSeeFiles); + btn.classList.toggle('disabled', canSeeFiles && !canUploadFiles); + btn.disabled = canSeeFiles && !canUploadFiles; + btn.title = canUploadFiles + ? 'Upload a file from a URL' + : 'File upload permission required'; + } + + function applyPermissionsToUI() { + if (!hasPerm('console_write')) { cmdRow.classList.add('hidden'); } + if (!hasConsoleReadAccess() && consoleContentEl) { + resetConsoleBuffer(); + } + if (!hasPerm('files_read')) { filesBtn.classList.add('disabled'); dockFiles.classList.add('disabled'); } + if (!hasPerm('files_upload')) { + uploadLabel.classList.add('hidden'); + fileUploadModal.classList.add('hidden'); + } + updateUrlUploaderButtonState(); + if (!hasPerm('files_create')) { newBtn.classList.add('hidden'); dockNew.classList.add('disabled'); editorSave.classList.add('disabled'); } + if (!hasPerm('server_start')) { + if (taskBtn) taskBtn.classList.add('disabled'); + if (dockTask) dockTask.classList.add('disabled'); + } + const schedulerBtn = document.getElementById('schedulerBtn'); + if (schedulerBtn && !hasPerm('scheduler_access')) { + schedulerBtn.classList.add('disabled'); + schedulerBtn.style.display = 'none'; + } + const activityBtnEl = document.getElementById('activityBtn'); + const dockActivity = document.getElementById('dockActivity'); + if (!hasPerm('activity_logs')) { + if (activityBtnEl) { activityBtnEl.classList.add('disabled'); activityBtnEl.style.display = 'none'; } + if (dockActivity) { dockActivity.classList.add('disabled'); dockActivity.style.display = 'none'; } + } + const storeBtnEl = document.getElementById('storeBtn'); + const dockStore = document.getElementById('dockStore'); + if (!hasPerm('store_access')) { + if (storeBtnEl) { storeBtnEl.classList.add('disabled'); } + if (dockStore) { dockStore.classList.add('disabled'); } + } + const backupsBtnEl = document.getElementById('backupsBtn'); + const dockBackups = document.getElementById('dockBackups'); + if (!hasPerm('backups_view')) { + if (backupsBtnEl) { backupsBtnEl.classList.add('disabled'); } + if (dockBackups) { dockBackups.classList.add('disabled'); } + } + const aiHelpBtnEl = document.getElementById('aiHelpBtn'); + const dockAiHelp = document.getElementById('dockAiHelp'); + if (!hasAgentAccess()) { + if (aiHelpBtnEl) { aiHelpBtnEl.classList.add('disabled'); } + if (dockAiHelp) { dockAiHelp.classList.add('disabled'); } + } + const reinstallBtnEl = document.getElementById('reinstallBtn'); + const dockReinstall = document.getElementById('dockReinstall'); + if (!hasPerm('server_reinstall')) { + if (reinstallBtnEl) { reinstallBtnEl.classList.add('disabled'); reinstallBtnEl.style.display = 'none'; } + if (dockReinstall) { dockReinstall.classList.add('disabled'); dockReinstall.style.display = 'none'; } + } else { + if (reinstallBtnEl) { reinstallBtnEl.classList.remove('disabled'); reinstallBtnEl.style.display = ''; } + if (dockReinstall) { dockReinstall.classList.remove('disabled'); dockReinstall.style.display = ''; } + } + const aiHelpSettingsBtnEl = document.getElementById('aiHelpSettingsBtn'); + if (aiHelpSettingsBtnEl) { + if (typeof IS_ADMIN !== 'undefined' && IS_ADMIN) { + aiHelpSettingsBtnEl.classList.remove('hidden'); + aiHelpSettingsBtnEl.removeAttribute('hidden'); + aiHelpSettingsBtnEl.style.removeProperty('display'); + aiHelpSettingsBtnEl.style.setProperty('display', 'flex', 'important'); + } else { + aiHelpSettingsBtnEl.classList.add('hidden'); + aiHelpSettingsBtnEl.setAttribute('hidden', 'true'); + aiHelpSettingsBtnEl.style.setProperty('display', 'none', 'important'); + } + } + updatePowerControlsInteractivity(); + } + socket.off("connect"); + socket.on("connect", () => { + socket.emit("join", bot); + }); + + socket.off("output"); + socket.on("output", (data) => { + if (REMOTE_MODE && remoteLogTransport === 'eventsource') return; + syncPowerStateFromPanelMessage(data); + if (!hasConsoleReadAccess()) return; + appendToConsole(data, { live: true }); + }); + + socket.off("nodeStatus"); + socket.on("nodeStatus", (data) => { + if (!data || typeof data.nodeOnline === 'undefined') return; + const nodeOnline = data.nodeOnline !== false; + powerNodeOnline = nodeOnline; + updatePowerControlsInteractivity(); + setNodeOnline(nodeOnline); + updateOfflineState(!nodeOnline); + }); + + if (socket.connected) socket.emit("join", bot); + socket.on("fileData", (d) => { openEditorModal(d.path, d.content); }); + async function loadServerInfo() { + if (!topoInfoPromise) topoInfoPromise = topoInfo(); + const [topoRes, srvRes] = await Promise.allSettled([ + topoInfoPromise.catch(() => null), + fetch(`/api/server-info/${encodeURIComponent(bot)}`) + .then(r => (r.ok ? r.json() : null)) + .catch(() => null) + ]); + const topo = topoRes.status === 'fulfilled' ? topoRes.value : null; + const srv = srvRes.status === 'fulfilled' ? srvRes.value : null; + REMOTE_MODE = !!(topo && topo.remote); + NODE_ID = (topo && topo.nodeId) || (srv && srv.nodeId) || null; + const topoInfoObj = (topo && topo.info) ? topo.info : {}; + serverInfo = Object.assign({}, topoInfoObj, srv || {}); + updateStoreVisibility(); + } + function formatAddress(ip, port) { + if (!ip) return ""; + const is6 = ip.includes(":") && !ip.includes("."); + const host = is6 ? `[${ip}]` : ip; + return port ? `${host}:${port}` : host; + } + async function nodeAction(cmd, options = {}) { + if (!SERVER_NODE_ID) throw new Error('no remote node'); + const r = await fetch(`/api/nodes/${encodeURIComponent(SERVER_NODE_ID)}/server/action`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(Object.assign({ name: bot, cmd }, options)) + }); + const j = await r.json().catch(() => ({})); + if (!r.ok || (j && j.error)) { + const msg = (j && (j.detail || j.error)) || `HTTP ${r.status}`; + throw new Error(msg); + } + return j; + } + async function nodeCommand(command) { + if (!SERVER_NODE_ID) throw new Error('no remote node'); + const r = await fetch(`/api/nodes/${encodeURIComponent(SERVER_NODE_ID)}/server/command`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: bot, command }) + }); + const j = await r.json().catch(() => ({})); + if (!r.ok || (j && j.error)) { + const msg = (j && (j.detail || j.error)) || `HTTP ${r.status}`; + throw new Error(msg); + } + return j; + } + function normalizeTemplate(t) { + const raw = (t ?? '').toString().trim().toLowerCase(); + if (!raw) return ''; + if (["discord", "discord-bot", "discord bot", "node", "nodejs", "python", "bot"].includes(raw)) return 'discord-bot'; + if (["mc", "minecraft"].includes(raw)) return 'minecraft'; + if (["fivem", "five-m", "five m", "fxserver", "cfx"].includes(raw)) return 'fivem'; + return raw; + } + function templateDisplayName(t) { + const tpl = normalizeTemplate(t); + if (tpl === 'discord-bot') return 'Node.js'; + if (tpl === 'minecraft') return 'Minecraft'; + if (tpl === 'fivem') return 'FiveM'; + return tpl || 'unknown'; + } + function loadStorePreferenceMap() { + try { + const raw = localStorage.getItem(STORE_PREF_STORAGE_KEY) || '{}'; + const parsed = JSON.parse(raw); + return parsed && typeof parsed === 'object' ? parsed : {}; + } catch { return {}; } + } + function saveStorePreferenceMap(map) { + try { localStorage.setItem(STORE_PREF_STORAGE_KEY, JSON.stringify(map || {})); } catch { } + } + function getStorePreference() { + const map = loadStorePreferenceMap(); + return map[bot] || null; + } + function setStorePreference(pref) { + const map = loadStorePreferenceMap(); + if (pref) map[bot] = pref; else delete map[bot]; + saveStorePreferenceMap(map); + } + async function persistStoreTemplateChoice(templateId) { + const tpl = normalizeTemplate(templateId); + if (!tpl) return false; + try { + const r = await changeServerTemplateWithActionToken(bot, tpl); + if (!r.ok) return false; + try { await loadServerInfo(); } catch { } + return true; + } catch (e) { + console.warn('Failed to persist template choice', e); + return false; + } + } + function resolveStoreTemplate() { + const tpl = serverInfo ? normalizeTemplate(serverInfo.template) : ''; + if (tpl === 'discord-bot' || tpl === 'minecraft' || tpl === 'fivem') return { template: tpl, source: 'template' }; + const saved = getStorePreference(); + if (saved === 'discord-bot' || saved === 'minecraft' || saved === 'fivem') return { template: saved, source: 'preference' }; + return { template: '', source: 'unknown' }; + } + function storeTemplateQuery() { + const { template: tpl, source } = resolveStoreTemplate(); + if (source === 'preference' && tpl) return `?template=${encodeURIComponent(tpl)}`; + return ''; + } + function renderStorePreferenceOptions() { + if (!storePrefOptions) return; + storePrefOptions.innerHTML = ''; + STORE_PREF_OPTIONS.forEach(opt => { + const card = document.createElement('button'); + card.type = 'button'; + card.className = 'store-pref-card'; + card.dataset.storePref = opt.id; + card.innerHTML = ` +
+ +
+
+
${opt.title}
+
${opt.description}
+
+
+ `; + card.addEventListener('click', async () => { + setStorePreference(opt.id); + const saved = await persistStoreTemplateChoice(opt.id); + closeStorePrefModal(); + updateStoreVisibility(); + if (!saved) alert('Saved locally but failed to persist template for this server.'); + if (pendingStoreOpen) { + pendingStoreOpen = false; + openStoreModal(); + } + }); + storePrefOptions.appendChild(card); + }); + } + function openStorePrefModal() { + if (!storePrefModal) return; + renderStorePreferenceOptions(); + showModalElement(storePrefModal); + } + function showModalElement(el, display = 'flex') { + if (!el) return; + el.classList.remove('closing'); + el.style.display = display; + el.classList.add('show'); + el.setAttribute('aria-hidden', 'false'); + } + function afterModalPaint(callback) { + requestAnimationFrame(() => { + requestAnimationFrame(callback); + }); + } + function animateClose(el, onComplete) { + if (!el) return; + if (el.classList.contains('closing')) return; + let done = false; + let fallbackTimer = null; + let handleAnimationEnd = null; + const finish = () => { + if (done) return; + done = true; + if (fallbackTimer) clearTimeout(fallbackTimer); + if (handleAnimationEnd) el.removeEventListener('animationend', handleAnimationEnd); + el.classList.remove('closing'); + el.classList.remove('show'); + el.style.display = 'none'; + el.setAttribute('aria-hidden', 'true'); + if (onComplete) onComplete(); + }; + el.classList.add('closing'); + handleAnimationEnd = (event) => { + if (event.target === el) finish(); + }; + fallbackTimer = setTimeout(finish, 360); + el.addEventListener('animationend', handleAnimationEnd); + } + + function closeStorePrefModal() { + if (!storePrefModal) return; + animateClose(storePrefModal, () => { + pendingStoreOpen = false; + }); + } + function updateStoreVisibility() { + const btn = document.getElementById('storeBtn'); + const dock = document.getElementById('dockStore'); + const tabs = document.getElementById('storeTabs'); + const { template: tpl } = resolveStoreTemplate(); + const showForDiscord = (tpl === 'discord-bot'); + const showForMinecraft = (tpl === 'minecraft'); + const showForFivem = (tpl === 'fivem'); + const hasExperience = !!tpl; + const showVersions = showForDiscord || showForMinecraft || showForFivem; + const showPlugins = showForMinecraft; + [btn, dock].forEach(el => { if (el) el.classList.remove('hidden'); }); + if (tabs) tabs.classList.toggle('hidden', !hasExperience); + if (storeTabVersions) storeTabVersions.classList.toggle('hidden', !showVersions); + if (storeTabPlugins) storeTabPlugins.classList.toggle('hidden', !showPlugins); + if (storeSubtitle && !hasExperience) { + storeSubtitle.textContent = 'Pick what you want to browse: Node.js runtimes, Minecraft cores, or FiveM artifacts.'; + } + const allowedTabs = new Set(); + if (showVersions) allowedTabs.add('versions'); + if (showPlugins) allowedTabs.add('plugins'); + if (allowedTabs.size && !allowedTabs.has(currentStoreTab)) { + const fallbackTab = showVersions ? 'versions' : (showPlugins ? 'plugins' : currentStoreTab); + setActiveStoreTab(fallbackTab); + } + } + function setActiveStoreTab(tab) { + currentStoreTab = tab; + if (storeTabVersions) storeTabVersions.classList.toggle('active', tab === 'versions'); + if (storeTabPlugins) storeTabPlugins.classList.toggle('active', tab === 'plugins'); + if (storeSubtitle) { + const { template: tpl } = resolveStoreTemplate(); + if (tab === 'versions') { + if (tpl === 'minecraft') { + storeSubtitle.textContent = 'Choose your core distribution and version.'; + } else if (tpl === 'fivem') { + storeSubtitle.textContent = 'Choose the Linux FXServer artifact for this server.'; + } else { + storeSubtitle.textContent = 'Choose the runtime/version for your bot container.'; + } + } else if (tpl === 'minecraft') { + storeSubtitle.textContent = 'Browse and install plugins from Modrinth.'; + } else { + storeSubtitle.textContent = ''; + } + } + } + document.addEventListener('DOMContentLoaded', () => { + updateStoreVisibility(); + }); + async function openStoreModal() { + if (!storeModal) return; + if (!hasPerm('store_access')) { alert('You do not have permission to access the store'); return; } + if (!serverInfo) await loadServerInfo(); + updateStoreVisibility(); + const { template: tpl } = resolveStoreTemplate(); + if (!tpl) { + pendingStoreOpen = true; + openStorePrefModal(); + return; + } + showModalElement(storeModal); + setActiveStoreTab('versions'); + storeContent.innerHTML = `
Loading providers...
`; + try { + const r = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions${storeTemplateQuery()}`); + if (!r.ok) { + storeContent.innerHTML = `
Failed to load providers (${r.status})
`; + return; + } + const data = await r.json(); + const providers = Array.isArray(data.providers) ? data.providers : []; + if (!providers.length) { + storeContent.innerHTML = '
No providers configured for this template.
'; + return; + } + if (tpl === 'fivem' && providers.length === 1) { + await openProviderDetails(providers[0], { direct: true }); + return; + } + await renderStoreProvidersView(providers); + } catch (e) { + storeContent.innerHTML = `
Failed to load providers
`; + } + } + function closeStoreModal() { + if (!storeModal) return; + animateClose(storeModal, () => { + storeCurrentProvider = null; + }); + } + function compareMcVersionsDesc(a, b) { + const pa = String(a).split('.').map(x => parseInt(x, 10) || 0); + const pb = String(b).split('.').map(x => parseInt(x, 10) || 0); + const len = Math.max(pa.length, pb.length); + for (let i = 0; i < len; i++) { + const va = typeof pa[i] === 'number' ? pa[i] : 0; + const vb = typeof pb[i] === 'number' ? pb[i] : 0; + if (va !== vb) return vb - va; + } + return 0; + } + + async function fetchVanillaVersions({ includeSnapshots = false, limit = 200 } = {}) { + const MANIFEST = 'https://piston-meta.mojang.com/mc/game/version_manifest_v2.json'; + let manifest; + try { + const r = await fetch(MANIFEST); + if (!r.ok) throw new Error('manifest not ok'); + manifest = await r.json(); + } catch (e) { + return { versions: [] }; + } + const latestReleaseId = manifest?.latest?.release || null; + const latestSnapshotId = manifest?.latest?.snapshot || null; + let list = Array.isArray(manifest?.versions) ? manifest.versions.slice() : []; + list = list.filter(v => includeSnapshots ? true : String(v.type) === 'release'); + list.sort((a, b) => new Date(b.releaseTime || b.time || 0) - new Date(a.releaseTime || a.time || 0)); + if (limit && Number.isFinite(limit)) list = list.slice(0, limit); + const results = []; + const concurrency = Math.min(8, Math.max(1, list.length)); + let idx = 0; + async function worker() { + while (idx < list.length) { + const i = idx++; + const v = list[i]; + try { + const res = await fetch(v.url); + if (!res.ok) continue; + const verMeta = await res.json(); + const server = verMeta?.downloads?.server; + if (!server?.url) continue; + const mc = String(v.id); + const date = String(v.releaseTime || v.time || '').split('T')[0] || ''; + const tags = []; + if (String(v.type) === 'snapshot') tags.push('snapshot'); else tags.push('release'); + if (mc === latestReleaseId) tags.push('latest'); + if (mc === latestSnapshotId) tags.push('latest-snapshot'); + results.push({ + id: mc, + name: mc, + label: `Vanilla ${mc}`, + mcVersion: mc, + releaseDate: date, + tags, + downloadUrl: server.url + }); + } catch { + } + } + } + await Promise.all(Array.from({ length: concurrency }, worker)); + try { + results.sort((a, b) => compareMcVersionsDesc(a.mcVersion, b.mcVersion)); + } catch { + results.sort((a, b) => (b.releaseDate > a.releaseDate ? 1 : -1)); + } + return { versions: results }; + } + async function fetchWithTimeout(url, opts = {}, ms = 8000) { + const ctrl = new AbortController(); + const id = setTimeout(() => ctrl.abort(), ms); + try { + return await fetch(url, { ...opts, signal: ctrl.signal }); + } finally { + clearTimeout(id); + } + } + function compareSemverDesc(a, b) { + const pa = a.split('.').map(n => parseInt(n, 10) || 0); + const pb = b.split('.').map(n => parseInt(n, 10) || 0); + for (let i = 0; i < Math.max(pa.length, pb.length); i++) { + const da = pa[i] ?? 0, db = pb[i] ?? 0; + if (da !== db) return db - da; + } + return 0; + } + function neoForgeToMcVersion(ver) { + const m = ver.match(/^(\d+)\.(\d+)\.(\d+)$/); + if (!m) return ''; + const major = Number(m[1]); + const minor = Number(m[2]); + return `1.${major}.${minor}`; + } + async function addLastModifiedDates(list, urlFn, pool = 6, timeout = 5000) { + let idx = 0; + const workers = []; + async function worker() { + while (idx < list.length) { + const i = idx++; + const u = urlFn(list[i]); + try { + const r = await fetchWithTimeout(u, { method: 'HEAD' }, timeout); + const lm = r.headers.get('last-modified'); + if (lm) list[i].releaseDate = new Date(lm).toISOString().slice(0, 10); + } catch (_) { } + } + } + for (let i = 0; i < pool; i++) workers.push(worker()); + await Promise.all(workers); + } + async function fetchPapermcVersions() { + if (papermcVersionsCache) return papermcVersionsCache; + const base = '/api/papermc/projects/paper'; + const dlBase = 'https://api.papermc.io/v2/projects/paper'; + let proj; + try { + const projRes = await fetch(base); + if (!projRes.ok) throw new Error('Failed to load Paper project'); + proj = await projRes.json().catch(() => ({})); + } catch (e) { + papermcVersionsCache = { versions: [] }; + return papermcVersionsCache; + } + let versions = Array.isArray(proj.versions) ? proj.versions.slice() : []; + if (!versions.length) { + papermcVersionsCache = { versions: [] }; + return papermcVersionsCache; + } + versions.sort(compareMcVersionsDesc); + const results = []; + const concurrency = 8; + let idx = 0; + async function worker() { + while (idx < versions.length) { + const i = idx++; + const ver = versions[i]; + try { + const verRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}`); + if (!verRes.ok) continue; + const verData = await verRes.json().catch(() => ({})); + const builds = Array.isArray(verData.builds) ? verData.builds : []; + if (!builds.length) continue; + const lastBuild = builds[builds.length - 1]; + let buildMeta = null; + try { + const buildRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}/builds/${lastBuild}`); + if (buildRes.ok) { + buildMeta = await buildRes.json().catch(() => null); + } + } catch (_) { } + const jarName = `paper-${ver}-${lastBuild}.jar`; + const downloadUrl = `${dlBase}/versions/${encodeURIComponent(ver)}/builds/${lastBuild}/downloads/${encodeURIComponent(jarName)}`; + const entry = { + id: String(ver), + name: String(ver), + label: `Paper ${ver}`, + mcVersion: String(ver), + releaseDate: (buildMeta && typeof buildMeta.time === 'string') + ? buildMeta.time.split('T')[0] + : '', + tags: [], + build: lastBuild, + downloadUrl + }; + const tags = entry.tags; + const channel = buildMeta && typeof buildMeta.channel === 'string' + ? buildMeta.channel.toLowerCase() + : ''; + if (channel) { + if (channel === 'default' || channel === 'stable') { + if (!tags.includes('stable')) tags.push('stable'); + } else { + if (!tags.includes('unstable')) tags.push('unstable'); + if (!tags.includes(channel)) tags.push(channel); + } + } else { + if (!tags.includes('stable')) tags.push('stable'); + } + if (buildMeta && buildMeta.promoted) { + if (!tags.includes('recommended')) tags.push('recommended'); + } + results.push(entry); + } catch (e) { } + } + } + const workers = []; + for (let i = 0; i < concurrency; i++) { + workers.push(worker()); + } + await Promise.all(workers); + results.sort((a, b) => compareMcVersionsDesc(a.mcVersion, b.mcVersion)); + if (results.length) { + const latestTags = results[0].tags || (results[0].tags = []); + if (!latestTags.includes('latest')) latestTags.push('latest'); + } + papermcVersionsCache = { versions: results }; + return papermcVersionsCache; + } + async function fetchVelocityVersions() { + const base = '/api/papermc/projects/velocity'; + const dlBase = 'https://api.papermc.io/v2/projects/velocity'; + let proj; + try { + const res = await fetch(base); + if (!res.ok) throw new Error('Failed to load Velocity project'); + proj = await res.json().catch(() => ({})); + } catch (e) { + return { versions: [] }; + } + let versions = Array.isArray(proj.versions) ? proj.versions.slice() : []; + if (!versions.length) return { versions: [] }; + versions.sort(compareMcVersionsDesc); + const results = []; + const concurrency = 8; + let idx = 0; + async function worker() { + while (idx < versions.length) { + const i = idx++; + const ver = versions[i]; + try { + const verRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}`); + if (!verRes.ok) continue; + const verData = await verRes.json().catch(() => ({})); + const builds = Array.isArray(verData.builds) ? verData.builds : []; + if (!builds.length) continue; + const lastBuild = builds[builds.length - 1]; + let buildMeta = null; + try { + const buildRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}/builds/${lastBuild}`); + if (buildRes.ok) { + buildMeta = await buildRes.json().catch(() => null); + } + } catch (_) { } + let fileName = null; + if (buildMeta && buildMeta.downloads) { + if (Array.isArray(buildMeta.downloads)) { + const app = buildMeta.downloads.find(d => d && d.name && /\.jar$/i.test(d.name)) || buildMeta.downloads[0]; + fileName = app && app.name; + } else if (buildMeta.downloads.application && buildMeta.downloads.application.name) { + fileName = buildMeta.downloads.application.name; + } + } + if (!fileName) fileName = `velocity-${ver}-${lastBuild}.jar`; + const downloadUrl = `${dlBase}/versions/${encodeURIComponent(ver)}/builds/${lastBuild}/downloads/${encodeURIComponent(fileName)}`; + const entry = { + id: String(ver), + name: String(ver), + label: `Velocity ${ver}`, + mcVersion: "", + releaseDate: (buildMeta && typeof buildMeta.time === 'string') ? buildMeta.time.split('T')[0] : '', + tags: [], + build: lastBuild, + downloadUrl + }; + const tags = entry.tags; + const channel = buildMeta && typeof buildMeta.channel === 'string' ? buildMeta.channel.toLowerCase() : ''; + if (channel) { + if (channel === 'default' || channel === 'stable') { + if (!tags.includes('stable')) tags.push('stable'); + } else { + if (!tags.includes('unstable')) tags.push('unstable'); + if (!tags.includes(channel)) tags.push(channel); + } + } else { + if (!tags.includes('stable')) tags.push('stable'); + } + if (buildMeta && buildMeta.promoted) { if (!tags.includes('recommended')) tags.push('recommended'); } + results.push(entry); + } catch (_) { } + } + } + const workers = []; + for (let i = 0; i < concurrency; i++) workers.push(worker()); + await Promise.all(workers); + results.sort((a, b) => compareMcVersionsDesc(a.name, b.name)); + if (results.length) { + const t = results[0].tags || (results[0].tags = []); + if (!t.includes('latest')) t.push('latest'); + } + return { versions: results }; + } + async function fetchPurpurVersions() { + const base = '/api/purpurmc/purpur'; + const dlBase = 'https://api.purpurmc.org/v2/purpur'; + let proj; + try { + const res = await fetch(base); + if (!res.ok) throw new Error('Failed to load Purpur project'); + proj = await res.json().catch(() => ({})); + } catch (e) { + return { versions: [] }; + } + let versions = Array.isArray(proj.versions) ? proj.versions.slice() : []; + if (!versions.length) return { versions: [] }; + versions.sort(compareMcVersionsDesc); + const results = []; + for (const ver of versions) { + try { + const latestRes = await fetch(`${base}/${encodeURIComponent(ver)}/latest`); + if (!latestRes.ok) continue; + const latest = await latestRes.json().catch(() => ({})); + const build = latest.build; + const time = latest.timestamp || latest.time || ''; + const date = typeof time === 'string' ? time.split('T')[0] : ''; + const downloadUrl = `${dlBase}/${encodeURIComponent(ver)}/${encodeURIComponent(build)}/download`; + const entry = { + id: String(ver), + name: String(ver), + label: `Purpur ${ver}`, + mcVersion: String(ver), + releaseDate: date, + tags: ['stable'], + build, + downloadUrl + }; + results.push(entry); + } catch (e) { } + } + if (results.length) { + const t = results[0].tags || (results[0].tags = []); + if (!t.includes('latest')) t.push('latest'); + } + return { versions: results }; + } + async function fetchLeavesVersions() { + const base = 'https://api.github.com/repos/LeavesMC/Leaves/releases'; + const pages = [1, 2, 3, 4, 5]; + const perPage = 990; + const headers = { 'Accept': 'application/vnd.github+json' }; + const chunks = await Promise.all(pages.map(async (p) => { + try { + const res = await fetch(`${base}?per_page=${perPage}&page=${p}`, { headers }); + if (!res.ok) return []; + const arr = await res.json(); + return Array.isArray(arr) ? arr : []; + } catch { + return []; + } + })); + const all = chunks.flat().filter(x => x && !x.draft && !x.prerelease); + all.sort((a, b) => { + const da = new Date(a.published_at || a.created_at || 0).getTime(); + const db = new Date(b.published_at || b.created_at || 0).getTime(); + return db - da; + }); + const seen = new Set(); + const out = []; + function extractMcVersionFromRelease(rel) { + const t = String(rel.tag_name || rel.name || ''); + let m = t.match(/(\d+\.\d+(?:\.\d+)?)/); + if (m) return m[1]; + if (Array.isArray(rel.assets)) { + for (const a of rel.assets) { + const s = String(a.name || a.browser_download_url || ''); + const mm = s.match(/(\d+\.\d+(?:\.\d+)?)/); + if (mm) return mm[1]; + } + } + return null; + } + function pickJarAsset(rel) { + if (!Array.isArray(rel.assets)) return { url: null, sha256: null }; + let pref = rel.assets.find(a => /\.jar$/i.test(a?.name || '') && + /leaves-\d+\.\d+(?:\.\d+)?\.jar$/i.test(a?.name || '')); + if (!pref) pref = rel.assets.find(a => /\.jar$/i.test(a?.name || '')); + if (!pref) return { url: null, sha256: null }; + let sha = null; + if (typeof pref.digest === 'string' && pref.digest.startsWith('sha256:')) { + sha = pref.digest.split(':')[1]; + } + return { url: pref.browser_download_url || null, sha256: sha }; + } + for (const rel of all) { + const mc = extractMcVersionFromRelease(rel); + if (!mc) continue; + if (seen.has(mc)) continue; + const { url: downloadUrl, sha256 } = pickJarAsset(rel); + const releaseDate = String(rel.published_at || rel.created_at || '').split('T')[0] || ''; + out.push({ + id: mc, + name: mc, + label: `Leaves ${mc}`, + mcVersion: mc, + releaseDate, + tags: ['github'], + downloadUrl, + tag: rel.tag_name || '', + url: rel.html_url || '', + sha256: sha256 || null + }); + seen.add(mc); + } + out.sort((a, b) => compareMcVersionsDesc(a.mcVersion, b.mcVersion)); + if (out.length) { + const t = out[0].tags || (out[0].tags = []); + if (!t.includes('latest')) t.push('latest'); + } + return { versions: out }; + } + async function fetchNeoForgeVersions() { + const META_URL = 'https://maven.neoforged.net/releases/net/neoforged/neoforge/maven-metadata.xml'; + const res = await fetch(META_URL); + if (!res.ok) return { versions: [] }; + const xml = await res.text(); + const doc = new DOMParser().parseFromString(xml, 'application/xml'); + const versions = [...doc.querySelectorAll('versioning > versions > version')] + .map(v => v.textContent.trim()) + .filter(Boolean) + .sort(compareSemverDesc); + function toMcVersion(neoforgeVer) { + const m = neoforgeVer.match(/^(\d+)\.(\d+)\.(\d+)$/); + if (!m) return ''; + const major = Number(m[1]); + const minor = Number(m[2]); + return `1.${major}.${minor}`; + } + + async function fetchNode(url, opts = {}, timeoutMs = 3500) { + const ctrl = new AbortController(); + const t = setTimeout(() => ctrl.abort(), timeoutMs); + + try { + const r = await fetch(url, { ...opts, signal: ctrl.signal, cache: "no-store" }); + setNodeOnline(true); + return r; + } catch (e) { + setNodeOnline(false); + throw e; + } finally { + clearTimeout(t); + } + } + + async function getLastModified(url) { + try { + const head = await fetch(url, { method: 'HEAD' }); + const lm = head.headers.get('last-modified'); + if (!lm) return ''; + const d = new Date(lm); + if (isNaN(d.getTime())) return ''; + return d.toISOString().slice(0, 10); + } catch { + return ''; + } + } + const out = []; + for (const ver of versions) { + const mcVersion = toMcVersion(ver); + const base = `https://maven.neoforged.net/releases/net/neoforged/neoforge/${ver}/neoforge-${ver}`; + const installerUrl = `${base}-installer.jar`; + const universalUrl = `${base}-universal.jar`; + const releaseDate = await getLastModified(installerUrl); + out.push({ + id: ver, + name: ver, + label: `NeoForge ${mcVersion || ver}`, + mcVersion: mcVersion || '', + releaseDate: releaseDate || '', + tags: ['stable'], + build: ver.split('.').pop() || '', + downloadUrl: installerUrl, + altDownloads: { installer: installerUrl, universal: universalUrl } + }); + } + if (out[0] && !out[0].tags.includes('latest')) out[0].tags.push('latest'); + return { versions: out }; + function compareSemverDesc(a, b) { + const pa = a.split('.').map(n => parseInt(n, 10) || 0); + const pb = b.split('.').map(n => parseInt(n, 10) || 0); + for (let i = 0; i < Math.max(pa.length, pb.length); i++) { + const da = pa[i] ?? 0, db = pb[i] ?? 0; + if (da !== db) return db - da; + } + return 0; + } + } + async function fetchSpigotVersions() { + const BASE = "https://api.github.com/repos/BaldGang/spigot-build/releases?per_page=1"; + function compareDesc(a, b) { + const pa = String(a).split('.').map(n => parseInt(n, 10) || 0); + const pb = String(b).split('.').map(n => parseInt(n, 10) || 0); + const len = Math.max(pa.length, pb.length); + for (let i = 0; i < len; i++) { + const va = pa[i] ?? 0, vb = pb[i] ?? 0; + if (va !== vb) return vb - va; + } + return 0; + } + const cmp = (typeof compareMcVersionsDesc === "function") ? compareMcVersionsDesc : compareDesc; + try { + const res = await fetch(BASE, { + headers: { "Accept": "application/vnd.github+json" } + }); + if (!res.ok) throw new Error(`GitHub API ${res.status}`); + const releases = await res.json(); + if (!Array.isArray(releases) || releases.length === 0) { + return { versions: [] }; + } + const rel = releases[0]; + const assets = Array.isArray(rel.assets) ? rel.assets : []; + const byVersion = new Map(); + for (const a of assets) { + const name = a?.name ?? ""; + const m = name.match(/^spigot-(\d+\.\d+(?:\.\d+)?).jar$/i); + if (!m || !a.browser_download_url) continue; + const ver = m[1]; + const rawDate = a.updated_at || a.created_at || rel.published_at || rel.created_at || ""; + const dateOnly = String(rawDate).split("T")[0] || ""; + const candidate = { + version: ver, + url: a.browser_download_url, + date: dateOnly, + _ts: Date.parse(a.updated_at || a.created_at || rel.published_at || rel.created_at || 0) || 0 + }; + const existing = byVersion.get(ver); + if (!existing || candidate._ts > existing._ts) { + byVersion.set(ver, candidate); + } + } + if (byVersion.size === 0) { + return { versions: [] }; + } + const candidates = Array.from(byVersion.values()) + .sort((x, y) => cmp(x.version, y.version)); + const out = candidates.map((c) => ({ + id: c.version, + name: c.version, + label: `SpigotMC ${c.version}`, + mcVersion: c.version, + releaseDate: c.date, + tags: ["stable"], + build: null, + downloadUrl: c.url + })); + out[0].tags = ["latest", "stable"]; + return { versions: out }; + } catch (e) { + console.error("fetchSpigotVersions failed:", e); + return { versions: [] }; + } + } + async function fetchFoliaVersions() { + const base = 'https://api.papermc.io/v2/projects/folia'; + let proj; + try { + const res = await fetch(base); + if (!res.ok) throw new Error('Failed to load Folia project'); + proj = await res.json().catch(() => ({})); + } catch (e) { + return { versions: [] }; + } + let versions = Array.isArray(proj.versions) ? proj.versions.slice() : []; + if (!versions.length) return { versions: [] }; + versions.sort(compareMcVersionsDesc); + const out = []; + const concurrency = 8; + let idx = 0; + async function worker() { + while (idx < versions.length) { + const i = idx++; + const ver = String(versions[i]); + try { + const verRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}`); + if (!verRes.ok) continue; + const verData = await verRes.json().catch(() => ({})); + const builds = Array.isArray(verData.builds) ? verData.builds : []; + if (!builds.length) continue; + const lastBuild = builds[builds.length - 1]; + let buildMeta = null; + try { + const bRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}/builds/${lastBuild}`); + if (bRes.ok) buildMeta = await bRes.json().catch(() => null); + } catch (_) { } + let jarName = null; + if (buildMeta && buildMeta.downloads) { + if (buildMeta.downloads.application && buildMeta.downloads.application.name) { + jarName = buildMeta.downloads.application.name; + } else if (Array.isArray(buildMeta.downloads)) { + const anyJar = buildMeta.downloads.find(d => d && d.name && /\.jar$/i.test(d.name)); + if (anyJar) jarName = anyJar.name; + } + } + if (!jarName) jarName = `folia-${ver}-${lastBuild}.jar`; + const downloadUrl = `${base}/versions/${encodeURIComponent(ver)}/builds/${lastBuild}/downloads/${encodeURIComponent(jarName)}`; + const date = (buildMeta && typeof buildMeta.time === 'string') ? buildMeta.time.split('T')[0] : ''; + const entry = { + id: ver, + name: ver, + label: `Folia ${ver}`, + mcVersion: ver, + releaseDate: date, + tags: [], + build: lastBuild, + downloadUrl + }; + const channel = buildMeta && typeof buildMeta.channel === 'string' + ? buildMeta.channel.toLowerCase() + : ''; + if (channel) { + if (channel === 'default' || channel === 'stable') entry.tags.push('stable'); + else entry.tags.push('unstable', channel); + } else { + entry.tags.push('stable'); + } + if (buildMeta && buildMeta.promoted) entry.tags.push('recommended'); + out.push(entry); + } catch (_) { } + } + } + const workers = []; + for (let i = 0; i < concurrency; i++) workers.push(worker()); + await Promise.all(workers); + out.sort((a, b) => compareMcVersionsDesc(a.mcVersion || a.name, b.mcVersion || b.name)); + if (out.length) { + const t = out[0].tags || (out[0].tags = []); + if (!t.includes('latest')) t.push('latest'); + } + return { versions: out }; + } + async function fetchWaterfallVersions() { + const base = 'https://api.papermc.io/v2/projects/waterfall'; + let proj; + try { + const res = await fetch(base); + if (!res.ok) throw new Error('Failed to load Waterfall project'); + proj = await res.json().catch(() => ({})); + } catch (e) { + return { versions: [] }; + } + let versions = Array.isArray(proj.versions) ? proj.versions.slice() : []; + if (!versions.length) return { versions: [] }; + versions.sort(compareMcVersionsDesc); + const out = []; + const concurrency = 8; + let idx = 0; + async function worker() { + while (idx < versions.length) { + const i = idx++; + const ver = String(versions[i]); + try { + const verRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}`); + if (!verRes.ok) continue; + const verData = await verRes.json().catch(() => ({})); + const builds = Array.isArray(verData.builds) ? verData.builds : []; + if (!builds.length) continue; + const lastBuild = builds[builds.length - 1]; + let buildMeta = null; + try { + const bRes = await fetch(`${base}/versions/${encodeURIComponent(ver)}/builds/${lastBuild}`); + if (bRes.ok) buildMeta = await bRes.json().catch(() => null); + } catch (_) { } + let jarName = null; + if (buildMeta && buildMeta.downloads) { + if (buildMeta.downloads.application && buildMeta.downloads.application.name) { + jarName = buildMeta.downloads.application.name; + } else if (Array.isArray(buildMeta.downloads)) { + const anyJar = buildMeta.downloads.find(d => d && d.name && /\.jar$/i.test(d.name)); + if (anyJar) jarName = anyJar.name; + } + } + if (!jarName) jarName = `Waterfall-${ver}-${lastBuild}.jar`; + const downloadUrl = `${base}/versions/${encodeURIComponent(ver)}/builds/${lastBuild}/downloads/${encodeURIComponent(jarName)}`; + const date = (buildMeta && typeof buildMeta.time === 'string') ? buildMeta.time.split('T')[0] : ''; + const entry = { + id: ver, + name: ver, + label: `Waterfall ${ver}`, + mcVersion: ver, + releaseDate: date, + tags: [], + build: lastBuild, + downloadUrl + }; + const channel = buildMeta && typeof buildMeta.channel === 'string' + ? buildMeta.channel.toLowerCase() + : ''; + if (channel) { + if (channel === 'default' || channel === 'stable') entry.tags.push('stable'); + else entry.tags.push('unstable', channel); + } else { + entry.tags.push('stable'); + } + if (buildMeta && buildMeta.promoted) entry.tags.push('recommended'); + out.push(entry); + } catch (_) { } + } + } + const workers = []; + for (let i = 0; i < concurrency; i++) workers.push(worker()); + await Promise.all(workers); + out.sort((a, b) => compareMcVersionsDesc(a.mcVersion || a.name, b.mcVersion || b.name)); + if (out.length) { + const t = out[0].tags || (out[0].tags = []); + if (!t.includes('latest')) t.push('latest'); + } + return { versions: out }; + } + async function fetchStoreProviders() { + const res = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions${storeTemplateQuery()}`); + if (!res.ok) throw new Error('Failed to load providers'); + const j = await res.json(); + storeProvidersCache = j.providers || []; + return j; + } + async function fetchStoreVersions(providerId) { + const pid = (providerId || '').toString().toLowerCase(); + if (pid.includes('vanilla')) return await fetchVanillaVersions(); + if (pid.includes('paper')) return await fetchPapermcVersions(); + if (pid.includes('purpur')) return await fetchPurpurVersions(); + if (pid.includes('velocity')) return await fetchVelocityVersions(); + if (pid.includes('waterfall')) return await fetchWaterfallVersions(); + if (pid.includes('folia')) return await fetchFoliaVersions(); + if (pid.includes('leaves')) return await fetchLeavesVersions(); + if (pid.includes('spigot')) return await fetchSpigotVersions(); + const res = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions/${encodeURIComponent(providerId)}${storeTemplateQuery()}`); + if (!res.ok) throw new Error('Failed to load provider versions'); + return await res.json(); + } + async function fetchPythonVersions() { + const list = document.getElementById("list"); + const response = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions/python${storeTemplateQuery()}`); + if (!response.ok) throw new Error('Failed to load Python versions'); + const data = await response.json(); + const versions = data.versions || []; + if (list) { + list.innerHTML = versions.map(v => ` +
+ ${escapeHtml(v.label)} +

+ +
+ `).join(""); + } + return { versions }; + } + async function loadNodeVersions() { + const list = document.getElementById("list"); + const res = await fetch(`/api/servers/${encodeURIComponent(bot)}/versions/nodejs${storeTemplateQuery()}`); + if (!res.ok) throw new Error('Failed to load Node.js versions'); + const data = await res.json(); + const versions = data.versions || []; + if (list) { + list.innerHTML = versions.map(v => ` +
+ ${escapeHtml(v.label)} +

+ +
+ `).join(""); + } + return { versions }; + } + async function submitStoreApplyRequest(payload, opts = {}) { + const { + confirmMessage = '', + skipConfirm = false, + progressMessage = 'Applying version...', + successMessage = 'Version applied', + errorPrefix = 'Apply failed', + silentSuccess = false + } = opts; + + if (!hasPerm('store_access')) throw new Error('Unauthorized'); + if (!skipConfirm && confirmMessage && !confirm(confirmMessage)) return { cancelled: true }; + + showProgressWheel(3, progressMessage); + try { + const response = await applyServerVersionWithActionToken(bot, payload); + const result = await response.json().catch(() => null); + if (response.status === 507 || (result && result.error === 'disk_limit_exceeded')) { + throw new Error((result && result.message) ? result.message : 'This server has exceeded its disk space limit.'); + } + if (!response.ok || !result?.ok) { + throw new Error(result?.detail || result?.error || `HTTP ${response.status}`); + } + try { await loadServerInfo(); updateStoreVisibility(); } catch { } + if (!silentSuccess) alert(result.message || successMessage); + return result; + } catch (e) { + throw new Error(`${errorPrefix}: ${e?.message || e}`); + } finally { + setTimeout(hideProgressWheel, 450); + } + } + async function changeNodeVersion(version, opts = {}) { + const payload = { providerId: 'nodejs', versionId: version }; + const tpl = resolveStoreTemplate().template; + if (tpl) payload.template = tpl; + return submitStoreApplyRequest(payload, { + confirmMessage: 'Switching Node.js versions will delete all existing files on this server. Continue?', + skipConfirm: !!opts.skipConfirm, + progressMessage: `Applying Node.js ${version}...`, + successMessage: 'Node.js version changed', + errorPrefix: 'Failed to change Node.js version', + silentSuccess: !!opts.silentSuccess + }); + } + async function changeVersion(version, opts = {}) { + const payload = { providerId: 'python', versionId: version }; + const tpl = resolveStoreTemplate().template; + if (tpl) payload.template = tpl; + return submitStoreApplyRequest(payload, { + confirmMessage: 'Switching Python versions will delete all existing files on this server. Continue?', + skipConfirm: !!opts.skipConfirm, + progressMessage: `Applying Python ${version}...`, + successMessage: 'Python version changed', + errorPrefix: 'Failed to change Python version', + silentSuccess: !!opts.silentSuccess + }); + } + async function renderStoreProvidersView(providersFromServer = null) { + if (!storeContent) return; + setActiveStoreTab('versions'); + storeCurrentProvider = null; + storeContent.innerHTML = '
Loading providers...
'; + try { + const providers = providersFromServer || (await fetchStoreProviders(), storeProvidersCache); + if (!providers || providers.length === 0) { + storeContent.innerHTML = '
No providers configured in versions.json.
'; + return; + } + const grid = document.createElement('div'); + grid.className = 'store-content-grid'; + providers.forEach(p => { + const card = document.createElement('button'); + card.className = 'store-provider-card'; + card.type = 'button'; + card.addEventListener('click', () => openProviderDetails(p)); + const logoWrap = document.createElement('div'); + logoWrap.className = 'store-provider-logo'; + if (p.logo) { + const img = document.createElement('img'); + img.src = p.logo; + img.alt = p.name || p.id || ''; + logoWrap.appendChild(img); + } else { + const span = document.createElement('span'); + span.className = 'store-provider-logo-placeholder'; + span.textContent = (p.name || p.id || '?').slice(0, 2).toUpperCase(); + logoWrap.appendChild(span); + } + const body = document.createElement('div'); + body.className = 'store-provider-body'; + const title = document.createElement('div'); + title.className = 'store-provider-name'; + title.textContent = p.name || p.id; + const desc = document.createElement('div'); + desc.className = 'store-provider-desc'; + desc.textContent = p.description || ''; + body.appendChild(title); + body.appendChild(desc); + const chevron = document.createElement('div'); + chevron.className = 'store-provider-chevron'; + chevron.innerHTML = ''; + card.appendChild(logoWrap); + card.appendChild(body); + card.appendChild(chevron); + grid.appendChild(card); + }); + storeContent.innerHTML = ''; + storeContent.appendChild(grid); + } catch (err) { + storeContent.innerHTML = `
Failed to load providers: ${escapeHtml(err.message || err)}
`; + } + } + async function applyVersion(providerId, versionId, displayLabel, downloadUrl, opts = {}) { + if (!hasPerm('store_access')) throw new Error('Unauthorized'); + const label = displayLabel || versionId; + const pid = (providerId || '').toString().toLowerCase(); + if (pid === 'python') { + return changeVersion(versionId, opts); + } + if (pid.includes('node')) { + return changeNodeVersion(versionId, opts); + } + if (pid === 'fivem') { + const payload = { providerId: 'fivem', versionId }; + payload.template = 'fivem'; + return submitStoreApplyRequest(payload, { + confirmMessage: `Install "${label}" on "${bot}"? This installation will delete your existing artifacts.`, + skipConfirm: !!opts.skipConfirm, + progressMessage: `Installing ${label}...`, + successMessage: `Installed ${label}`, + errorPrefix: 'Failed to install FiveM artifact', + silentSuccess: !!opts.silentSuccess + }); + } + const payload = { providerId, versionId }; + if (downloadUrl) payload.url = downloadUrl; + if (opts && opts.destPath) payload.destPath = opts.destPath; + const templateOverride = normalizeTemplate(opts?.template); + if (templateOverride) payload.template = templateOverride; + else { + const tpl = resolveStoreTemplate().template; + if (tpl) payload.template = tpl; + } + return submitStoreApplyRequest(payload, { + confirmMessage: `Install "${label}" on "${bot}"?`, + skipConfirm: !!opts.skipConfirm, + progressMessage: `Applying ${label}...`, + successMessage: `Installed ${label}`, + errorPrefix: 'Apply failed', + silentSuccess: !!opts.silentSuccess + }); + } + window.applyVersion = applyVersion; + async function openProviderDetails(provider, options = {}) { + if (!storeContent) return; + storeCurrentProvider = provider; + storeContent.innerHTML = '
Loading versions...
'; + try { + const data = await fetchStoreVersions(provider.id || provider.provider || ''); + const versions = data.versions || []; + const providerKey = (provider.id || provider.provider || data.provider || '').toString().toLowerCase(); + const isFivemProvider = providerKey === 'fivem'; + const wrapper = document.createElement('div'); + const header = document.createElement('div'); + header.className = 'store-provider-header'; + const left = document.createElement('div'); + left.className = 'store-provider-header-main'; + const logoWrap = document.createElement('div'); + logoWrap.className = 'store-provider-logo'; + if (provider.logo) { + const img = document.createElement('img'); + img.src = provider.logo; + img.alt = provider.name || provider.id || ''; + img.className = 'store-provider-header-logo'; + logoWrap.appendChild(img); + } else { + const span = document.createElement('span'); + span.className = 'store-provider-logo-placeholder'; + span.textContent = (provider.name || provider.id || '?').slice(0, 2).toUpperCase(); + logoWrap.appendChild(span); + } + const text = document.createElement('div'); + const nameEl = document.createElement('div'); + nameEl.className = 'store-provider-header-name'; + nameEl.textContent = provider.name || data.displayName || provider.id; + const descEl = document.createElement('div'); + descEl.className = 'store-provider-header-desc'; + descEl.textContent = provider.description || data.description || ''; + text.appendChild(nameEl); + text.appendChild(descEl); + left.appendChild(logoWrap); + left.appendChild(text); + const backBtn = document.createElement('button'); + backBtn.type = 'button'; + backBtn.className = 'store-back-btn'; + backBtn.innerHTML = ' Back'; + backBtn.addEventListener('click', () => renderStoreProvidersView()); + header.appendChild(left); + if (!options.direct) header.appendChild(backBtn); + wrapper.appendChild(header); + const note = document.createElement('div'); + note.className = 'store-note'; + if (isFivemProvider) { + note.textContent = 'NOTE: This installation will delete your existing artifacts'; + } else if ((provider.id || provider.provider || '').toString().toLowerCase() === 'python') { + note.textContent = 'WARNING: Switching Python runtimes will delete all existing files on this server.'; + } else { + note.textContent = 'NOTE: Click on a version to install it into the server (ONE-TAP)'; + } + wrapper.appendChild(note); + if (!versions.length) { + const empty = document.createElement('div'); + empty.className = 'store-empty'; + empty.textContent = 'No versions defined for this provider.'; + wrapper.appendChild(empty); + } else { + const list = document.createElement('div'); + list.className = 'store-version-list'; + versions.forEach(v => { + const row = document.createElement('div'); + row.className = 'store-version-row'; + const meta = document.createElement('div'); + meta.className = 'store-version-meta'; + const vn = document.createElement('div'); + vn.className = 'store-version-name'; + vn.textContent = v.label || v.name || v.id; + const vs = document.createElement('div'); + vs.className = 'store-version-sub'; + const parts = []; + if (v.mcVersion) parts.push(`MC ${v.mcVersion}`); + if (v.artifactVersion) parts.push(v.artifactVersion); + if (v.releaseDate) parts.push(v.releaseDate); + if (!parts.length && v.name) parts.push(String(v.name)); + const detail = parts.join(' • '); + vs.textContent = detail || (v.description || ''); + meta.appendChild(vn); + meta.appendChild(vs); + const tags = document.createElement('div'); + tags.className = 'store-version-tags'; + (v.tags || []).forEach(tag => { + if (!tag) return; + const t = String(tag).toLowerCase(); + const pill = document.createElement('span'); + pill.className = 'pill ' + (t === 'latest' || t === 'recommended' ? 'pill-green' : 'pill-muted'); + pill.textContent = t.toUpperCase(); + tags.appendChild(pill); + }); + row.appendChild(meta); + row.appendChild(tags); + row.addEventListener('click', () => { + 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)); + 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?`); + if (!proceed) return; + } + applyVersion(provider.id || provider.provider || '', id, label, downloadUrl) + .catch((err) => alert(err?.message || err)); + }); + list.appendChild(row); + }); + if (isFivemProvider) { + const customRow = document.createElement('div'); + customRow.className = 'store-version-row store-custom-version-row'; + customRow.innerHTML = ` +
+
Custom Version
+
Enter a build number or full artifact id.
+
+
+ + +
+ `; + const input = customRow.querySelector('.store-custom-version-input'); + const button = customRow.querySelector('.store-custom-version-btn'); + const submitCustom = () => { + const version = (input?.value || '').trim(); + if (!version) { + alert('Enter a FiveM artifact version first.'); + return; + } + applyVersion(provider.id || provider.provider || '', version, `FiveM artifact ${version}`, null, { template: 'fivem' }) + .catch((err) => alert(err?.message || err)); + }; + button.addEventListener('click', (event) => { + event.preventDefault(); + event.stopPropagation(); + submitCustom(); + }); + input.addEventListener('keydown', (event) => { + if (event.key === 'Enter') { + event.preventDefault(); + submitCustom(); + } + }); + list.appendChild(customRow); + } + wrapper.appendChild(list); + } + storeContent.innerHTML = ''; + storeContent.appendChild(wrapper); + } catch (err) { + storeContent.innerHTML = `
Failed to load versions: ${escapeHtml(err.message || err)}
`; + } + } + function renderPluginsPlaceholder() { + if (!storeContent) return; + setActiveStoreTab('plugins'); + storeContent.innerHTML = '
Plugins management UI will live here.
'; + } + function renderPluginsUI() { + if (!storeContent) return; + setActiveStoreTab('plugins'); + storeContent.innerHTML = ` +
+
+ + +
+
+ +
+ `; + const searchInput = document.getElementById("mrPluginSearch"); + const reloadBtn = document.getElementById("mrPluginReload"); + const loadMoreBtn = document.getElementById("mrPluginLoadMore"); + mrPluginsState.offset = 0; + mrPluginsState.more = true; + mrPluginsState.loading = false; + mrPluginsState.query = ""; + let searchTimeout = null; + searchInput.addEventListener("input", () => { + const q = searchInput.value.trim(); + if (searchTimeout) clearTimeout(searchTimeout); + searchTimeout = setTimeout(() => { + mrPluginsState.query = q; + loadModrinthPlugins(true); + }, 400); + }); + reloadBtn.addEventListener("click", () => { + searchInput.value = ""; + mrPluginsState.query = ""; + loadModrinthPlugins(true); + }); + loadMoreBtn.addEventListener("click", () => { + loadModrinthPlugins(false); + }); + loadModrinthPlugins(true); + } + async function loadModrinthPlugins(reset) { + const grid = document.getElementById("mrPluginGrid"); + const loadMoreBtn = document.getElementById("mrPluginLoadMore"); + if (!grid) return; + if (mrPluginsState.loading) return; + if (reset) { + mrPluginsState.offset = 0; + mrPluginsState.more = true; + grid.innerHTML = '
Loading plugins from Modrinth...
'; + } else if (!mrPluginsState.more) { + return; + } + mrPluginsState.loading = true; + try { + const facets = encodeURIComponent('[["project_type:plugin"]]'); + let url = `https://api.modrinth.com/v2/search?limit=${mrPluginsState.limit}&offset=${mrPluginsState.offset}&facets=${facets}`; + if (mrPluginsState.query) url += `&query=${encodeURIComponent(mrPluginsState.query)}`; + const res = await fetch(url); + if (!res.ok) { + grid.innerHTML = `
Failed to load plugins (${res.status})
`; + mrPluginsState.loading = false; + return; + } + const data = await res.json(); + const hits = Array.isArray(data.hits) ? data.hits : []; + if (reset) { + grid.innerHTML = ""; + } + if (!hits.length) { + if (mrPluginsState.offset === 0) { + grid.innerHTML = '
No plugins found on Modrinth for this query.
'; + } + mrPluginsState.more = false; + if (loadMoreBtn) loadMoreBtn.style.display = "none"; + } else { + const fragment = document.createDocumentFragment(); + hits.forEach(hit => renderModrinthCard(hit, fragment)); + grid.appendChild(fragment); + mrPluginsState.offset += hits.length; + if (loadMoreBtn) loadMoreBtn.style.display = (hits.length < mrPluginsState.limit) ? "none" : "inline-flex"; + } + } catch (e) { + grid.innerHTML = `
Failed to load plugins.
`; + } finally { + mrPluginsState.loading = false; + } + } + function renderModrinthCard(hit, target) { + const grid = target || document.getElementById("mrPluginGrid"); + if (!grid) return; + const card = document.createElement("div"); + card.className = "mr-plugin-card"; + const icon = hit.icon_url || ""; + const iconMarkup = icon + ? `` + : `
`; + const downloads = typeof hit.downloads === "number" ? hit.downloads : 0; + const downloadsText = downloads.toLocaleString(); + card.innerHTML = ` + ${iconMarkup} +
+
${escapeHtml(hit.title)}
+
${escapeHtml((hit.description || "").slice(0, 90))}${(hit.description || "").length > 90 ? "..." : ""}
+
+ + `; + card.querySelector(".mr-plugin-install-btn").addEventListener("click", (ev) => { + ev.stopPropagation(); + openModrinthPluginModal(hit.project_id, hit.title); + }); + card.addEventListener("click", () => openModrinthPluginModal(hit.project_id, hit.title)); + grid.appendChild(card); + } + async function openModrinthPluginModal(projectId, name) { + if (!mrPluginModal) return; + const requestedProjectId = projectId; + mrCurrentProjectId = projectId; + mrSelectedPlatform = null; + mrSelectedMcVersion = null; + mrPluginInstallBtn.disabled = true; + mrPluginName.textContent = name; + const platformSelect = document.getElementById("mrPlatformSelect"); + const versionSelect = document.getElementById("mrVersionSelect"); + if (!platformSelect || !versionSelect) return; + platformSelect.disabled = true; + versionSelect.disabled = true; + platformSelect.innerHTML = ``; + versionSelect.innerHTML = ``; + showModalElement(mrPluginModal); + try { + const res = await fetch(`https://api.modrinth.com/v2/project/${encodeURIComponent(projectId)}/version`); + if (mrCurrentProjectId !== requestedProjectId) return; + if (!res.ok) { + platformSelect.innerHTML = ``; + } else { + const versions = await res.json(); + if (mrCurrentProjectId !== requestedProjectId) return; + mrAllProjectVersions = Array.isArray(versions) ? versions : []; + populateModrinthPlatforms(); + } + } catch (e) { + if (mrCurrentProjectId !== requestedProjectId) return; + platformSelect.innerHTML = ``; + } + } + function closeModrinthPluginModal() { + if (!mrPluginModal) return; + mrCurrentProjectId = null; + animateClose(mrPluginModal, () => { + mrCurrentProjectId = null; + mrAllProjectVersions = []; + mrSelectedPlatform = null; + mrSelectedMcVersion = null; + const platformSelect = document.getElementById("mrPlatformSelect"); + const versionSelect = document.getElementById("mrVersionSelect"); + if (platformSelect) { + platformSelect.disabled = false; + platformSelect.innerHTML = ``; + } + if (versionSelect) { + versionSelect.disabled = true; + versionSelect.innerHTML = ``; + } + mrPluginInstallBtn.disabled = true; + mrPluginInstallBtn.classList.remove("is-loading"); + mrPluginInstallBtn.innerHTML = `Install Plugin`; + }); + } + if (mrPluginModalClose) mrPluginModalClose.addEventListener("click", (event) => { + event.preventDefault(); + event.stopImmediatePropagation(); + closeModrinthPluginModal(); + }); + if (mrPluginCancel) mrPluginCancel.addEventListener("click", (event) => { + event.preventDefault(); + closeModrinthPluginModal(); + }); + if (mrPluginModal) { + mrPluginModal.addEventListener("click", (e) => { + if (e.target === mrPluginModal) closeModrinthPluginModal(); + }); + } + function populateModrinthPlatforms() { + const platformSelect = document.getElementById("mrPlatformSelect"); + const versionSelect = document.getElementById("mrVersionSelect"); + if (!platformSelect || !versionSelect) return; + const loaderSet = new Set(); + (mrAllProjectVersions || []).forEach(v => { + (v.loaders || []).forEach(l => { + if (MR_VALID_LOADERS.includes(l)) loaderSet.add(l); + }); + }); + platformSelect.innerHTML = ``; + versionSelect.innerHTML = ``; + platformSelect.disabled = false; + versionSelect.disabled = true; + mrSelectedPlatform = null; + mrSelectedMcVersion = null; + mrPluginInstallBtn.disabled = true; + if (!loaderSet.size) { + platformSelect.disabled = true; + platformSelect.innerHTML = ``; + return; + } + Array.from(loaderSet).sort().forEach(loader => { + const opt = document.createElement('option'); + opt.value = loader; + opt.textContent = loader.toUpperCase(); + platformSelect.appendChild(opt); + }); + platformSelect.onchange = () => { + mrSelectedPlatform = platformSelect.value || null; + mrSelectedMcVersion = null; + mrPluginInstallBtn.disabled = true; + versionSelect.disabled = !mrSelectedPlatform; + populateModrinthVersions(); + }; + versionSelect.onchange = () => { + mrSelectedMcVersion = versionSelect.value || null; + mrPluginInstallBtn.disabled = !(mrSelectedPlatform && mrSelectedMcVersion); + }; + } + function populateModrinthVersions() { + const versionSelect = document.getElementById("mrVersionSelect"); + if (!versionSelect) return; + versionSelect.innerHTML = ``; + versionSelect.disabled = !mrSelectedPlatform; + if (!mrSelectedPlatform) return; + const versionsSet = new Set(); + (mrAllProjectVersions || []).forEach(v => { + if (!v.loaders || !v.game_versions) return; + if (!v.loaders.includes(mrSelectedPlatform)) return; + v.game_versions.forEach(gv => { + const match = String(gv).match(/^(\d+\.\d+(\.\d+)?)$/); + if (match) versionsSet.add(match[1]); + }); + }); + const list = Array.from(versionsSet).sort(compareMcVersionsDesc); + if (!list.length) { + versionSelect.disabled = true; + versionSelect.innerHTML = ``; + return; + } + versionSelect.disabled = false; + list.forEach(ver => { + const opt = document.createElement('option'); + opt.value = ver; + opt.textContent = ver; + versionSelect.appendChild(opt); + }); + } + mrPluginInstallBtn.addEventListener("click", async () => { + if (!mrCurrentProjectId || !mrSelectedPlatform || !mrSelectedMcVersion) return; + const match = (mrAllProjectVersions || []).find(v => + v.loaders && v.game_versions && + v.loaders.includes(mrSelectedPlatform) && + v.game_versions.includes(mrSelectedMcVersion) + ); + if (!match) { + alert("No matching Modrinth version found for this platform / Minecraft version."); + 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."); + return; + } + const label = `${mrPluginName.textContent} (${mrSelectedPlatform.toUpperCase()} ${mrSelectedMcVersion})`; + const pluginFileName = file.filename || file.url.split('/').pop() || 'plugin.jar'; + const installButtonHtml = mrPluginInstallBtn.innerHTML; + mrPluginInstallBtn.disabled = true; + mrPluginInstallBtn.classList.add("is-loading"); + 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)); + } finally { + mrPluginInstallBtn.classList.remove("is-loading"); + mrPluginInstallBtn.innerHTML = installButtonHtml; + if (!mrPluginModal || !mrPluginModal.classList.contains("closing")) { + mrPluginInstallBtn.disabled = !(mrSelectedPlatform && mrSelectedMcVersion); + } + } + }); + + function normalizeStoreComparable(value) { + return String(value || '').toLowerCase().replace(/[^a-z0-9.]+/g, ' ').trim(); + } + function buildStoreProviderAliases(provider) { + const aliases = new Set([ + String(provider?.id || '').toLowerCase(), + String(provider?.name || '').toLowerCase() + ]); + switch (String(provider?.id || '').toLowerCase()) { + case 'papermc': + aliases.add('paper'); + aliases.add('papermc'); + break; + case 'nodejs': + aliases.add('node'); + aliases.add('node.js'); + break; + case 'python': + aliases.add('py'); + break; + default: + break; + } + return Array.from(aliases).map((alias) => alias.trim()).filter(Boolean); + } + function matchStoreProviderFromMessage(message, providers) { + const raw = String(message || '').toLowerCase(); + let best = null; + for (const provider of (providers || [])) { + for (const alias of buildStoreProviderAliases(provider).sort((a, b) => b.length - a.length)) { + const pattern = new RegExp(`(^|[^a-z0-9])${escapeRegex(alias)}([^a-z0-9]|$)`, 'i'); + if (!pattern.test(raw)) continue; + const score = alias.length; + if (!best || score > best.score) { + best = { provider, score }; + } + break; + } + } + return best ? best.provider : null; + } + function findPreferredTaggedVersion(versions) { + const list = Array.isArray(versions) ? versions : []; + if (!list.length) return null; + const preferredTags = ['recommended', 'latest', 'lts', 'stable']; + for (const tag of preferredTags) { + const match = list.find((version) => + Array.isArray(version?.tags) && + version.tags.some((entry) => String(entry || '').toLowerCase() === tag) + ); + if (match) return match; + } + return list[0] || null; + } + function findRequestedVersionFromMessage(message, versions) { + const raw = String(message || '').toLowerCase(); + const list = Array.isArray(versions) ? versions : []; + if (!list.length) return null; + + const versionHints = Array.from(new Set(raw.match(/\b\d+(?:\.\d+){0,2}\b/g) || [])); + let best = null; + + list.forEach((version, index) => { + const candidates = [ + version?.id, + version?.name, + version?.label, + version?.mcVersion + ].filter(Boolean).map(normalizeStoreComparable); + const tagSet = new Set((version?.tags || []).map((entry) => String(entry || '').toLowerCase())); + let score = 0; + + versionHints.forEach((hint) => { + if (candidates.some((candidate) => candidate === hint)) score += 140; + else if (candidates.some((candidate) => candidate.endsWith(` ${hint}`) || candidate.startsWith(`${hint} `) || candidate.includes(hint))) score += 70; + }); + + if (/\brecommended\b/.test(raw) && tagSet.has('recommended')) score += 80; + if (/\blatest\b/.test(raw) && tagSet.has('latest')) score += 80; + if (/\blts\b/.test(raw) && tagSet.has('lts')) score += 80; + if (/\bstable\b/.test(raw) && (tagSet.has('stable') || tagSet.has('recommended'))) score += 70; + + if (!versionHints.length && !/\b(recommended|latest|lts|stable)\b/.test(raw)) { + return; + } + + if (!best || score > best.score || (score === best.score && index < best.index)) { + best = { version, score, index }; + } + }); + + if (best && best.score > 0) return best.version; + if (!versionHints.length) return findPreferredTaggedVersion(list); + if (list.length === 1) return list[0]; + return null; + } + function detectMinecraftProjectType(message) { + const raw = String(message || '').toLowerCase(); + if (/\bmods?\b/.test(raw)) return 'mod'; + if (/\bplugins?\b/.test(raw)) return 'plugin'; + return null; + } + function detectRequestedLoader(message, projectType) { + const raw = String(message || '').toLowerCase(); + const candidates = projectType === 'mod' ? MR_MOD_LOADERS : MR_PLUGIN_LOADERS; + return candidates.find((loader) => new RegExp(`(^|[^a-z0-9])${escapeRegex(loader)}([^a-z0-9]|$)`, 'i').test(raw)) || null; + } + function detectPreferredServerLoader(projectType) { + const runtimeHint = [ + serverInfo?.runtime?.providerId, + serverInfo?.start, + serverInfo?.template, + storeCurrentProvider?.id + ].filter(Boolean).join(' ').toLowerCase(); + + if (projectType === 'mod') { + if (runtimeHint.includes('neoforge')) return 'neoforge'; + if (runtimeHint.includes('forge')) return 'forge'; + if (runtimeHint.includes('fabric')) return 'fabric'; + if (runtimeHint.includes('quilt')) return 'quilt'; + return null; + } + + if (runtimeHint.includes('purpur')) return 'purpur'; + if (runtimeHint.includes('spigot')) return 'spigot'; + if (runtimeHint.includes('bukkit')) return 'bukkit'; + if (runtimeHint.includes('velocity')) return 'velocity'; + if (runtimeHint.includes('waterfall')) return 'waterfall'; + if (runtimeHint.includes('folia')) return 'folia'; + if (runtimeHint.includes('paper')) return 'paper'; + return null; + } + function detectRequestedMinecraftVersion(message) { + const match = String(message || '').match(/\b1\.\d+(?:\.\d+)?\b/); + return match ? match[0] : null; + } + function extractRequestedProjectName(message, projectType) { + const quoted = String(message || '').match(/["'`]([^"'`]{2,120})["'`]/); + if (quoted) return quoted[1].trim(); + + const pattern = projectType === 'mod' + ? /(?:install|add|download|setup|set up|use|put|pune|adauga|instaleaza)\s+(?:the\s+)?(?:mod(?:ul)?\s+)?(.+)/i + : /(?:install|add|download|setup|set up|use|put|pune|adauga|instaleaza)\s+(?:the\s+)?(?:plugin(?:ul)?\s+)?(.+)/i; + + const match = String(message || '').match(pattern); + let candidate = match ? match[1] : ''; + candidate = candidate.replace(/\b(?:for|on|pe|la|using|with)\b[\s\S]*$/i, ' ').trim(); + candidate = candidate + .replace(/\b(?:paper|purpur|spigot|bukkit|velocity|waterfall|folia|fabric|forge|neoforge|quilt)\b/gi, ' ') + .replace(/\b1\.\d+(?:\.\d+)?\b/g, ' ') + .replace(/\s+/g, ' ') + .trim(); + return candidate || null; + } + async function searchModrinthProjects(query, projectType) { + const facets = encodeURIComponent(JSON.stringify([[`project_type:${projectType}`]])); + const url = `https://api.modrinth.com/v2/search?limit=8&query=${encodeURIComponent(query)}&facets=${facets}`; + const response = await fetch(url); + if (!response.ok) throw new Error(`Modrinth search failed (${response.status})`); + const data = await response.json().catch(() => ({})); + return Array.isArray(data?.hits) ? data.hits : []; + } + async function fetchModrinthVersions(projectId) { + const response = await fetch(`https://api.modrinth.com/v2/project/${encodeURIComponent(projectId)}/version`); + if (!response.ok) throw new Error(`Modrinth versions failed (${response.status})`); + const data = await response.json().catch(() => []); + return Array.isArray(data) ? data : []; + } + function chooseModrinthSearchHit(hits, query) { + const needle = normalizeStoreComparable(query); + if (!needle) return hits[0] || null; + const exact = hits.find((hit) => { + const fields = [hit?.title, hit?.slug, hit?.project_id].filter(Boolean).map(normalizeStoreComparable); + return fields.some((field) => field === needle); + }); + return exact || hits[0] || null; + } + function chooseModrinthInstallVersion(allVersions, opts = {}) { + let loader = opts.loader || null; + let mcVersion = opts.mcVersion || null; + const versions = Array.isArray(allVersions) ? allVersions : []; + + const allLoaders = Array.from(new Set( + versions.flatMap((version) => Array.isArray(version?.loaders) ? version.loaders : []) + .map((entry) => String(entry || '').toLowerCase()) + .filter(Boolean) + )); + + if (!loader) { + if (allLoaders.length === 1) loader = allLoaders[0]; + else return { error: 'missing_loader', loaders: allLoaders.slice(0, 6) }; + } + + const loaderVersions = versions.filter((version) => + Array.isArray(version?.loaders) && + version.loaders.map((entry) => String(entry || '').toLowerCase()).includes(loader) + ); + if (!loaderVersions.length) return { error: 'no_loader_match', loader }; + + const availableVersions = Array.from(new Set( + loaderVersions.flatMap((version) => Array.isArray(version?.game_versions) ? version.game_versions : []) + .map((entry) => String(entry || '')) + .filter((entry) => /^\d+\.\d+(?:\.\d+)?$/.test(entry)) + )).sort(compareMcVersionsDesc); + + if (!mcVersion) { + if (availableVersions.length === 1) mcVersion = availableVersions[0]; + else return { error: 'missing_mc_version', loader, versions: availableVersions.slice(0, 6) }; + } + + const exactVersions = loaderVersions.filter((version) => + Array.isArray(version?.game_versions) && version.game_versions.includes(mcVersion) + ); + if (!exactVersions.length) return { error: 'no_version_match', loader, mcVersion, versions: availableVersions.slice(0, 6) }; + + exactVersions.sort((a, b) => { + if (!!b.featured !== !!a.featured) return b.featured ? 1 : -1; + const aTime = Date.parse(a?.date_published || a?.date_created || 0) || 0; + const bTime = Date.parse(b?.date_published || b?.date_created || 0) || 0; + return bTime - aTime; + }); + + const version = exactVersions[0]; + const file = (version?.files || []).find((entry) => entry?.primary) || (version?.files || [])[0]; + if (!file?.url) return { error: 'missing_file', loader, mcVersion }; + + return { loader, mcVersion, version, file }; + } + function collectModrinthLoaders(allVersions, projectType) { + const allowedLoaders = projectType === 'mod' + ? MR_MOD_LOADERS + : projectType === 'plugin' + ? MR_PLUGIN_LOADERS + : MR_VALID_LOADERS; + + return Array.from(new Set( + (Array.isArray(allVersions) ? allVersions : []) + .flatMap((version) => Array.isArray(version?.loaders) ? version.loaders : []) + .map((entry) => String(entry || '').toLowerCase()) + .filter((entry) => allowedLoaders.includes(entry)) + )).sort(); + } + function collectModrinthMinecraftVersions(allVersions, loader = null) { + const normalizedLoader = loader ? String(loader).toLowerCase() : null; + return Array.from(new Set( + (Array.isArray(allVersions) ? allVersions : []) + .filter((version) => { + if (!normalizedLoader) return true; + return Array.isArray(version?.loaders) && + version.loaders.map((entry) => String(entry || '').toLowerCase()).includes(normalizedLoader); + }) + .flatMap((version) => Array.isArray(version?.game_versions) ? version.game_versions : []) + .map((entry) => String(entry || '').trim()) + .filter((entry) => /^\d+\.\d+(?:\.\d+)?$/.test(entry)) + )).sort(compareMcVersionsDesc); + } + function planModrinthInstallRequirements(opts = {}) { + const projectVersions = Array.isArray(opts.projectVersions) ? opts.projectVersions : []; + const availableLoaders = collectModrinthLoaders(projectVersions, opts.projectType); + const selectedLoader = opts.loader ? String(opts.loader).toLowerCase() : (availableLoaders.length === 1 ? availableLoaders[0] : null); + const availableVersions = collectModrinthMinecraftVersions(projectVersions, selectedLoader); + const selectedMcVersion = opts.mcVersion || (availableVersions.length === 1 ? availableVersions[0] : null); + const missing = []; + + if (!selectedLoader) missing.push('loader'); + if (!selectedMcVersion) missing.push('mcVersion'); + + return { + projectType: opts.projectType, + query: opts.query, + projectId: opts.projectId, + projectTitle: opts.projectTitle, + loader: selectedLoader, + mcVersion: selectedMcVersion, + missing, + availableLoaders: availableLoaders.slice(0, 6), + availableVersions: availableVersions.slice(0, 6) + }; + } + function buildPendingStoreFollowUpPrompt(intent) { + const label = intent.projectTitle || intent.query || 'this project'; + const loaderLabel = intent.projectType === 'mod' ? 'loader' : 'server fork and loader'; + const loaderWord = intent.projectType === 'mod' ? 'loaders' : 'platforms'; + const exampleLoader = intent.loader || intent.availableLoaders[0] || (intent.projectType === 'mod' ? 'fabric' : 'paper'); + const exampleVersion = intent.mcVersion || intent.availableVersions[0] || '1.21.4'; + const loaderList = intent.availableLoaders.length ? ` Available ${loaderWord}: ${intent.availableLoaders.join(', ')}.` : ''; + const versionList = intent.availableVersions.length ? ` Available versions: ${intent.availableVersions.join(', ')}.` : ''; + + if (intent.missing.includes('loader') && intent.missing.includes('mcVersion')) { + return `I found **${label}**. Reply once with the ${loaderLabel} and Minecraft version, for example: ${exampleLoader} ${exampleVersion}.${loaderList}${versionList}`; + } + if (intent.missing.includes('loader')) { + return `I found **${label}**. Reply once with the ${loaderLabel}, for example: ${exampleLoader}.${loaderList}`; + } + return `I found **${label}**. Reply once with the Minecraft version for **${intent.loader}**, for example: ${exampleVersion}.${versionList}`; + } + function buildPendingModrinthFollowUpOperation(plan) { + if (!plan?.missing?.length) return null; + return { + type: 'follow_up', + source: 'modrinth', + projectType: plan.projectType, + query: plan.query, + projectId: plan.projectId, + projectTitle: plan.projectTitle, + loader: plan.loader || null, + mcVersion: plan.mcVersion || null, + missing: Array.isArray(plan.missing) ? plan.missing.slice() : [], + availableLoaders: Array.isArray(plan.availableLoaders) ? plan.availableLoaders.slice() : [], + availableVersions: Array.isArray(plan.availableVersions) ? plan.availableVersions.slice() : [], + prompt: buildPendingStoreFollowUpPrompt(plan) + }; + } + async function resolveModrinthProjectOperation(opts = {}) { + const projectType = opts.projectType; + const query = String(opts.query || opts.projectTitle || '').trim(); + let projectId = String(opts.projectId || '').trim(); + let projectTitle = String(opts.projectTitle || query || '').trim(); + + if (!projectType) { + return { type: 'message', message: 'Tell me whether you want a plugin or a mod.' }; + } + if (!projectId) { + if (!query) { + return { type: 'message', message: `Tell me the exact ${projectType} name you want to install.` }; + } + const hits = await searchModrinthProjects(query, projectType); + const hit = chooseModrinthSearchHit(hits, query); + if (!hit?.project_id) { + return { type: 'message', message: `I could not find a Modrinth ${projectType} matching "${query}".` }; + } + projectId = hit.project_id; + projectTitle = hit.title || query; + } + + const projectVersions = await fetchModrinthVersions(projectId); + if (!projectVersions.length) { + return { type: 'message', message: `I found **${projectTitle || query}**, but it has no installable builds on Modrinth right now.` }; + } + + const plan = planModrinthInstallRequirements({ + projectType, + query, + projectId, + projectTitle, + projectVersions, + loader: opts.loader, + mcVersion: opts.mcVersion + }); + const followUp = buildPendingModrinthFollowUpOperation(plan); + if (followUp) return followUp; + + const resolved = chooseModrinthInstallVersion(projectVersions, { + loader: plan.loader, + mcVersion: plan.mcVersion + }); + + if (resolved.error === 'no_loader_match') { + return buildPendingModrinthFollowUpOperation(planModrinthInstallRequirements({ + projectType, + query, + projectId, + projectTitle, + projectVersions, + loader: null, + mcVersion: opts.mcVersion + })) || { + type: 'message', + message: `I found **${projectTitle || query}**, but it does not support **${resolved.loader}**.` + }; + } + + if (resolved.error === 'no_version_match') { + return buildPendingModrinthFollowUpOperation(planModrinthInstallRequirements({ + projectType, + query, + projectId, + projectTitle, + projectVersions, + loader: resolved.loader || plan.loader, + mcVersion: null + })) || { + type: 'message', + message: `I found **${projectTitle || query}**, but not for Minecraft **${resolved.mcVersion}**.` + }; + } + + if (resolved.error === 'missing_file') { + return { + type: 'message', + message: `I found **${projectTitle || query}**, but the matched ${projectType} build does not expose a downloadable file.` + }; + } + + if (resolved.error) { + return { + type: 'message', + message: `I found **${projectTitle || query}**, but I could not match a downloadable ${projectType} build for this request.` + }; + } + + const fileName = resolved.file.filename || resolved.file.url.split('/').pop() || `${projectType}.jar`; + const destRoot = projectType === 'mod' ? 'mods' : 'plugins'; + return { + type: 'modrinth', + projectType, + projectId, + projectTitle: projectTitle || query, + loader: resolved.loader, + mcVersion: resolved.mcVersion, + versionId: resolved.version.id || `${projectId}-${resolved.loader}-${resolved.mcVersion}`, + label: `${projectTitle || query} (${resolved.loader.toUpperCase()} ${resolved.mcVersion})`, + downloadUrl: resolved.file.url, + destPath: `${destRoot}/${fileName}` + }; + } + function isLikelyStoreFollowUpAnswer(message, pending) { + if (!pending || pending.source !== 'modrinth') return false; + const raw = String(message || '').trim(); + if (!raw) return false; + if (detectRequestedLoader(raw, pending.projectType)) return true; + if (detectRequestedMinecraftVersion(raw)) return true; + return (pending.availableLoaders || []).some((loader) => + new RegExp(`(^|[^a-z0-9])${escapeRegex(loader)}([^a-z0-9]|$)`, 'i').test(raw) + ); + } + async function continuePendingStoreFollowUp(message) { + if (!aiPendingStoreFollowUp || aiPendingStoreFollowUp.source !== 'modrinth') return null; + if (!isLikelyStoreFollowUpAnswer(message, aiPendingStoreFollowUp)) return null; + + const loader = detectRequestedLoader(message, aiPendingStoreFollowUp.projectType) || aiPendingStoreFollowUp.loader || null; + const mcVersion = detectRequestedMinecraftVersion(message) || aiPendingStoreFollowUp.mcVersion || null; + const nextOperation = await resolveModrinthProjectOperation({ + projectType: aiPendingStoreFollowUp.projectType, + query: aiPendingStoreFollowUp.query, + projectId: aiPendingStoreFollowUp.projectId, + projectTitle: aiPendingStoreFollowUp.projectTitle, + loader, + mcVersion + }); + + if (nextOperation?.type === 'message') { + clearPendingStoreFollowUp(); + } + + return nextOperation; + } + function parseAiStoreInstallCommand(spec) { + const raw = String(spec || '').trim(); + if (!raw) return null; + + const parts = raw.split(':').map((part) => part.trim()).filter(Boolean); + if (!parts.length) return null; + + const projectName = parts[0].replace(/^["'`]+|["'`]+$/g, '').trim(); + if (!projectName) return null; + + let loader = null; + let mcVersion = null; + let projectType = aiPendingStoreFollowUp?.projectType || null; + + parts.slice(1).forEach((part) => { + const token = String(part || '').trim().split(/\s+/)[0].replace(/[.,!?;:]+$/g, ''); + const lowerToken = token.toLowerCase(); + if (!token) return; + if (!mcVersion && /^\d+\.\d+(?:\.\d+)?$/.test(token)) { + mcVersion = token; + return; + } + if (!loader && MR_VALID_LOADERS.includes(lowerToken)) { + loader = lowerToken; + if (!projectType) { + projectType = MR_MOD_LOADERS.includes(lowerToken) ? 'mod' : 'plugin'; + } + } + }); + + if (!projectType && loader) { + projectType = MR_MOD_LOADERS.includes(loader) ? 'mod' : 'plugin'; + } + + return { + type: 'ai_store_install', + projectName, + projectType, + loader, + mcVersion + }; + } + async function resolveDirectAiStoreOperation(message) { + const raw = String(message || '').trim(); + const lower = raw.toLowerCase(); + if (!raw) return null; + + const hasActionVerb = /\b(install|add|apply|switch|change|set|use|update|upgrade|downgrade|download|instaleaza|adauga|schimba|seteaza|pune|aplica|trece)\b/i.test(raw); + const touchesStore = /\b(store|version|runtime|container|paper|papermc|purpur|pufferfish|vanilla|spigot|velocity|waterfall|folia|leaves|node(?:\.js)?|python|fivem|fxserver|artifact|artifacts|plugin|plugins|mod|mods|modrinth)\b/i.test(raw); + if (!hasActionVerb || !touchesStore) return null; + + if (!hasPerm('store_access')) { + return { type: 'message', message: 'You do not have permission to use this server store.' }; + } + + if (!serverInfo) { + try { await loadServerInfo(); } catch { } + } + + const { template: tpl } = resolveStoreTemplate(); + if (!tpl) { + return { type: 'message', message: 'Choose the Store template for this server first, then I can install versions, plugins, or mods.' }; + } + + const projectType = detectMinecraftProjectType(raw); + if (projectType) { + if (tpl !== 'minecraft') { + return { type: 'message', message: 'Plugins and mods are available only for Minecraft server templates.' }; + } + + const query = extractRequestedProjectName(raw, projectType); + const loader = detectRequestedLoader(raw, projectType) || detectPreferredServerLoader(projectType); + const mcVersion = detectRequestedMinecraftVersion(raw); + return resolveModrinthProjectOperation({ + projectType, + query, + loader, + mcVersion + }); + } + + const providersData = await fetchStoreProviders().catch(() => null); + const providers = Array.isArray(storeProvidersCache) ? storeProvidersCache : (providersData?.providers || []); + if (!providers.length) { + return { type: 'message', message: 'I could not load the Store providers for this server.' }; + } + + const provider = matchStoreProviderFromMessage(raw, providers); + if (!provider) return null; + + const versionData = await fetchStoreVersions(provider.id).catch(() => null); + const versions = Array.isArray(versionData?.versions) ? versionData.versions : []; + if (!versions.length) { + return { type: 'message', message: `I could not find installable versions for ${provider.name || provider.id}.` }; + } + + const version = findRequestedVersionFromMessage(raw, versions); + if (!version) { + const examples = versions.slice(0, 5).map((entry) => entry?.label || entry?.name || entry?.id).filter(Boolean).join(', '); + return { + type: 'message', + message: `Tell me the exact ${provider.name || provider.id} version to install. Examples: ${examples}.` + }; + } + + return { + type: 'version', + providerId: provider.id, + versionId: version.id || version.name || version.version || '', + label: version.label || version.name || version.id || provider.name || provider.id, + downloadUrl: version.downloadUrl || version.url || null, + template: tpl + }; + } + async function executeStoreOperation(operation) { + if (!operation) return false; + if (operation.type === 'message') { + await addChatMessage('ai', operation.message); + return true; + } + + try { + if (operation.type === 'follow_up') { + aiPendingStoreFollowUp = { + ...operation, + missing: Array.isArray(operation.missing) ? operation.missing.slice() : [], + availableLoaders: Array.isArray(operation.availableLoaders) ? operation.availableLoaders.slice() : [], + availableVersions: Array.isArray(operation.availableVersions) ? operation.availableVersions.slice() : [] + }; + await addChatMessage('ai', operation.prompt || 'Tell me the missing Store details in one reply.'); + return true; + } + + clearPendingStoreFollowUp(); + + if (operation.type === 'ai_store_install') { + const candidateTypes = operation.projectType ? [operation.projectType] : ['plugin', 'mod']; + let resolved = null; + + for (const candidateType of candidateTypes) { + resolved = await resolveModrinthProjectOperation({ + projectType: candidateType, + query: operation.projectName, + loader: operation.loader, + mcVersion: operation.mcVersion + }); + if (!resolved) continue; + if (resolved.type !== 'message' || !/could not find a modrinth/i.test(String(resolved.message || ''))) { + break; + } + } + + if (!resolved) { + await addChatMessage('ai', 'I could not match that Store install request.'); + return true; + } + + return executeStoreOperation(resolved); + } + + if (operation.type === 'version') { + await applyVersion(operation.providerId, operation.versionId, operation.label, operation.downloadUrl, { + skipConfirm: true, + silentSuccess: true, + template: operation.template + }); + await addChatMessage('ai', `Installed **${operation.label}** on **${bot}**.`); + return true; + } + + if (operation.type === 'modrinth') { + await applyVersion(`modrinth-${operation.projectType}`, operation.versionId, operation.label, operation.downloadUrl, { + destPath: operation.destPath, + skipConfirm: true, + silentSuccess: true, + template: 'minecraft' + }); + await addChatMessage('ai', `Installed **${operation.label}** in \`${operation.destPath}\`.`); + return true; + } + } catch (err) { + clearPendingStoreFollowUp(); + await addChatMessage('ai', err?.message || 'Failed to complete the Store action.'); + return true; + } + + return false; + } + + async function openInfoModal() { + if (!serverInfo) await loadServerInfo(); + const ip = serverInfo && serverInfo.ip ? serverInfo.ip : "—"; + const port = (serverInfo && (serverInfo.port !== undefined && serverInfo.port !== null)) ? serverInfo.port : "—"; + infoIp.textContent = ip; + infoPort.textContent = String(port); + infoAddress.value = (ip !== "—") ? formatAddress(ip, (port !== "—") ? port : undefined) : ""; + + currentSftpPassword = null; + sftpPasswordVisible = false; + if (infoSftpSection) infoSftpSection.style.display = 'none'; + if (infoSftpNoAccess) infoSftpNoAccess.style.display = 'none'; + + showModalElement(infoModal); + + try { + const res = await fetch(`/api/server/${encodeURIComponent(bot)}/sftp-credentials`); + if (res.ok) { + const data = await res.json(); + + if (data.hasFileAccess) { + if (infoSftpSection) infoSftpSection.style.display = 'block'; + if (infoSftpNoAccess) infoSftpNoAccess.style.display = 'none'; + + if (infoSftpHost) infoSftpHost.textContent = data.connection?.host || ip || '—'; + if (infoSftpPort) infoSftpPort.textContent = data.connection?.port || '2022'; + + if (data.credentials) { + if (infoSftpUser) infoSftpUser.textContent = data.credentials.username || '—'; + + if (data.credentials.password) { + currentSftpPassword = data.credentials.password; + showSftpPassword(true); + } else { + currentSftpPassword = null; + hideSftpPassword(); + } + } + } else if (data.hasAccess) { + if (infoSftpSection) infoSftpSection.style.display = 'none'; + if (infoSftpNoAccess) infoSftpNoAccess.style.display = 'block'; + } else { + if (infoSftpSection) infoSftpSection.style.display = 'none'; + if (infoSftpNoAccess) infoSftpNoAccess.style.display = 'none'; + } + } + } catch (err) { + console.error('[Info Modal] Error fetching SFTP credentials:', err); + } + } + + function showSftpPassword(isNew = false) { + sftpPasswordVisible = true; + if (infoSftpPassMask) infoSftpPassMask.style.display = 'none'; + if (infoSftpPassText) { + infoSftpPassText.style.display = 'inline'; + infoSftpPassText.textContent = currentSftpPassword || '—'; + } + if (infoSftpTogglePass) { + const icon = infoSftpTogglePass.querySelector('i'); + if (icon) icon.className = 'fa-solid fa-eye-slash'; + } + if (isNew && currentSftpPassword) { + if (infoSftpPass) { + infoSftpPass.style.background = 'rgba(16, 185, 129, 0.15)'; + setTimeout(() => { if (infoSftpPass) infoSftpPass.style.background = ''; }, 2000); + } + } + } + + function hideSftpPassword() { + sftpPasswordVisible = false; + if (infoSftpPassMask) infoSftpPassMask.style.display = 'inline'; + if (infoSftpPassText) infoSftpPassText.style.display = 'none'; + if (infoSftpTogglePass) { + const icon = infoSftpTogglePass.querySelector('i'); + if (icon) icon.className = 'fa-solid fa-eye'; + } + } + + if (infoSftpTogglePass) { + infoSftpTogglePass.addEventListener('click', () => { + if (currentSftpPassword) { + if (sftpPasswordVisible) { + hideSftpPassword(); + } else { + showSftpPassword(); + } + } else { + alert('Password not available. Click "Regenerate Password" to create a new one.'); + } + }); + } + + if (infoSftpRegenBtn) { + infoSftpRegenBtn.addEventListener('click', async () => { + if (!confirm('This will generate a new SFTP password. Your old password will stop working immediately. Continue?')) { + return; + } + + infoSftpRegenBtn.disabled = true; + const originalText = infoSftpRegenBtn.innerHTML; + infoSftpRegenBtn.innerHTML = ' Generating...'; + + try { + const res = await fetch(`/api/server/${encodeURIComponent(bot)}/sftp-credentials/regenerate`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' } + }); + + if (res.ok) { + const data = await res.json(); + if (data.success && data.password) { + currentSftpPassword = data.password; + if (infoSftpUser) infoSftpUser.textContent = data.username || infoSftpUser.textContent; + showSftpPassword(true); + + try { + await navigator.clipboard.writeText(data.password); + alert('New password generated and copied to clipboard!\n\nMake sure to save it - it won\'t be shown again.'); + } catch { + alert('New password generated!\n\nPassword: ' + data.password + '\n\nMake sure to save it - it won\'t be shown again.'); + } + } else { + alert('Failed to regenerate password'); + } + } else { + const err = await res.json().catch(() => ({})); + alert('Error: ' + (err.error || 'Failed to regenerate password')); + } + } catch (err) { + console.error('[SFTP] Regenerate error:', err); + alert('Network error while regenerating password'); + } finally { + infoSftpRegenBtn.disabled = false; + infoSftpRegenBtn.innerHTML = originalText; + } + }); + } + + document.querySelectorAll('.info-card-copy[data-copy]').forEach(btn => { + btn.addEventListener('click', async () => { + const targetId = btn.getAttribute('data-copy'); + let value = ''; + + if (targetId === 'infoSftpPassValue') { + value = currentSftpPassword || ''; + if (!value) { + alert('Password not available. Click "Regenerate Password" to create a new one.'); + return; + } + } else { + const el = document.getElementById(targetId); + value = el?.textContent || ''; + } + + if (value && value !== '—') { + try { + await navigator.clipboard.writeText(value); + const icon = btn.querySelector('i'); + if (icon) { + icon.className = 'fa-solid fa-check'; + setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500); + } + } catch { + alert('Failed to copy: ' + value); + } + } + }); + }); + + function closeInfoModal() { + if (!infoModal) return; + animateClose(infoModal); + currentSftpPassword = null; + sftpPasswordVisible = false; + hideSftpPassword(); + } + + infoModalClose.addEventListener('click', closeInfoModal); + + const activityModal = document.getElementById('activityModal'); + const activityModalClose = document.getElementById('activityModalClose'); + const activityList = document.getElementById('activityList'); + const activitySearchInput = document.getElementById('activitySearchInput'); + const activityLoadMore = document.getElementById('activityLoadMore'); + let activityData = []; + let activityOffset = 0; + const ACTIVITY_LIMIT = 50; + let activityFilter = 'all'; + + async function loadActivityLogs(append = false) { + if (!append) { + activityOffset = 0; + activityData = []; + activityList.innerHTML = '
Loading activity...
'; + } + try { + const res = await fetch(`/api/server/${encodeURIComponent(bot)}/activity?offset=${activityOffset}&limit=${ACTIVITY_LIMIT}`); + if (!res.ok) throw new Error('Failed to load activity'); + const data = await res.json(); + const entries = Array.isArray(data.entries) ? data.entries : []; + activityData = append ? [...activityData, ...entries] : entries; + activityOffset += entries.length; + renderActivityList(); + if (activityLoadMore) { + activityLoadMore.style.display = entries.length < ACTIVITY_LIMIT ? 'none' : 'flex'; + } + } catch (err) { + console.error('Activity load error:', err); + activityList.innerHTML = '

Failed to load activity logs

'; + } + } + + function renderActivityList() { + const query = (activitySearchInput?.value || '').toLowerCase(); + let filtered = activityData.filter(e => { + if (activityFilter !== 'all') { + const action = String(e.action || '').toLowerCase(); + if (activityFilter === 'power' && !['start', 'stop', 'restart', 'kill', 'run'].some(a => action.includes(a))) return false; + if (activityFilter === 'console' && !action.includes('command')) return false; + if (activityFilter === 'file' && !['file', 'upload', 'delete', 'rename', 'create', 'extract'].some(a => action.includes(a))) return false; + } + if (query) { + const text = `${e.user || ''} ${e.ip || ''} ${e.action || ''} ${JSON.stringify(e.details || '')}`.toLowerCase(); + if (!text.includes(query)) return false; + } + return true; + }); + if (filtered.length === 0) { + activityList.innerHTML = '

No activity found

'; + return; + } + activityList.innerHTML = filtered.map(e => { + const ts = e.ts ? new Date(e.ts).toLocaleString() : '—'; + const action = escapeHtml(e.action || 'unknown'); + 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)) : ''; + let icon = 'fa-circle-info'; + const actionLower = 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'; + else if (actionLower.includes('command')) icon = 'fa-terminal'; + else if (actionLower.includes('file') || actionLower.includes('upload') || actionLower.includes('delete')) icon = 'fa-file'; + let iconType = 'console'; + if (actionLower.includes('start') || actionLower.includes('run')) iconType = 'start'; + else if (actionLower.includes('kill')) iconType = 'kill'; + else if (actionLower.includes('stop')) iconType = 'stop'; + else if (actionLower.includes('restart')) iconType = 'restart'; + else if (actionLower.includes('file') || actionLower.includes('upload') || actionLower.includes('delete')) iconType = 'file'; + return `
${action}
${details ? `
${details}
` : ''}
`; + }).join(''); + } + + function openActivityModal() { + if (!activityModal) return; + if (!hasPerm('activity_logs')) { alert('You do not have permission to view activity logs'); return; } + showModalElement(activityModal); + afterModalPaint(() => loadActivityLogs()); + } + + function closeActivityModal() { + if (!activityModal) return; + animateClose(activityModal); + } + + if (activityModalClose) activityModalClose.addEventListener('click', closeActivityModal); + if (activitySearchInput) activitySearchInput.addEventListener('input', () => renderActivityList()); + if (activityLoadMore) activityLoadMore.addEventListener('click', () => loadActivityLogs(true)); + document.querySelectorAll('.activity-pill').forEach(pill => { + pill.addEventListener('click', () => { + document.querySelectorAll('.activity-pill').forEach(p => p.classList.remove('active')); + pill.classList.add('active'); + activityFilter = pill.dataset.filter || 'all'; + renderActivityList(); + }); + }); + + const backupsModal = document.getElementById('backupsModal'); + const backupsModalClose = document.getElementById('backupsModalClose'); + const backupsList = document.getElementById('backupsList'); + const backupsCreateBtn = document.getElementById('backupsCreateBtn'); + const backupsRefreshBtn = document.getElementById('backupsRefreshBtn'); + const backupCreateModal = document.getElementById('backupCreateModal'); + const backupCreateClose = document.getElementById('backupCreateClose'); + const backupCreateCancel = document.getElementById('backupCreateCancel'); + const backupCreateConfirm = document.getElementById('backupCreateConfirm'); + const backupNameInput = document.getElementById('backupNameInput'); + const backupDescInput = document.getElementById('backupDescInput'); + + async function loadBackups() { + if (!backupsList) return; + backupsList.innerHTML = '
Loading backups...
'; + if (backupsRefreshBtn) backupsRefreshBtn.classList.add('is-loading'); + try { + const res = await fetch(`/api/nodes/server/${encodeURIComponent(bot)}/backups`); + if (!res.ok) throw new Error('Failed to load backups'); + const data = await res.json(); + const backups = Array.isArray(data.backups) ? data.backups : []; + renderBackupsList(backups); + } catch (err) { + console.error('Backups load error:', err); + backupsList.innerHTML = '

Failed to load backups

'; + } finally { + if (backupsRefreshBtn) backupsRefreshBtn.classList.remove('is-loading'); + } + } + + function renderBackupsList(backups) { + if (!backups || backups.length === 0) { + const hint = hasPerm('backups_create') ? 'Create your first backup to protect your server data' : 'No backups available'; + backupsList.innerHTML = `

No backups found

${hint}

`; + return; + } + const canDelete = hasPerm('backups_delete'); + backupsList.innerHTML = backups.map(b => { + const name = escapeHtml(b.name || b.id || 'Unnamed'); + const desc = b.description ? escapeHtml(b.description) : ''; + const size = b.size ? formatBytes(b.size) : '—'; + const created = b.created_at ? new Date(b.created_at).toLocaleString() : '—'; + const deleteBtn = canDelete ? `` : ''; + return `
${name}
${desc ? `
${desc}
` : ''}
${created} ${size}
${deleteBtn}
`; + }).join(''); + + backupsList.querySelectorAll('.backup-action-btn.restore').forEach(btn => { + btn.addEventListener('click', () => restoreBackup(btn.dataset.id)); + }); + backupsList.querySelectorAll('.backup-action-btn.delete').forEach(btn => { + btn.addEventListener('click', () => deleteBackup(btn.dataset.id)); + }); + } + + function formatBytes(bytes) { + if (!bytes || bytes === 0) return '0 B'; + const k = 1024; + const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; + } + + async function createBackup() { + if (!hasPerm('backups_create')) { + alert('You do not have permission to create backups.'); + return; + } + const name = backupNameInput?.value?.trim() || 'Backup'; + const description = backupDescInput?.value?.trim() || ''; + if (backupCreateConfirm) { + backupCreateConfirm.disabled = true; + backupCreateConfirm.innerHTML = ' Creating...'; + } + try { + const res = await fetch(`/api/nodes/server/${encodeURIComponent(bot)}/backups`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name, description }) + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + if (res.status === 507 || err.error === 'disk_limit_exceeded') { + throw new Error(err.message || 'This server has exceeded its disk space limit. Delete files to free space before creating a backup.'); + } + throw new Error(err.error || 'Failed to create backup'); + } + closeBackupCreateModal(); + loadBackups(); + alert('Backup created successfully!'); + } catch (err) { + alert('Failed to create backup: ' + (err.message || err)); + } finally { + if (backupCreateConfirm) { + backupCreateConfirm.disabled = false; + backupCreateConfirm.innerHTML = 'Create Backup'; + } + } + } + + async function restoreBackup(id) { + if (!id) return; + if (!confirm('Are you sure you want to restore this backup? Current server files will be replaced.')) return; + try { + const res = await fetch(`/api/nodes/server/${encodeURIComponent(bot)}/backups/${encodeURIComponent(id)}/restore`, { method: 'POST' }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + if (res.status === 507 || err.error === 'disk_limit_exceeded') { + throw new Error(err.message || 'This server has exceeded its disk space limit. Delete files to free space before restoring a backup.'); + } + throw new Error(err.error || 'Failed to restore backup'); + } + alert('Backup restored successfully!'); + loadBackups(); + } catch (err) { + alert('Failed to restore backup: ' + (err.message || err)); + } + } + + async function deleteBackup(id) { + if (!id) return; + if (!hasPerm('backups_delete')) { + alert('You do not have permission to delete backups.'); + return; + } + if (!confirm('Are you sure you want to delete this backup? This cannot be undone.')) return; + try { + const res = await fetch(`/api/nodes/server/${encodeURIComponent(bot)}/backups/${encodeURIComponent(id)}`, { method: 'DELETE' }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || 'Failed to delete backup'); + } + loadBackups(); + } catch (err) { + alert('Failed to delete backup: ' + (err.message || err)); + } + } + + function openBackupsModal() { + if (!backupsModal) return; + if (!hasPerm('backups_view')) { + alert('You do not have permission to view backups.'); + return; + } + showModalElement(backupsModal); + if (backupsCreateBtn) { + if (!hasPerm('backups_create')) { + backupsCreateBtn.style.display = 'none'; + } else { + backupsCreateBtn.style.display = ''; + } + } + afterModalPaint(() => loadBackups()); + } + + function closeBackupsModal() { + if (!backupsModal) return; + animateClose(backupsModal); + } + + function openBackupCreateModal() { + if (!backupCreateModal) return; + if (backupNameInput) backupNameInput.value = ''; + if (backupDescInput) backupDescInput.value = ''; + showModalElement(backupCreateModal); + } + + function closeBackupCreateModal() { + if (!backupCreateModal) return; + animateClose(backupCreateModal); + } + + if (backupsModalClose) backupsModalClose.addEventListener('click', closeBackupsModal); + if (backupsCreateBtn) backupsCreateBtn.addEventListener('click', openBackupCreateModal); + if (backupsRefreshBtn) backupsRefreshBtn.addEventListener('click', loadBackups); + if (backupCreateClose) backupCreateClose.addEventListener('click', closeBackupCreateModal); + if (backupCreateCancel) backupCreateCancel.addEventListener('click', closeBackupCreateModal); + if (backupCreateConfirm) backupCreateConfirm.addEventListener('click', createBackup); + + const schedulerModal = document.getElementById('schedulerModal'); + const schedulerModalClose = document.getElementById('schedulerModalClose'); + const schedulerTasksList = document.getElementById('schedulerTasksList'); + const schedulerRefreshBtn = document.getElementById('schedulerRefreshBtn'); + const schedulerCreateBtn = document.getElementById('schedulerCreateBtn'); + const schedulerTabs = document.querySelectorAll('.scheduler-tab'); + const schedulerTasksTab = document.getElementById('schedulerTasksTab'); + const schedulerCreateTab = document.getElementById('schedulerCreateTab'); + const schedulerStatusIndicator = document.getElementById('schedulerStatusIndicator'); + + const schedulerTaskName = document.getElementById('schedulerTaskName'); + const schedulerScheduleOptions = document.querySelectorAll('.scheduler-schedule-option'); + const schedulerOnceSection = document.getElementById('schedulerOnceSection'); + const schedulerRecurringSection = document.getElementById('schedulerRecurringSection'); + const schedulerDate = document.getElementById('schedulerDate'); + const schedulerTime = document.getElementById('schedulerTime'); + const schedulerRecurringType = document.getElementById('schedulerRecurringType'); + const schedulerSecondsConfig = document.getElementById('schedulerSecondsConfig'); + const schedulerMinutesConfig = document.getElementById('schedulerMinutesConfig'); + const schedulerHourlyConfig = document.getElementById('schedulerHourlyConfig'); + const schedulerDailyConfig = document.getElementById('schedulerDailyConfig'); + const schedulerWeeklyConfig = document.getElementById('schedulerWeeklyConfig'); + const schedulerSecondsInterval = document.getElementById('schedulerSecondsInterval'); + const schedulerMinutesInterval = document.getElementById('schedulerMinutesInterval'); + const schedulerHourlyInterval = document.getElementById('schedulerHourlyInterval'); + const schedulerDailyTime = document.getElementById('schedulerDailyTime'); + const schedulerWeeklyDay = document.getElementById('schedulerWeeklyDay'); + const schedulerWeeklyTime = document.getElementById('schedulerWeeklyTime'); + const schedulerActionType = document.getElementById('schedulerActionType'); + const schedulerActionConsole = document.getElementById('schedulerActionConsole'); + const schedulerActionServerControl = document.getElementById('schedulerActionServerControl'); + const schedulerActionFile = document.getElementById('schedulerActionFile'); + const schedulerActionBackup = document.getElementById('schedulerActionBackup'); + const schedulerActionPlanner = document.getElementById('schedulerActionPlanner'); + const schedulerActionAgentPrompt = document.getElementById('schedulerActionAgentPrompt'); + const schedulerCommand = document.getElementById('schedulerCommand'); + const schedulerServerControlText = document.getElementById('schedulerServerControlText'); + const schedulerFilePath = document.getElementById('schedulerFilePath'); + const schedulerFileContent = document.getElementById('schedulerFileContent'); + const schedulerBackupName = document.getElementById('schedulerBackupName'); + const schedulerBackupDesc = document.getElementById('schedulerBackupDesc'); + const schedulerPlannerRefreshBtn = document.getElementById('schedulerPlannerRefreshBtn'); + const schedulerPlannerPromptPreview = document.getElementById('schedulerPlannerPromptPreview'); + const schedulerAgentPrompt = document.getElementById('schedulerAgentPrompt'); + const schedulerAiModelSelector = document.getElementById('schedulerAiModelSelector'); + const schedulerAiModelSelect = document.getElementById('schedulerAiModelSelect'); + const schedulerAiModelTrigger = document.getElementById('schedulerAiModelTrigger'); + const schedulerAiModelCurrent = document.getElementById('schedulerAiModelCurrent'); + const schedulerAiModelOptions = document.getElementById('schedulerAiModelOptions'); + + let schedulerCurrentScheduleType = 'once'; + let schedulerPlannerPreviewLoading = false; + + function openSchedulerModal() { + if (!schedulerModal) return; + if (!hasPerm('scheduler_access')) { + alert('You do not have permission to access the scheduler.'); + return; + } + showModalElement(schedulerModal); + afterModalPaint(() => { + loadSchedulerTasks(); + checkSchedulerStatus(); + }); + if (schedulerDate) { + const today = new Date(); + schedulerDate.value = today.toISOString().split('T')[0]; + } + const createTab = document.querySelector('.scheduler-tab[data-tab="create"]'); + if (createTab) { + if (!hasPerm('scheduler_create')) { + createTab.style.display = 'none'; + } else { + createTab.style.display = ''; + } + } + } + + function closeSchedulerModal() { + if (!schedulerModal) return; + animateClose(schedulerModal); + } + + async function loadSchedulerTasks() { + if (!schedulerTasksList) return; + schedulerTasksList.innerHTML = '
Loading tasks...
'; + + if (schedulerRefreshBtn) { + schedulerRefreshBtn.classList.add('spinning'); + } + + try { + const res = await fetch(`/api/scheduler/${encodeURIComponent(bot)}/tasks`); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || 'Failed to load tasks'); + } + const data = await res.json(); + renderSchedulerTasks(data.tasks || [], data.recurring || []); + } catch (err) { + console.error('Scheduler tasks load error:', err); + schedulerTasksList.innerHTML = '

' + escapeHtml(err.message || 'Failed to load tasks') + '

'; + } finally { + if (schedulerRefreshBtn) { + schedulerRefreshBtn.classList.remove('spinning'); + } + } + } + + function renderSchedulerTasks(tasks, recurring) { + const allTasks = [...tasks, ...recurring]; + const canDelete = hasPerm('scheduler_delete'); + + if (allTasks.length === 0) { + schedulerTasksList.innerHTML = '

No scheduled tasks

Create a task to automate server operations

'; + return; + } + + schedulerTasksList.innerHTML = allTasks.map(task => { + const icon = getActionIcon(task.actionType); + const statusClass = task.status || 'pending'; + const timeText = task.status === 'recurring' + ? `Cron: ${task.cron || 'N/A'}` + : task.scheduledFor + ? new Date(task.scheduledFor).toLocaleString() + : 'N/A'; + + const deleteBtn = canDelete + ? `` + : ''; + + return ` +
+
${icon}
+
+
${escapeHtml(task.name || 'Unnamed Task')}
+
+ ${escapeHtml(timeText)} + ${escapeHtml(task.actionType || 'unknown')} +
+
+ ${statusClass} + ${deleteBtn} +
+ `; + }).join(''); + + if (canDelete) { + schedulerTasksList.querySelectorAll('.scheduler-task-delete').forEach(btn => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + deleteSchedulerTask(btn.dataset.id); + }); + }); + } + } + + function getActionIcon(actionType) { + const icons = { + 'console_command': '', + 'server_start': '', + 'server_stop': '', + 'create_file': '', + 'modify_file': '', + 'backup': '', + 'planner_next_to_agent': '', + 'agent_prompt': '' + }; + return icons[actionType] || ''; + } + + function closeSchedulerAiModelDropdown() { + if (!schedulerAiModelSelector || !schedulerAiModelTrigger) return; + schedulerAiModelSelector.classList.remove('open'); + schedulerAiModelTrigger.setAttribute('aria-expanded', 'false'); + schedulerAiModelOptions?.setAttribute('aria-hidden', 'true'); + } + + function updateSchedulerAiModelSelectorState({ persist = true } = {}) { + if (!schedulerAiModelSelect || !schedulerAiModelCurrent || !schedulerAiModelOptions) return; + const selectedOption = schedulerAiModelSelect.selectedOptions?.[0] || schedulerAiModelSelect.options[schedulerAiModelSelect.selectedIndex] || null; + schedulerAiModelCurrent.textContent = selectedOption?.textContent || 'Select model...'; + if (persist && selectedOption && !selectedOption.disabled && isPersistableAiModelSelection(schedulerAiModelSelect.value)) { + saveSelectedAiModelToStorage(schedulerAiModelSelect.value); + } + + const selectedValue = schedulerAiModelSelect.value; + schedulerAiModelOptions.querySelectorAll('.ai-model-option').forEach(optionEl => { + const isSelected = optionEl.dataset.value === selectedValue; + optionEl.classList.toggle('selected', isSelected); + optionEl.setAttribute('aria-selected', isSelected ? 'true' : 'false'); + }); + } + + function syncSchedulerAiModelSelectorFromNative({ persist = false } = {}) { + if (!schedulerAiModelSelect || !schedulerAiModelTrigger || !schedulerAiModelOptions || !schedulerAiModelCurrent || !schedulerAiModelSelector) return; + closeSchedulerAiModelDropdown(); + schedulerAiModelOptions.innerHTML = ''; + let hasSelectableOptions = false; + + const appendModelOption = (option) => { + if (!option) return; + if (option.disabled) { + if (!option.value) { + const emptyState = document.createElement('div'); + emptyState.className = 'ai-model-empty'; + emptyState.textContent = option.textContent; + schedulerAiModelOptions.appendChild(emptyState); + } + return; + } + + hasSelectableOptions = true; + const optionButton = document.createElement('button'); + optionButton.type = 'button'; + optionButton.className = 'ai-model-option'; + optionButton.dataset.value = option.value; + optionButton.setAttribute('role', 'option'); + optionButton.setAttribute('aria-selected', 'false'); + optionButton.innerHTML = ` + ${escapeHtml(option.textContent)} + + `; + schedulerAiModelOptions.appendChild(optionButton); + }; + + Array.from(schedulerAiModelSelect.children).forEach(child => { + const tagName = child.tagName?.toUpperCase(); + if (tagName === 'OPTGROUP') { + const groupLabel = document.createElement('div'); + groupLabel.className = 'ai-model-group'; + groupLabel.textContent = child.label; + schedulerAiModelOptions.appendChild(groupLabel); + Array.from(child.children).forEach(appendModelOption); + } else if (tagName === 'OPTION') { + appendModelOption(child); + } + }); + + schedulerAiModelTrigger.disabled = !hasSelectableOptions; + schedulerAiModelSelector.classList.toggle('is-disabled', !hasSelectableOptions); + schedulerAiModelOptions.setAttribute('aria-hidden', schedulerAiModelSelector.classList.contains('open') ? 'false' : 'true'); + updateSchedulerAiModelSelectorState({ persist }); + } + + async function populateSchedulerAiModelSelector() { + if (!schedulerAiModelSelect) return; + const backendSelectedModel = await loadSelectedAiModelFromBackend().catch(() => ''); + const previouslySelectedModel = backendSelectedModel || loadSelectedAiModelFromStorage(); + const keys = await loadAiKeysFromBackend(); + schedulerAiModelSelect.innerHTML = ''; + syncSchedulerAiModelSelectorFromNative({ persist: false }); + + let hasOptions = false; + const results = await Promise.all(Object.entries(AI_PROVIDERS).map(async ([providerId, config]) => { + if (!keys[providerId]) return null; + const models = await fetchModels(providerId); + return { providerId, name: config.name, models }; + })); + + schedulerAiModelSelect.innerHTML = ''; + for (const result of results) { + if (!result || !result.models.length) continue; + const optgroup = document.createElement('optgroup'); + optgroup.label = result.name; + for (const model of result.models) { + const opt = document.createElement('option'); + opt.value = encodeAiModelSelection(result.providerId, model); + opt.textContent = model; + optgroup.appendChild(opt); + } + schedulerAiModelSelect.appendChild(optgroup); + hasOptions = true; + } + + if (!hasOptions) { + schedulerAiModelSelect.innerHTML = ''; + } else { + const optionValues = Array.from(schedulerAiModelSelect.options).map((option) => option.value); + if (previouslySelectedModel && optionValues.includes(previouslySelectedModel)) { + schedulerAiModelSelect.value = previouslySelectedModel; + } else { + schedulerAiModelSelect.selectedIndex = 0; + } + } + + syncSchedulerAiModelSelectorFromNative({ persist: hasOptions }); + } + + async function loadSchedulerPlannerPreview() { + if (!schedulerPlannerPromptPreview || schedulerPlannerPreviewLoading) return; + schedulerPlannerPreviewLoading = true; + if (schedulerPlannerRefreshBtn) schedulerPlannerRefreshBtn.classList.add('spinning'); + schedulerPlannerPromptPreview.value = 'Loading next planner prompt...'; + try { + const data = await plannerRequest(); + const items = Array.isArray(data.items) ? data.items : []; + const nextItem = items.find((item) => !Number(item.is_done) && String(item.prompt || '').trim()); + schedulerPlannerPromptPreview.value = nextItem + ? String(nextItem.prompt || '').trim() + : 'No active planner prompt is queued yet.'; + } catch (err) { + schedulerPlannerPromptPreview.value = err.message || 'Failed to load planner prompt.'; + } finally { + schedulerPlannerPreviewLoading = false; + if (schedulerPlannerRefreshBtn) schedulerPlannerRefreshBtn.classList.remove('spinning'); + } + } + + async function deleteSchedulerTask(taskId) { + if (!taskId) return; + if (!hasPerm('scheduler_delete')) { + alert('You do not have permission to delete schedules'); + return; + } + if (!confirm('Are you sure you want to delete this scheduled task?')) return; + + try { + const res = await fetch(`/api/scheduler/${encodeURIComponent(bot)}/tasks/${encodeURIComponent(taskId)}`, { + method: 'DELETE' + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || 'Failed to delete task'); + } + loadSchedulerTasks(); + } catch (err) { + alert('Failed to delete task: ' + (err.message || err)); + } + } + + async function createSchedulerTask() { + if (!hasPerm('scheduler_create')) { + alert('You do not have permission to create schedules'); + return; + } + const name = schedulerTaskName?.value?.trim() || ''; + const actionType = schedulerActionType?.value; + + if (!actionType) { + alert('Please select an action type'); + return; + } + + let scheduleType, scheduleValue, scheduleTime, scheduledTimestamp; + let payload = {}; + + if (schedulerCurrentScheduleType === 'once') { + scheduleType = 'once'; + const dateVal = schedulerDate?.value; + const timeVal = schedulerTime?.value || '00:00'; + if (!dateVal) { + alert('Please select a date'); + return; + } + scheduledTimestamp = new Date(`${dateVal}T${timeVal}`).getTime(); + if (scheduledTimestamp < Date.now()) { + alert('Scheduled time must be in the future'); + return; + } + } else { + const recurringType = schedulerRecurringType?.value || 'seconds'; + scheduleType = recurringType; + + if (recurringType === 'seconds') { + scheduleValue = schedulerSecondsInterval?.value || '30'; + } else if (recurringType === 'minutes') { + scheduleValue = schedulerMinutesInterval?.value || '5'; + } else if (recurringType === 'hourly') { + scheduleValue = schedulerHourlyInterval?.value || '1'; + } else if (recurringType === 'daily') { + scheduleTime = schedulerDailyTime?.value || '00:00'; + } else if (recurringType === 'weekly') { + scheduleValue = schedulerWeeklyDay?.value || '0'; + scheduleTime = schedulerWeeklyTime?.value || '00:00'; + } + } + + if (actionType === 'console_command') { + const command = schedulerCommand?.value?.trim(); + if (!command) { + alert('Please enter a command'); + return; + } + payload.command = command; + } else if (actionType === 'create_file' || actionType === 'modify_file') { + const filePath = schedulerFilePath?.value?.trim(); + if (!filePath) { + alert('Please enter a file path'); + return; + } + payload.filePath = filePath; + payload.content = schedulerFileContent?.value || ''; + } else if (actionType === 'backup') { + payload.backupName = schedulerBackupName?.value?.trim() || 'Scheduled Backup'; + payload.description = schedulerBackupDesc?.value?.trim() || ''; + } else if (actionType === 'planner_next_to_agent') { + if (!hasAgentAccess()) { + alert('You do not have permission to access ADPanel Agent.'); + return; + } + await saveSelectedAiModelToBackendNow(aiModelSelect?.value || '').catch(() => false); + } else if (actionType === 'agent_prompt') { + if (!hasAgentAccess()) { + alert('You do not have permission to access ADPanel Agent.'); + return; + } + const prompt = schedulerAgentPrompt?.value?.trim() || ''; + if (!prompt) { + alert('Please enter the prompt for ADPanel Agent.'); + schedulerAgentPrompt?.focus(); + return; + } + const modelValue = schedulerAiModelSelect?.value || ''; + const { providerId, modelName } = decodeAiModelSelection(modelValue); + if (!providerId || !modelName) { + alert('Please select an AI model.'); + return; + } + payload.prompt = prompt; + payload.provider = providerId; + payload.model = modelName; + } + + if (schedulerCreateBtn) { + schedulerCreateBtn.disabled = true; + schedulerCreateBtn.innerHTML = ' Creating...'; + } + + try { + const res = await fetch(`/api/scheduler/${encodeURIComponent(bot)}/tasks`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + name: name || `${actionType} task`, + actionType, + payload, + scheduleType, + scheduleValue, + scheduleTime, + scheduledTimestamp + }) + }); + + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err.error || 'Failed to create task'); + } + + switchSchedulerTab('tasks'); + loadSchedulerTasks(); + resetSchedulerForm(); + alert('Task created successfully!'); + } catch (err) { + alert('Failed to create task: ' + (err.message || err)); + } finally { + if (schedulerCreateBtn) { + schedulerCreateBtn.disabled = false; + schedulerCreateBtn.innerHTML = ' Create Task'; + } + } + } + + function resetSchedulerForm() { + if (schedulerTaskName) schedulerTaskName.value = ''; + if (schedulerCommand) schedulerCommand.value = ''; + if (schedulerFilePath) schedulerFilePath.value = ''; + if (schedulerFileContent) schedulerFileContent.value = ''; + if (schedulerBackupName) schedulerBackupName.value = ''; + if (schedulerBackupDesc) schedulerBackupDesc.value = ''; + if (schedulerAgentPrompt) schedulerAgentPrompt.value = ''; + if (schedulerActionType) schedulerActionType.value = ''; + hideAllActionConfigs(); + } + + function switchSchedulerTab(tabName) { + schedulerTabs.forEach(tab => { + tab.classList.toggle('active', tab.dataset.tab === tabName); + }); + if (schedulerTasksTab) schedulerTasksTab.classList.toggle('hidden', tabName !== 'tasks'); + if (schedulerCreateTab) schedulerCreateTab.classList.toggle('hidden', tabName !== 'create'); + + if (tabName === 'tasks') { + loadSchedulerTasks(); + } + } + + function switchScheduleType(type) { + schedulerCurrentScheduleType = type; + schedulerScheduleOptions.forEach(opt => { + opt.classList.toggle('active', opt.dataset.schedule === type); + }); + if (schedulerOnceSection) schedulerOnceSection.classList.toggle('hidden', type !== 'once'); + if (schedulerRecurringSection) schedulerRecurringSection.classList.toggle('hidden', type !== 'recurring'); + } + + function updateRecurringConfig() { + const type = schedulerRecurringType?.value || 'seconds'; + if (schedulerSecondsConfig) schedulerSecondsConfig.classList.toggle('hidden', type !== 'seconds'); + if (schedulerMinutesConfig) schedulerMinutesConfig.classList.toggle('hidden', type !== 'minutes'); + if (schedulerHourlyConfig) schedulerHourlyConfig.classList.toggle('hidden', type !== 'hourly'); + if (schedulerDailyConfig) schedulerDailyConfig.classList.toggle('hidden', type !== 'daily'); + if (schedulerWeeklyConfig) schedulerWeeklyConfig.classList.toggle('hidden', type !== 'weekly'); + } + + function hideAllActionConfigs() { + [schedulerActionConsole, schedulerActionServerControl, schedulerActionFile, schedulerActionBackup, schedulerActionPlanner, schedulerActionAgentPrompt].forEach(el => { + if (el) el.classList.add('hidden'); + }); + } + + function updateActionConfig() { + hideAllActionConfigs(); + const action = schedulerActionType?.value; + + if ((action === 'planner_next_to_agent' || action === 'agent_prompt') && !hasAgentAccess()) { + alert('You do not have permission to access ADPanel Agent.'); + if (schedulerActionType) schedulerActionType.value = ''; + return; + } + + if (action === 'console_command' && schedulerActionConsole) { + schedulerActionConsole.classList.remove('hidden'); + } else if ((action === 'server_start' || action === 'server_stop') && schedulerActionServerControl) { + schedulerActionServerControl.classList.remove('hidden'); + if (schedulerServerControlText) { + schedulerServerControlText.textContent = action === 'server_start' + ? 'The server will be started at the scheduled time.' + : 'The server will be stopped at the scheduled time.'; + } + } else if ((action === 'create_file' || action === 'modify_file') && schedulerActionFile) { + schedulerActionFile.classList.remove('hidden'); + } else if (action === 'backup' && schedulerActionBackup) { + schedulerActionBackup.classList.remove('hidden'); + } else if (action === 'planner_next_to_agent' && schedulerActionPlanner) { + schedulerActionPlanner.classList.remove('hidden'); + loadSchedulerPlannerPreview().catch((err) => console.error('[scheduler] Planner preview error:', err)); + } else if (action === 'agent_prompt' && schedulerActionAgentPrompt) { + schedulerActionAgentPrompt.classList.remove('hidden'); + populateSchedulerAiModelSelector().catch((err) => console.error('[scheduler] Model selector error:', err)); + } + } + + async function checkSchedulerStatus() { + try { + const res = await fetch('/api/scheduler/status'); + if (!res.ok) throw new Error('Status check failed'); + const data = await res.json(); + + if (schedulerStatusIndicator) { + const dot = schedulerStatusIndicator.querySelector('.scheduler-status-dot'); + const text = schedulerStatusIndicator.querySelector('.scheduler-status-text'); + + if (data.available) { + if (dot) dot.classList.remove('offline'); + const pendingCount = (data.queue?.waiting || 0) + (data.queue?.delayed || 0); + if (text) text.textContent = `Scheduler Ready (${pendingCount} pending, ${data.queue?.active || 0} active)`; + } else { + if (dot) dot.classList.add('offline'); + if (text) { + if (!data.redisConfigured) { + text.textContent = 'Scheduler Offline (REDIS_URL not configured)'; + } else { + text.textContent = 'Scheduler Offline (Connection error)'; + } + } + } + } + } catch (err) { + console.error('Scheduler status check failed:', err); + if (schedulerStatusIndicator) { + const dot = schedulerStatusIndicator.querySelector('.scheduler-status-dot'); + const text = schedulerStatusIndicator.querySelector('.scheduler-status-text'); + if (dot) dot.classList.add('offline'); + if (text) text.textContent = 'Scheduler Status Unknown'; + } + } + } + + if (schedulerModalClose) schedulerModalClose.addEventListener('click', closeSchedulerModal); + if (schedulerRefreshBtn) schedulerRefreshBtn.addEventListener('click', loadSchedulerTasks); + if (schedulerCreateBtn) schedulerCreateBtn.addEventListener('click', createSchedulerTask); + + schedulerTabs.forEach(tab => { + tab.addEventListener('click', () => switchSchedulerTab(tab.dataset.tab)); + }); + + schedulerScheduleOptions.forEach(opt => { + opt.addEventListener('click', () => switchScheduleType(opt.dataset.schedule)); + }); + + if (schedulerRecurringType) { + schedulerRecurringType.addEventListener('change', updateRecurringConfig); + } + + if (schedulerActionType) { + schedulerActionType.addEventListener('change', updateActionConfig); + } + + if (schedulerPlannerRefreshBtn) { + schedulerPlannerRefreshBtn.addEventListener('click', () => { + loadSchedulerPlannerPreview().catch((err) => console.error('[scheduler] Planner preview refresh error:', err)); + }); + } + + if (schedulerAiModelTrigger) { + schedulerAiModelTrigger.addEventListener('click', (e) => { + e.stopPropagation(); + if (schedulerAiModelTrigger.disabled) return; + const willOpen = !schedulerAiModelSelector?.classList.contains('open'); + closeSchedulerAiModelDropdown(); + if (willOpen && schedulerAiModelSelector) { + schedulerAiModelSelector.classList.add('open'); + schedulerAiModelTrigger.setAttribute('aria-expanded', 'true'); + schedulerAiModelOptions?.setAttribute('aria-hidden', 'false'); + } + }); + } + + if (schedulerAiModelOptions && schedulerAiModelSelect) { + const handleSchedulerAiModelOptionSelect = (optionButton) => { + if (!optionButton) return; + if (!schedulerAiModelSelector?.classList.contains('open')) return; + const nextValue = optionButton.dataset.value || ''; + if (!nextValue) return; + schedulerAiModelSelect.value = nextValue; + schedulerAiModelSelect.dispatchEvent(new Event('change', { bubbles: true })); + updateSchedulerAiModelSelectorState({ persist: true }); + closeSchedulerAiModelDropdown(); + schedulerAiModelTrigger?.focus(); + }; + + schedulerAiModelOptions.addEventListener('pointerdown', (e) => { + const optionButton = e.target.closest('.ai-model-option'); + if (!optionButton) return; + e.preventDefault(); + handleSchedulerAiModelOptionSelect(optionButton); + }); + + schedulerAiModelOptions.addEventListener('click', (e) => { + const optionButton = e.target.closest('.ai-model-option'); + if (!optionButton) return; + handleSchedulerAiModelOptionSelect(optionButton); + }); + } + + if (schedulerAiModelSelect) { + schedulerAiModelSelect.addEventListener('change', () => updateSchedulerAiModelSelectorState({ persist: true })); + } + + document.addEventListener('click', (e) => { + if (!e.target.closest('#schedulerAiModelSelector')) { + closeSchedulerAiModelDropdown(); + } + }); + + if (schedulerModal) { + schedulerModal.addEventListener('click', (e) => { + if (e.target === schedulerModal || e.target.classList.contains('scheduler-glass-layer')) { + closeSchedulerModal(); + } + }); + } + + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && schedulerModal?.classList.contains('show')) { + closeSchedulerModal(); + } + if (e.key === 'Escape') { + const clearModal = document.getElementById('clearConsoleModal'); + if (typeof closeClearConsoleModal === 'function' && clearModal && clearModal.style.display !== 'none') { + closeClearConsoleModal(); + } else if (clearModal && clearModal.style.display !== 'none') { + clearModal.style.display = 'none'; + } + } + }); + + const plannerModal = document.getElementById('plannerModal'); + const plannerModalClose = document.getElementById('plannerModalClose'); + const plannerRefreshBtn = document.getElementById('plannerRefreshBtn'); + const plannerTabs = document.querySelectorAll('.planner-tab'); + const plannerBoardTab = document.getElementById('plannerBoardTab'); + const plannerComposeTab = document.getElementById('plannerComposeTab'); + const plannerSummary = document.getElementById('plannerSummary'); + const plannerActiveList = document.getElementById('plannerActiveList'); + const plannerCompletedSection = document.getElementById('plannerCompletedSection'); + const plannerCompletedList = document.getElementById('plannerCompletedList'); + const plannerOpenComposeBtn = document.getElementById('plannerOpenComposeBtn'); + const plannerItemIdInput = document.getElementById('plannerItemId'); + const plannerTitleInput = document.getElementById('plannerTitleInput'); + const plannerPromptInput = document.getElementById('plannerPromptInput'); + const plannerResetBtn = document.getElementById('plannerResetBtn'); + const plannerSaveBtn = document.getElementById('plannerSaveBtn'); + const plannerStatusIndicator = document.getElementById('plannerStatusIndicator'); + + const PLANNER_API_BASE = `/api/servers/${encodeURIComponent(bot)}/planner`; + + let plannerItems = []; + let plannerCurrentTab = 'board'; + let plannerLastActiveOrder = []; + + function setPlannerStatus(text, offline = false) { + if (!plannerStatusIndicator) return; + const dot = plannerStatusIndicator.querySelector('.planner-status-dot'); + const label = plannerStatusIndicator.querySelector('.planner-status-text'); + if (dot) dot.classList.toggle('offline', !!offline); + if (label) label.textContent = text; + } + + function plannerRequest(path = '', options = {}) { + return fetch(`${PLANNER_API_BASE}${path}`, options).then(async (response) => { + if (!response.ok) { + const err = await response.json().catch(() => ({})); + throw new Error(err.error || err.message || `Planner request failed (${response.status})`); + } + return response.json().catch(() => ({})); + }); + } + + function derivePlannerTitle(prompt) { + const clean = String(prompt || '').trim().replace(/\s+/g, ' '); + if (!clean) return 'Untitled Prompt'; + return clean.length > 72 ? `${clean.slice(0, 69)}...` : clean; + } + + function plannerAuthorLabel(email) { + const raw = String(email || '').trim(); + if (!raw) return 'Team'; + const base = raw.split('@')[0] || raw; + return base.slice(0, 28); + } + + function plannerActiveItems() { + return plannerItems.filter((item) => !Number(item.is_done)); + } + + function plannerCompletedItems() { + return plannerItems.filter((item) => Number(item.is_done)); + } + + function switchPlannerTab(tabName) { + plannerCurrentTab = tabName; + plannerTabs.forEach((tab) => { + tab.classList.toggle('active', tab.dataset.tab === tabName); + }); + if (plannerBoardTab) plannerBoardTab.classList.toggle('hidden', tabName !== 'board'); + if (plannerComposeTab) plannerComposeTab.classList.toggle('hidden', tabName !== 'compose'); + if (tabName === 'compose') { + setTimeout(() => plannerTitleInput?.focus(), 40); + } + } + + function resetPlannerForm() { + if (plannerItemIdInput) plannerItemIdInput.value = ''; + if (plannerTitleInput) plannerTitleInput.value = ''; + if (plannerPromptInput) plannerPromptInput.value = ''; + if (plannerSaveBtn) { + plannerSaveBtn.disabled = false; + plannerSaveBtn.innerHTML = 'Save Prompt'; + } + } + + function fillPlannerForm(item) { + if (!item) return; + if (plannerItemIdInput) plannerItemIdInput.value = String(item.id || ''); + if (plannerTitleInput) plannerTitleInput.value = item.title || ''; + if (plannerPromptInput) plannerPromptInput.value = item.prompt || ''; + if (plannerSaveBtn) { + plannerSaveBtn.innerHTML = 'Update Prompt'; + } + switchPlannerTab('compose'); + plannerTitleInput?.focus(); + } + + function renderPlannerSummaryCards(activeItems, completedItems) { + if (!plannerSummary) return; + const nextUp = activeItems[0]; + plannerSummary.innerHTML = ` +
+ Active + ${activeItems.length} + Shared prompts ready for the team on this server. +
+
+ Next Up + ${nextUp ? 'P1' : '0'} + ${escapeHtml(nextUp ? (nextUp.title || derivePlannerTitle(nextUp.prompt)) : 'Nothing queued yet')} +
+
+ Completed + ${completedItems.length} + Finished prompts can be reopened or sent again later. +
+ `; + } + + function renderPlannerItemCard(item, index, isDone = false) { + const title = escapeHtml(item.title || derivePlannerTitle(item.prompt)); + const prompt = escapeHtml(item.prompt || '').replace(/\n/g, '
'); + const relativeTime = item.updated_at ? formatRelativeTime(item.updated_at) : 'Just now'; + const priorityBadge = isDone + ? 'Done' + : `${index === 0 ? 'Now' : `P${index + 1}`}`; + + return ` +
+ +
+ + + + +
+
+ `; + } + + function renderPlannerBoard() { + if (!plannerActiveList || !plannerCompletedList) return; + const activeItems = plannerActiveItems(); + const completedItems = plannerCompletedItems(); + + renderPlannerSummaryCards(activeItems, completedItems); + plannerLastActiveOrder = activeItems.map((item) => Number(item.id)); + + if (!activeItems.length) { + plannerActiveList.innerHTML = ` +
+ +

No prompts in the queue yet.

+ +
+ `; + const emptyBtn = document.getElementById('plannerEmptyComposeBtn'); + if (emptyBtn) { + emptyBtn.addEventListener('click', () => { + resetPlannerForm(); + switchPlannerTab('compose'); + }); + } + } else { + plannerActiveList.innerHTML = activeItems.map((item, index) => renderPlannerItemCard(item, index, false)).join(''); + bindPlannerDragAndDrop(); + } + + if (!completedItems.length) { + plannerCompletedSection?.classList.add('hidden'); + plannerCompletedList.innerHTML = ''; + } else { + plannerCompletedSection?.classList.remove('hidden'); + plannerCompletedList.innerHTML = completedItems.map((item, index) => renderPlannerItemCard(item, index, true)).join(''); + } + } + + async function loadPlannerItems() { + if (!plannerActiveList || !plannerCompletedList) return; + plannerActiveList.innerHTML = '
Loading planner...
'; + plannerCompletedList.innerHTML = ''; + if (plannerRefreshBtn) plannerRefreshBtn.classList.add('spinning'); + setPlannerStatus('Loading planner...'); + + try { + const data = await plannerRequest(); + plannerItems = Array.isArray(data.items) ? data.items : []; + renderPlannerBoard(); + const activeCount = plannerActiveItems().length; + const completedCount = plannerCompletedItems().length; + setPlannerStatus(`${activeCount} active, ${completedCount} completed`); + } catch (err) { + console.error('[planner] Load error:', err); + plannerItems = []; + if (plannerSummary) plannerSummary.innerHTML = ''; + plannerActiveList.innerHTML = `

${escapeHtml(err.message || 'Failed to load planner')}

`; + plannerCompletedSection?.classList.add('hidden'); + setPlannerStatus('Planner unavailable', true); + } finally { + if (plannerRefreshBtn) plannerRefreshBtn.classList.remove('spinning'); + } + } + + function openPlannerModal() { + if (!plannerModal) return; + showModalElement(plannerModal); + switchPlannerTab('board'); + afterModalPaint(() => loadPlannerItems()); + } + + function closePlannerModal() { + if (!plannerModal) return; + animateClose(plannerModal); + } + + function plannerGetDragAfterElement(container, y) { + const draggableElements = [...container.querySelectorAll('.planner-item:not(.dragging)')]; + return draggableElements.reduce((closest, child) => { + const box = child.getBoundingClientRect(); + const offset = y - box.top - box.height / 2; + if (offset < 0 && offset > closest.offset) { + return { offset, element: child }; + } + return closest; + }, { offset: Number.NEGATIVE_INFINITY, element: null }).element; + } + + function bindPlannerDragAndDrop() { + if (!plannerActiveList) return; + plannerActiveList.querySelectorAll('.planner-item').forEach((item) => { + item.addEventListener('dragstart', () => { + item.classList.add('dragging'); + }); + + item.addEventListener('dragend', async () => { + item.classList.remove('dragging'); + const orderedIds = [...plannerActiveList.querySelectorAll('.planner-item')] + .map((entry) => parseInt(entry.dataset.id, 10)) + .filter((id) => !Number.isNaN(id)); + if (!orderedIds.length) return; + if (JSON.stringify(orderedIds) === JSON.stringify(plannerLastActiveOrder)) return; + try { + const data = await plannerRequest('/reorder', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ itemIds: orderedIds }) + }); + plannerItems = Array.isArray(data.items) ? data.items : plannerItems; + renderPlannerBoard(); + setPlannerStatus('Priority updated'); + } catch (err) { + console.error('[planner] Reorder error:', err); + await loadPlannerItems(); + alert(err.message || 'Failed to update planner order'); + } + }); + }); + + if (plannerActiveList.dataset.dragBound === '1') return; + plannerActiveList.dataset.dragBound = '1'; + + plannerActiveList.addEventListener('dragover', (e) => { + e.preventDefault(); + const dragging = plannerActiveList.querySelector('.planner-item.dragging'); + if (!dragging) return; + const afterElement = plannerGetDragAfterElement(plannerActiveList, e.clientY); + if (!afterElement) { + plannerActiveList.appendChild(dragging); + } else if (afterElement !== dragging) { + plannerActiveList.insertBefore(dragging, afterElement); + } + }); + } + + async function sendPlannerPromptToAgent(item) { + if (!item || !String(item.prompt || '').trim()) { + alert('This planner prompt is empty.'); + return; + } + if (!hasAgentAccess()) { + alert('You do not have permission to access ADPanel Agent.'); + return; + } + + setPlannerStatus('Sending to ADPanel Agent...'); + + try { + await saveSelectedAiModelToBackendNow(aiModelSelect?.value || '').catch(() => false); + const data = await plannerRequest(`/${encodeURIComponent(item.id)}/send-agent`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}) + }); + + closePlannerModal(); + await new Promise((resolve) => setTimeout(resolve, 120)); + await openAiHelpModal(); + + if (data.chatId) { + aiCurrentChatId = Number(data.chatId); + await loadChatsFromDb(); + await switchToChat(aiCurrentChatId); + } + + if (data.jobId) { + pollAiAgentJob(data.jobId, data.chatId).catch((err) => console.error('[ai-agent-job] Poll failed:', err)); + } + } catch (err) { + setPlannerStatus('Send failed', true); + alert(err.message || 'Failed to send planner prompt to ADPanel Agent.'); + } + } + + async function pollAiAgentJob(jobId, chatId = null) { + const safeJobId = Number(jobId); + if (!Number.isFinite(safeJobId) || safeJobId <= 0) return; + + for (let attempt = 0; attempt < 90; attempt += 1) { + await new Promise((resolve) => setTimeout(resolve, attempt < 6 ? 1200 : 2500)); + const response = await fetch(`/api/ai/jobs/${encodeURIComponent(safeJobId)}`, { cache: 'no-store' }); + if (!response.ok) return; + const data = await response.json().catch(() => ({})); + const status = String(data?.job?.status || '').toLowerCase(); + if (!status || status === 'queued' || status === 'running') continue; + + const targetChatId = Number(chatId || data?.job?.chat_id || aiCurrentChatId); + if (targetChatId && aiCurrentChatId === targetChatId) { + await switchToChat(targetChatId); + } else { + await loadChatsFromDb(); + renderChatsList(); + } + return; + } + } + + async function savePlannerItem() { + const prompt = String(plannerPromptInput?.value || '').trim(); + const id = parseInt(plannerItemIdInput?.value || '', 10); + const isEditing = !Number.isNaN(id); + let restoreAsEdit = isEditing; + const title = String(plannerTitleInput?.value || '').trim() || derivePlannerTitle(prompt); + + if (!prompt) { + alert('Write a prompt first.'); + plannerPromptInput?.focus(); + return; + } + + if (plannerSaveBtn) { + plannerSaveBtn.disabled = true; + plannerSaveBtn.innerHTML = `${isEditing ? 'Updating...' : 'Saving...'}`; + } + + try { + if (!isEditing) { + await plannerRequest('', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title, prompt }) + }); + } else { + await plannerRequest(`/${encodeURIComponent(id)}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title, prompt }) + }); + } + + resetPlannerForm(); + restoreAsEdit = false; + switchPlannerTab('board'); + await loadPlannerItems(); + setPlannerStatus('Prompt saved'); + } catch (err) { + console.error('[planner] Save error:', err); + alert(err.message || 'Failed to save prompt'); + } finally { + if (plannerSaveBtn) { + plannerSaveBtn.disabled = false; + plannerSaveBtn.innerHTML = restoreAsEdit + ? 'Update Prompt' + : 'Save Prompt'; + } + } + } + + async function togglePlannerItem(item) { + if (!item) return; + try { + await plannerRequest(`/${encodeURIComponent(item.id)}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + title: item.title || derivePlannerTitle(item.prompt), + prompt: item.prompt || '', + isDone: !Number(item.is_done) + }) + }); + await loadPlannerItems(); + setPlannerStatus(Number(item.is_done) ? 'Prompt moved back to active' : 'Prompt marked as completed'); + } catch (err) { + console.error('[planner] Toggle error:', err); + alert(err.message || 'Failed to update prompt'); + } + } + + async function deletePlannerItem(item) { + if (!item) return; + if (!confirm(`Delete "${item.title || derivePlannerTitle(item.prompt)}"?`)) return; + try { + await plannerRequest(`/${encodeURIComponent(item.id)}`, { method: 'DELETE' }); + await loadPlannerItems(); + setPlannerStatus('Prompt deleted'); + } catch (err) { + console.error('[planner] Delete error:', err); + alert(err.message || 'Failed to delete prompt'); + } + } + + async function handlePlannerListClick(e) { + const itemEl = e.target.closest('.planner-item'); + if (!itemEl) return; + const itemId = parseInt(itemEl.dataset.id, 10); + if (Number.isNaN(itemId)) return; + const item = plannerItems.find((entry) => Number(entry.id) === itemId); + if (!item) return; + + const actionEl = e.target.closest('[data-planner-action]'); + const action = actionEl?.dataset?.plannerAction; + if (!action) return; + + if (action === 'send') { + await sendPlannerPromptToAgent(item); + } else if (action === 'edit') { + fillPlannerForm(item); + } else if (action === 'toggle') { + await togglePlannerItem(item); + } else if (action === 'delete') { + await deletePlannerItem(item); + } + } + + if (plannerActiveList) { + plannerActiveList.addEventListener('click', (e) => { + handlePlannerListClick(e).catch((err) => console.error('[planner] Active list error:', err)); + }); + } + + if (plannerCompletedList) { + plannerCompletedList.addEventListener('click', (e) => { + handlePlannerListClick(e).catch((err) => console.error('[planner] Completed list error:', err)); + }); + } + + if (plannerModalClose) plannerModalClose.addEventListener('click', closePlannerModal); + if (plannerRefreshBtn) plannerRefreshBtn.addEventListener('click', loadPlannerItems); + if (plannerOpenComposeBtn) { + plannerOpenComposeBtn.addEventListener('click', () => { + resetPlannerForm(); + switchPlannerTab('compose'); + }); + } + if (plannerResetBtn) plannerResetBtn.addEventListener('click', resetPlannerForm); + if (plannerSaveBtn) plannerSaveBtn.addEventListener('click', savePlannerItem); + plannerTabs.forEach((tab) => { + tab.addEventListener('click', () => switchPlannerTab(tab.dataset.tab)); + }); + + if (plannerModal) { + plannerModal.addEventListener('click', (e) => { + if (e.target === plannerModal || e.target.classList.contains('planner-glass-layer')) { + closePlannerModal(); + } + }); + } + + if (plannerPromptInput) { + plannerPromptInput.addEventListener('keydown', (e) => { + if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') { + e.preventDefault(); + savePlannerItem(); + } + }); + } + + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && plannerModal?.classList.contains('show')) { + closePlannerModal(); + } + }); + + const clearConsoleModal = document.getElementById('clearConsoleModal'); + const clearConsoleConfirm = document.getElementById('clearConsoleConfirm'); + const clearConsoleCancel = document.getElementById('clearConsoleCancel'); + const clearConsoleToggleWrapper = document.getElementById('clearConsoleToggleWrapper'); + const dockWrap = document.querySelector('.dock-wrap'); + + if (clearConsoleToggleWrapper) { + clearConsoleToggleWrapper.addEventListener('click', function (e) { + var cb = document.getElementById('clearConsoleNoAsk'); + if (!cb) return; + if (e.target === cb) return; + e.preventDefault(); + cb.checked = !cb.checked; + }); + } + + function toggleDock(show) { + if (!dockWrap) return; + dockWrap.classList.toggle('dock-hidden', !show); + } + + function closeClearConsoleModal() { + if (!clearConsoleModal) return; + clearConsoleModal.classList.remove('show'); + setTimeout(function () { + if (!clearConsoleModal.classList.contains('show')) { + clearConsoleModal.style.display = 'none'; + toggleDock(true); + } + }, 300); + } + + function openClearConsoleModal() { + if (!clearConsoleModal) return; + clearConsoleModal.style.display = 'flex'; + requestAnimationFrame(function () { + clearConsoleModal.classList.add('show'); + toggleDock(false); + }); + var cb = document.getElementById('clearConsoleNoAsk'); + if (cb) cb.checked = false; + } + + if (clearConsoleConfirm) { + clearConsoleConfirm.addEventListener('click', async function () { + resetConsoleBuffer(); + + var cb = document.getElementById('clearConsoleNoAsk'); + if (cb && cb.checked) { + currentUserPreferences.clear_console_no_ask = true; + saveClearConsoleNoAskToStorage(true); + try { + var resp = await fetch('/api/me/preferences', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ preferences: { clear_console_no_ask: true } }) + }); + var data = await resp.json(); + if (data && data.ok) { + mergeCurrentUserPreferences(data.preferences || { clear_console_no_ask: true }); + console.log('[ClearConsole] Preference saved successfully'); + } else { + console.error('[ClearConsole] Save failed:', data); + } + } catch (err) { + console.error('[ClearConsole] Failed to save preference:', err); + } + } + closeClearConsoleModal(); + }); + } + + if (clearConsoleCancel) { + clearConsoleCancel.addEventListener('click', function () { + closeClearConsoleModal(); + }); + } + + if (clearConsoleModal) { + clearConsoleModal.addEventListener('click', function (e) { + if (e.target === clearConsoleModal || e.target.classList.contains('clear-console-glass-layer')) { + closeClearConsoleModal(); + } + }); + } + + const resourceStatsPopup = document.getElementById('resourceStatsPopup'); + const resourceStatsClose = document.getElementById('resourceStatsClose'); + const resMemoryLabel = document.getElementById('resMemoryLabel'); + const resMemoryBar = document.getElementById('resMemoryBar'); + const resDiskLabel = document.getElementById('resDiskLabel'); + const resDiskBar = document.getElementById('resDiskBar'); + const resCpuLabel = document.getElementById('resCpuLabel'); + const resCpuBar = document.getElementById('resCpuBar'); + const resNetworkInboundLabel = document.getElementById('resNetworkInboundLabel'); + const resNetworkOutboundLabel = document.getElementById('resNetworkOutboundLabel'); + const resUptimeLabel = document.getElementById('resUptimeLabel'); + + let resourceStatsUptimeInterval = null; + let lastFetchedUptime = null; + let uptimeFetchedAt = null; + let resourceStatsSubscribed = false; + let lastNetworkInboundBytes = 0; + let lastNetworkOutboundBytes = 0; + + function readNetworkBytes(network, keys) { + if (!network || typeof network !== 'object') return null; + for (const key of keys) { + const value = Number(network[key]); + if (Number.isFinite(value) && value >= 0) return value; + } + return null; + } + + function onResourceData(data) { + if (!data || data.server !== bot) return; + const isRunning = data.status === 'running' || data.status === 'online'; + + if (data.memory && isRunning) { + let usedMb, limitMb, pct; + if (typeof data.memory === 'object') { + usedMb = data.memory.used || 0; + limitMb = data.memory.total || 0; + pct = data.memory.percent ?? (limitMb > 0 ? Math.min(100, Math.round((usedMb / limitMb) * 100)) : 0); + } else { + usedMb = data.memory; limitMb = 0; pct = 0; + } + if (resMemoryLabel) resMemoryLabel.textContent = limitMb > 0 + ? `${formatBytes(usedMb * 1048576)} / ${formatBytes(limitMb * 1048576)} (${Math.round(pct)}%)` + : `${formatBytes(usedMb * 1048576)} / Unlimited`; + if (resMemoryBar) resMemoryBar.style.width = `${pct}%`; + } else { + if (resMemoryLabel) resMemoryLabel.textContent = '—'; + if (resMemoryBar) resMemoryBar.style.width = '0%'; + } + + if (data.disk) { + let usedGb, limitGb, pct; + if (typeof data.disk === 'object') { + usedGb = data.disk.used || 0; + limitGb = data.disk.total || 0; + pct = data.disk.percent ?? (limitGb > 0 ? Math.min(100, Math.round((usedGb / limitGb) * 100)) : 0); + } else { + usedGb = data.disk / 1024; limitGb = 0; pct = 0; + } + 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 + ? `${formatBytes(usedGb * 1073741824)} / ${formatBytes(limitGb * 1073741824)} (${Math.round(pct)}%)` + : `${formatBytes(usedGb * 1073741824)} / Unlimited`; + if (resDiskBar) resDiskBar.style.width = `${pct}%`; + } else { + if (resDiskLabel) resDiskLabel.textContent = '—'; + if (resDiskBar) resDiskBar.style.width = '0%'; + } + + if (data.cpu !== undefined && data.cpu !== null && isRunning) { + const cpuMax = data.cpuLimit || 100; + const cpuPct = Math.min(cpuMax, Math.round(data.cpu)); + const cpuBarWidth = cpuMax > 0 ? Math.min(100, (cpuPct / cpuMax) * 100) : 0; + if (resCpuLabel) resCpuLabel.textContent = `${cpuPct}% / ${Math.round(cpuMax)}%`; + if (resCpuBar) resCpuBar.style.width = `${cpuBarWidth}%`; + } else { + if (resCpuLabel) resCpuLabel.textContent = '—'; + if (resCpuBar) resCpuBar.style.width = '0%'; + } + + const network = data.network || null; + const inboundBytes = readNetworkBytes(network, ['inboundBytes', 'rxBytes', 'receivedBytes']); + const outboundBytes = readNetworkBytes(network, ['outboundBytes', 'txBytes', 'transmittedBytes']); + if (inboundBytes !== null) { + lastNetworkInboundBytes = Math.max(lastNetworkInboundBytes, inboundBytes); + if (resNetworkInboundLabel) resNetworkInboundLabel.textContent = formatBytes(lastNetworkInboundBytes); + } else if (resNetworkInboundLabel) { + resNetworkInboundLabel.textContent = '—'; + } + if (outboundBytes !== null) { + lastNetworkOutboundBytes = Math.max(lastNetworkOutboundBytes, outboundBytes); + if (resNetworkOutboundLabel) resNetworkOutboundLabel.textContent = formatBytes(lastNetworkOutboundBytes); + } else if (resNetworkOutboundLabel) { + resNetworkOutboundLabel.textContent = '—'; + } + + if (data.uptime && data.uptime > 0 && isRunning) { + lastFetchedUptime = data.uptime; + uptimeFetchedAt = Date.now(); + if (resUptimeLabel) resUptimeLabel.textContent = formatUptime(data.uptime); + startUptimeCounter(); + } else { + lastFetchedUptime = null; + uptimeFetchedAt = null; + stopUptimeCounter(); + if (resUptimeLabel) resUptimeLabel.textContent = isRunning ? 'Starting...' : 'Offline'; + } + } + + function subscribeResourceStats() { + if (resourceStatsSubscribed) return; + resourceStatsSubscribed = true; + socket.on('resources:data', onResourceData); + socket.emit('resources:subscribe', { server: bot }); + } + + function unsubscribeResourceStats() { + if (!resourceStatsSubscribed) return; + resourceStatsSubscribed = false; + socket.off('resources:data', onResourceData); + socket.emit('resources:unsubscribe', { server: bot }); + stopUptimeCounter(); + } + + socket.on('connect', () => { + if (resourceStatsSubscribed) { + resourceStatsSubscribed = false; + if (resourceStatsPopup && resourceStatsPopup.classList.contains('visible')) { + subscribeResourceStats(); + } + } + }); + + function startUptimeCounter() { + stopUptimeCounter(); + if (lastFetchedUptime === null || uptimeFetchedAt === null) return; + resourceStatsUptimeInterval = setInterval(() => { + if (lastFetchedUptime === null || uptimeFetchedAt === null) { + stopUptimeCounter(); + return; + } + const elapsed = Math.floor((Date.now() - uptimeFetchedAt) / 1000); + const currentUptime = lastFetchedUptime + elapsed; + if (resUptimeLabel) resUptimeLabel.textContent = formatUptime(currentUptime); + }, 1000); + } + + function stopUptimeCounter() { + if (resourceStatsUptimeInterval) { + clearInterval(resourceStatsUptimeInterval); + resourceStatsUptimeInterval = null; + } + } + + function formatUptime(seconds) { + if (!seconds || seconds < 0) return '—'; + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + const mins = Math.floor((seconds % 3600) / 60); + const secs = Math.floor(seconds % 60); + const parts = []; + if (days > 0) parts.push(`${days}d`); + if (hours > 0) parts.push(`${hours}h`); + if (mins > 0) parts.push(`${mins}m`); + if (secs > 0 || parts.length === 0) parts.push(`${secs}s`); + return parts.join(' '); + } + + function openResourceStatsPopup() { + if (!resourceStatsPopup) return; + resourceStatsPopup.classList.add('visible'); + if (floatingSidebar && floatingSidebar.matches(':hover')) { + resourceStatsPopup.classList.add('sidebar-expanded'); + } + subscribeResourceStats(); + } + + function closeResourceStatsPopup() { + if (!resourceStatsPopup) return; + resourceStatsPopup.classList.remove('visible'); + resourceStatsPopup.classList.remove('sidebar-expanded'); + unsubscribeResourceStats(); + lastFetchedUptime = null; + uptimeFetchedAt = null; + } + + if (floatingSidebar && resourceStatsPopup) { + floatingSidebar.addEventListener('mouseenter', () => { + if (resourceStatsPopup.classList.contains('visible')) { + resourceStatsPopup.classList.add('sidebar-expanded'); + } + }); + floatingSidebar.addEventListener('mouseleave', () => { + resourceStatsPopup.classList.remove('sidebar-expanded'); + }); + } + + if (resourceStatsClose) resourceStatsClose.addEventListener('click', closeResourceStatsPopup); + document.addEventListener('click', (e) => { + if (resourceStatsPopup && resourceStatsPopup.classList.contains('visible')) { + if (!resourceStatsPopup.contains(e.target) && !e.target.closest('[data-action="open-resource-stats"]')) { + closeResourceStatsPopup(); + } + } + }); + + const openResourceStatsTab = document.getElementById("openResourceStatsTab"); + if (openResourceStatsTab) { + openResourceStatsTab.addEventListener("click", () => { + window.open(`/server/${encodeURIComponent(bot)}/resources`, 'ResourceStats', 'width=400,height=500,resizable=yes,scrollbars=yes,status=no,toolbar=no,menubar=no,location=no'); + closeResourceStatsPopup(); + }); + } + + copyAddressBtn.addEventListener('click', async () => { + try { + if (!infoAddress.value) return; + await navigator.clipboard.writeText(infoAddress.value); + const icon = copyAddressBtn.querySelector('i'); + if (icon) { + icon.className = 'fa-solid fa-check'; + setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1200); + } + } catch (e) { infoAddress.select(); document.execCommand('copy'); } + }); + if (storeModalClose) storeModalClose.addEventListener('click', closeStoreModal); + if (storePrefClose) storePrefClose.addEventListener('click', closeStorePrefModal); + if (storePrefModal) storePrefModal.addEventListener('click', (e) => { if (e.target === storePrefModal) closeStorePrefModal(); }); + if (storeTabVersions) storeTabVersions.addEventListener('click', async () => { + const { template: tpl } = resolveStoreTemplate(); + if (tpl === 'fivem') { + try { + const data = await fetchStoreProviders(); + const providers = Array.isArray(data.providers) ? data.providers : []; + const fivemProvider = providers.find(p => String(p.id || p.provider || '').toLowerCase() === 'fivem') || providers[0]; + if (fivemProvider) { + await openProviderDetails(fivemProvider, { direct: true }); + return; + } + } catch { } + } + renderStoreProvidersView(); + }); + if (storeTabPlugins) storeTabPlugins.addEventListener('click', () => { + if (storeTabPlugins.classList.contains('hidden')) return; + renderPluginsUI(); + }); + function focusConsole() { openInfoModal(); } + function clearSelection() { + selectedEntries.clear(); + if (selectAllToggle) selectAllToggle.checked = false; + updateSelectionUI(); + } + function updateSelectionUI() { + if (!entriesEl) return; + const entries = Array.from(entriesEl.querySelectorAll('.entry')); + entries.forEach(li => { + const rel = li.dataset.relPath || ""; + const isSelected = selectedEntries.has(rel); + li.classList.toggle('selected', isSelected); + li.classList.toggle('selectable', entries.length > 0); + }); + const allSelected = entries.length > 0 && entries.every(li => selectedEntries.has(li.dataset.relPath || "")); + if (selectAllToggle) selectAllToggle.checked = allSelected; + if (bulkDeleteBtn) bulkDeleteBtn.classList.toggle('show', selectedEntries.size > 0 && hasPerm('files_delete')); + if (bulkArchiveBtn) bulkArchiveBtn.classList.toggle('show', selectedEntries.size > 0 && hasPerm('files_archive')); + } + function toggleEntrySelection(li) { + if (!li) return; + const rel = li.dataset.relPath; + if (!rel) return; + if (selectedEntries.has(rel)) selectedEntries.delete(rel); else selectedEntries.add(rel); + updateSelectionUI(); + } + function selectAllEntries() { + if (!entriesEl) return; + selectedEntries.clear(); + entriesEl.querySelectorAll('.entry').forEach(li => { + const rel = li.dataset.relPath; + if (rel) selectedEntries.add(rel); + }); + updateSelectionUI(); + } + let currentPath = ""; + let activeInlineRename = null; + function cancelActiveInlineRename() { + if (!activeInlineRename || typeof activeInlineRename.cancel !== 'function') return; + activeInlineRename.cancel(); + } + + function renderFileBreadcrumb(pathValue = "") { + if (!breadcrumbs) return; + const cleanPath = String(pathValue || "").replace(/\\/g, "/").replace(/^\/+|\/+$/g, ""); + const parts = cleanPath ? cleanPath.split("/").filter(Boolean) : []; + const serverLabel = String(bot || "server"); + const crumbs = [ + '/', + `${escapeHtml(serverLabel)}` + ]; + let acc = ""; + parts.forEach((part) => { + acc = acc ? `${acc}/${part}` : part; + crumbs.push('/'); + crumbs.push(`${escapeHtml(part)}`); + }); + breadcrumbs.innerHTML = ``; + } + + function startInlineRename(li, nameNode, currentName, oldPath) { + if (!li || !nameNode) return; + if (activeInlineRename && activeInlineRename.li !== li) cancelActiveInlineRename(); + if (li.classList.contains('renaming')) return; + + let submitting = false; + const input = document.createElement("input"); + input.type = "text"; + input.className = "entry-rename-input"; + input.value = currentName; + input.setAttribute("aria-label", `Rename ${currentName}`); + + const actions = document.createElement("div"); + actions.className = "entry-rename-actions"; + + const saveBtn = document.createElement("button"); + saveBtn.type = "button"; + saveBtn.className = "entry-rename-btn save"; + saveBtn.title = "Save"; + saveBtn.setAttribute("aria-label", "Save rename"); + saveBtn.innerHTML = ''; + + const cancelBtn = document.createElement("button"); + cancelBtn.type = "button"; + cancelBtn.className = "entry-rename-btn cancel"; + cancelBtn.title = "Cancel"; + cancelBtn.setAttribute("aria-label", "Cancel rename"); + cancelBtn.innerHTML = ''; + + actions.appendChild(saveBtn); + actions.appendChild(cancelBtn); + + const editor = document.createElement("div"); + editor.className = "entry-rename-inline"; + editor.appendChild(input); + editor.appendChild(actions); + + const originalText = nameNode.textContent; + li.classList.add('renaming'); + nameNode.textContent = ""; + nameNode.appendChild(editor); + + const stopClick = (ev) => ev.stopPropagation(); + editor.addEventListener('mousedown', stopClick); + editor.addEventListener('click', stopClick); + + const cleanup = () => { + if (activeInlineRename && activeInlineRename.li === li) activeInlineRename = null; + li.classList.remove('renaming'); + nameNode.textContent = originalText; + }; + + const cancelRename = () => { + cleanup(); + }; + + const setEditingState = (isBusy) => { + input.disabled = isBusy; + saveBtn.disabled = isBusy; + cancelBtn.disabled = isBusy; + }; + + const saveRename = async () => { + if (submitting) return; + const newName = input.value.trim(); + if (!newName) { input.focus(); return; } + if (newName === currentName) { cleanup(); return; } + + submitting = true; + setEditingState(true); + try { + await apiRename(oldPath, newName); + flashFilesBar(); + await loadExplorer(currentPath); + } catch (err) { + submitting = false; + setEditingState(false); + flashFilesBar(); + input.focus(); + input.select(); + } + }; + + saveBtn.addEventListener('click', (ev) => { + ev.preventDefault(); + ev.stopPropagation(); + saveRename(); + }); + cancelBtn.addEventListener('click', (ev) => { + ev.preventDefault(); + ev.stopPropagation(); + cancelRename(); + }); + input.addEventListener('keydown', (ev) => { + ev.stopPropagation(); + if (ev.key === 'Enter') { + ev.preventDefault(); + saveRename(); + } else if (ev.key === 'Escape') { + ev.preventDefault(); + cancelRename(); + } + }); + + activeInlineRename = { li, cancel: cancelRename }; + input.focus(); + input.select(); + } + async function loadExplorer(path = "") { + try { + if (!hasPerm('files_read')) { entriesEl.innerHTML = `
  • Unauthorized
  • `; return; } + const data = await apiExplore(path); + currentPath = data.path || ""; + renderFileBreadcrumb(currentPath); + cancelActiveInlineRename(); + clearSelection(); + entriesEl.innerHTML = ""; + const explorerEntries = (Array.isArray(data.entries) ? data.entries : []) + .map(normalizeExplorerEntry) + .filter((entry) => entry.name) + .sort(compareExplorerEntries); + currentExplorerEntryMeta.clear(); + explorerEntries.forEach((entry) => { + currentExplorerEntryMeta.set(entry.name, { isDir: entry.isDir, size: entry.size }); + }); + explorerEntries.forEach((e) => { + const li = document.createElement("li"); li.className = "entry selectable"; + const relPath = currentPath ? currentPath + "/" + e.name : e.name; + li.dataset.relPath = relPath; + li.dataset.isDir = e.isDir ? "true" : "false"; + const left = document.createElement("div"); left.className = "entry-left"; + const icon = document.createElement("div"); icon.className = `entry-icon ${e.isDir ? 'folder' : 'file'}`; icon.innerHTML = e.isDir ? '' : ''; + const nameWrap = document.createElement("div"); nameWrap.className = "entry-text-wrap"; + const nm = document.createElement("div"); nm.className = "entry-name"; nm.textContent = e.name; + const meta = document.createElement("div"); meta.className = "entry-meta"; + if (e.isDir) { + meta.textContent = "Folder"; + } else { + meta.textContent = typeof e.size === "number" ? formatFileSize(e.size) : "File"; + } + nameWrap.appendChild(nm); nameWrap.appendChild(meta); + left.appendChild(icon); left.appendChild(nameWrap); + let longPressTimeout = null; + let longPressTriggered = false; + left.addEventListener('mousedown', (ev) => { + if (ev.button !== 0) return; + longPressTriggered = false; + if (longPressTimeout) clearTimeout(longPressTimeout); + longPressTimeout = setTimeout(() => { + longPressTriggered = true; + clearSelection(); + const rel = li.dataset.relPath; + if (rel) selectedEntries.add(rel); + updateSelectionUI(); + }, 2000); + }); + ['mouseup', 'mouseleave', 'mouseout'].forEach(evt => { + left.addEventListener(evt, () => { + if (longPressTimeout) { + clearTimeout(longPressTimeout); + longPressTimeout = null; + } + }); + }); + left.addEventListener('click', (ev) => { + ev.stopPropagation(); + if (longPressTriggered) { longPressTriggered = false; return; } + toggleEntrySelection(li); + }); + const actions = document.createElement("div"); actions.className = "entry-actions"; + ['pointerdown', 'mousedown', 'mouseup', 'click', 'dblclick'].forEach((eventName) => { + actions.addEventListener(eventName, (ev) => ev.stopPropagation()); + }); + const moreBtn = document.createElement("button"); moreBtn.type = "button"; moreBtn.className = "more-btn"; moreBtn.innerHTML = ''; + const menu = document.createElement("div"); menu.className = "more-menu"; + ['pointerdown', 'mousedown', 'mouseup', 'click', 'dblclick'].forEach((eventName) => { + menu.addEventListener(eventName, (ev) => ev.stopPropagation()); + }); + if (!e.isDir && hasPerm('files_read')) { + const downloadBtn = document.createElement("button"); downloadBtn.type = "button"; downloadBtn.innerHTML = 'Download'; + downloadBtn.addEventListener('click', (ev) => { + ev.preventDefault(); ev.stopPropagation(); menu.classList.remove('show'); + const rel = currentPath ? currentPath + "/" + e.name : e.name; + apiDownloadFile(rel); + }); + menu.appendChild(downloadBtn); + } + if (hasPerm('files_rename')) { + const renameBtn = document.createElement("button"); renameBtn.type = "button"; renameBtn.innerHTML = 'Rename'; + renameBtn.addEventListener('click', (ev) => { + ev.preventDefault(); + ev.stopPropagation(); + menu.classList.remove('show'); + startInlineRename(li, nm, e.name, relPath); + }); + menu.appendChild(renameBtn); + } + if (hasPerm('files_delete')) { + const deleteBtn = document.createElement("button"); deleteBtn.type = "button"; deleteBtn.innerHTML = 'Delete'; + deleteBtn.addEventListener('click', async (ev) => { + ev.preventDefault(); + ev.stopPropagation(); + if (!confirm(`Delete ${e.isDir ? "folder" : "file"} "${e.name}"?`)) { menu.classList.remove('show'); return; } + try { + const rel = currentPath ? currentPath + "/" + e.name : e.name; + await apiDelete(rel, e.isDir); + setTimeout(() => loadExplorer(currentPath), 200); + } catch (err) { flashFilesBar(); } + menu.classList.remove('show'); + }); + menu.appendChild(deleteBtn); + } + const isArchive = !e.isDir && /\.(zip|tar|tgz|tar\.gz|tar\.bz2|bz2|rar|7z)$/i.test(e.name); + if (isArchive && hasPerm('files_create')) { + const unarchiveBtn = document.createElement("button"); unarchiveBtn.type = "button"; unarchiveBtn.textContent = "Unarchive"; + unarchiveBtn.addEventListener('click', async (ev) => { + ev.preventDefault(); ev.stopPropagation(); menu.classList.remove('show'); + const targetRel = currentPath ? currentPath + "/" + e.name : e.name; + if (!confirm(`Unarchive "${e.name}" into current folder?`)) return; + showProgressWheel(6, "Unarchiving..."); + try { + const j = await apiExtract(targetRel); + setProgress(100, j.msg || 'Unarchive complete'); await new Promise(r => setTimeout(r, 250)); + loadExplorer(currentPath); flashFilesBar(); + } catch (err) { flashFilesBar(); } + finally { hideProgressWheel(); } + }); + menu.appendChild(unarchiveBtn); + } + actions.appendChild(moreBtn); actions.appendChild(menu); + moreBtn.addEventListener('click', (ev) => { + ev.stopPropagation(); + document.querySelectorAll('.more-menu.show').forEach(m => { if (m !== menu) m.classList.remove('show'); }); + menu.classList.toggle('show'); + }); + li.addEventListener('click', async (ev) => { + if (li.classList.contains('renaming')) return; + if (ev.defaultPrevented || ev.target.closest('.entry-actions, .more-menu, button, input, textarea, a, .entry-rename-inline')) return; + if (e.isDir) { + loadExplorer(currentPath ? currentPath + "/" + e.name : e.name); + } else if (hasPerm('files_read')) { + const rel = relPath; + if (typeof e.size === 'number' && e.size > FILE_SIZE_EDITOR_LIMIT) { + if (confirm(`This file is ${formatFileSize(e.size)} which exceeds the 5 MB editor limit.\n\nDownload instead?`)) { + apiDownloadFile(rel); + } + return; + } + if (REMOTE_MODE) { + try { + const content = await apiReadFile(rel); + if (content !== null) openEditorModal(rel, content); + } catch (err) { flashFilesBar(); } + } else { + socket.emit("readFile", { bot, path: rel }); + } + } + }); + const arrow = document.createElement("div"); arrow.className = "entry-arrow"; arrow.innerHTML = ''; + const right = document.createElement("div"); right.className = "entry-right"; right.appendChild(actions); right.appendChild(arrow); + li.appendChild(left); li.appendChild(right); entriesEl.appendChild(li); + }); + updateSelectionUI(); + const scripts = explorerEntries.filter(e => !e.isDir).map(e => e.name); + if (taskStartupSelect) { + taskStartupSelect.innerHTML = `` + scripts.map(s => ``).join(""); + } + } catch (err) { + console.error("[FileManager] Load failed:", err); + entriesEl.innerHTML = `
  • + + ${hasPerm('files_read') ? ' Failed to load: ' + (err.message || String(err)) : ' Unauthorized'} +
  • `; + } + } + if (selectAllToggle) { + selectAllToggle.addEventListener('change', (ev) => { + if (ev.target.checked) selectAllEntries(); else clearSelection(); + }); + } + if (bulkDeleteBtn) { + bulkDeleteBtn.addEventListener('click', async () => { + if (selectedEntries.size === 0) return; + if (!confirm(`Delete ${selectedEntries.size} selected item(s)?`)) return; + const toDelete = Array.from(entriesEl.querySelectorAll('.entry')).filter(li => selectedEntries.has(li.dataset.relPath)); + try { + showProgressWheel(4, "Deleting..."); + for (const li of toDelete) { + const rel = li.dataset.relPath; + const isDir = li.dataset.isDir === 'true'; + if (!rel) continue; + await apiDelete(rel, isDir); + } + setProgress(100, "Delete complete"); + setTimeout(() => hideProgressWheel(), 300); + loadExplorer(currentPath); + } catch (err) { + alert('Delete failed: ' + (err && err.message ? err.message : err)); + } finally { + clearSelection(); + } + }); + } + if (bulkArchiveBtn) { + bulkArchiveBtn.addEventListener('click', async () => { + if (selectedEntries.size === 0) return; + if (!hasPerm('files_archive')) return alert('Unauthorized: missing files_archive permission'); + const paths = Array.from(selectedEntries); + try { + showProgressWheel(10, "Creating archive..."); + const result = await apiArchive(paths, currentPath); + setProgress(100, `Archive created: ${result.name}`); + setTimeout(() => hideProgressWheel(), 300); + loadExplorer(currentPath); + flashFilesBar(); + } catch (err) { + hideProgressWheel(); + alert('Archive failed: ' + (err && err.message ? err.message : err)); + } finally { + clearSelection(); + } + }); + } + let currentProgress = 0, simInterval = null, isActiveOperation = false, operationStart = null; + function showProgressWheel(initial = 0, msg = "Processing...") { isActiveOperation = true; operationStart = Date.now(); resetUploadProgressList(); progressWheel.classList.remove('hidden'); setProgress(initial, msg); } + function hideProgressWheel() { isActiveOperation = false; setTimeout(() => { progressWheel.classList.add('hidden'); setProgress(0); closeProgressPopup(); operationStart = null; popupTime.textContent = "—"; }, 300); } + function setProgress(percent, msg = "Processing...") { + if (typeof percent !== 'number') percent = 0; percent = Math.max(0, Math.min(100, Math.round(percent))); + currentProgress = percent; progressFill.style.height = percent + "%"; popupPercent.textContent = percent + "%"; popupBar.style.width = percent + "%"; + if (msg) popupMsg.textContent = msg; + if (operationStart) { const elapsed = Math.floor((Date.now() - operationStart) / 1000); popupTime.textContent = `${elapsed}s elapsed`; } else popupTime.textContent = "—"; + if (percent >= 100 && isActiveOperation) { setTimeout(() => hideProgressWheel(), 450); } + } + + function openProgressPopup() { progressPopup.style.display = "block"; progressPopup.setAttribute('aria-hidden', 'false'); popupPercent.textContent = currentProgress + "%"; popupBar.style.width = currentProgress + "%"; if (operationStart) { const elapsed = Math.floor((Date.now() - operationStart) / 1000); popupTime.textContent = `${elapsed}s elapsed`; } else popupTime.textContent = "—"; } + function closeProgressPopup() { + if (!progressPopup) return; + animateClose(progressPopup); + } + function escapeProgressText(value) { + return String(value || '').replace(/[&<>"']/g, (ch) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[ch])); + } + function resetUploadProgressList() { + if (!popupFileList) return; + popupFileList.innerHTML = ''; + popupFileList.classList.remove('visible'); + } + function initUploadProgressList(files) { + if (!popupFileList) return; + const items = Array.from(files || []).filter(Boolean); + if (!items.length) return resetUploadProgressList(); + popupFileList.innerHTML = items.map((file, index) => ` +
    +
    ${escapeProgressText(file.name || 'file')}
    +
    0%
    +
    +
    + `).join(''); + popupFileList.classList.add('visible'); + } + function updateUploadProgressList(index, percent) { + if (!popupFileList) return; + const item = popupFileList.querySelector(`[data-upload-index="${index}"]`); + if (!item) return; + const value = Math.max(0, Math.min(100, Math.round(Number(percent) || 0))); + const pct = item.querySelector('.progress-file-percent'); + const fill = item.querySelector('.progress-file-fill'); + if (pct) pct.textContent = `${value}%`; + if (fill) fill.style.width = `${value}%`; + } + if (progressWheel && progressPopup && popupClose) { + progressWheel.addEventListener('click', () => { + if (progressPopup.style.display === 'block') closeProgressPopup(); + else openProgressPopup(); + }); + popupClose.addEventListener('click', () => closeProgressPopup()); + } + function enableDropHandlers() { + if (!hasPerm('files_upload')) return; + const modalInner = document.querySelector('#filesModal .modal'); if (!modalInner) return; + ['dragenter', 'dragover', 'dragleave', 'drop'].forEach(evt => { modalInner.addEventListener(evt, (e) => e.preventDefault(), { passive: false }); }); + modalInner.addEventListener('dragenter', onDragEnter); + modalInner.addEventListener('dragover', onDragOver); + modalInner.addEventListener('dragleave', onDragLeave); + modalInner.addEventListener('drop', onDrop); + } + function disableDropHandlers() { + const modalInner = document.querySelector('#filesModal .modal'); if (!modalInner) return; + modalInner.removeEventListener('dragenter', onDragEnter); + modalInner.removeEventListener('dragover', onDragOver); + modalInner.removeEventListener('dragleave', onDragLeave); + modalInner.removeEventListener('drop', onDrop); + } + let dragCounter = 0; + function dataTransferHasDirectory(dataTransfer) { + const items = Array.from(dataTransfer?.items || []); + return items.some((item) => { + if (!item || item.kind !== 'file') return false; + try { + const entry = item.webkitGetAsEntry ? item.webkitGetAsEntry() : null; + return !!(entry && entry.isDirectory); + } catch (_) { + return false; + } + }); + } + function fileListHasDirectory(files) { + return Array.from(files || []).some((file) => String(file?.webkitRelativePath || '').includes('/')); + } + function blockFolderUpload() { + alert('Upload folders as an archive.'); + } + function onDragEnter(e) { e.preventDefault(); dragCounter++; if (!dropOverlay) return; dropOverlay.classList.add('visible'); if (dropTitle) dropTitle.textContent = "Drop to upload"; if (dropSubtitle) dropSubtitle.textContent = "Release to upload to current folder"; } + function onDragOver(e) { e.preventDefault(); if (e.dataTransfer) e.dataTransfer.dropEffect = 'copy'; if (dropOverlay && !dropOverlay.classList.contains('visible')) dropOverlay.classList.add('visible'); } + function onDragLeave(e) { e.preventDefault(); dragCounter = Math.max(0, dragCounter - 1); if (dragCounter === 0 && dropOverlay) dropOverlay.classList.remove('visible'); } + async function onDrop(e) { + e.preventDefault(); + dragCounter = 0; + if (dropOverlay) dropOverlay.classList.remove('visible'); + if (!hasPerm('files_upload')) return; + if (dataTransferHasDirectory(e.dataTransfer)) { + blockFolderUpload(); + return; + } + const items = e.dataTransfer.files; + if (!items || items.length === 0) return; + const files = Array.from(items); + if (fileListHasDirectory(files)) { + blockFolderUpload(); + return; + } + await uploadFilesSequential(files); + } + async function uploadFilesSequential(files) { + files = Array.from(files || []).filter(Boolean); + if (!files.length) return; + if (fileListHasDirectory(files)) { + blockFolderUpload(); + return; + } + showProgressWheel(0, files.length === 1 ? `Uploading 1 of 1 — ${files[0].name}` : `Uploading 0 of ${files.length}`); + initUploadProgressList(files); + let completed = 0; + for (let i = 0; i < files.length; i++) { + const file = files[i], idx = i + 1, total = files.length, msgBase = `Uploading ${idx} of ${total} — ${file.name}`; + try { + await apiUploadWithProgress(file, currentPath, (percent, state) => { + const filePercent = Math.max(0, Math.min(100, Number(percent) || 0)); + updateUploadProgressList(i, filePercent); + const overall = total <= 1 + ? filePercent + : ((i / total) * 100) + (filePercent / total); + setProgress(overall, state || msgBase); + }, msgBase); + completed++; + updateUploadProgressList(i, 100); + setProgress((completed / total) * 100, `Uploaded ${completed} of ${total}`); + await new Promise(r => setTimeout(r, 150)); loadExplorer(currentPath); + } catch (err) { + flashFilesBar(); + alert(`Upload failed for "${file.name}": ` + ((err && err.message) ? err.message : 'upload failed')); + } + } + setTimeout(() => { hideProgressWheel(); }, 400); + flashFilesBar(); + } + function normalizeInput(raw) { + if (typeof raw !== 'string') return ''; + return raw.replace(/\r\n?/g, '\n'); + } + function detectMonacoLanguage(path) { + const lower = (path || "").toLowerCase(); + if (lower.endsWith(".js")) return "javascript"; + if (lower.endsWith(".ts")) return "typescript"; + if (lower.endsWith(".json")) return "json"; + if (lower.endsWith(".jsonc")) return "jsonc"; + if (lower.endsWith(".yml") || lower.endsWith(".yaml")) return "yaml"; + if (lower.endsWith(".html") || lower.endsWith(".htm")) return "html"; + if (lower.endsWith(".css")) return "css"; + if (lower.endsWith(".java")) return "java"; + if (lower.endsWith(".php")) return "php"; + if (lower.endsWith(".py")) return "python"; + if (lower.endsWith(".rb")) return "ruby"; + if (lower.endsWith(".go")) return "go"; + if (lower.endsWith(".rs")) return "rust"; + if (lower.endsWith(".cs")) return "csharp"; + if (lower.endsWith(".c")) return "c"; + if (lower.endsWith(".cpp") || lower.endsWith(".cc") || lower.endsWith(".cxx")) return "cpp"; + if (lower.endsWith(".xml") || lower.endsWith(".xsd") || lower.endsWith(".svg") || lower.endsWith(".plist")) return "xml"; + if (lower.endsWith(".toml")) return "toml"; + if (lower.endsWith(".sql")) return "sql"; + if (lower.endsWith(".md") || lower.endsWith(".markdown")) return "markdown"; + if (lower.endsWith(".properties") || lower.endsWith(".ini") || lower.endsWith(".cfg") || lower.endsWith(".conf") || lower.endsWith(".env")) return "ini"; + if (lower.endsWith(".sh") || lower.endsWith(".bash") || lower.endsWith(".zsh") || lower.endsWith(".ksh")) return "shell"; + if (lower.endsWith(".ps1")) return "powershell"; + if (lower.endsWith("dockerfile")) return "dockerfile"; + return "plaintext"; + } + function detectAceLanguage(path) { + const lower = (path || "").toLowerCase(); + if (lower.endsWith(".js") || lower.endsWith(".mjs") || lower.endsWith(".cjs")) return "ace/mode/javascript"; + if (lower.endsWith(".ts")) return "ace/mode/typescript"; + if (lower.endsWith(".json") || lower.endsWith(".jsonc")) return "ace/mode/json"; + if (lower.endsWith(".yml") || lower.endsWith(".yaml")) return "ace/mode/yaml"; + if (lower.endsWith(".html") || lower.endsWith(".htm")) return "ace/mode/html"; + if (lower.endsWith(".css")) return "ace/mode/css"; + if (lower.endsWith(".java")) return "ace/mode/java"; + if (lower.endsWith(".php")) return "ace/mode/php"; + if (lower.endsWith(".py")) return "ace/mode/python"; + if (lower.endsWith(".rb")) return "ace/mode/ruby"; + if (lower.endsWith(".go")) return "ace/mode/golang"; + if (lower.endsWith(".rs")) return "ace/mode/rust"; + if (lower.endsWith(".cs")) return "ace/mode/csharp"; + if (lower.endsWith(".c") || lower.endsWith(".cpp") || lower.endsWith(".cc") || lower.endsWith(".cxx") || lower.endsWith(".h")) return "ace/mode/c_cpp"; + if (lower.endsWith(".xml") || lower.endsWith(".xsd") || lower.endsWith(".svg") || lower.endsWith(".plist")) return "ace/mode/xml"; + if (lower.endsWith(".toml")) return "ace/mode/toml"; + if (lower.endsWith(".sql")) return "ace/mode/sql"; + if (lower.endsWith(".md") || lower.endsWith(".markdown")) return "ace/mode/markdown"; + if (lower.endsWith(".properties") || lower.endsWith(".ini") || lower.endsWith(".cfg") || lower.endsWith(".conf") || lower.endsWith(".env")) return "ace/mode/ini"; + if (lower.endsWith(".sh") || lower.endsWith(".bash") || lower.endsWith(".zsh") || lower.endsWith(".ksh")) return "ace/mode/sh"; + if (lower.endsWith(".ps1")) return "ace/mode/powershell"; + if (lower.endsWith("dockerfile")) return "ace/mode/dockerfile"; + return "ace/mode/text"; + } + async function shouldUseAceFallback() { + if (useAceFallback !== null) return useAceFallback; + if (typeof ace === "undefined") { useAceFallback = false; return false; } + const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) + || (navigator.maxTouchPoints > 1 && window.innerWidth < 1100); + if (isMobile) { + console.log("[Editor] Mobile/tablet detected → Ace fallback"); + useAceFallback = true; return true; + } + const cores = navigator.hardwareConcurrency || 2; + const memory = navigator.deviceMemory || 4; + if (cores < 2 || memory < 2) { + console.log("[Editor] Low-spec device detected (cores:", cores, "mem:", memory, "GB) → Ace fallback"); + useAceFallback = true; return true; + } + try { + const conn = navigator.connection || navigator.mozConnection || navigator.webkitConnection; + if (conn && typeof conn.downlink === "number" && conn.downlink < 2) { + console.log("[Editor] Slow connection detected (downlink:", conn.downlink, "Mbps) → Ace fallback"); + useAceFallback = true; return true; + } + const t0 = performance.now(); + const testUrl = "/style.css?_cb=" + Date.now(); + const resp = await fetch(testUrl, { cache: "no-store" }); + const blob = await resp.blob(); + const elapsed = performance.now() - t0; + const sizeBits = blob.size * 8; + const speedMbps = (sizeBits / elapsed) * 1000 / 1_000_000; + if (speedMbps < 2) { + console.log("[Editor] Speed test:", speedMbps.toFixed(2), "Mbps → Ace fallback"); + useAceFallback = true; return true; + } + } catch (e) { + console.warn("[Editor] Speed test failed, assuming capable:", e); + } + useAceFallback = false; + return false; + } + function loadMonaco() { + if (window.monaco) { + return Promise.resolve(window.monaco); + } + if (monacoLoaderPromise) return monacoLoaderPromise; + monacoLoaderPromise = new Promise((resolve, reject) => { + if (typeof require === "undefined") { + reject(new Error("Monaco loader (require) nu este disponibil")); + return; + } + require.config({ + paths: { + vs: "https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs" + }, + waitSeconds: 10 + }); + require(["vs/editor/editor.main"], function (m) { + try { + m.editor.setTheme("vs-dark"); + } catch (e) { } + resolve(m); + }, function (err) { + console.error("Failed to load Monaco", err); + reject(err); + }); + }); + return monacoLoaderPromise; + } + function patchMonacoFindWidgetLayout(root) { + const host = root || monacoContainer; + if (!host) return; + host.querySelectorAll(".find-widget .monaco-inputbox > .wrapper > .input").forEach((el) => { + el.style.margin = "0"; + el.style.padding = "2px 4px"; + el.style.border = "none"; + el.style.borderRadius = "0"; + el.style.background = "transparent"; + el.style.minHeight = "0"; + el.style.height = "100%"; + el.style.lineHeight = "inherit"; + el.style.fontFamily = "inherit"; + el.style.fontSize = "inherit"; + el.style.boxSizing = "border-box"; + el.style.resize = "none"; + el.style.backdropFilter = "none"; + el.style.webkitBackdropFilter = "none"; + el.style.boxShadow = "none"; + }); + host.querySelectorAll(".find-widget .monaco-inputbox > .wrapper > .mirror").forEach((el) => { + el.style.padding = "2px 4px"; + el.style.boxSizing = "border-box"; + }); + } + function ensureMonacoFindWidgetPatch() { + if (!monacoContainer) return; + patchMonacoFindWidgetLayout(monacoContainer); + if (monacoFindWidgetObserver) return; + monacoFindWidgetObserver = new MutationObserver(() => { + patchMonacoFindWidgetLayout(monacoContainer); + }); + monacoFindWidgetObserver.observe(monacoContainer, { + childList: true, + subtree: true, + attributes: true, + attributeFilter: ["class", "style"] + }); + } + async function openAceEditor(content, filePath) { + if (monacoContainer) monacoContainer.style.display = "none"; + if (aceContainer) aceContainer.style.display = "block"; + codeShell.style.display = "flex"; + textArea.style.display = "none"; + const legacyPane = document.querySelector("#codeShell .code-pane"); + if (legacyPane) legacyPane.style.display = "none"; + if (lineGutter) lineGutter.style.display = "none"; + if (typeof ace === "undefined") { + console.error("[Editor] Ace not available — using raw textarea"); + codeShell.style.display = "none"; + if (aceContainer) aceContainer.style.display = "none"; + textArea.style.display = "block"; + textArea.value = content; + textArea.dataset.original = content; + textArea.focus(); + return; + } + if (!aceEditor) { + ace.config.set("basePath", "https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict"); + aceEditor = ace.edit(aceContainer, { + theme: "ace/theme/one_dark", + fontSize: 14, + fontFamily: "ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', monospace", + showPrintMargin: false, + tabSize: 2, + useSoftTabs: true, + wrap: false, + scrollPastEnd: false, + animatedScroll: true, + enableBasicAutocompletion: false, + enableLiveAutocompletion: false, + highlightActiveLine: true, + highlightGutterLine: true, + showLineNumbers: true, + showGutter: true, + displayIndentGuides: true, + fixedWidthGutter: false + }); + aceEditor.resize(true); + } + const mode = detectAceLanguage(filePath); + aceEditor.session.setMode(mode); + aceEditor.setValue(content, -1); + aceEditor.clearSelection(); + aceEditor.moveCursorTo(0, 0); + requestAnimationFrame(() => { + if (aceEditor) aceEditor.resize(true); + }); + aceEditor.focus(); + } + async function openEditorModal(path, content) { + currentEditorPath = path || ""; + showModalElement(editorModal); + editorPath.textContent = currentEditorPath; + const isRich = true; + const normalized = normalizeInput(content || ""); + editorOriginalContent = normalized; + setEditorSaveButtonState(false); + if (!hasPerm("files_create")) { + editorSave.classList.add("disabled"); + } else { + editorSave.classList.remove("disabled"); + } + if (isRich) { + codeShell.style.display = "flex"; + if (lineGutter) lineGutter.style.display = "none"; + const legacyPane = document.querySelector("#codeShell .code-pane"); + if (legacyPane) legacyPane.style.display = "none"; + textArea.style.display = "none"; + + const fallback = await shouldUseAceFallback(); + + if (!fallback) { + if (monacoContainer) monacoContainer.style.display = "block"; + if (aceContainer) aceContainer.style.display = "none"; + try { + const monaco = await loadMonaco(); + if (!monacoContainer) { + console.error("monacoContainer missing"); + return; + } + const lang = detectMonacoLanguage(currentEditorPath); + if (monacoEditor) { + const oldModel = monacoEditor.getModel(); + const newModel = monaco.editor.createModel(normalized, lang); + monacoEditor.setModel(newModel); + if (oldModel) oldModel.dispose(); + monacoEditor.setScrollTop(0); + monacoEditor.setScrollLeft(0); + } else { + monacoEditor = monaco.editor.create(monacoContainer, { + value: normalized, + language: lang, + theme: "vs-dark", + automaticLayout: true, + fontSize: 14, + minimap: { enabled: false }, + quickSuggestions: false, + suggestOnTriggerCharacters: false, + wordBasedSuggestions: "off", + parameterHints: { enabled: false }, + snippetSuggestions: "none", + scrollBeyondLastLine: false, + scrollBeyondLastColumn: 0, + tabSize: 2, + insertSpaces: true, + detectIndentation: false, + autoIndent: "full", + formatOnType: true, + formatOnPaste: true + }); + } + setupMonacoIdleSuggestions(monacoEditor); + ensureMonacoFindWidgetPatch(); + monacoEditor.focus(); + monacoEditor.__originalValue = normalized; + } catch (err) { + console.error("Failed to init Monaco, trying Ace fallback:", err); + useAceFallback = true; + monacoLoaderPromise = null; + if (monacoContainer) monacoContainer.style.display = "none"; + await openAceEditor(normalized, currentEditorPath); + } + } else { + await openAceEditor(normalized, currentEditorPath); + } + } else { + codeShell.style.display = "none"; + if (monacoContainer) monacoContainer.style.display = "none"; + textArea.style.display = "block"; + textArea.value = normalized; + textArea.dataset.original = normalized; + textArea.focus(); + } + } + function closeEditorModal() { + if (!editorModal) return; + animateClose(editorModal, () => { + editorPath.textContent = ''; + if (monacoIdleSuggestTimer) { + clearTimeout(monacoIdleSuggestTimer); + monacoIdleSuggestTimer = null; + } + if (monacoEditor) { + const model = monacoEditor.getModel && monacoEditor.getModel(); + if (model) model.dispose(); + monacoEditor.setModel(null); + } + if (aceEditor) { + aceEditor.setValue('', -1); + } + if (aceContainer) aceContainer.style.display = 'none'; + if (codeOverlay) codeOverlay.innerHTML = ''; + if (codeInput) { + codeInput.value = ''; + codeInput.dataset.original = ''; + } + if (codeShell) codeShell.style.display = 'none'; + if (textArea) { + textArea.value = ''; + textArea.dataset.original = ''; + textArea.style.display = 'none'; + } + if (lineGutter) lineGutter.innerHTML = ''; + editorOriginalContent = ""; + currentEditorPath = ''; + }); + } + function setEditorSaveButtonState(isSaving) { + if (!editorSave) return; + editorSave.innerHTML = isSaving + ? 'Saving...' + : 'Save'; + } + async function performSave() { + if (editorSaving) return; + if (!hasPerm('files_create')) return alert('Unauthorized'); + const path = document.getElementById('editorPath').textContent; + if (!path) return alert('No file open'); + let contentToSave = ""; + if (monacoEditor && monacoEditor.getModel && monacoEditor.getModel()) { + contentToSave = monacoEditor.getValue(); + } else if (aceEditor && aceContainer && aceContainer.style.display !== 'none') { + contentToSave = aceEditor.getValue(); + } else if (textArea && textArea.style.display !== 'none') { + contentToSave = textArea.value; + } else if (codeInput) { + contentToSave = codeInput.value; + } + editorSaving = true; + if (editorSave) { + editorSave.disabled = true; + editorSave.classList.add("disabled"); + setEditorSaveButtonState(true); + } + try { + await apiWriteFile(path, contentToSave); + editorOriginalContent = contentToSave; + if (monacoEditor) monacoEditor.__originalValue = contentToSave; + if (textArea) textArea.dataset.original = contentToSave; + if (codeInput) codeInput.dataset.original = contentToSave; + if (editorModal && editorModal.classList.contains('show')) flashEditorBar(); + loadExplorer(currentPath); + } catch (err) { + flashEditorBar(); + alert('Save failed: ' + (err && err.message ? err.message : err)); + } finally { + editorSaving = false; + if (editorSave) { + editorSave.disabled = false; + setEditorSaveButtonState(false); + editorSave.classList.toggle("disabled", !hasPerm("files_create")); + } + } + } + if (editorSave) { + editorSave.onclick = (e) => { + e.preventDefault(); + performSave(); + }; + } + editorDiscard.addEventListener('click', () => { + if (monacoEditor && monacoEditor.getModel && monacoEditor.getModel()) { + monacoEditor.setValue(editorOriginalContent || ""); + monacoEditor.setScrollTop(0); + monacoEditor.setScrollLeft(0); + return; + } + if (aceEditor && aceContainer && aceContainer.style.display !== 'none') { + aceEditor.setValue(editorOriginalContent || "", -1); + aceEditor.clearSelection(); + aceEditor.moveCursorTo(0, 0); + return; + } + if (textArea && textArea.style.display !== 'none') { + textArea.value = editorOriginalContent || textArea.dataset.original || ''; + return; + } + if (codeInput) { + const original = editorOriginalContent || codeInput.dataset.original || ''; + codeInput.value = original; + renderHighlightedEditor(original); + } + }); + + if (editorModalClose) { + editorModalClose.addEventListener("click", closeEditorModal); + } + if (editorModal) { + editorModal.addEventListener("click", (e) => { + if (e.target === editorModal) closeEditorModal(); + }); + } + + function appendConsoleNotice(text) { + appendToConsole(`${String(text || '')}\n`); + } + + function run() { + 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 }); + const onRunError = (err) => { + const message = err && err.message ? err.message : String(err || 'Run failed.'); + appendConsoleNotice(`[ADaemon] ${message}`); + alert('Run failed: ' + message); + refreshPowerState({ force: true }).catch(() => { }); + }; + const startRequest = apiAction({ bot, cmd: 'run' }); + appendConsoleNotice('[ADaemon] Start request accepted.'); + window.setTimeout(() => { + refreshPowerState({ force: true }).catch(() => { }); + }, 250); + startRequest + .then(() => { + return refreshPowerState({ force: true }).catch(() => { }); + }) + .catch(onRunError); + } + function stop() { + if (!hasPerm('server_stop')) return alert('Unauthorized'); + if (!isPowerActionAllowed('stop')) return; + setPowerState(POWER_STATE.STOPPING); + appendConsoleNotice('[ADaemon] Stopping server...'); + apiAction({ bot, cmd: 'stop' }) + .then(() => { + appendConsoleNotice('[ADaemon] Stop request accepted.'); + return refreshPowerState({ force: true }).catch(() => { }); + }) + .catch(err => { + const message = err && err.message ? err.message : String(err || 'Stop failed.'); + appendConsoleNotice(`[ADaemon] ${message}`); + alert('Stop failed: ' + message); + refreshPowerState({ force: true }).catch(() => { }); + }); + } + function killServer() { + if (!hasPerm('server_stop')) return alert('Unauthorized'); + if (!isPowerActionAllowed('kill')) return; + setPowerState(POWER_STATE.STOPPING); + appendConsoleNotice('[ADaemon] Sending kill signal...'); + apiAction({ bot, cmd: 'kill' }) + .then(() => { + appendConsoleNotice('[ADaemon] Kill request accepted.'); + return refreshPowerState({ force: true }).catch(() => { }); + }) + .catch(err => { + const message = err && err.message ? err.message : String(err || 'Kill failed.'); + appendConsoleNotice(`[ADaemon] ${message}`); + alert('Kill failed: ' + message); + refreshPowerState({ force: true }).catch(() => { }); + }); + } + fileUploadModal.addEventListener('change', () => { + if (!hasPerm('files_upload')) return alert('Unauthorized'); + const files = Array.from(fileUploadModal.files || []); + if (!files.length) return; + if (fileListHasDirectory(files)) { + blockFolderUpload(); + fileUploadModal.value = ''; + return; + } + uploadFilesSequential(files) + .then(() => { loadExplorer(currentPath); }) + .catch((err) => { + hideProgressWheel(); + flashFilesBar(); + alert('Upload failed: ' + ((err && err.message) ? err.message : 'upload failed')); + }) + .finally(() => { fileUploadModal.value = ''; }); + }); + + // ============= URL Uploader ============= + const urlUploaderBtn = document.getElementById('urlUploaderBtn'); + const urlUploaderModal = document.getElementById('urlUploaderModal'); + const urlUploaderClose = document.getElementById('urlUploaderClose'); + const urlUploaderCancel = document.getElementById('urlUploaderCancel'); + const urlUploaderConfirm = document.getElementById('urlUploaderConfirm'); + const urlUploaderInput = document.getElementById('urlUploaderInput'); + const urlUploaderError = document.getElementById('urlUploaderError'); + const urlUploaderTargetPath = document.getElementById('urlUploaderTargetPath'); + + function setUrlUploaderError(msg) { + if (!urlUploaderError) return; + if (!msg) { + urlUploaderError.style.display = 'none'; + urlUploaderError.textContent = ''; + } else { + urlUploaderError.style.display = 'block'; + urlUploaderError.textContent = String(msg); + } + } + + function openUrlUploaderModal() { + if (!urlUploaderModal) return; + if (!hasPerm('files_upload')) return alert('Unauthorized'); + if (urlUploaderInput) urlUploaderInput.value = ''; + setUrlUploaderError(''); + if (urlUploaderTargetPath) { + const display = currentPath && currentPath.length ? '/' + String(currentPath).replace(/^\/+/, '') : '/'; + urlUploaderTargetPath.textContent = display; + } + if (urlUploaderConfirm) urlUploaderConfirm.disabled = false; + showModalElement(urlUploaderModal); + setTimeout(() => { try { urlUploaderInput && urlUploaderInput.focus(); } catch (_) { } }, 30); + } + + function closeUrlUploaderModal() { + if (!urlUploaderModal) return; + if (typeof animateClose === 'function') animateClose(urlUploaderModal); + else { urlUploaderModal.classList.remove('show'); urlUploaderModal.style.display = 'none'; urlUploaderModal.setAttribute('aria-hidden', 'true'); } + } + + function normalizeUserUrl(raw) { + let s = String(raw || '').trim(); + if (!s) return ''; + // Reject control chars and embedded credentials/whitespace tricks early. + if (/[\s\u0000-\u001F\u007F]/.test(s)) return ''; + // If user supplied no scheme (e.g., example.com/server.tar), default to https. + if (!/^[a-zA-Z][a-zA-Z0-9+.\-]*:\/\//.test(s)) { + s = 'https://' + s; + } + let parsed; + try { parsed = new URL(s); } catch (_) { return ''; } + const proto = (parsed.protocol || '').toLowerCase(); + if (proto !== 'http:' && proto !== 'https:') return ''; + if (parsed.username || parsed.password) return ''; + if (!parsed.hostname) return ''; + return parsed.toString(); + } + + async function startUrlUpload() { + if (!hasPerm('files_upload')) return alert('Unauthorized'); + if (!urlUploaderInput) return; + setUrlUploaderError(''); + + const normalized = normalizeUserUrl(urlUploaderInput.value); + if (!normalized) { + setUrlUploaderError('Please enter a valid http(s) URL.'); + return; + } + + if (urlUploaderConfirm) urlUploaderConfirm.disabled = true; + + const dirForUpload = currentPath || ''; + const baseMsg = 'Uploading from URL...'; + closeUrlUploaderModal(); + showProgressWheel(2, baseMsg); + startSimulatedProgress(2, 92, 800); + + try { + const endpoint = REMOTE_MODE ? `${NODE_API_BASE}/upload-url` : '/upload-url'; + const headers = { 'Content-Type': 'application/json' }; + const payload = REMOTE_MODE + ? { url: normalized, path: dirForUpload } + : { bot, url: normalized, path: dirForUpload }; + + if (!REMOTE_MODE) { + try { + const tok = await ensureServerActionToken('fileUpload', { refresh: true }); + if (tok) headers['x-action-token'] = tok; + } catch (_) { } + } + + const res = await fetch(endpoint, { + method: 'POST', + headers, + body: JSON.stringify(payload) + }); + + let body = null; + try { body = await res.json(); } catch (_) { body = null; } + + if (!res.ok || !body || body.ok === false) { + const message = (body && (body.message || body.error)) ? (body.message || body.error) : `Upload failed (HTTP ${res.status})`; + hideProgressWheel(); + flashFilesBar(); + if (urlUploaderConfirm) urlUploaderConfirm.disabled = false; + alert('URL upload failed: ' + message); + return; + } + + setProgress(100, body.msg || 'Upload complete'); + loadExplorer(currentPath); + setTimeout(() => { hideProgressWheel(); flashFilesBar(); }, 350); + } catch (err) { + hideProgressWheel(); + flashFilesBar(); + if (urlUploaderConfirm) urlUploaderConfirm.disabled = false; + alert('URL upload failed: ' + ((err && err.message) ? err.message : 'network error')); + } + } + + if (urlUploaderBtn) { + urlUploaderBtn.addEventListener('click', openUrlUploaderModal); + updateUrlUploaderButtonState(); + } + if (urlUploaderClose) urlUploaderClose.addEventListener('click', closeUrlUploaderModal); + if (urlUploaderCancel) urlUploaderCancel.addEventListener('click', closeUrlUploaderModal); + if (urlUploaderConfirm) urlUploaderConfirm.addEventListener('click', startUrlUpload); + if (urlUploaderModal) { + urlUploaderModal.addEventListener('click', (e) => { + if (e.target === urlUploaderModal) closeUrlUploaderModal(); + }); + } + if (urlUploaderInput) { + urlUploaderInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + startUrlUpload(); + } + }); + urlUploaderInput.addEventListener('input', () => setUrlUploaderError('')); + } + // ============= /URL Uploader ============= + + async function createNew() { + if (!hasPerm('files_create')) return alert('Unauthorized'); + const type = prompt("Type 'file' to create a file or 'folder' to create a folder:"); if (!type || (type !== 'file' && type !== 'folder')) return alert('Invalid type.'); + const name = prompt(`Enter ${type} name:`); if (!name) return; + showProgressWheel(4, type === 'file' ? "Creating file..." : "Creating folder..."); startSimulatedProgress(4, 88, 420); + try { + await apiCreate(type, name, currentPath); + setProgress(100, (type === 'file' ? "File created" : "Folder created")); + loadExplorer(currentPath); + setTimeout(() => { hideProgressWheel(); flashFilesBar(); }, 350); + } catch (err) { + hideProgressWheel(); flashFilesBar(); + } + } + async function sendCommand() { + if (!hasPerm('console_write')) return alert('Unauthorized'); + const cmd = cmdInput.value.trim(); if (cmd === '') return; + const now = Date.now(); + if (commandSendInFlight) return; + if (cmd === lastSubmittedCommand && (now - lastSubmittedAt) < COMMAND_SUBMIT_DEDUPE_MS) return; + const requestId = createCommandRequestId(); + commandSendInFlight = true; + lastSubmittedCommand = cmd; + lastSubmittedAt = now; + lastCommandRequestId = requestId; + setCommandSendingState(true); + cmdInput.value = ''; + rememberConsoleCommandForInput(cmd); + appendCommandEcho(cmd, now); + try { + await apiCommand(cmd, now, requestId); + } catch (err) { + alert('Command failed: ' + (err.message || err)); + } finally { + commandSendInFlight = false; + if (lastCommandRequestId === requestId) { + setCommandSendingState(false); + } + } + } + cmdInput.addEventListener('keydown', (e) => { + if (e.key === 'ArrowUp') { + e.preventDefault(); + recallConsoleCommand(-1); + return; + } + if (e.key === 'ArrowDown') { + e.preventDefault(); + recallConsoleCommand(1); + return; + } + if (e.key === 'Enter') { + e.preventDefault(); + sendCommand(); + } + }); + cmdInput.addEventListener('input', () => { + consoleCommandHistoryIndex = -1; + }); + function clearConsole() { + if (currentUserPreferences.clear_console_no_ask || loadClearConsoleNoAskFromStorage()) { + currentUserPreferences.clear_console_no_ask = true; + resetConsoleBuffer(); + return; + } + if (typeof openClearConsoleModal === 'function') { + openClearConsoleModal(); + } else { + const modal = document.getElementById('clearConsoleModal'); + if (modal) { + modal.style.display = 'flex'; + const cb = document.getElementById('clearConsoleNoAsk'); + if (cb) cb.checked = false; + } + } + } + function openFilesModal() { + if (!filesModal) return; + if (!hasPerm('files_read')) return alert('Unauthorized'); + showModalElement(filesModal); + afterModalPaint(() => { + topoInfo().catch(() => null); + loadExplorer(currentPath); + enableDropHandlers(); + }); + } + function closeFilesModal() { + if (!filesModal) return; + animateClose(filesModal, () => { + disableDropHandlers(); + }); + } + + function closeTaskModal() { + if (!taskModal) return; + animateClose(taskModal); + } + + function closeFileUploadModal() { + if (fileInput) fileInput.value = ''; + } + + const fileInput = document.getElementById('fileInput'); + if (fileUploadModal) { + const closeBtn = document.getElementById('fileUploadModalClose'); + if (closeBtn) closeBtn.addEventListener('click', closeFileUploadModal); + fileUploadModal.addEventListener('click', (e) => { + if (e.target === fileUploadModal) closeFileUploadModal(); + }); + } + + + + if (filesModalClose) { + filesModalClose.addEventListener("click", closeFilesModal); + } + if (filesModal) { + filesModal.addEventListener("click", (e) => { + if (e.target === filesModal) { + e.stopPropagation(); + } + }); + } + if (editorModal) { + editorModal.addEventListener("click", (e) => { + if (e.target === editorModal) { + e.stopPropagation(); + } + }); + } + + if (taskModalClose) { + taskModalClose.addEventListener("click", closeTaskModal); + } + if (taskModal) { + taskModal.addEventListener("click", (e) => { + if (e.target === taskModal) closeTaskModal(); + }); + } + + if (document.getElementById('schedulerModalClose')) { + document.getElementById('schedulerModalClose').addEventListener('click', closeSchedulerModal); + } + function openTaskModal() { + if (!taskModal) return; + if (!hasPerm('server_start')) return alert('Unauthorized'); + showModalElement(taskModal); + afterModalPaint(() => loadExplorer(currentPath)); + } + if (taskModalClose) taskModalClose.addEventListener('click', closeTaskModal); + document.addEventListener('keydown', (e) => { + if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 's') { + if (editorModal && editorModal.classList.contains('show')) { + e.preventDefault(); + performSave(); + return; + } + } + if (e.key === 'Escape') { + if (aiHelpModal && aiHelpModal.classList.contains('show')) { closeAiHelpModal(); return; } + if (editorModal && editorModal.classList.contains('show')) { closeEditorModal(); return; } + if (filesModal && filesModal.classList.contains('show')) { closeFilesModal(); return; } + if (taskModal && taskModal.classList.contains('show')) { closeTaskModal(); return; } + if (infoModal && infoModal.classList.contains('show')) { closeInfoModal(); return; } + if (mrPluginModal && mrPluginModal.classList.contains('show')) { closeModrinthPluginModal(); return; } + if (storeModal && storeModal.classList.contains('show')) { closeStoreModal(); return; } + if (activityModal && activityModal.classList.contains('show')) { closeActivityModal(); return; } + if (backupsModal && backupsModal.classList.contains('show')) { closeBackupsModal(); return; } + if (backupCreateModal && backupCreateModal.classList.contains('show')) { closeBackupCreateModal(); return; } + if (resourceStatsPopup && resourceStatsPopup.classList.contains('show')) { closeResourceStatsPopup(); return; } + if (progressPopup && progressPopup.style.display === 'block') { closeProgressPopup(); return; } + } + }); + document.querySelectorAll('.modal-close').forEach((btn) => { + btn.addEventListener('click', (e) => { + e.preventDefault(); + const escEvent = new KeyboardEvent('keydown', { + key: 'Escape', + code: 'Escape', + keyCode: 27, + which: 27, + bubbles: true + }); + document.dispatchEvent(escEvent); + }); + }); + document.addEventListener('click', () => { document.querySelectorAll('.more-menu.show').forEach(m => m.classList.remove('show')); }); + async function runBootstrapStep(label, fn) { + try { + return await fn(); + } catch (err) { + console.error(`[bot-bootstrap] ${label} failed:`, err); + return null; + } + } + document.addEventListener('DOMContentLoaded', async () => { + profileEmailEl = document.getElementById('profileEmail'); + await runBootstrapStep('restore-file-backups', async () => { + loadFileBackupsFromStorage(); + }); + await runBootstrapStep('fetch-permissions', async () => { + await fetchPerms(); + applyPermissionsToUI(); + }); + let initialConsoleHistoryCount = 0; + await runBootstrapStep('hydrate-console-history', async () => { + initialConsoleHistoryCount = await hydrateInitialConsoleHistory(120); + }); + startPowerStatePolling(); + await runBootstrapStep('refresh-power-state-initial', async () => { + await refreshPowerState({ force: true }); + }); + await runBootstrapStep('load-server-info', async () => { + await loadServerInfo(); + }); + await runBootstrapStep('attach-log-stream', async () => { + attachLogStreamIfRemote({ tail: initialConsoleHistoryCount > 0 ? 0 : 100 }); + }); + window.setTimeout(() => { + loadMonaco().catch(() => { }); + }, 1200); + 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(); + }); + await runBootstrapStep('load-profile', async () => { + await loadMeIntoProfileEmail(); + }); + runRequestedAssistantBotAction(assistantActionHandlers); + }); + function escapeHtmlRaw(s) { + return String(s) + .replace(/&/g, '&') + .replace(//g, '>'); + } + function detectLanguageFromPath(path) { + const lower = (path || '').toLowerCase(); + if (lower.endsWith('.yml') || lower.endsWith('.yaml')) return 'yaml'; + if (lower.endsWith('.json')) return 'json'; + if (lower.endsWith('.html') || lower.endsWith('.htm')) return 'html'; + if (lower.endsWith('.css')) return 'css'; + if (lower.endsWith('.ts')) return 'ts'; + if (lower.endsWith('.js')) return 'js'; + return 'plain'; + } + function highlightCode(src, path) { + if (typeof src !== 'string') src = ''; + const lang = detectLanguageFromPath(path); + const span = (tok, val) => `${val}`; + let out = escapeHtmlRaw(src); + if (lang === 'yaml') { + out = out.replace(/(#.*)$/gm, (_, m) => span('com', m)); + out = out.replace(/("([^"\\]|\\.)*"|'([^'\\]|\\.)*')/g, m => span('str', m)); + } else if (lang === 'json') { + out = out.replace(/"(\\.|[^"\\])*"/g, m => span('str', m)); + out = out.replace(/\b(true|false|null)\b/g, m => span('kw', m)); + out = out.replace(/\b(\d+(\.\d+)?)\b/g, m => span('num', m)); + } else if (lang === 'html') { + out = out.replace(/()/g, (_, m) => span('com', m)); + out = out.replace(/(<\/?)([a-zA-Z0-9\-]+)([^>]*?)(>)/g, (m, open, tag, attrs, close) => { + attrs = attrs.replace(/([a-zA-Z0-9\-:]+)=(".*?"|'.*?')/g, (_, k, v) => `${span('attr', k)}=${span('str', v)}`); + return span('tag', `${open}${tag}${attrs}${close}`); + }); + } else if (lang === 'css') { + out = out.replace(/(\/\*[\s\S]*?\*\/)/g, (_, m) => span('com', m)); + out = out.replace(/([a-zA-Z\-]+)(?=\s*:)/g, m => span('prop', m)); + out = out.replace(/("([^"\\]|\\.)*"|'([^'\\]|\\.)*')/g, m => span('str', m)); + out = out.replace(/\b(\d+(\.\d+)?)(px|rem|em|%)?\b/g, m => span('num', m)); + } else { + out = out.replace(/(\/\*[\s\S]*?\*\/|\/\/[^\n]*)/g, m => span('com', m.replace(/ span('str', m.replace(/ span('num', m)); + out = out.replace(/\b(true|false|null|undefined)\b/g, m => span('bool', m)); + out = out.replace(/\bclass\s+([A-Za-z_$][\w$]*)/g, (_, n) => `class ${span('cls', n)}`); + out = out.replace(/\bfunction\s+([A-Za-z_$][\w$]*)\s*\(/g, (_, n) => `function ${span('fn', n)}(`); + out = out.replace(/([A-Za-z_$][\w$]*)\s*=\s*\(.*?\)\s*=>/g, m => m.replace(/([A-Za-z_$][\w$]*)/, p => span('fn', p))); + out = out.replace(/\b(new|require|module|exports)\b/g, m => span('const', m)); + out = out.replace(/\b([A-Za-z_$][\w$]*)\s*\(/g, m => span('call', m)); + out = out.replace(/:\s*([A-Z][A-Za-z0-9_$]*)/g, (_, n) => `: ${span('type', n)}`); + const keywords = ['const', 'let', 'var', 'return', 'if', 'else', 'for', 'while', 'switch', 'case', 'break', 'continue', 'class', 'new', 'try', 'catch', 'finally', 'throw', 'await', 'async', 'import', 'from', 'export', 'extends', 'super', 'this', 'typeof', 'instanceof', 'in']; + const kwRegex = new RegExp('\\b(' + keywords.join('|') + ')\\b', 'g'); + out = out.replace(kwRegex, m => span('kw', m)); + } + const lines = out.split(/\r\n|\r|\n/); + return lines.map(line => `
    ${line || ' '}
    `).join(''); + } + let _monacoIdleSuggestDisposable = null; + function setupMonacoIdleSuggestions(editor) { + if (!editor) return; + if (monacoIdleSuggestTimer) { + clearTimeout(monacoIdleSuggestTimer); + monacoIdleSuggestTimer = null; + } + if (_monacoIdleSuggestDisposable) { + _monacoIdleSuggestDisposable.dispose(); + _monacoIdleSuggestDisposable = null; + } + _monacoIdleSuggestDisposable = editor.onDidChangeModelContent(() => { + if (monacoIdleSuggestTimer) { + clearTimeout(monacoIdleSuggestTimer); + } + monacoIdleSuggestTimer = setTimeout(() => { + if (!editor || (editor.isDisposed && editor.isDisposed()) || (editor.hasTextFocus && !editor.hasTextFocus())) { + return; + } + const action = editor.getAction && editor.getAction("editor.action.triggerSuggest"); + if (action && action.run) { + action.run().catch(() => { }); + } + }, 7000); + }); + } + function getLineHeightPx() { + const lh = codeInput ? parseFloat(getComputedStyle(codeInput).lineHeight) : NaN; + return Number.isFinite(lh) ? lh : 22; + } + function getCodePadding() { + const styleTarget = codeOverlay || codeInput; + if (!styleTarget) return { top: 16, bottom: 88 }; + const cs = getComputedStyle(styleTarget); + const top = parseFloat(cs.paddingTop) || 16; + const bottom = parseFloat(cs.paddingBottom) || 88; + return { top, bottom }; + } + function getGutterPadding() { + if (!lineGutter) return { top: 16, bottom: 88 }; + const cs = getComputedStyle(lineGutter); + const top = parseFloat(cs.paddingTop) || 16; + const bottom = parseFloat(cs.paddingBottom) || 88; + return { top, bottom }; + } + function measureContentHeight(raw) { + const normalized = normalizeInput(raw || ''); + const lineCount = Math.max(1, normalized.split('\n').length); + const lineHeight = getLineHeightPx(); + const { top: paddingTop, bottom: paddingBottom } = getCodePadding(); + return (lineCount * lineHeight) + paddingTop + paddingBottom; + } + function renderHighlightedEditor(raw) { + const normalized = normalizeInput(raw || ''); + if (codeInput && codeInput.value !== normalized) { + const start = codeInput.selectionStart || 0; + const end = codeInput.selectionEnd || 0; + codeInput.value = normalized; + const clampPos = (pos) => Math.max(0, Math.min(normalized.length, pos)); + codeInput.selectionStart = clampPos(start); + codeInput.selectionEnd = clampPos(end); + } + codeOverlay.innerHTML = highlightCode(normalized, currentEditorPath || ''); + syncLineNumbers(normalized); + syncCodeSpacer(normalized); + syncScrollPositions(); + } + function syncLineNumbers(raw) { + const count = Math.max(1, (raw.match(/\n/g) || []).length + 1); + lineGutter.innerHTML = Array.from({ length: count }, (_, i) => `
    ${i + 1}
    `).join(''); + } + function syncCodeSpacer(raw) { + if (!codeSpacer || !codePane) return; + const measured = measureContentHeight(raw || (codeInput ? codeInput.value : '')); + const paneHeight = codePane.clientHeight || 0; + const spacerHeight = Math.max(0, measured - paneHeight); + codeSpacer.style.height = `${spacerHeight}px`; + if (codeInput) codeInput.style.minHeight = `${measured}px`; + if (codeOverlay) codeOverlay.style.minHeight = `${measured}px`; + } + function syncScrollPositions() { + const top = codePane ? codePane.scrollTop : (codeInput ? codeInput.scrollTop : 0); + if (lineGutter) lineGutter.scrollTop = top; + } + if (codeInput) { + codeInput.addEventListener('input', () => { + renderHighlightedEditor(codeInput.value); + }); + codeInput.addEventListener('keydown', (e) => { + if (e.key === 'Tab') { + e.preventDefault(); + const start = codeInput.selectionStart; + const end = codeInput.selectionEnd; + const val = codeInput.value; + codeInput.value = `${val.slice(0, start)} ${val.slice(end)}`; + codeInput.selectionStart = codeInput.selectionEnd = start + 2; + renderHighlightedEditor(codeInput.value); + } + }); + } + if (codePane) { + codePane.addEventListener('scroll', syncScrollPositions); + } + if (lineGutter && codePane) { + lineGutter.addEventListener('wheel', (e) => { + e.preventDefault(); + codePane.scrollTop += e.deltaY; + syncScrollPositions(); + }, { passive: false }); + lineGutter.addEventListener('scroll', () => { + if (Math.abs((codePane.scrollTop || 0) - (lineGutter.scrollTop || 0)) > 1) { + codePane.scrollTop = lineGutter.scrollTop || 0; + } + }); + } + function highlightJS(src) { + return highlightCode(src, currentEditorPath || ''); + } + function startSimulatedProgress(from = 0, to = 90, duration = 400) { + if (simInterval) { clearInterval(simInterval); simInterval = null; } + let pct = from; const steps = Math.max(8, Math.floor(duration / 80)); const step = (to - from) / steps; + simInterval = setInterval(() => { pct = Math.min(99, pct + step); setProgress(Math.round(pct), popupMsg ? popupMsg.textContent : undefined); if (pct >= to) { clearInterval(simInterval); simInterval = null; } }, Math.max(40, Math.floor(duration / steps))); + } + + (function () { + function setDockHidden(hidden) { + const dock = document.querySelector('.dock'); + if (!dock) return; + dock.style.display = hidden ? 'none' : ''; + } + + function isAnyModalVisible() { + const overlays = document.querySelectorAll('.modal-overlay'); + for (const el of overlays) { + if (el.classList.contains('show')) return true; + const cs = getComputedStyle(el); + if (cs.display !== 'none' && cs.visibility !== 'hidden' && cs.opacity !== '0') { + return true; + } + } + return false; + } + + function updateDockVisibility() { + setDockHidden(isAnyModalVisible()); + } + + const modalObserver = new MutationObserver(updateDockVisibility); + function attachModalObservers() { + document.querySelectorAll('.modal-overlay').forEach(el => { + modalObserver.observe(el, { + attributes: true, + attributeFilter: ['class', 'style', 'aria-hidden'] + }); + }); + } + + const docObserver = new MutationObserver(muts => { + let shouldReattach = false; + for (const m of muts) { + if (m.type === 'childList' && (m.addedNodes.length || m.removedNodes.length)) { + shouldReattach = true; + } + } + if (shouldReattach) attachModalObservers(); + updateDockVisibility(); + }); + + document.addEventListener('DOMContentLoaded', () => { + attachModalObservers(); + docObserver.observe(document.body, { childList: true, subtree: true }); + updateDockVisibility(); + }); + + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + if (aiHelpModal && aiHelpModal.classList.contains('show')) { + closeAiHelpModal(); + e.preventDefault(); + } + } + setTimeout(updateDockVisibility, 0); + }); + + window.updateDockVisibility = updateDockVisibility; + })(); + + const aiHelpModal = document.getElementById('aiHelpModal'); + const aiHelpSetup = document.getElementById('aiHelpSetup'); + const aiHelpChat = document.getElementById('aiHelpChat'); + const aiProviderGrid = document.getElementById('aiProviderGrid'); + const aiApiKeyForm = document.getElementById('aiApiKeyForm'); + const aiApiKeyInput = document.getElementById('aiApiKeyInput'); + const aiBaseUrlField = document.getElementById('aiBaseUrlField'); + const aiBaseUrlInput = document.getElementById('aiBaseUrlInput'); + const aiKeyHint = document.getElementById('aiKeyHint'); + const aiKeyProviderName = document.getElementById('aiKeyProviderName'); + const aiKeyBack = document.getElementById('aiKeyBack'); + const aiKeyToggle = document.getElementById('aiKeyToggle'); + const aiKeySave = document.getElementById('aiKeySave'); + const aiChatMessages = document.getElementById('aiChatMessages'); + const aiChatInput = document.getElementById('aiChatInput'); + const aiChatSend = document.getElementById('aiChatSend'); + const aiModelSelector = document.getElementById('aiModelSelector'); + const aiModelSelect = document.getElementById('aiModelSelect'); + const aiModelTrigger = document.getElementById('aiModelTrigger'); + const aiModelCurrent = document.getElementById('aiModelCurrent'); + const aiModelOptions = document.getElementById('aiModelOptions'); + const aiChatClear = document.getElementById('aiChatClear'); + const aiHelpModalClose = document.getElementById('aiHelpModalClose'); + const aiHelpSettingsBtn = document.getElementById('aiHelpSettingsBtn'); + const aiFilePermission = document.getElementById('aiFilePermission'); + const aiPermAllow = document.getElementById('aiPermAllow'); + const aiPermDeny = document.getElementById('aiPermDeny'); + const aiPermFileName = document.getElementById('aiPermFileName'); + const aiUndoToast = document.getElementById('aiUndoToast'); + const aiUndoBtn = document.getElementById('aiUndoBtn'); + const aiUndoDismiss = document.getElementById('aiUndoDismiss'); + const aiFileInput = document.getElementById('aiFileInput'); + const aiChatAttach = document.getElementById('aiChatAttach'); + + const AI_PROVIDERS = { + openai: { + name: 'OpenAI', + apiKeyPlaceholder: 'Enter your OpenAI API key', + }, + anthropic: { + name: 'Anthropic', + apiKeyPlaceholder: 'Enter your Anthropic API key', + connectionHint: 'Saved on this ADPanel instance and used server-side through Anthropic Messages API and model discovery.', + }, + 'openai-compatible': { + name: 'OpenAI Compatible', + requiresBaseUrl: true, + keyOptional: true, + apiKeyPlaceholder: 'Enter your API key', + baseUrlPlaceholder: 'https://your-provider.example.com/v1', + }, + google: { + name: 'Google AI', + apiKeyPlaceholder: 'Enter your Google AI API key', + }, + groq: { + name: 'Groq', + apiKeyPlaceholder: 'Enter your Groq API key', + }, + huggingface: { + name: 'HuggingFace', + apiKeyPlaceholder: 'Enter your Hugging Face token', + }, + together: { + name: 'Together AI', + apiKeyPlaceholder: 'Enter your Together AI API key', + }, + cohere: { + name: 'Cohere', + apiKeyPlaceholder: 'Enter your Cohere API key', + }, + openrouter: { + name: 'OpenRouter', + apiKeyPlaceholder: 'Enter your OpenRouter API key', + } + }; + + let aiCurrentProvider = null; + let aiChatHistory = []; + let aiFileBackups = []; + let aiPendingFileOperations = []; + let aiCurrentPendingOp = null; + let aiKeysCache = null; + let aiProviderStateCache = {}; + let aiProviderModelsCache = {}; + let aiLastReadFileContent = null; + let aiLastReadFilePath = null; + let aiCurrentChatId = null; + let aiChatsList = []; + let aiChatLoadToken = 0; + let aiAttachedFile = null; + let aiAbortController = null; + let aiIsGenerating = false; + let aiSelectedModelSaveTimer = null; + + const AI_FILE_BACKUPS_KEY = `ai-file-backups-${bot}`; + const AI_SELECTED_MODEL_KEY = 'adpanel-ai-selected-model'; + const AI_SELECTED_MODEL_SERVER_KEY = `adpanel-ai-selected-model-${bot}`; + + async function loadSelectedAiModelFromBackend() { + try { + if (!hasAgentAccess()) return ''; + const response = await fetch('/api/ai/selection', { cache: 'no-store' }); + if (!response.ok) return ''; + const data = await response.json().catch(() => ({})); + const provider = String(data?.selection?.provider || '').trim(); + const model = String(data?.selection?.model || '').trim(); + return provider && model ? encodeAiModelSelection(provider, model) : ''; + } catch { + return ''; + } + } + + function queueSelectedAiModelBackendSave(value) { + if (aiSelectedModelSaveTimer) { + clearTimeout(aiSelectedModelSaveTimer); + aiSelectedModelSaveTimer = null; + } + const normalized = String(value || '').trim(); + if (!normalized || !isPersistableAiModelSelection(normalized) || !hasAgentAccess()) return; + aiSelectedModelSaveTimer = setTimeout(() => { + aiSelectedModelSaveTimer = null; + const { providerId, modelName } = decodeAiModelSelection(normalized); + if (!providerId || !modelName) return; + fetch('/api/ai/selection', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ provider: providerId, model: modelName }) + }).catch(() => { }); + }, 300); + } + + async function saveSelectedAiModelToBackendNow(value = '') { + if (aiSelectedModelSaveTimer) { + clearTimeout(aiSelectedModelSaveTimer); + aiSelectedModelSaveTimer = null; + } + const normalized = String(value || loadSelectedAiModelFromStorage() || '').trim(); + if (!normalized || !isPersistableAiModelSelection(normalized) || !hasAgentAccess()) return false; + const { providerId, modelName } = decodeAiModelSelection(normalized); + if (!providerId || !modelName) return false; + const response = await fetch('/api/ai/selection', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ provider: providerId, model: modelName }) + }); + return response.ok; + } + + function loadSelectedAiModelFromStorage() { + try { + const serverValue = String(localStorage.getItem(AI_SELECTED_MODEL_SERVER_KEY) || '').trim(); + if (serverValue) return serverValue; + return String(localStorage.getItem(AI_SELECTED_MODEL_KEY) || '').trim(); + } catch { + return ''; + } + } + + function saveSelectedAiModelToStorage(value) { + const normalized = String(value || '').trim(); + try { + if (normalized) { + localStorage.setItem(AI_SELECTED_MODEL_SERVER_KEY, normalized); + localStorage.setItem(AI_SELECTED_MODEL_KEY, normalized); + } else { + localStorage.removeItem(AI_SELECTED_MODEL_SERVER_KEY); + localStorage.removeItem(AI_SELECTED_MODEL_KEY); + } + } catch { } + if (normalized) queueSelectedAiModelBackendSave(normalized); + } + + function isPersistableAiModelSelection(value) { + const { providerId, modelName } = decodeAiModelSelection(String(value || '').trim()); + return !!(providerId && modelName); + } + + function loadFileBackupsFromStorage() { + try { + const stored = localStorage.getItem(AI_FILE_BACKUPS_KEY); + if (stored) { + aiFileBackups = JSON.parse(stored); + const oneDayAgo = Date.now() - (24 * 60 * 60 * 1000); + aiFileBackups = aiFileBackups.filter(b => b.timestamp > oneDayAgo); + saveFileBackupsToStorage(); + } + } catch (e) { + aiFileBackups = []; + } + renderFileChangesBar(); + } + + function saveFileBackupsToStorage() { + try { + localStorage.setItem(AI_FILE_BACKUPS_KEY, JSON.stringify(aiFileBackups)); + } catch (e) { + console.warn('[AI] Failed to save backups to localStorage:', e); + } + renderFileChangesBar(); + } + + const aiFileChangesBar = document.getElementById('aiFileChangesBar'); + const aiFileChangesList = document.getElementById('aiFileChangesList'); + const aiFileChangesCount = document.getElementById('aiFileChangesCount'); + const aiAcceptAllChanges = document.getElementById('aiAcceptAllChanges'); + const aiUndoAllChanges = document.getElementById('aiUndoAllChanges'); + const aiFileChangesToggle = document.getElementById('aiFileChangesToggle'); + const aiConfirmDialog = document.getElementById('aiConfirmDialog'); + const aiConfirmAction = document.getElementById('aiConfirmAction'); + const aiConfirmPath = document.getElementById('aiConfirmPath'); + const aiConfirmPreview = document.getElementById('aiConfirmPreview'); + const aiConfirmAllow = document.getElementById('aiConfirmAllow'); + const aiConfirmDeny = document.getElementById('aiConfirmDeny'); + + let aiActionTokens = {}; + + function getStoredAiProviderState(provider) { + return aiProviderStateCache?.[provider] || {}; + } + + function encodeAiModelSelection(providerId, modelName) { + return JSON.stringify({ provider: providerId, model: modelName }); + } + + function decodeAiModelSelection(rawValue) { + if (!rawValue) return { providerId: '', modelName: '' }; + try { + const parsed = JSON.parse(rawValue); + return { + providerId: String(parsed?.provider || '').trim(), + modelName: String(parsed?.model || '').trim() + }; + } catch { + const separatorIdx = rawValue.indexOf(':'); + if (separatorIdx === -1) return { providerId: '', modelName: '' }; + return { + providerId: rawValue.slice(0, separatorIdx).trim(), + modelName: rawValue.slice(separatorIdx + 1).trim() + }; + } + } + + function buildAiProviderApiKeyPlaceholder(provider, providerState = getStoredAiProviderState(provider)) { + const config = AI_PROVIDERS[provider]; + if (!config) return 'Enter your API key'; + if (providerState?.maskedKey) { + return `Leave empty to keep the saved key (${providerState.maskedKey})`; + } + return config.apiKeyPlaceholder || 'Enter your API key'; + } + + function updateAiProviderFormState() { + if (!aiKeySave) return; + if (!aiCurrentProvider) { + aiKeySave.disabled = true; + return; + } + + const config = AI_PROVIDERS[aiCurrentProvider]; + const stored = getStoredAiProviderState(aiCurrentProvider); + const hasKey = config?.keyOptional ? true : !!(aiApiKeyInput?.value.trim() || stored?.keyConfigured); + const hasBaseUrl = !config?.requiresBaseUrl || !!(aiBaseUrlInput?.value.trim() || stored?.baseUrl); + aiKeySave.disabled = !(hasKey && hasBaseUrl); + } + + async function loadAiKeysFromBackend() { + try { + const response = await fetch('/api/ai/keys'); + if (!response.ok) return {}; + const data = await response.json(); + if (!data.ok) return {}; + + if (data.actionTokens) { + aiActionTokens = data.actionTokens; + } + + aiProviderStateCache = data.providers || {}; + const keys = {}; + for (const [provider, info] of Object.entries(aiProviderStateCache)) { + if (info?.configured) { + keys[provider] = true; + } + } + aiKeysCache = keys; + return keys; + } catch { + return aiKeysCache || {}; + } + } + + async function saveAiProviderConfig(provider, { key = '', baseUrl = '' } = {}) { + try { + if (!aiActionTokens.setKey) { + await loadAiKeysFromBackend(); + } + const response = await fetch('/api/ai/keys', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': aiActionTokens.setKey || '' + }, + body: JSON.stringify({ provider, key, baseUrl }) + }); + const data = await response.json().catch(() => ({})); + if (!response.ok || !data.ok) { + return { ok: false, error: data.error || `Failed to connect provider (${response.status})` }; + } + + if (data.providerState) { + aiProviderStateCache[provider] = data.providerState; + } + if (!aiKeysCache) aiKeysCache = {}; + if (data.providerState?.configured) { + aiKeysCache[provider] = true; + } else { + delete aiKeysCache[provider]; + } + if (Array.isArray(data.models)) { + aiProviderModelsCache[provider] = data.models; + } + loadAiKeysFromBackend().catch(() => { }); + return data; + } catch { + return { ok: false, error: 'Failed to connect provider' }; + } + } + + function hasConfiguredProvider() { + if (!aiKeysCache) return false; + return Object.values(aiKeysCache).some(Boolean); + } + + async function updateProviderStatuses() { + const keys = await loadAiKeysFromBackend(); + for (const provider of Object.keys(AI_PROVIDERS)) { + const statusEl = document.getElementById(`status-${provider}`); + const statusLabelEl = document.getElementById(`status-label-${provider}`); + const cardEl = document.querySelector(`[data-provider="${provider}"]`); + const isConnected = !!keys[provider]; + if (statusEl) { + statusEl.classList.toggle('connected', isConnected); + } + if (statusLabelEl) { + statusLabelEl.textContent = isConnected ? 'Connected' : ''; + } + if (cardEl) { + cardEl.classList.toggle('connected', isConnected); + } + } + } + + async function fetchModels(provider, { forceRefresh = false } = {}) { + const config = AI_PROVIDERS[provider]; + if (!config) return []; + if (!forceRefresh && Array.isArray(aiProviderModelsCache[provider]) && aiProviderModelsCache[provider].length > 0) { + return aiProviderModelsCache[provider]; + } + + try { + const response = await fetch(`/api/ai/models/${encodeURIComponent(provider)}`); + const data = await response.json().catch(() => ({})); + if (!response.ok || !data.ok) { + throw new Error(data.error || `Failed to load models (${response.status})`); + } + + const models = Array.isArray(data.models) ? data.models : []; + aiProviderModelsCache[provider] = models; + if (data.providerState) { + aiProviderStateCache[provider] = data.providerState; + } + return models; + } catch (err) { + console.warn(`[AI] Failed to fetch models for ${provider}:`, err); + return []; + } + } + + function closeAiModelDropdown() { + if (!aiModelSelector || !aiModelTrigger) return; + aiModelSelector.classList.remove('open'); + aiModelTrigger.setAttribute('aria-expanded', 'false'); + aiModelOptions?.setAttribute('aria-hidden', 'true'); + } + + function updateAiModelSelectorState({ persist = true } = {}) { + if (!aiModelSelect || !aiModelCurrent || !aiModelOptions) return; + + const selectedOption = aiModelSelect.selectedOptions?.[0] || aiModelSelect.options[aiModelSelect.selectedIndex] || null; + aiModelCurrent.textContent = selectedOption?.textContent || 'Select model...'; + if (persist && selectedOption && !selectedOption.disabled && isPersistableAiModelSelection(aiModelSelect.value)) { + saveSelectedAiModelToStorage(aiModelSelect.value); + } + + const selectedValue = aiModelSelect.value; + aiModelOptions.querySelectorAll('.ai-model-option').forEach(optionEl => { + const isSelected = optionEl.dataset.value === selectedValue; + optionEl.classList.toggle('selected', isSelected); + optionEl.setAttribute('aria-selected', isSelected ? 'true' : 'false'); + }); + } + + function syncAiModelSelectorFromNative({ persist = false } = {}) { + if (!aiModelSelect || !aiModelTrigger || !aiModelOptions || !aiModelCurrent || !aiModelSelector) return; + + closeAiModelDropdown(); + aiModelOptions.innerHTML = ''; + let hasSelectableOptions = false; + + const appendModelOption = (option) => { + if (!option) return; + + if (option.disabled) { + if (!option.value) { + const emptyState = document.createElement('div'); + emptyState.className = 'ai-model-empty'; + emptyState.textContent = option.textContent; + aiModelOptions.appendChild(emptyState); + } + return; + } + + hasSelectableOptions = true; + const optionButton = document.createElement('button'); + optionButton.type = 'button'; + optionButton.className = 'ai-model-option'; + optionButton.dataset.value = option.value; + optionButton.setAttribute('role', 'option'); + optionButton.setAttribute('aria-selected', 'false'); + optionButton.innerHTML = ` + ${escapeHtmlAi(option.textContent)} + + `; + aiModelOptions.appendChild(optionButton); + }; + + Array.from(aiModelSelect.children).forEach(child => { + const tagName = child.tagName?.toUpperCase(); + if (tagName === 'OPTGROUP') { + const groupLabel = document.createElement('div'); + groupLabel.className = 'ai-model-group'; + groupLabel.textContent = child.label; + aiModelOptions.appendChild(groupLabel); + Array.from(child.children).forEach(appendModelOption); + return; + } + + if (tagName === 'OPTION') { + appendModelOption(child); + } + }); + + aiModelTrigger.disabled = !hasSelectableOptions; + aiModelSelector.classList.toggle('is-disabled', !hasSelectableOptions); + aiModelOptions.setAttribute('aria-hidden', aiModelSelector.classList.contains('open') ? 'false' : 'true'); + updateAiModelSelectorState({ persist }); + } + + async function populateModelSelector() { + if (!aiModelSelect) return; + const backendSelectedModel = await loadSelectedAiModelFromBackend(); + const previouslySelectedModel = backendSelectedModel || loadSelectedAiModelFromStorage(); + const keys = await loadAiKeysFromBackend(); + aiModelSelect.innerHTML = ''; + syncAiModelSelectorFromNative({ persist: false }); + + let hasOptions = false; + + const promises = Object.entries(AI_PROVIDERS).map(async ([providerId, config]) => { + if (!keys[providerId]) return null; + + const models = await fetchModels(providerId); + return { providerId, name: config.name, models }; + }); + + const results = await Promise.all(promises); + + aiModelSelect.innerHTML = ''; + + for (const result of results) { + if (!result || result.models.length === 0) continue; + + const optgroup = document.createElement('optgroup'); + optgroup.label = result.name; + + for (const model of result.models) { + const opt = document.createElement('option'); + opt.value = encodeAiModelSelection(result.providerId, model); + opt.textContent = model; + optgroup.appendChild(opt); + } + + aiModelSelect.appendChild(optgroup); + hasOptions = true; + } + + if (!hasOptions) { + aiModelSelect.innerHTML = ''; + } else if (aiModelSelect.options.length > 0) { + const optionValues = Array.from(aiModelSelect.options).map((option) => option.value); + if (previouslySelectedModel && optionValues.includes(previouslySelectedModel)) { + aiModelSelect.value = previouslySelectedModel; + } else { + aiModelSelect.selectedIndex = 0; + } + } + + syncAiModelSelectorFromNative({ persist: hasOptions }); + } + + async function openAiHelpModal() { + if (!aiHelpModal) return; + if (!hasAgentAccess()) { alert('You do not have permission to access ADPanel Agent'); return; } + showModalElement(aiHelpModal); + + await updateProviderStatuses(); + + if (hasConfiguredProvider()) { + if (aiHelpSetup) aiHelpSetup.style.display = 'none'; + if (aiHelpChat) aiHelpChat.style.display = 'flex'; + await populateModelSelector(); + await loadChatHistory(); + } else { + if (aiHelpSetup) aiHelpSetup.style.display = 'flex'; + if (aiHelpChat) aiHelpChat.style.display = 'none'; + if (aiApiKeyForm) aiApiKeyForm.style.display = 'none'; + if (aiProviderGrid) aiProviderGrid.style.display = 'grid'; + } + } + + function closeAiHelpModal() { + if (!aiHelpModal) return; + animateClose(aiHelpModal, () => { + saveChatHistory(); + }); + } + + function showApiKeyForm(provider) { + if (!aiApiKeyForm || !aiProviderGrid) return; + aiCurrentProvider = provider; + const config = AI_PROVIDERS[provider]; + if (!config) return; + const stored = getStoredAiProviderState(provider); + + aiProviderGrid.style.display = 'none'; + aiApiKeyForm.style.display = 'block'; + if (aiKeyProviderName) aiKeyProviderName.textContent = config.name; + if (aiBaseUrlField) { + aiBaseUrlField.style.display = config.requiresBaseUrl ? 'block' : 'none'; + } + if (aiBaseUrlInput) { + aiBaseUrlInput.value = config.requiresBaseUrl ? String(stored.baseUrl || '') : ''; + aiBaseUrlInput.placeholder = config.baseUrlPlaceholder || 'https://your-provider.example.com/v1'; + } + if (aiApiKeyInput) { + aiApiKeyInput.value = ''; + aiApiKeyInput.placeholder = buildAiProviderApiKeyPlaceholder(provider, stored); + aiApiKeyInput.type = 'password'; + } + if (aiKeyToggle) { + aiKeyToggle.innerHTML = ''; + } + if (aiKeyHint) { + aiKeyHint.textContent = config.connectionHint || 'Saved on this ADPanel instance and used server-side for model discovery and chat requests.'; + } + if (config.requiresBaseUrl && aiBaseUrlInput) { + aiBaseUrlInput.focus(); + } else if (aiApiKeyInput) { + aiApiKeyInput.focus(); + } + updateAiProviderFormState(); + } + + function hideApiKeyForm() { + if (!aiApiKeyForm || !aiProviderGrid) return; + aiApiKeyForm.style.display = 'none'; + aiProviderGrid.style.display = 'grid'; + aiCurrentProvider = null; + if (aiApiKeyInput) aiApiKeyInput.value = ''; + if (aiBaseUrlInput) aiBaseUrlInput.value = ''; + updateAiProviderFormState(); + } + + + async function loadChatsFromDb() { + try { + const response = await fetch('/api/ai/chats'); + if (!response.ok) { + aiChatsList = []; + return []; + } + const data = await response.json(); + aiChatsList = Array.isArray(data.chats) ? data.chats : []; + return aiChatsList; + } catch { + aiChatsList = []; + return []; + } + } + + async function createNewChat(title = 'New Chat') { + try { + const response = await fetch('/api/ai/chats', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title }) + }); + if (!response.ok) return null; + const data = await response.json(); + return data.chatId; + } catch { + return null; + } + } + + async function loadChatFromDb(chatId) { + try { + const response = await fetch(`/api/ai/chats/${chatId}`); + if (!response.ok) return null; + const data = await response.json(); + return data; + } catch { + return null; + } + } + + async function saveMessageToDb(chatId, role, content, thinkingTimeMs = null, model = null, imageData = null, thinkingContent = null) { + try { + const response = await fetch(`/api/ai/chats/${chatId}/messages`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ role, content, thinking_time_ms: thinkingTimeMs, thinking_content: thinkingContent, model, image_data: imageData }) + }); + return response.ok; + } catch { + return false; + } + } + + async function deleteChatFromDb(chatId) { + try { + const response = await fetch(`/api/ai/chats/${chatId}`, { method: 'DELETE' }); + return response.ok; + } catch { + return false; + } + } + + async function updateChatTitle(chatId, title) { + try { + const response = await fetch(`/api/ai/chats/${chatId}`, { + method: 'PUT', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ title }) + }); + return response.ok; + } catch { + return false; + } + } + + async function saveChatHistory() { + } + + async function loadChatHistory() { + const loadToken = ++aiChatLoadToken; + await loadChatsFromDb(); + if (loadToken !== aiChatLoadToken) return; + + if (!aiCurrentChatId && aiChatsList.length > 0) { + aiCurrentChatId = aiChatsList[0].id; + } + + let nextHistory = []; + + if (aiCurrentChatId) { + const requestedChatId = aiCurrentChatId; + const data = await loadChatFromDb(requestedChatId); + if (loadToken !== aiChatLoadToken || aiCurrentChatId !== requestedChatId) return; + if (data && data.messages) { + nextHistory = data.messages.map(m => ({ + role: m.role === 'assistant' ? 'ai' : m.role, + content: m.content, + thinking_time_ms: m.thinking_time_ms, + thinking_content: m.thinking_content, + model: m.model, + timestamp: new Date(m.created_at).getTime(), + attachment: m.image_data ? { isImage: true, data: m.image_data, name: 'Image' } : null + })); + } + } + + if (loadToken !== aiChatLoadToken) return; + aiChatHistory = nextHistory; + renderChatHistory(); + renderChatsList(); + } + + function renderChatsList() { + const chatsList = document.getElementById('aiChatsList'); + if (!chatsList) return; + + if (!Array.isArray(aiChatsList)) { + aiChatsList = []; + } + + if (aiChatsList.length === 0) { + chatsList.innerHTML = ` +
    + +

    No chats yet

    +
    + `; + return; + } + + chatsList.innerHTML = aiChatsList.map(chat => ` +
    + +
    + ${escapeHtmlAi(chat.title)} + ${formatRelativeTime(chat.updated_at)} +
    + +
    + `).join(''); + + chatsList.querySelectorAll('.ai-chat-item').forEach(item => { + item.addEventListener('click', async (e) => { + if (e.target.closest('.ai-chat-item-delete')) return; + const chatId = parseInt(item.dataset.chatId, 10); + await switchToChat(chatId); + }); + }); + + chatsList.querySelectorAll('.ai-chat-item-delete').forEach(btn => { + btn.addEventListener('click', async (e) => { + e.stopPropagation(); + const chatId = parseInt(btn.dataset.chatId, 10); + if (confirm('Delete this chat?')) { + await deleteChatFromDb(chatId); + if (aiCurrentChatId === chatId) { + aiCurrentChatId = null; + aiChatHistory = []; + } + await loadChatHistory(); + } + }); + }); + } + + function formatRelativeTime(dateStr) { + const date = new Date(dateStr); + const now = new Date(); + const diffMs = now - date; + const diffMins = Math.floor(diffMs / 60000); + const diffHours = Math.floor(diffMs / 3600000); + const diffDays = Math.floor(diffMs / 86400000); + + if (diffMins < 1) return 'Just now'; + if (diffMins < 60) return `${diffMins}m ago`; + if (diffHours < 24) return `${diffHours}h ago`; + if (diffDays < 7) return `${diffDays}d ago`; + return date.toLocaleDateString(); + } + + async function switchToChat(chatId) { + const loadToken = ++aiChatLoadToken; + aiCurrentChatId = chatId; + const data = await loadChatFromDb(chatId); + if (loadToken !== aiChatLoadToken || aiCurrentChatId !== chatId) return; + if (data && data.messages) { + aiChatHistory = data.messages.map(m => ({ + role: m.role === 'assistant' ? 'ai' : m.role, + content: m.content, + thinking_time_ms: m.thinking_time_ms, + thinking_content: m.thinking_content, + model: m.model, + timestamp: new Date(m.created_at).getTime(), + attachment: m.image_data ? { isImage: true, data: m.image_data, name: 'Image' } : null + })); + } else { + aiChatHistory = []; + } + renderChatHistory(); + renderChatsList(); + } + + async function startNewChat() { + const loadToken = ++aiChatLoadToken; + aiCurrentChatId = null; + aiChatHistory = []; + await loadChatsFromDb(); + if (loadToken !== aiChatLoadToken) return; + renderChatHistory(); + renderChatsList(); + } + + function renderChatHistory(options = {}) { + if (!aiChatMessages) return; + const { animateLatest = false } = options; + + if (aiChatHistory.length === 0) { + const suggestionItems = []; + if (hasPerm('server_stop')) suggestionItems.push('Stop this server'); + if (hasPerm('server_start')) suggestionItems.push('Restart this server'); + if (hasPerm('files_read')) suggestionItems.push('What files are in my server?'); + if (hasPerm('files_read')) suggestionItems.push('Help me edit config.yml'); + suggestionItems.push(hasPerm('console_write') ? 'Explain server logs' : 'Help me troubleshoot an error'); + const suggestions = suggestionItems.slice(0, 4).map((label) => ``).join(''); + aiChatMessages.innerHTML = ` +
    +
    👋
    +

    Hello there!

    +

    Ask for a quick action, files help, or troubleshooting.

    +
    + ${suggestions} +
    +
    + `; + bindSuggestionButtons(); + return; + } + + const userAvatarEl = document.querySelector('#profileCard .icon img'); + const userAvatarSrc = userAvatarEl ? userAvatarEl.src : ''; + + aiChatMessages.innerHTML = aiChatHistory.map((msg, index) => { + const thinkingBadge = buildThinkingBadgeHtml(msg.thinking_time_ms, msg.thinking_content); + const messageClass = `ai-message ${msg.role}${animateLatest && index === aiChatHistory.length - 1 ? ' ai-enter' : ''}`; + + const attachmentHtml = msg.attachment && msg.attachment.isImage + ? `
    ${escapeHtmlAi(msg.attachment.name || 'Image')}
    ` + : ''; + + const avatarContent = msg.role === 'ai' + ? 'AI' + : (userAvatarSrc + ? `You` + : ''); + + return ` +
    +
    + ${avatarContent} +
    +
    + ${msg.role === 'ai' && thinkingBadge ? `
    ${thinkingBadge}
    ` : ''} +
    ${msg.role === 'ai' ? (msg.isTyping ? '' : renderAiMarkdown(msg.content)) : escapeHtmlAi(msg.content).replace(/\n/g, '
    ')}
    + ${attachmentHtml} +
    +
    + `; + }).join(''); + + aiChatMessages.scrollTop = aiChatMessages.scrollHeight; + + bindAiCodeCopyButtons(aiChatMessages); + } + + function escapeHtmlAi(s) { + return String(s) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + function aiCopyToClipboard(text, btn) { + const cleanText = text.trim(); + function onSuccess() { + btn.innerHTML = ''; + btn.classList.add('copied'); + setTimeout(() => { btn.innerHTML = ''; btn.classList.remove('copied'); }, 1500); + } + if (navigator.clipboard && window.isSecureContext) { + navigator.clipboard.writeText(cleanText).then(onSuccess).catch(() => fallbackCopy(cleanText)); + } else { + fallbackCopy(cleanText); + } + function fallbackCopy(t) { + const ta = document.createElement('textarea'); + ta.value = t; ta.style.position = 'fixed'; ta.style.opacity = '0'; + document.body.appendChild(ta); ta.select(); + try { document.execCommand('copy'); onSuccess(); } catch (e) { } + document.body.removeChild(ta); + } + } + + function renderAiMarkdown(s) { + let html = escapeHtmlAi(String(s)); + + html = html.replace(/```(\w*)\n([\s\S]*?)```/g, (_, lang, code) => { + const langLabel = lang || 'bash'; + const codeId = 'code-' + Math.random().toString(36).substr(2, 9); + const trimmedCode = code.replace(/^\s+|\s+$/g, ''); + return '
    ' + + '
    ' + + '
    ' + + '' + escapeHtmlAi(langLabel) + '' + + '' + + '
    ' + + '
    ' + trimmedCode + '
    ' + + '
    '; + }); + + html = html.replace(/`([^`\n]+)`/g, '$1'); + + html = html.replace(/\*\*([^*]+)\*\*/g, '$1'); + + html = html.replace(/\*([^*]+)\*/g, '$1'); + + html = html.replace(/~~([^~]+)~~/g, '$1'); + + html = html.replace(/^### (.+)$/gm, '

    $1

    '); + html = html.replace(/^## (.+)$/gm, '

    $1

    '); + html = html.replace(/^# (.+)$/gm, '

    $1

    '); + + html = html.replace(/^[\s]*[-] (.+)$/gm, '
  • $1
  • '); + + html = html.replace(/((?:
  • .*<\/li>\n?)+)/g, '
      $1
    '); + + html = html.replace(/^(\d+)\. (.+)$/gm, '
  • $2
  • '); + html = html.replace(/((?:
  • \n?)+)/g, '
      $1
    '); + + html = html.replace(/^> (.+)$/gm, '
    $1
    '); + + html = html.replace(/^---$/gm, '
    '); + + html = html.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (match, text, url) => { + const trimmed = url.trim().toLowerCase(); + if (trimmed.startsWith('http://') || trimmed.startsWith('https://') || trimmed.startsWith('mailto:')) { + return '' + text + ''; + } + return text; + }); + + html = html.replace(/\n/g, '
    '); + + html = html.replace(/
    \s*(<(?:div|ul|ol|h[2-4]|blockquote|hr|pre))/g, '$1'); + html = html.replace(/(<\/(?:div|ul|ol|h[2-4]|blockquote|hr|pre)>)\s*
    /g, '$1'); + + return html; + } + + function bindSuggestionButtons() { + document.querySelectorAll('.ai-suggestion').forEach(btn => { + btn.addEventListener('click', () => { + if (aiChatInput) { + aiChatInput.value = btn.textContent; + aiChatInput.focus(); + updateSendButton(); + } + }); + }); + } + + async function typewriteHtml(element, htmlContent, msgObj, speedMs = 15) { + const tempDiv = document.createElement('div'); + tempDiv.innerHTML = htmlContent; + element.innerHTML = ''; + + async function typeNode(node, parent) { + if (node.nodeType === Node.TEXT_NODE) { + const text = node.textContent; + const textNode = document.createTextNode(''); + parent.appendChild(textNode); + + const chunkSize = Math.max(1, Math.floor(text.length / 40)); + for (let i = 0; i < text.length; i += chunkSize) { + if (!aiChatHistory.includes(msgObj)) return; + textNode.textContent += text.substr(i, chunkSize); + if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight; + await new Promise(r => setTimeout(r, speedMs)); + } + } else if (node.nodeType === Node.ELEMENT_NODE) { + const el = document.createElement(node.tagName); + for (let attr of node.attributes) { + el.setAttribute(attr.name, attr.value); + } + parent.appendChild(el); + for (let child of node.childNodes) { + await typeNode(child, el); + if (!aiChatHistory.includes(msgObj)) return; + } + if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight; + } + } + + for (let child of tempDiv.childNodes) { + await typeNode(child, element); + if (!aiChatHistory.includes(msgObj)) return; + } + + bindAiCodeCopyButtons(element); + } + + function bindAiCodeCopyButtons(scope) { + if (!scope) return; + scope.querySelectorAll('.ai-code-copy[data-code-id]').forEach(btn => { + if (btn.dataset.boundCopy === 'true') return; + btn.dataset.boundCopy = 'true'; + btn.addEventListener('click', () => { + const codeEl = document.getElementById(btn.dataset.codeId); + if (codeEl) aiCopyToClipboard(codeEl.textContent, btn); + }); + }); + } + + function buildThinkingBadgeHtml(thinkingTimeMs, thinkingContent = null) { + const cleanThinkingContent = sanitizeAiThinkingText(thinkingContent); + if (!cleanThinkingContent) return ''; + + const durationLabel = formatAiThinkingDuration(thinkingTimeMs); + const badgeLabel = durationLabel ? `Thought for ${durationLabel}` : 'Thinking'; + + return ` +
    + + + + ${escapeHtmlAi(badgeLabel)} + + + +
    ${renderAiMarkdown(cleanThinkingContent)}
    +
    + `; + } + + function formatAiThinkingDuration(thinkingTimeMs) { + const ms = Number(thinkingTimeMs); + if (!Number.isFinite(ms) || ms <= 0) return ''; + if (ms >= 10000) return `${Math.round(ms / 1000)}s`; + return `${(ms / 1000).toFixed(1)}s`; + } + + function sanitizeAiThinkingText(text) { + return String(text || '') + .replace(//gi, '') + .replace(/<\/think(?:ing)?>/gi, '') + .replace(/\[thinking\]/gi, '') + .replace(/\[\/thinking\]/gi, '') + .trim(); + } + + function claimTypingIndicatorMessageSlot(thinkingTimeMs = null, thinkingContent = null) { + if (!aiChatMessages) return null; + const indicator = aiChatMessages.querySelector('.ai-typing-container'); + if (!indicator) return null; + + indicator.classList.remove('ai-typing-container', 'is-exiting'); + + const avatar = indicator.querySelector('.ai-message-avatar, .ai-msg-avatar'); + if (avatar) avatar.className = 'ai-msg-avatar ai'; + + let body = indicator.querySelector('.ai-message-body'); + let content = indicator.querySelector('.ai-message-content'); + + if (!body) { + body = document.createElement('div'); + body.className = 'ai-message-body'; + indicator.appendChild(body); + } + + if (content && content.parentElement !== body) { + body.appendChild(content); + } + + if (!content) { + content = document.createElement('div'); + content.className = 'ai-message-content'; + body.appendChild(content); + } + + const existingMeta = body.querySelector('.ai-message-meta'); + if (existingMeta) existingMeta.remove(); + + const thinkingHtml = buildThinkingBadgeHtml(thinkingTimeMs, thinkingContent); + if (thinkingHtml) { + const meta = document.createElement('div'); + meta.className = 'ai-message-meta'; + meta.innerHTML = thinkingHtml; + body.insertBefore(meta, content); + } + + content.classList.add('ai-streaming-content'); + content.innerHTML = ''; + return content; + } + + async function addChatMessage(role, content, thinkingTimeMs = null, model = null, attachment = null, doTypewriter = false, thinkingContent = null) { + const msg = { + role, + content, + thinking_time_ms: thinkingTimeMs, + thinking_content: sanitizeAiThinkingText(thinkingContent), + model, + timestamp: Date.now(), + attachment, + isTyping: doTypewriter && role === 'ai' + }; + aiChatHistory.push(msg); + const liveAiContent = role === 'ai' ? claimTypingIndicatorMessageSlot(thinkingTimeMs, msg.thinking_content) : null; + if (!liveAiContent) { + renderChatHistory({ animateLatest: true }); + } + + if (aiCurrentChatId) { + const dbRole = role === 'ai' ? 'assistant' : role; + const imageData = attachment && attachment.isImage ? attachment.data : null; + saveMessageToDb(aiCurrentChatId, dbRole, content, thinkingTimeMs, model, imageData, msg.thinking_content).catch(console.error); + } + + if (liveAiContent) { + if (msg.isTyping) { + await typewriteHtml(liveAiContent, renderAiMarkdown(content), msg); + } else { + liveAiContent.innerHTML = renderAiMarkdown(content); + } + bindAiCodeCopyButtons(liveAiContent.closest('.ai-message-body') || liveAiContent); + liveAiContent.classList.remove('ai-streaming-content'); + msg.isTyping = false; + if (aiChatMessages) aiChatMessages.scrollTop = aiChatMessages.scrollHeight; + return; + } + + if (msg.isTyping) { + const messages = aiChatMessages.querySelectorAll('.ai-message.ai'); + if (messages.length > 0) { + const lastMessage = messages[messages.length - 1]; + const contentDiv = lastMessage.querySelector('.ai-message-content'); + if (contentDiv) { + await typewriteHtml(contentDiv, renderAiMarkdown(content), msg); + } + } + msg.isTyping = false; + } + } + + function showTypingIndicator() { + if (!aiChatMessages) return; + const existing = aiChatMessages.querySelector('.ai-typing-container'); + if (existing) return; + + const typingHtml = ` +
    +
    AI
    +
    +
    + +
    +
    +
    + `; + aiChatMessages.insertAdjacentHTML('beforeend', typingHtml); + aiChatMessages.scrollTop = aiChatMessages.scrollHeight; + } + + function hideTypingIndicator() { + if (!aiChatMessages) return; + const indicator = aiChatMessages.querySelector('.ai-typing-container'); + if (!indicator) return; + if (indicator.classList.contains('is-exiting')) return; + indicator.classList.add('is-exiting'); + const cleanup = () => { + if (indicator.parentNode) indicator.remove(); + }; + indicator.addEventListener('transitionend', cleanup, { once: true }); + setTimeout(cleanup, 220); + } + + function updateSendButton() { + if (aiChatSend && aiChatInput) { + const hasContent = aiChatInput.value.trim() || aiAttachedFile; + aiChatSend.disabled = !hasContent && !aiIsGenerating; + + if (aiIsGenerating) { + aiChatSend.innerHTML = ''; + aiChatSend.classList.add('generating'); + aiChatSend.disabled = false; + aiChatSend.title = 'Stop generating'; + } else { + aiChatSend.innerHTML = ''; + aiChatSend.classList.remove('generating'); + aiChatSend.title = 'Send message'; + } + } + } + + function handleFileAttachment(file) { + if (!file) return; + + const maxSize = 5 * 1024 * 1024; + if (file.size > maxSize) { + alert('File is too large. Maximum size is 5MB.'); + return; + } + + const reader = new FileReader(); + reader.onload = (e) => { + aiAttachedFile = { + name: file.name, + type: file.type, + data: e.target.result, + isImage: file.type.startsWith('image/') + }; + showAttachedFilePreview(); + updateSendButton(); + }; + + if (file.type.startsWith('image/')) { + reader.readAsDataURL(file); + } else { + reader.readAsText(file); + } + } + + function showAttachedFilePreview() { + if (!aiAttachedFile) return; + + const existingPreview = document.querySelector('.ai-attached-preview'); + if (existingPreview) existingPreview.remove(); + + const inputBox = document.querySelector('.ai-chat-input-box'); + if (!inputBox) return; + + const previewHtml = aiAttachedFile.isImage + ? `
    + Attached + +
    ` + : `
    + + +
    `; + + const inputRow = inputBox.querySelector('.ai-chat-input-row'); + if (inputRow) { + inputRow.insertAdjacentHTML('beforebegin', previewHtml); + } else { + inputBox.insertAdjacentHTML('afterbegin', previewHtml); + } + + const removeBtn = inputBox.querySelector('.ai-attached-remove'); + if (removeBtn) { + removeBtn.addEventListener('click', clearAttachedFile); + } + } + + function clearAttachedFile() { + aiAttachedFile = null; + const preview = document.querySelector('.ai-attached-preview'); + if (preview) preview.remove(); + if (aiFileInput) aiFileInput.value = ''; + updateSendButton(); + } + + function stopAiGeneration() { + if (aiAbortController) { + aiAbortController.abort(); + aiAbortController = null; + } + aiIsGenerating = false; + hideTypingIndicator(); + updateSendButton(); + } + + async function sendAiMessage() { + if (aiIsGenerating) { + stopAiGeneration(); + return; + } + + const messageText = aiChatInput ? aiChatInput.value.trim() : ''; + if (!messageText && !aiAttachedFile) return; + + let message = messageText; + let attachmentInfo = null; + + if (aiAttachedFile) { + attachmentInfo = { ...aiAttachedFile }; + if (aiAttachedFile.isImage) { + message = message || 'Please analyze this image.'; + } else { + message = `[Attached file: ${aiAttachedFile.name}]\n\nFile content:\n\`\`\`\n${aiAttachedFile.data}\n\`\`\`\n\n${message || 'Please review this file.'}`; + } + } + + if (aiChatInput) aiChatInput.value = ''; + clearAttachedFile(); + + if (!aiCurrentChatId) { + const title = message.slice(0, 50) + (message.length > 50 ? '...' : ''); + const chatId = await createNewChat(title); + if (chatId) { + aiCurrentChatId = chatId; + await loadChatsFromDb(); + renderChatHistory(); + renderChatsList(); + } else { + console.warn('[AI Chat] Failed to create chat in database, continuing with local-only mode'); + } + } + + if (attachmentInfo && attachmentInfo.isImage) { + await addChatMessage('user', messageText || '(Image attached)', null, null, attachmentInfo); + } else { + await addChatMessage('user', message); + } + + showTypingIndicator(); + aiIsGenerating = true; + aiAbortController = new AbortController(); + updateSendButton(); + + try { + const result = await callAiApi(message, attachmentInfo, aiAbortController.signal); + + aiIsGenerating = false; + aiAbortController = null; + updateSendButton(); + + console.log('[AI Chat] Parsed response:', result); + + if (Array.isArray(result.clientActions) && result.clientActions.length > 0) { + await handleAiClientActions(result.clientActions); + } + + let handledStructuredAction = false; + + if (result.fileOperations && result.fileOperations.length > 0) { + handledStructuredAction = true; + for (const op of result.fileOperations) { + await executeFileOperation(op); + } + } else if (result.fileOperation) { + handledStructuredAction = true; + await executeFileOperation(result); + } + + if (handledStructuredAction) { + if (result.message && result.message.trim()) { + await addChatMessage('ai', result.message.trim(), result.thinking_time_ms, null, null, true, result.thinking_content); + } + } else { + await addChatMessage('ai', result.content || 'Sorry, I could not generate a response.', result.thinking_time_ms, null, null, true, result.thinking_content); + } + } catch (err) { + aiIsGenerating = false; + aiAbortController = null; + updateSendButton(); + + if (err.name === 'AbortError') { + await addChatMessage('ai', '⏹️ Generation stopped.'); + } else { + await addChatMessage('ai', `Error: ${err.message || 'Failed to get response. Please check your API key.'}`); + } + } + } + + async function executeFileOperation(op) { + if (!op || !op.action) { + await addChatMessage('ai', 'Unable to process file operation.'); + return; + } + + if (!hasPerm('files_read')) { + await addChatMessage('ai', 'You don\'t have permission to access server files.'); + return; + } + + if (op.action === 'list' || op.action === 'read') { + await executeFileOperationDirect(op); + } else { + if ((op.action === 'write' || op.action === 'create' || op.action === 'mkdir') && !hasPerm('files_create')) { + await addChatMessage('ai', 'You don\'t have permission to create or modify files.'); + return; + } + if (op.action === 'delete' && !hasPerm('files_delete')) { + await addChatMessage('ai', 'You don\'t have permission to delete files.'); + return; + } + aiPendingFileOperations.push(op); + if (aiPendingFileOperations.length === 1) { + processNextPendingOperation(); + } + } + } + + async function executeFileOperationDirect(op) { + if (!op || !op.action) { + await addChatMessage('ai', 'Unable to process file operation.'); + return; + } + + const serverName = document.documentElement.dataset.bot; + + const normalizePath = (p) => { + if (!p) return ''; + let normalized = String(p).trim(); + while (normalized.startsWith('/')) { + normalized = normalized.slice(1); + } + return normalized; + }; + + const filePath = normalizePath(op.path); + + try { + if (op.action === 'read') { + const response = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(filePath)}`); + if (!response.ok) { + const errData = await response.json().catch(() => ({})); + if (response.status === 502 || (errData.error && errData.error.includes('node'))) { + await addChatMessage('ai', `⚠️ Cannot connect to server node. Please check if the server is online.`); + return; + } else if (response.status === 404) { + await addChatMessage('ai', `⚠️ File not found: **${filePath}**`); + return; + } + throw new Error(errData.error || `Failed to read file: ${filePath}`); + } + const data = await response.json(); + const fileContent = data.content || '(empty file)'; + + aiLastReadFileContent = fileContent; + aiLastReadFilePath = filePath; + + await addChatMessage('ai', `📄 **${filePath}**:\n\`\`\`\n${fileContent}\n\`\`\`\n\nWhat would you like me to change?`, null, null, null, true); + + } else if (op.action === 'write' || op.action === 'create') { + try { + const readResp = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(filePath)}`); + if (readResp.ok) { + const data = await readResp.json(); + aiFileBackups.push({ path: filePath, content: data.content || '', timestamp: Date.now(), action: 'modify' }); + } else { + aiFileBackups.push({ path: filePath, content: null, timestamp: Date.now(), action: 'create' }); + } + } catch { + aiFileBackups.push({ path: filePath, content: null, timestamp: Date.now(), action: 'create' }); + } + saveFileBackupsToStorage(); + + const response = await writeServerFileWithActionToken(serverName, filePath, op.content || ''); + + if (!response.ok) { + const errData = await response.json().catch(() => ({})); + if (response.status === 507 || errData.error === 'disk_limit_exceeded') { + await addChatMessage('ai', `⚠️ **Disk limit exceeded.** ${errData.message || 'Free up space or increase the storage limit.'}`); + return; + } + if (response.status === 502 || (errData.error && errData.error.includes('node'))) { + await addChatMessage('ai', `⚠️ Cannot connect to server node. Please check if the server is online.`); + return; + } + throw new Error(errData.error || `Failed to ${op.action} file: ${filePath}`); + } + + aiLastReadFileContent = null; + aiLastReadFilePath = null; + + const actionWord = op.action === 'create' ? 'Created' : 'Modified'; + await addChatMessage('ai', `✅ ${actionWord} **${filePath}**`, op.thinking_time_ms); + showUndoToast(); + + } else if (op.action === 'mkdir') { + aiFileBackups.push({ path: filePath, content: null, timestamp: Date.now(), action: 'mkdir' }); + saveFileBackupsToStorage(); + + const response = await createServerFolderWithActionToken(serverName, filePath); + + if (!response.ok) { + const errData = await response.json().catch(() => ({})); + if (response.status === 502 || (errData.error && errData.error.includes('node'))) { + await addChatMessage('ai', `⚠️ Cannot connect to server node. Please check if the server is online.`); + return; + } + throw new Error(errData.error || `Failed to create folder: ${filePath}`); + } + + await addChatMessage('ai', `📁 Created folder **${filePath}**`); + showUndoToast(); + + } else if (op.action === 'list') { + const listPath = filePath || '.'; + try { + const response = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/list?path=${encodeURIComponent(listPath)}`); + + if (!response.ok) { + const errData = await response.json().catch(() => ({})); + const errorMsg = errData.error || `HTTP ${response.status}`; + + if (response.status === 502 || errorMsg.includes('node') || errorMsg === 'node_offline') { + await addChatMessage('ai', `⚠️ **Cannot connect to server node**\n\nThe server node appears to be offline or unreachable.\n\n**Please check:**\n1. Is the node agent running?\n2. Can the panel reach the node? (check firewall)\n3. Check the server status in the dashboard\n\n*File operations require an active node connection.*`); + return; + } else if (response.status === 404) { + await addChatMessage('ai', `⚠️ Directory not found: **${listPath}**`); + return; + } else if (response.status === 403) { + await addChatMessage('ai', `⚠️ You don't have permission to access files on this server.`); + return; + } + throw new Error(errorMsg); + } + + const data = await response.json(); + + const files = data.entries || data.files || []; + if (files.length === 0) { + await addChatMessage('ai', `📂 **${listPath === '.' ? '/' : listPath}** is empty.`); + } else { + const fileList = files.map(f => { + const isDir = f.isDirectory === true || f.type === 'dir' || f.type === 'directory'; + const icon = isDir ? '📁' : '📄'; + const size = isDir ? '' : (f.size ? ` (${formatFileSize(f.size)})` : ''); + return `${icon} ${f.name}${size}`; + }).join('\n'); + await addChatMessage('ai', `📂 Contents of **${listPath === '.' ? '/' : listPath}**:\n\n${fileList}`, null, null, null, true); + } + } catch (fetchErr) { + await addChatMessage('ai', `⚠️ Failed to list files: ${fetchErr.message || 'Connection error'}`); + return; + } + + } else if (op.action === 'delete') { + try { + const readResp = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(filePath)}`); + if (readResp.ok) { + const data = await readResp.json(); + aiFileBackups.push({ path: filePath, content: data.content || '', timestamp: Date.now(), action: 'delete' }); + saveFileBackupsToStorage(); + } + } catch { } + + const response = await deleteServerPathWithActionToken(serverName, filePath); + + if (!response.ok) throw new Error(`Failed to delete: ${filePath}`); + + await addChatMessage('ai', `🗑️ Deleted **${filePath}**`); + showUndoToast(); + } + } catch (err) { + await addChatMessage('ai', `❌ Error: ${err.message}`); + } + } + + function formatFileSize(bytes) { + if (bytes === 0) return '0 B'; + const k = 1024; + const sizes = ['B', 'KB', 'MB', 'GB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; + } + + function sanitizeAiVisibleAssistantText(text) { + let value = String(text || '') + .replace(/[\s\S]*?<\/think>/gi, ' ') + .replace(/[\s\S]*?<\/thinking>/gi, ' ') + .replace(/^\s*(?:thought|thinking|reasoning|analysis)\s*:\s*[\s\S]*$/gim, ' ') + .trim(); + + if (!value) return ''; + if (/^[`'"“”‘’()[\]{}<>.,:;!?*_~\\/\-|+=\s]+$/.test(value)) return ''; + + const normalized = value.replace(/\s+/g, ' ').trim(); + const leakedInstructionTalk = [ + /\bwait,\s*the prompt says\b/i, + /\bthe prompt says\b/i, + /\bprevious reply was invalid\b/i, + /\bentire reply must be one\b/i, + //i, + /\bcurrent page server is\b/i, + /\bcurrent page server:\b/i, + /\bthe user wants to\b/i, + /\bi have the\b/i, + /\bi can use\b/i, + /\bi should use\b/i, + /\bi need to use\b/i, + /\blet'?s refine\b/i, + /\brespond with exactly one\b/i, + /\bi need to check\b/i, + /\btool which can be used\b/i + ].some((pattern) => pattern.test(normalized)); + const leakedToolReference = /\b(?:power_server|inspect_server|query_console|send_console_command|list_backups|create_backup|restore_backup|delete_backup)\b/i.test(normalized); + const truncatedReasoning = /(?:i should use the|i can use the|i need to use the)\s*`?$/i.test(normalized); + + if (leakedInstructionTalk || (leakedToolReference && /\b(?:the user wants to|i have the|i can use|i should use|i need to use|let'?s refine|i need to check|tool which can be used)\b/i.test(normalized)) || truncatedReasoning) { + return ''; + } + + return value; + } + + function compactAiAssistantReply(text) { + const raw = sanitizeAiVisibleAssistantText(text); + if (!raw) return raw; + return raw; + } + + function normalizeAiServerNameCandidate(value) { + const normalized = String(value || '') + .trim() + .replace(/^["'`]+|["'`]+$/g, '') + .replace(/[.,!?;:]+$/g, '') + .trim(); + return normalized; + } + + function applyAiServerActionState(action, serverName) { + const target = normalizeAiServerNameCandidate(serverName); + const current = normalizeAiServerNameCandidate(bot); + if (!target || !current || target.toLowerCase() !== current.toLowerCase()) return; + + if (action === 'start' || action === 'restart') { + resetConsoleBuffer(); + resetServerConsoleHistorySession(); + } + if (action === 'start') setPowerState(POWER_STATE.STARTING); + if (action === 'stop' || action === 'kill') setPowerState(POWER_STATE.STOPPING); + if (action === 'restart') setPowerState(POWER_STATE.STARTING); + + if (action === 'start' || action === 'restart') { + attachLogStreamIfRemote({ tail: 0, forceReconnect: true }); + } + + setTimeout(() => { + refreshPowerState({ force: true }).catch(() => { }); + }, 250); + } + + async function handleAiClientActions(actions) { + const list = Array.isArray(actions) ? actions : []; + const seenActionKeys = new Set(); + for (const action of list) { + const type = String(action && action.type || '').trim().toLowerCase(); + const targetServer = normalizeAiServerNameCandidate(action && action.server); + const actionKey = type === 'refresh_power_state' + ? `${type}:${targetServer}:${String(action && action.action || '').trim().toLowerCase()}` + : type === 'console_command_executed' + ? `${type}:${targetServer}:${String(action && action.command || '').trim()}:${Number(action && action.sentAt) || 0}` + : `${type}:${targetServer}`; + if (seenActionKeys.has(actionKey)) continue; + seenActionKeys.add(actionKey); + + if (type === 'refresh_power_state') { + if (targetServer && targetServer.toLowerCase() === String(bot || '').trim().toLowerCase()) { + applyAiServerActionState(action.action, targetServer); + } + continue; + } + + if (type === 'console_command_executed') { + if (targetServer && targetServer.toLowerCase() === String(bot || '').trim().toLowerCase()) { + const commandText = String(action.command || '').trim(); + const sentAt = Number(action.sentAt) || Date.now(); + if (commandText && hasConsoleReadAccess()) { + appendCommandEcho(commandText, sentAt); + } + scheduleConsoleHistoryResync(commandText, sentAt); + } + continue; + } + + if (type === 'backups_updated') { + if (targetServer && targetServer.toLowerCase() === String(bot || '').trim().toLowerCase()) { + if (backupsModal && backupsModal.classList.contains('show')) { + await loadBackups().catch(() => { }); + } + } + } + } + } + + async function callAiApi(message, attachmentInfo = null, abortSignal = null) { + const modelValue = aiModelSelect?.value || ''; + const { providerId, modelName } = decodeAiModelSelection(modelValue); + + if (!providerId || !modelName) { + throw new Error('Please select a model first.'); + } + saveSelectedAiModelToStorage(modelValue); + + const config = AI_PROVIDERS[providerId]; + if (!config) { + throw new Error('Unknown provider.'); + } + + const filePatterns = [ + /(?:modify|change|edit|update|set|turn|enable|disable|fix|put|add|remove|optimize)\s+(?:in\s+)?(?:the\s+)?(?:file\s+)?([^\s]+\.(yml|yaml|json|properties|txt|conf|cfg|toml|ini))/i, + /(?:in|at)\s+([^\s]+\.(yml|yaml|json|properties|txt|conf|cfg|toml|ini))/i, + /([^\s]+\.(yml|yaml|json|properties|txt|conf|cfg|toml|ini))\s+(?:and\s+)?(?:modify|change|edit|update|set|turn|enable|disable|fix|put|add|remove|optimize)/i + ]; + + let targetFile = null; + for (const pattern of filePatterns) { + const match = message.match(pattern); + if (match) { + targetFile = match[1]; + break; + } + } + + if (targetFile && !aiLastReadFileContent && hasPerm('files_read')) { + try { + const serverName = document.documentElement.dataset.bot; + const response = await fetch(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(targetFile)}`); + if (response.ok) { + const data = await response.json(); + if (data.content) { + aiLastReadFileContent = data.content; + aiLastReadFilePath = targetFile; + } + } + } catch (e) { + } + } + + let augmentedMessage = message; + if (aiLastReadFileContent && aiLastReadFilePath) { + const modifyIntent = /(?:set|change|modify|edit|update|enable|disable|fix|optimize|turn|make|add|remove)/i.test(message); + if (modifyIntent) { + augmentedMessage = `User request: ${message} + +The file "${aiLastReadFilePath}" currently contains: +\`\`\` +${aiLastReadFileContent} +\`\`\` + +Apply the user's requested changes. You MUST output the complete modified file using this exact format: +FILE_WRITE:${aiLastReadFilePath} +---FILE_CONTENT_START--- +(paste the ENTIRE file with changes applied here) +---FILE_CONTENT_END---`; + } + } + + const canReadFiles = hasPerm('files_read'); + const canWriteFiles = hasPerm('files_create'); + const canDeleteFiles = hasPerm('files_delete'); + const canReadConsole = hasPerm('console_read'); + const canWriteConsole = hasPerm('console_write'); + const canStartServer = hasPerm('server_start'); + const canStopServer = hasPerm('server_stop'); + const canViewBackups = hasPerm('backups_view'); + const canCreateBackups = hasPerm('backups_create'); + const canDeleteBackups = hasPerm('backups_delete'); + const currentServerName = String(bot || '').trim(); + + let systemPrompt; + + const baseIdentity = `You are ADPanel Agent, an intelligent AI assistant integrated into ADPanel — an enterprise server management panel that lets users host and manage their Docker-based servers (FiveM, Minecraft, and more). + +CORE BEHAVIOR: +1. NEVER use diacritical marks, accents, or special unicode characters in ANY language. Write as if you only have a standard US English keyboard. +2. Reply naturally, like a fast voice assistant. +3. Default to one short sentence. Use two short sentences only when needed. +4. Prefer plain text. Use markdown only when it clearly helps. +5. For greetings, answer in 2-6 words. +6. For actions, say what you did or what you need next. +7. Prioritize the user's latest message and the live server context over older chat history if they conflict. +8. Never narrate internal planning, hidden reasoning, or which tool you are about to use. +9. Never say phrases like "The user wants", "I need to", "I should use", "Plan", or "Current page server".`; + + const nativeToolLines = [ + 'Sensitive server actions, console actions, and backup actions are executed through native backend tools.', + `Current server: ${currentServerName || 'current-server'}.`, + 'Do not explain your internal planning or mention internal tool names in the visible reply.', + 'Do not emit SERVER_START, SERVER_STOP, SERVER_RESTART, or SERVER_KILL lines.', + 'If backend tools are needed, let the backend orchestrator handle them; never write planning text such as "I need to use inspect_server".', + 'Use the current server when the user means this server or current server.', + 'Backend permissions are re-checked on every native action, so do not claim success before the tool result confirms it.', + 'For live console checks or crash diagnosis, prefer the native console inspection tool.', + 'For real console execution, only use the native console command tool when the user explicitly asked to run a command.', + 'For backup restore or delete, inspect the available backups first when the reference is unclear.' + ].filter(Boolean).join('\n'); + + if (canReadFiles) { + systemPrompt = `${baseIdentity} + +You have access to this server's file system. You can browse, read, create, edit, and manage files directly. + +${nativeToolLines} + +Use these commands (one per line, no extra formatting): + +FILE_LIST:. +FILE_LIST:config +FILE_READ:config/settings.yml +${canWriteFiles ? `FILE_MKDIR:plugins/myfolder` : ''} +${canDeleteFiles ? `FILE_DELETE:old-file.txt` : ''} + +${canWriteFiles ? `To create or modify a file: +FILE_CREATE:path/to/file.txt +---FILE_CONTENT_START--- +(file content here) +---FILE_CONTENT_END--- + +To modify an existing file: +FILE_WRITE:path/to/file.yml +---FILE_CONTENT_START--- +(complete modified file content) +---FILE_CONTENT_END---` : ''} + +IMPORTANT RULES: +1. Put each command on its own line +2. Path comes immediately after the colon (no spaces) +3. Use . for root directory listing +4. Use relative paths (no leading /) +5. Only list files or perform file operations when the user explicitly asks for it +6. When modifying a file, output the COMPLETE file content +7. After completing a task, briefly describe what you did +8. Do NOT automatically list files or show server files unless the user specifically asks to see them +9. When the user greets you or asks general questions, respond conversationally without performing file operations +10. When asked what ADPanel is, explain it is an enterprise Docker server management panel with file management, console, scheduling, backups, store, and AI agent features`; + } else { + systemPrompt = `${baseIdentity} + +You do NOT have file system access for this user. Do not attempt to list, read, or modify any server files. + +${nativeToolLines} + +Instead, provide helpful advice, explain concepts, troubleshoot issues, and guide users on configuring their servers. If the user asks you to manage files, let them know they need file management permissions and suggest contacting their server administrator.`; + } + + if (canReadConsole) { + systemPrompt += `\n\nWhen the user shares server logs or console output, analyze them carefully and provide helpful troubleshooting advice. Identify errors, warnings, and suggest specific fixes.`; + } + + if (attachmentInfo && attachmentInfo.isImage) { + systemPrompt += `\n\nYou also have vision capabilities. When the user provides an image, analyze it and describe what you see. If the image appears to be a screenshot or configuration, provide helpful insights about it.`; + } + + const historyMessages = aiChatHistory.slice(-10).map(m => { + if (m.attachment && m.attachment.isImage) { + return { + role: m.role === 'ai' ? 'assistant' : m.role, + content: m.content, + image: m.attachment.data + }; + } + return { role: m.role === 'ai' ? 'assistant' : m.role, content: m.content }; + }); + + if (historyMessages.length > 0 && historyMessages[historyMessages.length - 1].role === 'user') { + if (attachmentInfo && attachmentInfo.isImage) { + historyMessages[historyMessages.length - 1] = { role: 'user', content: augmentedMessage, image: attachmentInfo.data }; + } else { + historyMessages[historyMessages.length - 1] = { role: 'user', content: augmentedMessage }; + } + } + + const messages = [ + { role: 'system', content: systemPrompt }, + ...historyMessages + ]; + + const result = await callAiBackendProxy(providerId, modelName, messages, abortSignal); + if (result && typeof result.content === 'string') { + result.content = compactAiAssistantReply(sanitizeAiVisibleAssistantText(result.content)); + } + if (result && typeof result.message === 'string') { + result.message = compactAiAssistantReply(sanitizeAiVisibleAssistantText(result.message)); + } + + if (result.fileOperation && result.action === 'write' && aiLastReadFileContent) { + const originalContent = aiLastReadFileContent; + const originalLength = originalContent.length; + const newContent = result.content || ''; + const newLength = newContent.length; + + if (originalLength > 100 && newLength < originalLength * 0.3) { + const mergedContent = tryMergePartialChange(originalContent, newContent, aiLastReadFilePath); + if (mergedContent) { + result.content = mergedContent; + } else { + const savedPath = aiLastReadFilePath; + aiLastReadFileContent = null; + aiLastReadFilePath = null; + return { + content: `The AI only provided partial content which would corrupt your file. Please try again with a clearer instruction like "in ${savedPath}, change [setting] to [value]".` + }; + } + } + + aiLastReadFileContent = null; + aiLastReadFilePath = null; + } + + return result; + } + + function tryMergePartialChange(originalContent, partialContent, filePath) { + const ext = filePath.split('.').pop().toLowerCase(); + + if (['yml', 'yaml', 'properties'].includes(ext)) { + const lines = partialContent.trim().split('\n'); + let modifiedContent = originalContent; + let changesMade = false; + + for (const line of lines) { + const yamlMatch = line.match(/^(\s*)([a-zA-Z0-9_-]+)\s*:\s*(.*)$/); + const propsMatch = line.match(/^([a-zA-Z0-9_.-]+)\s*=\s*(.*)$/); + + if (yamlMatch) { + const [, indent, key, value] = yamlMatch; + const keyPattern = new RegExp(`^(\\s*)${escapeRegex(key)}\\s*:.*$`, 'gm'); + if (keyPattern.test(modifiedContent)) { + modifiedContent = modifiedContent.replace(keyPattern, `$1${key}: ${value}`); + changesMade = true; + } + } else if (propsMatch) { + const [, key, value] = propsMatch; + const keyPattern = new RegExp(`^${escapeRegex(key)}\\s*=.*$`, 'gm'); + if (keyPattern.test(modifiedContent)) { + modifiedContent = modifiedContent.replace(keyPattern, `${key}=${value}`); + changesMade = true; + } + } + } + + if (changesMade) { + return modifiedContent; + } + } + + if (ext === 'json') { + try { + const originalJson = JSON.parse(originalContent); + const partialJson = JSON.parse(partialContent); + const merged = deepMerge(originalJson, partialJson); + return JSON.stringify(merged, null, 2); + } catch { + } + } + + return null; + } + + function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + } + + function deepMerge(target, source) { + const result = { ...target }; + for (const key in source) { + if (source[key] && typeof source[key] === 'object' && !Array.isArray(source[key])) { + result[key] = deepMerge(result[key] || {}, source[key]); + } else { + result[key] = source[key]; + } + } + return result; + } + + async function callAiBackendProxy(provider, model, messages, abortSignal = null, onChunk = null) { + const fetchOptions = { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + provider, + model, + messages, + stream: !!onChunk, + serverContext: { + currentServer: String(bot || '').trim() + } + }) + }; + + if (abortSignal) { + fetchOptions.signal = abortSignal; + } + + const response = await fetch('/api/ai/chat', fetchOptions); + + if (!response.ok) { + const error = await response.json().catch(() => ({})); + throw new Error(error.error || `API error: ${response.status}`); + } + + if (onChunk) { + const reader = response.body.getReader(); + const decoder = new TextDecoder('utf-8'); + let done = false; + let buffer = ''; + let thinkingTimeMs = null; + let thinkingContent = ''; + let fullContent = ''; + + while (!done) { + const { value, done: readerDone } = await reader.read(); + done = readerDone; + if (value) { + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split('\n'); + buffer = lines.pop(); + for (const line of lines) { + const trimmed = line.trim(); + if (trimmed.startsWith('data: ')) { + if (trimmed === 'data: [DONE]') continue; + try { + const parsed = JSON.parse(trimmed.substring(6)); + if (parsed.error) { + throw new Error(parsed.error); + } + if (parsed.chunk) { + fullContent += parsed.chunk; + onChunk(parsed.chunk, fullContent); + } + if (parsed.done) { + thinkingTimeMs = parsed.thinking_time_ms; + thinkingContent = typeof parsed.thinking_content === 'string' ? parsed.thinking_content : thinkingContent; + } + } catch (e) { + } + } + } + } + } + + const parsedContent = parseAiResponse(fullContent); + parsedContent.thinking_time_ms = thinkingTimeMs; + parsedContent.thinking_content = thinkingContent; + parsedContent.clientActions = []; + return parsedContent; + } else { + const data = await response.json(); + if (!data.ok) { + throw new Error(data.error || 'AI request failed'); + } + + const result = parseAiResponse(data.content || ''); + result.thinking_time_ms = data.thinking_time_ms || null; + result.thinking_content = typeof data.thinking_content === 'string' ? data.thinking_content : ''; + result.clientActions = Array.isArray(data.clientActions) ? data.clientActions : []; + return result; + } + } + + + async function callOpenAiCompatible(endpoint, apiKey, model, messages, providerId) { + return await callAiBackendProxy(providerId, model, messages); + } + + async function callGoogleAi(apiKey, model, messages) { + return await callAiBackendProxy('google', model, messages); + } + + async function callCohereAi(apiKey, model, messages) { + return await callAiBackendProxy('cohere', model, messages); + } + + function parseAiResponse(content) { + if (!content || typeof content !== 'string') { + return { content: content || 'No response received.' }; + } + + let trimmed = content.trim().replace(/\\n/g, '\n'); + const operations = []; + let remainingMessage = trimmed; + + const toolCallPattern = /\[TOOL_CALL\]\s*\{tool\s*=>\s*"([^"]+)",\s*args\s*=>\s*\{([^}]*)\}\s*\}\s*\[\/TOOL_CALL\]/gi; + let toolMatch; + while ((toolMatch = toolCallPattern.exec(trimmed)) !== null) { + const toolName = toolMatch[1].toLowerCase(); + const argsContent = toolMatch[2]; + + const pathMatch = argsContent.match(/--path\s+"([^"]+)"/i); + const contentArgMatch = argsContent.match(/--content\s+"([^"]+)"/i); + + if (pathMatch) { + const path = pathMatch[1]; + const fileContent = contentArgMatch ? contentArgMatch[1] : null; + + if (toolName === 'file_mkdir' || toolName === 'mkdir') { + operations.push({ action: 'mkdir', path }); + } else if (toolName === 'file_create' || toolName === 'create') { + operations.push({ action: 'create', path, content: fileContent || '' }); + } else if (toolName === 'file_write' || toolName === 'write') { + operations.push({ action: 'write', path, content: fileContent || '' }); + } else if (toolName === 'file_read' || toolName === 'read') { + operations.push({ action: 'read', path }); + } else if (toolName === 'file_list' || toolName === 'list') { + operations.push({ action: 'list', path }); + } else if (toolName === 'file_delete' || toolName === 'delete') { + operations.push({ action: 'delete', path }); + } + } + remainingMessage = remainingMessage.replace(toolMatch[0], ''); + } + + + const invokePattern = /\s*<(FILE_\w+)>([\s\S]*?)<\/\1>\s*<\/invoke>/gi; + let invokeMatch; + while ((invokeMatch = invokePattern.exec(trimmed)) !== null) { + const action = invokeMatch[1].toLowerCase().replace('file_', ''); + const innerContent = invokeMatch[2]; + parseXmlOperation(action, innerContent, operations); + remainingMessage = remainingMessage.replace(invokeMatch[0], ''); + } + + const directPattern = /<(FILE_\w+)>([\s\S]*?)<\/\1>/gi; + let directMatch; + while ((directMatch = directPattern.exec(trimmed)) !== null) { + if (!operations.some(op => op._rawMatch === directMatch[0])) { + const action = directMatch[1].toLowerCase().replace('file_', ''); + const innerContent = directMatch[2]; + parseXmlOperation(action, innerContent, operations); + remainingMessage = remainingMessage.replace(directMatch[0], ''); + } + } + + const antlPattern = /]*>([\s\S]*?)<\/antml:invoke>/gi; + let antlMatch; + while ((antlMatch = antlPattern.exec(trimmed)) !== null) { + const action = antlMatch[1].toLowerCase().replace('file_', ''); + const innerContent = antlMatch[2]; + parseXmlOperation(action, innerContent, operations); + remainingMessage = remainingMessage.replace(antlMatch[0], ''); + } + + const listPattern = /FILE_LIST:([^\s\n]+)/gi; + let listMatch; + while ((listMatch = listPattern.exec(trimmed)) !== null) { + let path = listMatch[1].trim(); + if (path.includes('FILE_')) continue; + if (!operations.some(op => op.action === 'list' && op.path === path)) { + operations.push({ action: 'list', path }); + } + remainingMessage = remainingMessage.replace(listMatch[0], ''); + } + + const readPattern = /FILE_READ:([^\s\n]+)/gi; + let readMatch; + while ((readMatch = readPattern.exec(trimmed)) !== null) { + let path = readMatch[1].trim(); + if (path.includes('FILE_')) continue; + if (!operations.some(op => op.action === 'read' && op.path === path)) { + operations.push({ action: 'read', path }); + } + remainingMessage = remainingMessage.replace(readMatch[0], ''); + } + + const mkdirPattern = /FILE_MKDIR:([^\s\n]+)/gi; + let mkdirMatch; + while ((mkdirMatch = mkdirPattern.exec(trimmed)) !== null) { + let path = mkdirMatch[1].trim(); + if (path.includes('FILE_')) continue; + if (!operations.some(op => op.action === 'mkdir' && op.path === path)) { + operations.push({ action: 'mkdir', path }); + } + remainingMessage = remainingMessage.replace(mkdirMatch[0], ''); + } + + const deletePattern = /FILE_DELETE:([^\s\n]+)/gi; + let deleteMatch; + while ((deleteMatch = deletePattern.exec(trimmed)) !== null) { + let path = deleteMatch[1].trim(); + if (path.includes('FILE_')) continue; + if (!operations.some(op => op.action === 'delete' && op.path === path)) { + operations.push({ action: 'delete', path }); + } + remainingMessage = remainingMessage.replace(deleteMatch[0], ''); + } + + const createPattern = /FILE_CREATE:([^\s\n]+)/i; + const createMatch = trimmed.match(createPattern); + if (createMatch) { + const filePath = createMatch[1].trim(); + if (!filePath.includes('FILE_') && !operations.some(op => op.action === 'create' && op.path === filePath)) { + const fileContent = extractFileContent(trimmed, createMatch[0]); + if (fileContent !== null) { + operations.push({ action: 'create', path: filePath, content: fileContent }); + remainingMessage = remainingMessage.replace(/FILE_CREATE:[^\n]*[\s\S]*?---FILE_CONTENT_END---/i, ''); + remainingMessage = remainingMessage.replace(/FILE_CREATE:[^\n]*[\s\S]*?```[\s\S]*?```/i, ''); + } + } + } + + const writePattern = /FILE_WRITE:([^\s\n]+)/i; + const writeMatch = trimmed.match(writePattern); + if (writeMatch) { + const filePath = writeMatch[1].trim(); + if (!filePath.includes('FILE_') && !operations.some(op => op.action === 'write' && op.path === filePath)) { + const fileContent = extractFileContent(trimmed, writeMatch[0]); + if (fileContent !== null) { + operations.push({ action: 'write', path: filePath, content: fileContent }); + remainingMessage = remainingMessage.replace(/FILE_WRITE:[^\n]*[\s\S]*?---FILE_CONTENT_END---/i, ''); + remainingMessage = remainingMessage.replace(/FILE_WRITE:[^\n]*[\s\S]*?```[\s\S]*?```/i, ''); + } else { + return { content: `I couldn't extract the file content for ${filePath}. Please try again.` }; + } + } + } + + remainingMessage = remainingMessage + .replace(/---FILE_CONTENT_START---|---FILE_CONTENT_END---/g, '') + .replace(/<\/?antml:[^>]+>/g, '') + .replace(/<\/?invoke>/g, '') + .replace(/<\/?FILE_\w+>/g, '') + .replace(/[^<]*<\/path>/g, '') + .replace(/[\s\S]*?<\/content>/g, '') + .replace(/\[TOOL_CALL\][\s\S]*?\[\/TOOL_CALL\]/g, '') + .replace(/SERVER_(?:START|STOP|RESTART|KILL)(?::[^\s\n]+)?/gi, '') + .trim(); + + if (operations.length > 0) { + const response = { message: remainingMessage || null }; + if (operations.length === 1) { + response.fileOperation = true; + Object.assign(response, operations[0]); + } else if (operations.length > 1) { + response.fileOperations = operations; + } + return response; + } + + return { content }; + } + + function parseXmlOperation(action, innerContent, operations) { + let path = null; + let fileContent = null; + + const pathMatch = innerContent.match(/([^<]+)<\/path>/i); + if (pathMatch) { + path = pathMatch[1].trim(); + } + + const contentMatch = innerContent.match(/([\s\S]*?)<\/content>/i); + if (contentMatch) { + fileContent = contentMatch[1].trim(); + } + + if (!path) { + const plainPath = innerContent.trim().split(/\s+/)[0]; + if (plainPath && !plainPath.startsWith('<')) { + path = plainPath; + } + } + + if (!path) return; + + switch (action) { + case 'list': + operations.push({ action: 'list', path }); + break; + case 'read': + operations.push({ action: 'read', path }); + break; + case 'mkdir': + operations.push({ action: 'mkdir', path }); + break; + case 'delete': + operations.push({ action: 'delete', path }); + break; + case 'create': + if (fileContent !== null) { + operations.push({ action: 'create', path, content: fileContent }); + } + break; + case 'write': + if (fileContent !== null) { + operations.push({ action: 'write', path, content: fileContent }); + } + break; + } + } + + function extractFileContent(fullContent, afterMarker) { + const afterIdx = fullContent.indexOf(afterMarker); + if (afterIdx === -1) return null; + + const afterWrite = fullContent.slice(afterIdx + afterMarker.length); + + const startMarker = '---FILE_CONTENT_START---'; + const endMarker = '---FILE_CONTENT_END---'; + let startIdx = afterWrite.indexOf(startMarker); + let endIdx = afterWrite.indexOf(endMarker); + + if (startIdx !== -1 && endIdx !== -1 && endIdx > startIdx) { + return afterWrite.slice(startIdx + startMarker.length, endIdx).trim(); + } + + const codeBlockMatch = afterWrite.match(/```(?:\w*\n)?([\s\S]*?)```/); + if (codeBlockMatch) { + return codeBlockMatch[1].trim(); + } + + const lines = afterWrite.split('\n'); + const contentLines = []; + let foundContent = false; + for (const line of lines) { + const trimLine = line.trim(); + if (!foundContent && trimLine === '') continue; + if (trimLine.startsWith('FILE_') || trimLine.startsWith('---')) break; + foundContent = true; + contentLines.push(line); + } + + const result = contentLines.join('\n').trim(); + return result || null; + } + + + function renderFileChangesBar() { + if (!aiFileChangesBar || !aiFileChangesList || !aiFileChangesCount) return; + + if (aiFileBackups.length === 0) { + aiFileChangesBar.classList.remove('show'); + return; + } + + aiFileChangesBar.classList.add('show'); + aiFileChangesCount.textContent = aiFileBackups.length; + + aiFileChangesList.innerHTML = aiFileBackups.map((backup, index) => { + const actionLabel = backup.action === 'create' ? 'Created' : + backup.action === 'mkdir' ? 'Folder Created' : + backup.action === 'delete' ? 'Deleted' : 'Modified'; + const iconClass = backup.action === 'create' ? 'create' : + backup.action === 'mkdir' ? 'mkdir' : + backup.action === 'delete' ? 'delete' : 'modify'; + const icon = backup.action === 'create' ? 'fa-file-circle-plus' : + backup.action === 'mkdir' ? 'fa-folder-plus' : + backup.action === 'delete' ? 'fa-trash' : 'fa-file-pen'; + + return ` +
    +
    + +
    +
    +
    ${escapeHtmlAi(backup.path).replace(/
    /g, '')}
    +
    ${actionLabel}
    +
    +
    + + +
    +
    + `; + }).join(''); + + aiFileChangesList.querySelectorAll('.ai-file-change-accept').forEach(btn => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + const index = parseInt(btn.dataset.index, 10); + acceptFileChange(index); + }); + }); + + aiFileChangesList.querySelectorAll('.ai-file-change-undo').forEach(btn => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + const index = parseInt(btn.dataset.index, 10); + undoFileChangeByIndex(index); + }); + }); + } + + function acceptFileChange(index) { + if (index < 0 || index >= aiFileBackups.length) return; + const backup = aiFileBackups[index]; + aiFileBackups.splice(index, 1); + saveFileBackupsToStorage(); + addChatMessage('ai', `✓ Accepted change to **${backup.path}**`); + } + + async function acceptAllFileChanges() { + const count = aiFileBackups.length; + aiFileBackups = []; + saveFileBackupsToStorage(); + await addChatMessage('ai', `✓ Accepted all ${count} file change(s)`); + hideUndoToast(); + } + + async function undoFileChangeByIndex(index) { + if (index < 0 || index >= aiFileBackups.length) return; + + const backup = aiFileBackups[index]; + aiFileBackups.splice(index, 1); + saveFileBackupsToStorage(); + + const serverName = document.documentElement.dataset.bot; + + try { + if (backup.action === 'create' || backup.action === 'mkdir') { + const response = await deleteServerPathWithActionToken(serverName, backup.path, backup.action === 'mkdir'); + if (!response.ok) throw new Error('Failed to delete'); + await addChatMessage('ai', `↩️ Undone: Deleted ${backup.path}`); + } else if (backup.action === 'delete') { + const response = await writeServerFileWithActionToken(serverName, backup.path, backup.content); + if (response.status === 507) { + const errData = await response.json().catch(() => ({})); + throw new Error(errData.message || 'Disk space limit exceeded. Cannot restore file.'); + } + if (!response.ok) throw new Error('Failed to restore file'); + await addChatMessage('ai', `↩️ Undone: Restored ${backup.path}`); + } else { + const response = await writeServerFileWithActionToken(serverName, backup.path, backup.content); + if (response.status === 507) { + const errData = await response.json().catch(() => ({})); + throw new Error(errData.message || 'Disk space limit exceeded. Cannot restore file.'); + } + if (!response.ok) throw new Error('Failed to restore file'); + await addChatMessage('ai', `↩️ Undone: Reverted ${backup.path}`); + } + } catch (err) { + await addChatMessage('ai', `❌ Undo failed: ${err.message}`); + } + } + + async function undoAllFileChanges() { + const backupsToUndo = [...aiFileBackups]; + for (let i = backupsToUndo.length - 1; i >= 0; i--) { + await undoFileChangeByIndex(0); + } + hideUndoToast(); + } + + + function showConfirmDialog(op) { + if (!aiConfirmDialog) return; + aiCurrentPendingOp = op; + + const actionLabels = { + 'write': 'Modify File', + 'create': 'Create File', + 'mkdir': 'Create Folder', + 'delete': 'Delete' + }; + + if (aiConfirmAction) aiConfirmAction.textContent = actionLabels[op.action] || op.action.toUpperCase(); + if (aiConfirmPath) aiConfirmPath.textContent = op.path; + + if (aiConfirmPreview) { + if ((op.action === 'write' || op.action === 'create') && op.content) { + const preview = op.content.length > 500 ? op.content.slice(0, 500) + '\n... (truncated)' : op.content; + aiConfirmPreview.textContent = preview; + aiConfirmPreview.style.display = 'block'; + } else { + aiConfirmPreview.style.display = 'none'; + } + } + + aiConfirmDialog.classList.add('show'); + } + + function hideConfirmDialog() { + if (!aiConfirmDialog) return; + aiConfirmDialog.classList.remove('show'); + aiCurrentPendingOp = null; + } + + async function processNextPendingOperation() { + if (aiPendingFileOperations.length === 0) return; + + const op = aiPendingFileOperations[0]; + + if (op.action === 'list' || op.action === 'read') { + aiPendingFileOperations.shift(); + await executeFileOperationDirect(op); + processNextPendingOperation(); + } else { + showConfirmDialog(op); + } + } + + async function handleConfirmAllow() { + if (!aiCurrentPendingOp) return; + const op = aiCurrentPendingOp; + hideConfirmDialog(); + aiPendingFileOperations.shift(); + await executeFileOperationDirect(op); + processNextPendingOperation(); + } + + async function handleConfirmDeny() { + if (!aiCurrentPendingOp) return; + const op = aiCurrentPendingOp; + hideConfirmDialog(); + aiPendingFileOperations.shift(); + await addChatMessage('ai', `⛔ Operation denied: ${op.action} ${op.path}`); + processNextPendingOperation(); + } + + let undoToastTimeout = null; + + function showUndoToast() { + if (!aiUndoToast) return; + if (undoToastTimeout) { + clearTimeout(undoToastTimeout); + undoToastTimeout = null; + } + aiUndoToast.classList.add('show'); + undoToastTimeout = setTimeout(() => { + hideUndoToast(); + }, 8000); + } + + function hideUndoToast() { + if (!aiUndoToast) return; + if (undoToastTimeout) { + clearTimeout(undoToastTimeout); + undoToastTimeout = null; + } + aiUndoToast.classList.remove('show'); + } + + async function undoLastFileChange() { + if (aiFileBackups.length === 0) return; + + const backup = aiFileBackups.pop(); + if (!backup) return; + + const serverName = document.documentElement.dataset.bot; + + try { + if (backup.action === 'create' || backup.action === 'mkdir') { + const response = await deleteServerPathWithActionToken(serverName, backup.path, backup.action === 'mkdir'); + if (!response.ok) throw new Error('Failed to delete'); + await addChatMessage('ai', `↩️ Undone: Deleted ${backup.path}`); + } else if (backup.action === 'delete') { + const response = await writeServerFileWithActionToken(serverName, backup.path, backup.content); + if (response.status === 507) { + const errData = await response.json().catch(() => ({})); + throw new Error(errData.message || 'Disk space limit exceeded. Cannot restore file.'); + } + if (!response.ok) throw new Error('Failed to restore file'); + await addChatMessage('ai', `↩️ Undone: Restored ${backup.path}`); + } else { + const response = await writeServerFileWithActionToken(serverName, backup.path, backup.content); + if (response.status === 507) { + const errData = await response.json().catch(() => ({})); + throw new Error(errData.message || 'Disk space limit exceeded. Cannot restore file.'); + } + if (!response.ok) throw new Error('Failed to restore file'); + await addChatMessage('ai', `↩️ Undone: Reverted ${backup.path}`); + } + + hideUndoToast(); + } catch (err) { + await addChatMessage('ai', `❌ Undo failed: ${err.message}`); + } + } + + function clearAiChat() { + aiChatHistory = []; + localStorage.removeItem(AI_CHAT_HISTORY); + renderChatHistory(); + } + + if (aiHelpModalClose) { + aiHelpModalClose.addEventListener('click', closeAiHelpModal); + } + + if (aiProviderGrid) { + aiProviderGrid.addEventListener('click', (e) => { + const card = e.target.closest('[data-provider]'); + if (card) { + showApiKeyForm(card.dataset.provider); + } + }); + } + + if (aiKeyBack) { + aiKeyBack.addEventListener('click', hideApiKeyForm); + } + + if (aiKeyToggle && aiApiKeyInput) { + aiKeyToggle.addEventListener('click', () => { + const isPassword = aiApiKeyInput.type === 'password'; + aiApiKeyInput.type = isPassword ? 'text' : 'password'; + aiKeyToggle.innerHTML = ``; + }); + } + + if (aiApiKeyInput) { + aiApiKeyInput.addEventListener('input', () => { + updateAiProviderFormState(); + }); + } + + if (aiBaseUrlInput) { + aiBaseUrlInput.addEventListener('input', () => { + updateAiProviderFormState(); + }); + } + + if (aiKeySave) { + aiKeySave.addEventListener('click', async () => { + if (!aiCurrentProvider) return; + aiKeySave.disabled = true; + aiKeySave.textContent = 'Connecting...'; + + const result = await saveAiProviderConfig(aiCurrentProvider, { + key: aiApiKeyInput?.value.trim() || '', + baseUrl: aiBaseUrlInput?.value.trim() || '' + }); + + if (result.ok) { + await updateProviderStatuses(); + hideApiKeyForm(); + + if (hasConfiguredProvider()) { + if (aiHelpSetup) aiHelpSetup.style.display = 'none'; + if (aiHelpChat) aiHelpChat.style.display = 'flex'; + await populateModelSelector(); + await loadChatHistory(); + } + } else { + alert(result.error || 'Failed to connect provider'); + } + + aiKeySave.textContent = 'Save & Connect'; + updateAiProviderFormState(); + }); + } + + if (aiModelTrigger) { + aiModelTrigger.addEventListener('click', (e) => { + e.stopPropagation(); + if (aiModelTrigger.disabled) return; + const willOpen = !aiModelSelector?.classList.contains('open'); + closeAiModelDropdown(); + if (willOpen && aiModelSelector) { + aiModelSelector.classList.add('open'); + aiModelTrigger.setAttribute('aria-expanded', 'true'); + aiModelOptions?.setAttribute('aria-hidden', 'false'); + } + }); + + aiModelTrigger.addEventListener('keydown', (e) => { + if (e.key === 'Enter' || e.key === ' ') { + e.preventDefault(); + aiModelTrigger.click(); + } else if (e.key === 'Escape') { + closeAiModelDropdown(); + } + }); + } + + if (aiModelOptions && aiModelSelect) { + const handleAiModelOptionSelect = (optionButton) => { + if (!optionButton) return; + if (!aiModelSelector?.classList.contains('open')) return; + const nextValue = optionButton.dataset.value || ''; + if (!nextValue) return; + + aiModelSelect.value = nextValue; + aiModelSelect.dispatchEvent(new Event('change', { bubbles: true })); + updateAiModelSelectorState(); + closeAiModelDropdown(); + aiModelTrigger?.focus(); + }; + + aiModelOptions.addEventListener('pointerdown', (e) => { + const optionButton = e.target.closest('.ai-model-option'); + if (!optionButton) return; + e.preventDefault(); + handleAiModelOptionSelect(optionButton); + }); + + aiModelOptions.addEventListener('click', (e) => { + const optionButton = e.target.closest('.ai-model-option'); + if (!optionButton) return; + handleAiModelOptionSelect(optionButton); + }); + } + + if (aiModelSelect) { + aiModelSelect.addEventListener('change', () => updateAiModelSelectorState({ persist: true })); + } + + document.addEventListener('click', (e) => { + if (!e.target.closest('#aiModelSelector')) { + closeAiModelDropdown(); + } + }); + + if (aiChatInput) { + aiChatInput.addEventListener('input', () => { + updateSendButton(); + aiChatInput.style.height = 'auto'; + aiChatInput.style.height = Math.min(aiChatInput.scrollHeight, 120) + 'px'; + }); + + aiChatInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + sendAiMessage(); + } + }); + + aiChatInput.addEventListener('paste', (e) => { + const clipboardItems = e.clipboardData?.items; + if (!clipboardItems) return; + + for (const item of clipboardItems) { + if (item.type.startsWith('image/')) { + e.preventDefault(); + const file = item.getAsFile(); + if (file) { + handleFileAttachment(file); + } + return; + } + } + }); + } + + if (aiChatSend) { + aiChatSend.addEventListener('click', sendAiMessage); + } + + syncAiModelSelectorFromNative(); + updateSendButton(); + + if (aiChatAttach && aiFileInput) { + aiChatAttach.addEventListener('click', () => { + aiFileInput.click(); + }); + + aiFileInput.addEventListener('change', (e) => { + const file = e.target.files[0]; + if (file) handleFileAttachment(file); + }); + } + + if (aiChatClear) { + aiChatClear.addEventListener('click', () => { + if (confirm('Start a new chat?')) startNewChat(); + }); + } + + if (aiHelpSettingsBtn) { + aiHelpSettingsBtn.addEventListener('click', async () => { + if (aiHelpChat) aiHelpChat.style.display = 'none'; + if (aiHelpSetup) aiHelpSetup.style.display = 'flex'; + if (aiApiKeyForm) aiApiKeyForm.style.display = 'none'; + if (aiProviderGrid) aiProviderGrid.style.display = 'grid'; + await updateProviderStatuses(); + }); + } + + const aiNewChatBtn = document.getElementById('aiNewChatBtn'); + if (aiNewChatBtn) { + aiNewChatBtn.addEventListener('click', startNewChat); + } + + const aiSidebarToggle = document.getElementById('aiSidebarToggle'); + if (aiSidebarToggle) { + aiSidebarToggle.addEventListener('click', () => { + const sidebar = document.getElementById('aiChatSidebar'); + if (sidebar) { + sidebar.classList.toggle('collapsed'); + } + }); + } + + const aiSidebarExpand = document.getElementById('aiSidebarExpand'); + if (aiSidebarExpand) { + aiSidebarExpand.addEventListener('click', () => { + const sidebar = document.getElementById('aiChatSidebar'); + if (sidebar) { + sidebar.classList.remove('collapsed'); + } + }); + } + + const aiHelpBtn = document.getElementById('aiHelpBtn'); + const dockAiHelp = document.getElementById('dockAiHelp'); + + if (aiHelpBtn) { + aiHelpBtn.addEventListener('click', (e) => { + e.preventDefault(); + openAiHelpModal(); + }); + } + + if (dockAiHelp) { + dockAiHelp.addEventListener('click', (e) => { + e.preventDefault(); + openAiHelpModal(); + }); + } + + if (aiUndoBtn) { + aiUndoBtn.addEventListener('click', undoLastFileChange); + } + + if (aiUndoDismiss) { + aiUndoDismiss.addEventListener('click', hideUndoToast); + } + + if (aiAcceptAllChanges) { + aiAcceptAllChanges.addEventListener('click', acceptAllFileChanges); + } + + if (aiUndoAllChanges) { + aiUndoAllChanges.addEventListener('click', undoAllFileChanges); + } + + if (aiFileChangesToggle && aiFileChangesBar) { + aiFileChangesToggle.addEventListener('click', () => { + aiFileChangesBar.classList.toggle('collapsed'); + }); + } + + if (aiConfirmAllow) { + aiConfirmAllow.addEventListener('click', handleConfirmAllow); + } + + if (aiConfirmDeny) { + aiConfirmDeny.addEventListener('click', handleConfirmDeny); + } + + window.openAiHelpModal = openAiHelpModal; + window.closeAiHelpModal = closeAiHelpModal; + + const reinstallModal = document.getElementById('reinstallModal'); + const reinstallModalClose = document.getElementById('reinstallModalClose'); + const reinstallCancelBtn = document.getElementById('reinstallCancelBtn'); + const reinstallConfirmBtn = document.getElementById('reinstallConfirmBtn'); + const reinstallConfirmNo = document.getElementById('reinstallConfirmNo'); + const reinstallConfirmYes = document.getElementById('reinstallConfirmYes'); + const reinstallDoneBtn = document.getElementById('reinstallDoneBtn'); + const reinstallErrorClose = document.getElementById('reinstallErrorClose'); + const reinstallDefaultView = document.getElementById('reinstallDefaultView'); + const reinstallConfirmView = document.getElementById('reinstallConfirmView'); + const reinstallProgressView = document.getElementById('reinstallProgressView'); + const reinstallSuccessView = document.getElementById('reinstallSuccessView'); + const reinstallErrorView = document.getElementById('reinstallErrorView'); + const reinstallErrorDesc = document.getElementById('reinstallErrorDesc'); + + function reinstallShowView(viewId) { + [reinstallDefaultView, reinstallConfirmView, reinstallProgressView, reinstallSuccessView, reinstallErrorView].forEach(v => { + if (v) v.style.display = 'none'; + }); + const target = document.getElementById(viewId); + if (target) target.style.display = ''; + } + + function openReinstallModal() { + if (!reinstallModal) return; + if (!hasPerm('server_reinstall')) { + return; + } + reinstallShowView('reinstallDefaultView'); + showModalElement(reinstallModal); + } + + function closeReinstallModal() { + if (!reinstallModal) return; + animateClose(reinstallModal); + } + + if (reinstallModalClose) reinstallModalClose.addEventListener('click', closeReinstallModal); + if (reinstallCancelBtn) reinstallCancelBtn.addEventListener('click', closeReinstallModal); + if (reinstallErrorClose) reinstallErrorClose.addEventListener('click', closeReinstallModal); + if (reinstallDoneBtn) reinstallDoneBtn.addEventListener('click', closeReinstallModal); + + if (reinstallConfirmBtn) { + reinstallConfirmBtn.addEventListener('click', () => { + reinstallShowView('reinstallConfirmView'); + }); + } + + if (reinstallConfirmNo) { + reinstallConfirmNo.addEventListener('click', () => { + reinstallShowView('reinstallDefaultView'); + }); + } + + if (reinstallConfirmYes) { + reinstallConfirmYes.addEventListener('click', async () => { + if (!hasPerm('server_reinstall')) { + reinstallShowView('reinstallDefaultView'); + closeReinstallModal(); + return; + } + + reinstallShowView('reinstallProgressView'); + + try { + const res = await fetch(`/api/servers/${encodeURIComponent(bot)}/reinstall`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}) + }); + + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + const errMsg = data.error || 'Reinstall failed. Please try again later.'; + if (reinstallErrorDesc) reinstallErrorDesc.textContent = errMsg; + reinstallShowView('reinstallErrorView'); + return; + } + + reinstallShowView('reinstallSuccessView'); + } catch (err) { + console.error('[reinstall] Network error:', err); + if (reinstallErrorDesc) reinstallErrorDesc.textContent = 'Network error. Please check your connection and try again.'; + reinstallShowView('reinstallErrorView'); + } + }); + } + + if (reinstallModal) { + reinstallModal.addEventListener('click', (e) => { + if (e.target === reinstallModal) closeReinstallModal(); + }); + } + + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && reinstallModal && reinstallModal.classList.contains('show')) { + closeReinstallModal(); + } + }); + + const subdomainsModal = document.getElementById('subdomainsModal'); + const subdomainsModalClose = document.getElementById('subdomainsModalClose'); + const subdomainsList = document.getElementById('subdomainsList'); + const subdomainsAddBtn = document.getElementById('subdomainsAddBtn'); + const subdomainsRefreshBtn = document.getElementById('subdomainsRefreshBtn'); + + const subdomainCreateModal = document.getElementById('subdomainCreateModal'); + const subdomainCreateClose = document.getElementById('subdomainCreateClose'); + const subdomainInput = document.getElementById('subdomainInput'); + const subdomainCreateCancel = document.getElementById('subdomainCreateCancel'); + const subdomainVerifyBtn = document.getElementById('subdomainVerifyBtn'); + const subdomainVerificationResult = document.getElementById('subdomainVerificationResult'); + const overlay = document.getElementById('modalOverlay') || document.querySelector('.activity-modal-overlay') || document.createElement('div'); + + function openSubdomainsModal() { + if (!subdomainsModal) return; + showModalElement(subdomainsModal); + afterModalPaint(() => loadSubdomains()); + } + + function closeSubdomainsModal() { + if (!subdomainsModal) return; + animateClose(subdomainsModal); + } + + if (subdomainsModalClose) { + subdomainsModalClose.addEventListener('click', closeSubdomainsModal); + } + + if (subdomainsRefreshBtn) { + subdomainsRefreshBtn.addEventListener('click', loadSubdomains); + } + + if (subdomainsAddBtn) { + subdomainsAddBtn.addEventListener('click', () => { + openSubdomainCreateModal(); + }); + } + + async function loadSubdomains() { + if (!subdomainsList) return; + subdomainsList.innerHTML = `
    Loading subdomains...
    `; + try { + const res = await fetch(`/api/subdomains/${encodeURIComponent(bot)}`); + if (!res.ok) { + if (res.status === 403) { + subdomainsList.innerHTML = `
    Access Denied
    `; + } else { + subdomainsList.innerHTML = `
    Failed to load subdomains
    `; + } + return; + } + const data = await res.json(); + renderSubdomains(data.subdomains || []); + } catch (e) { + console.error(e); + subdomainsList.innerHTML = `
    Network error
    `; + } + } + + function renderSubdomains(list) { + if (!list || list.length === 0) { + subdomainsList.innerHTML = `
    No subdomains found
    `; + return; + } + subdomainsList.innerHTML = ''; + + list.sort((a, b) => new Date(b.created_at) - new Date(a.created_at)); + + list.forEach(sub => { + const row = document.createElement('div'); + row.className = 'subdomain-card'; + + row.addEventListener('mousemove', e => { + const rect = row.getBoundingClientRect(); + const x = e.clientX - rect.left; + const y = e.clientY - rect.top; + row.style.setProperty('--mouse-x', `${x}px`); + row.style.setProperty('--mouse-y', `${y}px`); + }); + + let statusBadgeClass = 'pending'; + let statusIcon = 'fa-circle-notch fa-spin'; + let statusText = 'Pending'; + + if (sub.status === 'approved') { + statusBadgeClass = 'approved'; + statusIcon = 'fa-check'; + statusText = 'Active'; + } else if (sub.status === 'canceled') { + statusBadgeClass = 'canceled'; + statusIcon = 'fa-xmark'; + statusText = 'Invalid DNS'; + } + + let actionsHtml = ` + + `; + + if (sub.status === 'pending') { + actionsHtml = ` + + ${actionsHtml} + `; + } + + row.innerHTML = ` +
    +
    + +
    +
    +
    ${escapeHtml(sub.domain)}
    +
    Added ${new Date(sub.created_at).toLocaleString()}
    +
    +
    + ${escapeHtml(statusText)} +
    +
    + + `; + const delBtn = row.querySelector('.delete-subdomain'); + if (delBtn) delBtn.addEventListener('click', () => deleteSubdomain(sub.id, sub.domain)); + + const verBtn = row.querySelector('.verify-subdomain'); + if (verBtn) verBtn.addEventListener('click', () => verifySubdomain(sub.id)); + + subdomainsList.appendChild(row); + }); + } + + async function verifySubdomain(id) { + const btn = document.querySelector(`.verify-subdomain[data-id="${id}"] i`); + if (btn) btn.className = 'fa-solid fa-spinner fa-spin'; + + try { + const res = await fetch(`/api/subdomains/${encodeURIComponent(bot)}/${id}/verify`, { method: 'POST' }); + const data = await res.json(); + if (res.ok) { + loadSubdomains(); + } else { + alert(data.error || 'Verification failed'); + loadSubdomains(); + } + } catch (e) { + console.error(e); + loadSubdomains(); + } + } + + async function deleteSubdomain(id, domain) { + if (!confirm(`Delete subdomain ${domain}? This cannot be undone.`)) return; + try { + const res = await fetch(`/api/subdomains/${encodeURIComponent(bot)}/${id}`, { method: 'DELETE' }); + if (!res.ok) throw new Error('Failed to delete'); + loadSubdomains(); + } catch (e) { + alert('Error deleting subdomain: ' + e.message); + } + } + + function openSubdomainCreateModal() { + if (!subdomainCreateModal) return; + subdomainsModal.classList.remove('show'); + subdomainsModal.style.display = 'none'; + subdomainsModal.setAttribute('aria-hidden', 'true'); + showModalElement(subdomainCreateModal); + + if (subdomainInput) subdomainInput.value = ''; + if (subdomainVerificationResult) { + subdomainVerificationResult.style.display = 'none'; + subdomainVerificationResult.innerHTML = ''; + } + if (subdomainVerifyBtn) { + subdomainVerifyBtn.disabled = false; + subdomainVerifyBtn.innerHTML = ' Verify & Add'; + } + } + + function closeSubdomainCreateModal() { + if (!subdomainCreateModal) return; + animateClose(subdomainCreateModal, () => { + if (subdomainsModal) { + showModalElement(subdomainsModal); + } + }); + } + + if (subdomainCreateClose) subdomainCreateClose.addEventListener('click', closeSubdomainCreateModal); + if (subdomainCreateCancel) subdomainCreateCancel.addEventListener('click', closeSubdomainCreateModal); + + if (subdomainVerifyBtn) { + subdomainVerifyBtn.addEventListener('click', async () => { + const domain = subdomainInput.value.trim(); + if (!domain) return; + + try { + subdomainVerifyBtn.disabled = true; + subdomainVerifyBtn.innerHTML = ' Verifying...'; + + const res = await fetch(`/api/subdomains/${encodeURIComponent(bot)}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ domain }) + }); + + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + let errorMsg = data.error || 'Failed to add subdomain'; + if (data.details) { + errorMsg += `
    ${escapeHtml(data.details)}`; + } + showVerificationError(errorMsg); + subdomainVerifyBtn.disabled = false; + subdomainVerifyBtn.innerHTML = ' Verify & Add'; + return; + } + + closeSubdomainCreateModal(); + loadSubdomains(); + + } catch (e) { + console.error(e); + showVerificationError('Network error'); + subdomainVerifyBtn.disabled = false; + subdomainVerifyBtn.innerHTML = ' Verify & Add'; + } + }); + } + + function showVerificationError(msg) { + if (!subdomainVerificationResult) return; + subdomainVerificationResult.style.display = 'block'; + subdomainVerificationResult.innerHTML = `
    ${escapeHtml(msg)}
    `; + } +})(); diff --git a/public/js/dashboard-assistant.js b/public/js/dashboard-assistant.js new file mode 100644 index 0000000..d2322ba --- /dev/null +++ b/public/js/dashboard-assistant.js @@ -0,0 +1,4927 @@ +(function () { + const AudioContextClass = window.AudioContext || window.webkitAudioContext || null; + const SpeechRecognitionClass = window.SpeechRecognition || window.webkitSpeechRecognition || null; + const TARGET_PCM_SAMPLE_RATE = 16000; + const ACCESSIBLE_SERVER_CACHE_TTL_MS = 5 * 60 * 1000; + const ASSISTANT_PROVIDER_META = Object.freeze({ + groq: { + label: "Groq", + tokenLabel: "Groq API key", + emptyText: "No Groq key has been saved yet.", + placeholder: "Paste your Groq API key", + }, + google: { + label: "Google AI Studio", + tokenLabel: "Google AI Studio API key", + emptyText: "No Google AI Studio key has been saved yet.", + placeholder: "Paste your Google AI Studio API key", + }, + }); + const TECHNICAL_DIGIT_WORDS = Object.freeze({ + zero: "0", + oh: "0", + o: "0", + one: "1", + won: "1", + two: "2", + too: "2", + to: "2", + three: "3", + tree: "3", + four: "4", + for: "4", + five: "5", + six: "6", + seven: "7", + eight: "8", + ate: "8", + nine: "9", + ten: "10", + eleven: "11", + twelve: "12", + }); + + function getInitialSpeechLanguage() { + const locale = String((navigator.languages && navigator.languages[0]) || navigator.language || "").trim(); + if (!locale) return "en-US"; + return /^en(?:-|$)/i.test(locale) ? locale : "en-US"; + } + + const state = { + open: false, + bootstrapLoaded: false, + bootstrapPromise: null, + bootstrapRequestId: 0, + requestInFlight: false, + transcribing: false, + recording: false, + speaking: false, + voicePrimed: false, + chatId: null, + canConfigure: false, + isAdmin: false, + allowNormalUsers: false, + configured: false, + actionTokens: {}, + savingAccessSetting: false, + tokenFieldUsesStoredValue: false, + mediaRecorder: null, + mediaStream: null, + mediaMimeType: "", + mediaChunks: [], + audioContext: null, + audioSourceNode: null, + audioProcessorNode: null, + audioMonitorGain: null, + audioFilterNodes: [], + pcmChunks: [], + pcmSampleRate: 44100, + recognition: null, + recognitionMode: false, + recognitionFinalTranscript: "", + recognitionInterimTranscript: "", + recognitionStopping: false, + recognitionErrorMessage: "", + recognitionPreviewOnly: false, + recognitionFallbackTranscript: "", + lastAssistantReply: "", + provider: "groq", + providers: [], + preferredSpeechLang: getInitialSpeechLanguage(), + recordingSessionId: 0, + chatGeneration: 0, + lastSubmittedTranscript: "", + lastSubmittedAt: 0, + pendingDeleteServer: null, + deletingServer: false, + accessibleServerDirectory: [], + accessibleServerDirectoryFetchedAt: 0, + accessibleServerDirectoryPromise: null, + }; + + const els = {}; + + function $(id) { + return document.getElementById(id); + } + + function getProviderMeta(providerId) { + return ASSISTANT_PROVIDER_META[String(providerId || "").trim().toLowerCase()] || ASSISTANT_PROVIDER_META.groq; + } + + function getSelectedProviderState(providerId = state.provider) { + return state.providers.find((item) => item && item.id === providerId) || null; + } + + function getStoredTokenFieldValue(providerId = state.provider) { + const providerState = getSelectedProviderState(providerId); + if (!providerState?.configured) return ""; + return String(providerState.obscuredValue || ""); + } + + function populateStoredTokenField(providerId = state.provider) { + if (!els.tokenInput) return; + const nextValue = getStoredTokenFieldValue(providerId); + els.tokenInput.value = nextValue; + state.tokenFieldUsesStoredValue = !!nextValue; + els.tokenInput.dataset.storedValue = state.tokenFieldUsesStoredValue ? "1" : ""; + } + + function clearStoredTokenFieldIfNeeded() { + if (!els.tokenInput || !state.tokenFieldUsesStoredValue) return; + els.tokenInput.value = ""; + state.tokenFieldUsesStoredValue = false; + els.tokenInput.dataset.storedValue = ""; + } + + function syncStoredTokenField(force = false) { + if (!els.tokenInput) return; + const preserveTypedValue = !force + && document.activeElement === els.tokenInput + && !state.tokenFieldUsesStoredValue + && !!String(els.tokenInput.value || "").trim(); + if (preserveTypedValue) return; + populateStoredTokenField(state.provider); + } + + function updateTokenStateText() { + if (!els.tokenState) return; + const selectedProvider = getSelectedProviderState(state.provider); + els.tokenState.textContent = selectedProvider?.configured + ? `${getProviderMeta(state.provider).label} key saved.` + : getProviderMeta(state.provider).emptyText; + } + + function syncAssistantAccessUi() { + if (!els.userAccessToggle) return; + els.userAccessToggle.checked = !!state.allowNormalUsers; + els.userAccessToggle.disabled = !state.canConfigure || state.savingAccessSetting; + } + + function supportsSpeechSynthesis() { + return "speechSynthesis" in window && typeof window.SpeechSynthesisUtterance !== "undefined"; + } + + function supportsSpeechRecognition() { + return !!SpeechRecognitionClass; + } + + function isLocalhostHost() { + const host = String(location.hostname || "").trim().toLowerCase(); + return host === "localhost" || host === "127.0.0.1" || host === "::1"; + } + + function getMicrophoneCapabilityIssue() { + if (!navigator.mediaDevices?.getUserMedia && !supportsSpeechRecognition()) { + if (!window.isSecureContext && !isLocalhostHost()) { + return "Microphone access requires HTTPS or localhost. Safari and other browsers will not show the permission prompt on plain HTTP."; + } + return "This browser does not expose microphone access on this page."; + } + + if (!supportsSpeechRecognition() && typeof MediaRecorder === "undefined" && !AudioContextClass) { + return "This browser cannot capture audio for voice input here."; + } + + return null; + } + + function inferAudioExtension(mimeType) { + const value = String(mimeType || "").toLowerCase(); + if (value.includes("wav")) return "wav"; + if (value.includes("mp4") || value.includes("m4a")) return "m4a"; + if (value.includes("ogg")) return "ogg"; + if (value.includes("mpeg") || value.includes("mp3")) return "mp3"; + return "webm"; + } + + function clampSample(sample) { + if (sample > 1) return 1; + if (sample < -1) return -1; + return sample; + } + + function mergePcmChunks(chunks) { + const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0); + const merged = new Float32Array(totalLength); + let offset = 0; + for (const chunk of chunks) { + merged.set(chunk, offset); + offset += chunk.length; + } + return merged; + } + + function encodeWavBlob(pcm, sampleRate) { + const buffer = new ArrayBuffer(44 + pcm.length * 2); + const view = new DataView(buffer); + + function writeString(offset, value) { + for (let i = 0; i < value.length; i += 1) { + view.setUint8(offset + i, value.charCodeAt(i)); + } + } + + writeString(0, "RIFF"); + view.setUint32(4, 36 + pcm.length * 2, true); + writeString(8, "WAVE"); + writeString(12, "fmt "); + view.setUint32(16, 16, true); + view.setUint16(20, 1, true); + view.setUint16(22, 1, true); + view.setUint32(24, sampleRate, true); + view.setUint32(28, sampleRate * 2, true); + view.setUint16(32, 2, true); + view.setUint16(34, 16, true); + writeString(36, "data"); + view.setUint32(40, pcm.length * 2, true); + + let offset = 44; + for (let i = 0; i < pcm.length; i += 1) { + const sample = clampSample(pcm[i]); + view.setInt16(offset, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true); + offset += 2; + } + + return new Blob([buffer], { type: "audio/wav" }); + } + + function trimPcmSilence(pcm, sampleRate, threshold = 0.01, paddingMs = 120) { + if (!(pcm instanceof Float32Array) || !pcm.length) return pcm; + + let start = -1; + let end = -1; + for (let index = 0; index < pcm.length; index += 1) { + if (Math.abs(pcm[index]) >= threshold) { + if (start === -1) start = index; + end = index; + } + } + + if (start === -1 || end === -1) { + return pcm; + } + + const padding = Math.max(0, Math.round((sampleRate * paddingMs) / 1000)); + const safeStart = Math.max(0, start - padding); + const safeEnd = Math.min(pcm.length, end + padding + 1); + return pcm.slice(safeStart, safeEnd); + } + + function normalizePcm(pcm) { + if (!(pcm instanceof Float32Array) || !pcm.length) return pcm; + + let peak = 0; + for (let index = 0; index < pcm.length; index += 1) { + const value = Math.abs(pcm[index]); + if (value > peak) peak = value; + } + + if (!peak || peak >= 0.92) return pcm; + + const gain = Math.min(4, 0.92 / peak); + const normalized = new Float32Array(pcm.length); + for (let index = 0; index < pcm.length; index += 1) { + normalized[index] = clampSample(pcm[index] * gain); + } + return normalized; + } + + function resamplePcmLinear(pcm, fromRate, toRate) { + if (!(pcm instanceof Float32Array) || !pcm.length) return pcm; + if (!fromRate || !toRate || fromRate === toRate) return pcm; + + const ratio = fromRate / toRate; + const targetLength = Math.max(1, Math.round(pcm.length / ratio)); + const resampled = new Float32Array(targetLength); + + for (let index = 0; index < targetLength; index += 1) { + const sourceIndex = index * ratio; + const leftIndex = Math.floor(sourceIndex); + const rightIndex = Math.min(pcm.length - 1, leftIndex + 1); + const weight = sourceIndex - leftIndex; + resampled[index] = (pcm[leftIndex] * (1 - weight)) + (pcm[rightIndex] * weight); + } + + return resampled; + } + + function prepareSpeechPcm(chunks, sampleRate) { + let pcm = mergePcmChunks(chunks); + pcm = trimPcmSilence(pcm, sampleRate); + pcm = normalizePcm(pcm); + pcm = resamplePcmLinear(pcm, sampleRate, TARGET_PCM_SAMPLE_RATE); + return { + pcm, + sampleRate: TARGET_PCM_SAMPLE_RATE, + }; + } + + function getPreferredTranscriptionLanguage() { + const locale = String(state.preferredSpeechLang || "").trim().toLowerCase(); + if (!locale) return ""; + const primary = locale.split(/[-_]/)[0]; + return primary === "en" ? "en" : ""; + } + + function buildTranscriptionPrompt() { + return [ + "The user is speaking to ADPanel Assistant.", + "Transcribe the speech accurately and literally, keeping technical product words intact.", + "The user may speak English with a non-native accent, so prefer technical dashboard vocabulary over generic words when the audio is close.", + "Important product terms may include: ADPanel, Hey ADPanel, Groq, NGINX, systemctl, Redis, MySQL, server.properties, 2FA, recovery codes.", + "The user may also talk about nodes, templates, ports, host port, RAM, CPU, swap, storage, backups, schedules, server creation, Minecraft, Paper, Purpur, Velocity, BungeeCord, Node.js, Python, and Discord bot templates.", + "Prefer numeric digits for ports, versions, RAM, CPU, storage sizes, and 2FA.", + "If a spoken word sounds like to or too in a numeric technical context, prefer the digit 2.", + "If the user says port two five five six five, write 25565.", + "In ADPanel context, prefer node or nodes over note or notes.", + "Prefer the product name ADPanel over similar-sounding words." + ].join(" "); + } + + function normalizeTechnicalUnits(text) { + return String(text || "") + .replace(/\bg\s*b\b/gi, "GB") + .replace(/\bm\s*b\b/gi, "MB") + .replace(/\bt\s*b\b/gi, "TB") + .replace(/\bgigabytes?\b/gi, "GB") + .replace(/\bgigs?\b/gi, "GB") + .replace(/\bmegabytes?\b/gi, "MB") + .replace(/\bterabytes?\b/gi, "TB"); + } + + function technicalWordToDigit(token) { + const lowered = String(token || "").trim().toLowerCase(); + if (!lowered) return null; + if (/^\d+$/.test(lowered)) return lowered; + return TECHNICAL_DIGIT_WORDS[lowered] || null; + } + + function convertTechnicalDigitSequence(raw) { + const parts = String(raw || "").trim().split(/[\s-]+/).filter(Boolean); + if (!parts.length || parts.length > 8) return null; + const converted = parts.map(technicalWordToDigit); + if (converted.some((entry) => !entry)) return null; + return converted.join(""); + } + + function normalizeTechnicalNumbers(text) { + let normalized = normalizeTechnicalUnits(text); + + normalized = normalized.replace( + /\b(host\s+port|hostport|port)\s+((?:(?:zero|oh|o|one|won|two|too|to|three|tree|four|for|five|six|seven|eight|ate|nine|\d+)[\s-]+){0,7}(?:zero|oh|o|one|won|two|too|to|three|tree|four|for|five|six|seven|eight|ate|nine|\d+))\b/gi, + (match, label, sequence) => { + const digits = convertTechnicalDigitSequence(sequence); + return digits ? `${label} ${digits}` : match; + } + ); + + normalized = normalized.replace( + /\b(zero|oh|o|one|won|two|too|to|three|tree|four|for|five|six|seven|eight|ate|nine|ten|eleven|twelve)\b(?=\s+(?:GB|MB|TB|RAM|CPU|cores?|ports?|schedules?|backups?|players?)\b)/gi, + (match) => technicalWordToDigit(match) || match + ); + + normalized = normalized.replace( + /\b(RAM|CPU|storage|swap|backups?|schedules?|players?)\s+(zero|oh|o|one|won|two|too|to|three|tree|four|for|five|six|seven|eight|ate|nine|ten|eleven|twelve)\b/gi, + (match, label, amount) => `${label} ${technicalWordToDigit(amount) || amount}` + ); + + normalized = normalized.replace(/\b(to|too|two)\s*fa\b/gi, "2FA"); + normalized = normalized.replace(/\b(to|too|two)\s*factor\b/gi, "2FA"); + normalized = normalized.replace(/\b2\s*factor\b/gi, "2FA"); + + return normalized; + } + + function normalizeRecognizedTranscript(value) { + let transcript = String(value || "").trim(); + if (!transcript) return ""; + + transcript = normalizeTechnicalNumbers(transcript) + .replace(/\b(?:a\.?\s*d\.?\s*panel|ad[\s-]*panel|adpannel|ad pannel)\b/gi, "ADPanel") + .replace(/\bhey\s+adpanel\b/gi, "Hey ADPanel") + .replace(/\bnotes\b/gi, "nodes") + .replace(/\bnote\b/gi, "node") + .replace(/\bnoads\b/gi, "nodes") + .replace(/\bwhat'?s\s+app\b/gi, "WhatsApp") + .replace(/\bserver\s+properties\b/gi, "server.properties") + .replace(/\b(?:two[\s-]*factor|two fa|2 fa)\b/gi, "2FA") + .replace(/\bgrok\b/gi, "Groq") + .replace(/\bgroq\b/gi, "Groq") + .replace(/\bnode\s*js\b/gi, "Node.js") + .replace(/\bdiscord\s+bot\b/gi, "Discord bot") + .replace(/\bram\b/gi, "RAM") + .replace(/\bcpu\b/gi, "CPU") + .replace(/\bnginx\b/gi, "NGINX"); + + return transcript.trim(); + } + + function getRecognitionTranscript() { + return normalizeRecognizedTranscript([ + state.recognitionFinalTranscript, + state.recognitionInterimTranscript, + ].filter(Boolean).join(" ")); + } + + function hasCapturedAudioActive() { + return !!state.mediaRecorder || !!state.audioContext || !!state.mediaStream; + } + + function scoreSpeechCandidate(transcript, confidence = 0) { + const text = String(transcript || "").toLowerCase(); + let score = Number.isFinite(confidence) ? confidence : 0; + if (/\bad\s*panel\b|\badpanel\b/.test(text)) score += 2; + if (/hey\s+ad\s*panel|hey\s+adpanel/.test(text)) score += 3; + if (/server\.?properties|systemctl|nginx|groq|2fa|redis|mysql/.test(text)) score += 0.75; + if (/\bnodes?\b|\btemplates?\b|\bhost port\b|\bram\b|\bcpu\b|\bstorage\b|\bminecraft\b|\bpaper\b|\bpurpur\b|\bnode\.?js\b/.test(text)) score += 1.1; + return score; + } + + function pickBestRecognitionAlternative(result) { + const alternatives = Array.from(result || []); + if (!alternatives.length) return ""; + alternatives.sort((left, right) => ( + scoreSpeechCandidate(right?.transcript, right?.confidence) - scoreSpeechCandidate(left?.transcript, left?.confidence) + )); + return String(alternatives[0]?.transcript || "").trim(); + } + + function setStatus(message, kind = "idle") { + if (!els.status) return; + els.status.dataset.state = kind; + els.status.textContent = message; + } + + function setNotice(message) { + if (!els.notice) return; + if (!message) { + els.notice.hidden = true; + els.notice.textContent = ""; + return; + } + els.notice.hidden = false; + els.notice.textContent = message; + } + + function setVoiceState(message) { + if (!els.voiceState) return; + els.voiceState.textContent = message; + } + + function syncAssistantLayout() { + const compactSetup = !state.configured; + const showBlockedEmptyState = compactSetup && !state.canConfigure; + const showAdminSetupOnly = compactSetup && state.canConfigure; + const showProviderOnly = !!els.config && !els.config.hidden; + + if (els.menu) { + els.menu.classList.toggle("dashboard-assistant-menu--setup", compactSetup); + } + + if (els.messages) { + els.messages.hidden = showAdminSetupOnly || showProviderOnly; + } + + if (els.composer) { + els.composer.hidden = compactSetup || showProviderOnly; + } + + if (els.reset) { + els.reset.hidden = compactSetup; + } + + if (els.notice) { + if (showBlockedEmptyState) { + els.notice.hidden = true; + els.notice.textContent = ""; + } else if (showProviderOnly) { + els.notice.hidden = true; + } else if (String(els.notice.textContent || "").trim()) { + els.notice.hidden = false; + } + } + } + + function syncProviderUi() { + const meta = getProviderMeta(state.provider); + if (els.providerSelect) { + els.providerSelect.value = state.provider; + } + if (els.tokenLabel) { + els.tokenLabel.textContent = meta.tokenLabel; + } + if (els.tokenInput) { + els.tokenInput.placeholder = meta.placeholder; + } + } + + function setTranscriptPreview(message) { + if (!els.transcript) return; + if (!message) { + els.transcript.hidden = true; + els.transcript.textContent = ""; + return; + } + els.transcript.hidden = false; + els.transcript.textContent = message; + } + + function openDeleteModal(action) { + if (!els.deleteModal) return; + state.pendingDeleteServer = action && typeof action === "object" ? action : null; + state.deletingServer = false; + const displayName = state.pendingDeleteServer?.displayName || state.pendingDeleteServer?.server || "—"; + if (els.deleteName) { + els.deleteName.textContent = displayName; + } + if (els.deleteSubtitle) { + els.deleteSubtitle.textContent = `Confirm deletion before the assistant removes "${displayName}".`; + } + if (els.deleteConfirm) { + els.deleteConfirm.disabled = false; + els.deleteConfirm.innerHTML = 'Delete server'; + } + els.deleteModal.classList.add("show"); + els.deleteModal.setAttribute("aria-hidden", "false"); + } + + function closeDeleteModal(force = false) { + if (!els.deleteModal || (state.deletingServer && !force)) return; + els.deleteModal.classList.remove("show"); + els.deleteModal.setAttribute("aria-hidden", "true"); + state.pendingDeleteServer = null; + } + + function updateComposerAvailability() { + const canUseVoice = state.configured && !state.requestInFlight && !state.transcribing; + if (els.mic) els.mic.disabled = !canUseVoice; + if (els.replay) els.replay.disabled = !state.lastAssistantReply || state.speaking; + if (els.reset) els.reset.disabled = !!(state.requestInFlight || state.transcribing || state.recording); + if (els.send) { + const canSendText = state.configured && !state.requestInFlight && !state.transcribing && !state.recording && + !!String(els.textInput?.value || "").trim(); + els.send.disabled = !canSendText; + } + if (els.textInput) { + els.textInput.disabled = !state.configured || state.requestInFlight || state.transcribing; + } + } + + function updateButtons() { + if (els.trigger) els.trigger.setAttribute("aria-expanded", String(state.open)); + if (els.menu) { + els.menu.hidden = !state.open; + els.menu.classList.toggle("is-open", state.open); + els.menu.setAttribute("aria-hidden", String(!state.open)); + } + + syncAssistantLayout(); + + if (els.mic) { + els.mic.classList.toggle("dashboard-assistant-voice-btn--recording", state.recording); + els.mic.innerHTML = state.recording + ? 'Stop and send' + : 'Tap to talk'; + els.mic.title = state.recording ? "Stop recording and send" : "Start voice input"; + } + + if (els.replay) { + els.replay.disabled = !state.lastAssistantReply || state.speaking; + } + + if (els.speakingIndicator) { + els.speakingIndicator.hidden = !state.speaking; + } + + updateComposerAvailability(); + } + + function getAssistantCopyButtonMarkup(copied = false) { + return copied + ? 'Copied' + : 'Copy'; + } + + function setAssistantCopyButtonState(button, copied = false) { + if (!(button instanceof HTMLElement)) return; + button.classList.toggle("is-copied", !!copied); + button.innerHTML = getAssistantCopyButtonMarkup(copied); + } + + function captureDocumentSelection() { + const selection = typeof window.getSelection === "function" ? window.getSelection() : null; + if (!selection || typeof selection.rangeCount !== "number") { + return { selection: null, ranges: [] }; + } + + const ranges = []; + for (let index = 0; index < selection.rangeCount; index += 1) { + try { + const range = selection.getRangeAt(index); + if (range) { + ranges.push(range.cloneRange()); + } + } catch { + } + } + + return { selection, ranges }; + } + + function restoreDocumentSelection(snapshot) { + const selection = snapshot?.selection; + const ranges = Array.isArray(snapshot?.ranges) ? snapshot.ranges : []; + if (!selection || typeof selection.removeAllRanges !== "function") { + return; + } + + try { + selection.removeAllRanges(); + ranges.forEach((range) => selection.addRange(range)); + } catch { + } + } + + function restoreFocusedElement(element) { + if (!(element instanceof HTMLElement) || typeof element.focus !== "function") { + return; + } + + try { + element.focus({ preventScroll: true }); + } catch { + try { + element.focus(); + } catch { + } + } + } + + function copyTextWithExecCommand(value) { + if (!document?.body || typeof document.execCommand !== "function") { + return false; + } + + const selectionSnapshot = captureDocumentSelection(); + const activeElement = document.activeElement instanceof HTMLElement ? document.activeElement : null; + const textarea = document.createElement("textarea"); + textarea.value = value; + textarea.setAttribute("aria-hidden", "true"); + textarea.setAttribute("tabindex", "-1"); + textarea.style.position = "fixed"; + textarea.style.top = "0"; + textarea.style.left = "-9999px"; + textarea.style.width = "1px"; + textarea.style.height = "1px"; + textarea.style.opacity = "0"; + textarea.style.pointerEvents = "none"; + textarea.style.fontSize = "16px"; + textarea.style.padding = "0"; + textarea.style.border = "0"; + textarea.style.outline = "0"; + textarea.style.boxShadow = "none"; + textarea.style.background = "transparent"; + textarea.style.whiteSpace = "pre-wrap"; + textarea.style.userSelect = "text"; + textarea.style.webkitUserSelect = "text"; + + document.body.appendChild(textarea); + + let copied = false; + try { + textarea.focus({ preventScroll: true }); + } catch { + textarea.focus(); + } + textarea.select(); + textarea.setSelectionRange(0, textarea.value.length); + + try { + copied = document.execCommand("copy"); + } catch { + copied = false; + } finally { + textarea.remove(); + restoreDocumentSelection(selectionSnapshot); + restoreFocusedElement(activeElement); + } + + if (copied) { + return true; + } + + const selectionFallback = captureDocumentSelection(); + const activeFallback = document.activeElement instanceof HTMLElement ? document.activeElement : null; + const copyNode = document.createElement("div"); + copyNode.textContent = value; + copyNode.setAttribute("aria-hidden", "true"); + copyNode.setAttribute("tabindex", "-1"); + copyNode.contentEditable = "true"; + copyNode.style.position = "fixed"; + copyNode.style.top = "0"; + copyNode.style.left = "-9999px"; + copyNode.style.opacity = "0"; + copyNode.style.pointerEvents = "none"; + copyNode.style.whiteSpace = "pre-wrap"; + copyNode.style.fontSize = "16px"; + copyNode.style.userSelect = "text"; + copyNode.style.webkitUserSelect = "text"; + + document.body.appendChild(copyNode); + + try { + const range = document.createRange(); + range.selectNodeContents(copyNode); + const selection = typeof window.getSelection === "function" ? window.getSelection() : null; + if (selection) { + selection.removeAllRanges(); + selection.addRange(range); + } + copyNode.focus({ preventScroll: true }); + copied = document.execCommand("copy"); + } catch { + copied = false; + } finally { + copyNode.remove(); + restoreDocumentSelection(selectionFallback); + restoreFocusedElement(activeFallback); + } + + return copied; + } + + async function copyAssistantText(text, button) { + const value = String(text || "").trim(); + if (!value) return false; + + let copied = copyTextWithExecCommand(value); + + if (!copied && navigator.clipboard?.writeText) { + try { + await navigator.clipboard.writeText(value); + copied = true; + } catch { + } + } + + if (button) { + setAssistantCopyButtonState(button, copied); + if (button._assistantCopyTimer) { + window.clearTimeout(button._assistantCopyTimer); + } + button._assistantCopyTimer = window.setTimeout(() => { + setAssistantCopyButtonState(button, false); + }, copied ? 1800 : 1200); + } + + setStatus(copied ? "Reply copied." : "Could not copy that reply.", copied ? "idle" : "warning"); + return copied; + } + + function appendAssistantBubbleContent(bubble, text) { + const content = String(text || ""); + const urlPattern = /https?:\/\/[^\s]+/g; + let lastIndex = 0; + let matched = false; + + content.replace(urlPattern, (match, offset) => { + matched = true; + if (offset > lastIndex) { + bubble.appendChild(document.createTextNode(content.slice(lastIndex, offset))); + } + + const link = document.createElement("a"); + link.href = match; + link.target = "_blank"; + link.rel = "noopener noreferrer"; + link.className = "dashboard-assistant-message-link"; + link.textContent = match; + bubble.appendChild(link); + + lastIndex = offset + match.length; + return match; + }); + + if (!matched) { + bubble.textContent = content; + return; + } + + if (lastIndex < content.length) { + bubble.appendChild(document.createTextNode(content.slice(lastIndex))); + } + } + + function createMessageNode(message) { + const role = message.role === "user" ? "user" : "assistant"; + const wrapper = document.createElement("article"); + wrapper.className = `dashboard-assistant-message dashboard-assistant-message--${role}`; + + const bubble = document.createElement("div"); + bubble.className = "dashboard-assistant-message-bubble"; + const bubbleText = String(message.content || "").trim() || (role === "assistant" ? "Done." : ""); + appendAssistantBubbleContent(bubble, bubbleText); + if (role === "assistant") { + bubble.title = "Select text or use copy."; + } + wrapper.appendChild(bubble); + + const metaRow = document.createElement("div"); + metaRow.className = "dashboard-assistant-message-meta-row"; + + const meta = document.createElement("div"); + meta.className = "dashboard-assistant-message-meta"; + const createdAt = message.created_at ? new Date(message.created_at) : null; + meta.textContent = createdAt && !Number.isNaN(createdAt.getTime()) + ? `${role === "user" ? "You said" : "Assistant"} • ${createdAt.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}` + : role === "user" ? "You said" : "Assistant"; + metaRow.appendChild(meta); + + if (role === "assistant" && bubbleText) { + const copyButton = document.createElement("button"); + copyButton.type = "button"; + copyButton.className = "dashboard-assistant-message-copy"; + copyButton.setAttribute("aria-label", "Copy assistant reply"); + setAssistantCopyButtonState(copyButton, false); + copyButton.addEventListener("click", async (event) => { + event.preventDefault(); + event.stopPropagation(); + await copyAssistantText(bubbleText, copyButton); + }); + metaRow.appendChild(copyButton); + } + + wrapper.appendChild(metaRow); + + return wrapper; + } + + function renderMessages(messages) { + if (!els.messages) return; + els.messages.innerHTML = ""; + + const blockedByMissingProvider = !state.configured && !state.canConfigure; + const sourceMessages = blockedByMissingProvider ? [] : (Array.isArray(messages) ? messages : []); + const visibleMessages = sourceMessages.filter((message) => + message && (message.role === "user" || message.role === "assistant") + ); + + const lastAssistant = [...visibleMessages].reverse().find((message) => message.role === "assistant"); + state.lastAssistantReply = lastAssistant ? String(lastAssistant.content || "").trim() : ""; + + if (!visibleMessages.length) { + const empty = document.createElement("div"); + empty.className = "dashboard-assistant-empty"; + const activeMeta = getProviderMeta(state.provider); + empty.textContent = state.configured + ? "Start a conversation." + : state.canConfigure + ? `Save a ${activeMeta.label} API key to unlock voice input, context-aware chat, and spoken replies.` + : "Your admin didn't put an API Key."; + els.messages.appendChild(empty); + updateButtons(); + return; + } + + visibleMessages.forEach((message) => { + els.messages.appendChild(createMessageNode(message)); + }); + els.messages.scrollTop = els.messages.scrollHeight; + updateButtons(); + } + + function appendMessageToUi(message) { + if (!els.messages) return; + if (els.messages.querySelector(".dashboard-assistant-empty")) { + els.messages.innerHTML = ""; + } + els.messages.appendChild(createMessageNode(message)); + els.messages.scrollTop = els.messages.scrollHeight; + if (message?.role === "assistant") { + state.lastAssistantReply = String(message.content || "").trim(); + } + } + + function countAssistantMessagesInUi() { + if (!els.messages) return 0; + return els.messages.querySelectorAll(".dashboard-assistant-message--assistant").length; + } + + function positionMenu() { + if (!state.open || !els.menu || !els.trigger) return; + const triggerRect = els.trigger.getBoundingClientRect(); + const preferredWidth = state.configured ? 580 : 430; + const menuWidth = Math.min(preferredWidth, window.innerWidth - 24); + const leftBias = 150; + + // 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)); + + els.menu.style.width = `${menuWidth}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'; + } + + function stopSpeaking() { + if (!supportsSpeechSynthesis()) return; + try { + window.speechSynthesis.cancel(); + } catch { + } + state.speaking = false; + updateButtons(); + } + + function getPreferredVoiceLangs() { + const langs = []; + const normalizedPreferred = String(state.preferredSpeechLang || "en-US").trim().toLowerCase(); + if (normalizedPreferred) langs.push(normalizedPreferred); + if (normalizedPreferred.includes("-")) langs.push(normalizedPreferred.split("-")[0]); + langs.push("en-us", "en-gb", "en"); + return Array.from(new Set(langs.filter(Boolean))); + } + + function scoreAssistantVoice(voice) { + const name = String(voice?.name || "").trim().toLowerCase(); + const lang = String(voice?.lang || "").trim().toLowerCase(); + let score = 0; + + const preferredLangs = getPreferredVoiceLangs(); + const exactIndex = preferredLangs.indexOf(lang); + if (exactIndex >= 0) { + score += 160 - (exactIndex * 12); + } else { + const partialIndex = preferredLangs.findIndex((candidate) => candidate && lang.startsWith(candidate)); + if (partialIndex >= 0) { + score += 120 - (partialIndex * 10); + } + } + + if (/^en(?:-|$)/.test(lang)) score += 24; + if (voice?.localService) score += 18; + if (voice?.default) score += 10; + + if (/\bsiri\b/.test(name)) score += 280; + if (/\bsamantha\b/.test(name)) score += 220; + if (/\b(ava|allison|serena|karen|moira|tessa)\b/.test(name)) score += 190; + if (/\b(jenny|aria)\b/.test(name)) score += 180; + if (/\bdaniel\b/.test(name)) score += 150; + if (/\bgoogle us english\b/.test(name)) score += 170; + if (/\b(microsoft .+ online|natural|neural|enhanced|premium)\b/.test(name)) score += 70; + + if (/\b(whisper|zarvox|bad news|good news|bells|boing|bubble|cellos|fred|junior|pipe organ|superstar|trinoids)\b/.test(name)) { + score -= 320; + } + + return score; + } + + function findPreferredVoice() { + if (!supportsSpeechSynthesis()) return null; + const voices = window.speechSynthesis.getVoices(); + if (!Array.isArray(voices) || !voices.length) return null; + + return voices + .slice() + .sort((left, right) => scoreAssistantVoice(right) - scoreAssistantVoice(left))[0] || null; + } + + function primeSpeechSynthesis() { + if (!supportsSpeechSynthesis() || state.voicePrimed) return; + try { + window.speechSynthesis.getVoices(); + const utterance = new window.SpeechSynthesisUtterance(" "); + utterance.volume = 0; + utterance.rate = 1; + utterance.pitch = 1; + window.speechSynthesis.speak(utterance); + window.speechSynthesis.cancel(); + state.voicePrimed = true; + } catch { + } + } + + function speakAssistantReply(text) { + const message = String(text || "").trim(); + if (!message || !supportsSpeechSynthesis()) return false; + + stopSpeaking(); + + const utterance = new window.SpeechSynthesisUtterance(message); + const voice = findPreferredVoice(); + if (voice) { + utterance.voice = voice; + utterance.lang = voice.lang; + } else { + utterance.lang = state.preferredSpeechLang || "en-US"; + } + utterance.rate = 0.96; + utterance.pitch = 1.02; + utterance.volume = 1; + + utterance.onstart = () => { + state.speaking = true; + setVoiceState("Speaking response..."); + updateButtons(); + }; + utterance.onend = () => { + state.speaking = false; + setVoiceState(state.configured ? "Voice replies are on." : "Voice replies are unavailable."); + updateButtons(); + }; + utterance.onerror = () => { + state.speaking = false; + setVoiceState("Voice playback could not start in this browser."); + updateButtons(); + }; + + try { + window.speechSynthesis.speak(utterance); + return true; + } catch { + state.speaking = false; + updateButtons(); + return false; + } + } + + function applyBootstrap(data, options = {}) { + const preserveRenderedMessages = !!options.preserveRenderedMessages; + state.bootstrapLoaded = true; + state.bootstrapPromise = null; + const nextChatId = data.chat?.id || null; + if (state.chatId && nextChatId && state.chatId !== nextChatId) { + state.chatGeneration += 1; + state.lastSubmittedTranscript = ""; + state.lastSubmittedAt = 0; + state.recognitionFallbackTranscript = ""; + state.recognitionFinalTranscript = ""; + state.recognitionInterimTranscript = ""; + setTranscriptPreview(""); + } + state.chatId = nextChatId; + state.canConfigure = !!data.canConfigure; + if (Object.prototype.hasOwnProperty.call(data || {}, "allowNormalUsers")) { + state.allowNormalUsers = !!data.allowNormalUsers; + } + if (data.user) { + state.isAdmin = !!data.user.admin; + } + state.configured = !!data.configured; + state.provider = String(data.provider || state.provider || "groq").trim().toLowerCase() || "groq"; + state.providers = Array.isArray(data.providers) ? data.providers : []; + state.actionTokens = data.actionTokens || {}; + syncProviderUi(); + syncStoredTokenField(true); + updateTokenStateText(); + syncAssistantAccessUi(); + + if (els.configToggle) { + els.configToggle.hidden = !state.canConfigure || !state.configured; + } + + if (els.config) { + const shouldShowConfig = state.canConfigure && !state.configured; + els.config.hidden = !shouldShowConfig; + } + + const capabilityIssue = getMicrophoneCapabilityIssue(); + if (!state.configured && !state.canConfigure) { + setNotice(""); + } else if (capabilityIssue) { + setNotice(capabilityIssue); + } else { + setNotice(""); + } + + if (!preserveRenderedMessages) { + renderMessages(data.messages || []); + } else { + updateButtons(); + } + warmAccessibleServerDirectory(); + updateButtons(); + if (state.open) { + positionMenu(); + } + setVoiceState( + supportsSpeechSynthesis() + ? "Voice replies are on." + : "Voice playback is not available in this browser." + ); + setStatus( + state.recording + ? "Listening..." + : state.transcribing + ? "Transcribing your recording..." + : state.requestInFlight + ? "Assistant is working..." + : state.configured + ? "Voice assistant ready." + : state.canConfigure + ? `Save a ${getProviderMeta(state.provider).label} key to continue.` + : "No AI provider is configured.", + state.recording + ? "recording" + : state.transcribing + ? "transcribing" + : state.requestInFlight + ? "working" + : state.configured + ? "idle" + : "warning" + ); + } + + async function fetchJson(url, options) { + const response = await fetch(url, Object.assign({ credentials: "include" }, options || {})); + const data = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(data.error || data.message || "Request failed."); + } + return data; + } + + async function ensureBootstrap(force = false) { + if (state.bootstrapPromise && !force) return state.bootstrapPromise; + if (state.bootstrapLoaded && !force) return Promise.resolve(); + + const requestId = ++state.bootstrapRequestId; + const startedAt = Date.now(); + state.bootstrapPromise = (async () => { + const data = await fetchJson("/api/dashboard-assistant/bootstrap"); + if (requestId !== state.bootstrapRequestId) return; + const preserveRenderedMessages = !force && state.lastSubmittedAt > startedAt; + applyBootstrap(data, { preserveRenderedMessages }); + })().catch((error) => { + if (requestId === state.bootstrapRequestId) { + state.bootstrapPromise = null; + } + throw error; + }); + + return state.bootstrapPromise; + } + + function openMenu() { + state.open = true; + primeSpeechSynthesis(); + updateButtons(); + positionMenu(); + ensureBootstrap().catch((error) => { + setStatus(error.message || "Failed to load the assistant.", "error"); + setNotice(error.message || "Failed to load the assistant."); + }); + } + + function closeMenu() { + state.open = false; + updateButtons(); + } + + async function saveToken(event) { + event?.preventDefault(); + if (!els.tokenInput || !els.providerSelect) return; + + const token = state.tokenFieldUsesStoredValue ? "" : els.tokenInput.value.trim(); + const provider = String(els.providerSelect.value || state.provider || "groq").trim().toLowerCase(); + const providerMeta = getProviderMeta(provider); + if (!token && !state.providers.some((item) => item && item.id === provider && item.configured)) { + setStatus(`Enter a ${providerMeta.label} API key first.`, "warning"); + return; + } + + const saveTokenHeader = state.actionTokens?.saveToken; + const headers = { "Content-Type": "application/json" }; + if (saveTokenHeader) headers["x-action-token"] = saveTokenHeader; + + try { + if (els.saveToken) els.saveToken.disabled = true; + setStatus(token ? `Saving ${providerMeta.label} API key...` : `Activating ${providerMeta.label}...`, "working"); + await fetchJson("/api/dashboard-assistant/token", { + method: "POST", + headers, + body: JSON.stringify({ provider, token }), + }); + state.tokenFieldUsesStoredValue = false; + els.tokenInput.value = ""; + await ensureBootstrap(true); + setStatus(token ? `${providerMeta.label} API key saved.` : `${providerMeta.label} is now active.`, "idle"); + } catch (error) { + setStatus(error.message || "Failed to save the assistant provider key.", "error"); + } finally { + if (els.saveToken) els.saveToken.disabled = false; + } + } + + async function saveAssistantAccessSetting(enabled) { + const previousValue = !!state.allowNormalUsers; + state.allowNormalUsers = !!enabled; + state.savingAccessSetting = true; + syncAssistantAccessUi(); + + try { + setStatus("Saving assistant access...", "working"); + await fetchJson("/api/dashboard-assistant/access", { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-action-token": state.actionTokens?.updateAccess || "", + }, + body: JSON.stringify({ allowNormalUsers: !!enabled }), + }); + setStatus( + enabled + ? "Normal users can now access Assistant." + : "Assistant access is now limited to admins.", + "idle" + ); + } catch (error) { + state.allowNormalUsers = previousValue; + syncAssistantAccessUi(); + setStatus(error.message || "Failed to save assistant access.", "error"); + } finally { + state.savingAccessSetting = false; + syncAssistantAccessUi(); + } + } + + async function resetChat() { + try { + state.bootstrapRequestId += 1; + state.chatGeneration += 1; + state.lastSubmittedTranscript = ""; + state.lastSubmittedAt = 0; + state.recognitionFallbackTranscript = ""; + state.recognitionFinalTranscript = ""; + state.recognitionInterimTranscript = ""; + if (els.reset) els.reset.disabled = true; + setStatus("Starting a new chat...", "working"); + const data = await fetchJson("/api/dashboard-assistant/reset", { method: "POST" }); + setTranscriptPreview(""); + applyBootstrap({ + configured: state.configured, + canConfigure: state.canConfigure, + allowNormalUsers: state.allowNormalUsers, + provider: state.provider, + providers: state.providers, + chat: data.chat, + messages: data.messages || [], + actionTokens: state.actionTokens, + }); + setStatus("New voice chat ready.", "idle"); + } catch (error) { + setStatus(error.message || "Failed to reset the assistant chat.", "error"); + } finally { + if (els.reset) els.reset.disabled = false; + } + } + + function normalizeAssistantPowerAction(value) { + const action = String(value || "").trim().toLowerCase(); + return ["start", "stop", "restart", "kill"].includes(action) ? action : ""; + } + + function capitalizeText(value) { + const text = String(value || ""); + return text ? `${text.charAt(0).toUpperCase()}${text.slice(1)}` : ""; + } + + function getPowerActionWord(action, tense = "base") { + const normalized = normalizeAssistantPowerAction(action); + if (!normalized) return "update"; + + if (tense === "progressive") { + if (normalized === "start") return "starting"; + if (normalized === "stop") return "stopping"; + if (normalized === "restart") return "restarting"; + if (normalized === "kill") return "killing"; + } + + if (tense === "past") { + if (normalized === "start") return "started"; + if (normalized === "stop") return "stopped"; + if (normalized === "restart") return "restarted"; + if (normalized === "kill") return "killed"; + } + + return normalized; + } + + function getPowerTargetLabel(target) { + return String(target?.displayName || target?.server || target?.name || "that server").trim() || "that server"; + } + + async function requestAssistantClientFollowUp(message, options = {}) { + const summary = String(message || "").trim(); + if (!summary || !state.chatId || !state.configured) return ""; + + try { + const data = await fetchJson("/api/dashboard-assistant/client-follow-up", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + chatId: state.chatId, + summary, + sourceType: String(options.sourceType || "").trim(), + context: options.context && typeof options.context === "object" ? options.context : null, + skipAi: options.skipAi !== false, + }), + }); + return String(data?.reply || "").trim(); + } catch { + return ""; + } + } + + function appendAssistantFollowUpToUi(message, options = {}) { + const text = String(message || "").trim(); + if (!text) return ""; + + appendMessageToUi({ role: "assistant", content: text, created_at: new Date().toISOString() }); + state.lastAssistantReply = text; + if (options.speak) { + const spoken = speakAssistantReply(text); + if (!spoken) { + setVoiceState("Voice playback could not start automatically."); + } + } + + return text; + } + + async function appendAssistantFollowUp(message, options = {}) { + const text = String(message || "").trim(); + if (!text) return ""; + + if (options.ai === true && state.chatId && state.configured) { + const aiReply = await requestAssistantClientFollowUp(text, { + sourceType: options.sourceType, + context: options.context, + skipAi: false, + }); + + if (aiReply) { + return appendAssistantFollowUpToUi(aiReply, options); + } + } + + const localText = appendAssistantFollowUpToUi(text, options); + void requestAssistantClientFollowUp(localText, { + sourceType: options.sourceType, + context: options.context, + skipAi: true, + }); + return localText; + } + + function messageLooksLikeAssistantServerPrefetchIntent(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + if (/\b(open|show|take me|go to|goto|navigate|bring me|launch|new tab|tab|pop ?up)\b/.test(text)) return true; + if (/\b(start|stop|restart|kill|power)\b/.test(text)) return true; + if (/\b(console|logs?|crash|crashed|startup|started|healthy|health|running well|running okay|diagnos)\b/.test(text)) return true; + if (/\b(limits?|quota|ram|memory|cpu|disk|storage|headroom|remaining)\b/.test(text)) return true; + if (/\b(server|servers|bot|instance|backups?|files?|activity|scheduler|resources?)\b/.test(text)) return true; + return false; + } + + function buildAssistantAbsoluteUrl(url) { + const targetUrl = String(url || "").trim(); + if (!targetUrl) return ""; + try { + return new URL(targetUrl, window.location.origin).toString(); + } catch { + return targetUrl; + } + } + + function assistantActionMatches(action, types) { + const value = String(action?.type || "").trim().toLowerCase(); + return Array.isArray(types) && types.includes(value); + } + + function isExecutionClientAction(action) { + if ( + action?.type === "power_servers" + || action?.type === "assistant_resolve_power_server" + || action?.type === "resolve_power_server" + || action?.type === "assistant_power_accessible_servers" + || action?.type === "power_accessible_servers" + ) return true; + return assistantActionMatches(action, [ + "find_busiest_node", + "assistant_find_busiest_node", + "busiest_node", + "find_busiest_server", + "assistant_find_busiest_server", + "busiest_server", + "check_server_console", + "assistant_check_server_console", + "server_console_check", + "check_server_limits", + "assistant_check_server_limits", + "server_limits_check", + "open_server_page", + "assistant_open_server_page", + "open_settings_destination", + "assistant_open_settings_destination", + "diagnose_server", + "assistant_diagnose_server", + "server_diagnosis", + "update_minecraft_server_property", + "assistant_update_minecraft_server_property", + "update_minecraft_server_properties", + "assistant_update_minecraft_server_properties", + "batch_update_server_properties", + "batch_update_minecraft_property", + ]); + } + + function normalizeAssistantServerTarget(target) { + if (!target) return null; + const server = typeof target === "string" + ? String(target).trim() + : String(target.server || target.name || "").trim(); + if (!server) return null; + + return { + server, + name: server, + displayName: String(target.displayName || target.label || server).trim() || server, + template: String(target.template || target.templateId || "").trim().toLowerCase() || null, + nodeId: target.nodeId || null, + hostPort: Number.isFinite(Number(target.hostPort)) ? Number(target.hostPort) : null, + }; + } + + function normalizeAssistantServerTargets(targets) { + const list = Array.isArray(targets) ? targets : (targets ? [targets] : []); + const seen = new Set(); + const normalized = []; + + list.forEach((target) => { + const entry = normalizeAssistantServerTarget(target); + if (!entry) return; + const key = entry.server.toLowerCase(); + if (seen.has(key)) return; + seen.add(key); + normalized.push(entry); + }); + + return normalized; + } + + function storeAccessibleServerDirectory(data) { + const serverEntries = Array.isArray(data?.servers) ? data.servers : []; + const normalizedDirectory = serverEntries.length + ? serverEntries.map((entry) => normalizeAssistantServerTarget(entry)).filter(Boolean) + : normalizeAssistantServerTargets(Array.isArray(data?.names) ? data.names : []); + + state.accessibleServerDirectory = normalizedDirectory; + state.accessibleServerDirectoryFetchedAt = Date.now(); + return normalizedDirectory.slice(); + } + + function getCachedAccessibleServerDirectory() { + if (!Array.isArray(state.accessibleServerDirectory) || !state.accessibleServerDirectory.length) { + return []; + } + if ((Date.now() - Number(state.accessibleServerDirectoryFetchedAt || 0)) > ACCESSIBLE_SERVER_CACHE_TTL_MS) { + return []; + } + return state.accessibleServerDirectory.slice(); + } + + async function ensureAccessibleServerDirectory(options = {}) { + const force = !!options.force; + const cachedDirectory = !force ? getCachedAccessibleServerDirectory() : []; + if (cachedDirectory.length) { + return cachedDirectory; + } + + if (state.accessibleServerDirectoryPromise && !force) { + return state.accessibleServerDirectoryPromise; + } + + const requestPromise = (async () => { + const data = await fetchJson("/api/my-servers", { cache: "no-store" }); + return storeAccessibleServerDirectory(data); + })(); + + state.accessibleServerDirectoryPromise = requestPromise; + try { + return await requestPromise; + } finally { + if (state.accessibleServerDirectoryPromise === requestPromise) { + state.accessibleServerDirectoryPromise = null; + } + } + } + + function warmAccessibleServerDirectory() { + void ensureAccessibleServerDirectory().catch(() => {}); + } + + function normalizeAssistantNodeTargets(targets) { + const list = Array.isArray(targets) ? targets : (targets ? [targets] : []); + const seen = new Set(); + const normalized = []; + + list.forEach((target) => { + const id = typeof target === "string" + ? String(target).trim() + : String(target.id || target.uuid || target.nodeId || target.name || "").trim(); + if (!id) return; + const key = id.toLowerCase(); + if (seen.has(key)) return; + seen.add(key); + normalized.push({ + id, + name: String(target?.name || id).trim() || id, + }); + }); + + return normalized; + } + + function normalizePercent(value) { + const number = Number(value); + if (!Number.isFinite(number)) return null; + return Math.max(0, Math.min(100, Math.round(number))); + } + + function normalizeStatusLabel(value) { + return String(value || "").trim().toLowerCase(); + } + + function stripAssistantLookupDiacritics(value) { + return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, ""); + } + + function normalizeAssistantLookupPhrase(value) { + return stripAssistantLookupDiacritics(value) + .toLowerCase() + .replace(/[`"'“”‘’]/g, " ") + .replace(/[_./-]+/g, " ") + .replace(/[^a-z0-9 ]+/g, " ") + .replace(/\s+/g, " ") + .trim(); + } + + function compactAssistantLookupPhrase(value) { + return normalizeAssistantLookupPhrase(value).replace(/\s+/g, ""); + } + + function stripAssistantServerLookupFiller(value) { + return normalizeAssistantLookupPhrase(value) + .replace(/\b(?:the|my|our|please|pls|now|right|right now|server|servers|serverul|serverele|servere|srv|named|called|bot|instance|start|run|boot|bring|spin|restart|reboot|stop|shutdown|shut|kill|terminate|turn|power|on|off|up|down|for|on|la|pe)\b/g, " ") + .replace(/\s+/g, " ") + .trim(); + } + + function addAssistantLookupForms(set, value) { + const raw = String(value || "").trim().toLowerCase(); + if (raw) set.add(raw); + + const normalized = normalizeAssistantLookupPhrase(value); + if (normalized) set.add(normalized); + + const compact = compactAssistantLookupPhrase(value); + if (compact) set.add(compact); + } + + function buildAssistantRequestedServerForms(requestedServer) { + const forms = new Set(); + const raw = String(requestedServer || "").trim(); + if (!raw) return forms; + + addAssistantLookupForms(forms, raw); + addAssistantLookupForms(forms, stripAssistantServerLookupFiller(raw)); + + const quoted = raw.match(/["'`“”]([^"'`“”]{1,120})["'`“”]/); + if (quoted) { + addAssistantLookupForms(forms, quoted[1]); + addAssistantLookupForms(forms, stripAssistantServerLookupFiller(quoted[1])); + } + + const wrappedMatches = Array.from(raw.matchAll(/[\(\[]([^()\[\]]{1,120})[\)\]]/g)); + for (const match of wrappedMatches) { + addAssistantLookupForms(forms, match[1]); + addAssistantLookupForms(forms, stripAssistantServerLookupFiller(match[1])); + } + + return forms; + } + + function buildAssistantServerAliases(entry) { + const aliases = new Set(); + for (const value of [entry?.name, entry?.displayName, entry?.id]) { + const cleaned = String(value || "").trim(); + if (!cleaned) continue; + aliases.add(cleaned); + const spaced = cleaned.replace(/[_./-]+/g, " ").replace(/\s+/g, " ").trim(); + if (spaced) aliases.add(spaced); + } + return Array.from(aliases); + } + + function scoreAssistantServerAliasMatch(alias, requestedForms) { + const aliasRaw = String(alias || "").trim().toLowerCase(); + const aliasNormalized = normalizeAssistantLookupPhrase(alias); + const aliasCompact = compactAssistantLookupPhrase(alias); + const aliasTokens = new Set(aliasNormalized.split(" ").filter(Boolean)); + let best = 0; + + for (const requested of Array.from(requestedForms || [])) { + const needle = String(requested || "").trim().toLowerCase(); + if (!needle) continue; + + if (needle === aliasRaw || needle === aliasNormalized || needle === aliasCompact) { + return 1000; + } + + const needleNormalized = normalizeAssistantLookupPhrase(needle); + const needleCompact = compactAssistantLookupPhrase(needle); + if (!needleNormalized && !needleCompact) continue; + + if (needleCompact && aliasCompact && (aliasCompact.startsWith(needleCompact) || needleCompact.startsWith(aliasCompact))) { + best = Math.max(best, 260 - Math.abs(aliasCompact.length - needleCompact.length)); + } + if (needleCompact && aliasCompact && (aliasCompact.includes(needleCompact) || needleCompact.includes(aliasCompact))) { + best = Math.max(best, 210 - Math.abs(aliasCompact.length - needleCompact.length)); + } + if (needleNormalized && aliasNormalized && (aliasNormalized.startsWith(needleNormalized) || needleNormalized.startsWith(aliasNormalized))) { + best = Math.max(best, 180 - Math.abs(aliasNormalized.length - needleNormalized.length)); + } + if (needleNormalized && aliasNormalized && (aliasNormalized.includes(needleNormalized) || needleNormalized.includes(aliasNormalized))) { + best = Math.max(best, 150 - Math.abs(aliasNormalized.length - needleNormalized.length)); + } + + const needleTokens = needleNormalized.split(" ").filter(Boolean); + const overlap = needleTokens.filter((token) => aliasTokens.has(token)).length; + if (overlap > 0) { + best = Math.max(best, overlap * 40 - Math.max(0, aliasTokens.size - overlap) * 4); + } + } + + return best; + } + + function resolveAssistantServerFromDirectory(servers, requestedServer) { + const requested = String(requestedServer || "").trim(); + if (!requested) { + return { error: "A server name is required." }; + } + + const requestedForms = buildAssistantRequestedServerForms(requested); + const scoredEntries = (Array.isArray(servers) ? servers : []) + .filter((entry) => entry?.name) + .map((entry) => { + const aliases = buildAssistantServerAliases(entry); + const score = aliases.reduce((best, alias) => Math.max(best, scoreAssistantServerAliasMatch(alias, requestedForms)), 0); + return { entry, score }; + }); + + const exactMatches = scoredEntries.filter((item) => item.score >= 1000).map((item) => item.entry); + if (exactMatches.length === 1) { + return { entry: exactMatches[0] }; + } + if (exactMatches.length > 1) { + return { + error: "Multiple servers matched that name.", + candidates: exactMatches.map((entry) => entry.displayName || entry.name), + }; + } + + const partialMatches = scoredEntries + .filter((item) => item.score >= 120) + .sort((left, right) => right.score - left.score); + if (partialMatches.length === 1) { + return { entry: partialMatches[0].entry }; + } + if (partialMatches.length > 1) { + if (partialMatches[0] && partialMatches[1] && partialMatches[0].score >= partialMatches[1].score + 50) { + return { entry: partialMatches[0].entry }; + } + return { + error: "The server name is ambiguous.", + candidates: partialMatches.slice(0, 5).map((item) => item.entry.displayName || item.entry.name), + }; + } + + return { + error: "I could not match that server name.", + candidates: scoredEntries + .filter((item) => item.score > 0) + .sort((left, right) => right.score - left.score) + .slice(0, 5) + .map((item) => item.entry.displayName || item.entry.name), + }; + } + + function getReadableTargetLabel(target) { + return String(target?.displayName || target?.server || target?.name || "that target").trim() || "that target"; + } + + async function mapWithConcurrency(items, limit, mapper) { + const list = Array.isArray(items) ? items : []; + if (!list.length) return []; + + const maxConcurrency = Math.max(1, Math.min(list.length, Number(limit) || 1)); + const results = new Array(list.length); + let nextIndex = 0; + + async function worker() { + while (true) { + const currentIndex = nextIndex; + nextIndex += 1; + if (currentIndex >= list.length) return; + results[currentIndex] = await mapper(list[currentIndex], currentIndex); + } + } + + await Promise.all(Array.from({ length: maxConcurrency }, () => worker())); + return results; + } + + async function fetchAccessibleServerNames() { + const directory = await ensureAccessibleServerDirectory(); + return directory + .map((entry) => String(entry?.server || entry?.name || "").trim()) + .filter(Boolean); + } + + async function fetchAccessibleServerDirectory() { + return ensureAccessibleServerDirectory(); + } + + async function fetchKnownNodes() { + const data = await fetchJson("/api/nodes", { cache: "no-store" }); + return normalizeAssistantNodeTargets(Array.isArray(data?.nodes) ? data.nodes : []); + } + + async function fetchAssistantServerStatuses(names) { + const cleanNames = [...new Set((Array.isArray(names) ? names : []).map((name) => String(name || "").trim()).filter(Boolean))]; + if (!cleanNames.length) return {}; + + const data = await fetchJson("/api/servers/statuses", { + method: "POST", + cache: "no-store", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ names: cleanNames }), + }); + return data?.statuses && typeof data.statuses === "object" ? data.statuses : {}; + } + + async function fetchAssistantSingleServerStatus(serverName) { + const cleanName = String(serverName || "").trim(); + if (!cleanName) return null; + return fetchJson(`/api/server/${encodeURIComponent(cleanName)}/node-status`, { cache: "no-store" }); + } + + async function fetchAssistantCachedServerStatus(serverName) { + const cleanName = String(serverName || "").trim(); + if (!cleanName) return null; + return fetchJson(`/api/server/${encodeURIComponent(cleanName)}/status`, { cache: "no-store" }); + } + + function normalizeAssistantServerPageSectionValue(value) { + const text = normalizeAssistantLookupPhrase(value); + if (!text) return "console"; + if (/\b(backups?|snapshots?)\b/.test(text)) return "backups"; + if (/\b(files?|file manager|explorer|folders?|directory|directories)\b/.test(text)) return "files"; + if (/\b(activity|history|events?)\b/.test(text)) return "activity"; + if (/\b(scheduler|schedule|schedules|tasks?)\b/.test(text)) return "scheduler"; + if (/\b(store|plugins?|versions?|marketplace)\b/.test(text)) return "store"; + if (/\b(resource(?:s| stats?)?|cpu|ram|memory|disk|storage)\b/.test(text)) return "resource_stats"; + if (/\b(subdomains?|domains?)\b/.test(text)) return "subdomains"; + if (/\b(reinstall|rebuild|reimage|re image)\b/.test(text)) return "reinstall"; + if (/\b(ai help|assistant help)\b/.test(text)) return "ai_help"; + if (/\b(info|overview|details?)\b/.test(text)) return "info"; + return "console"; + } + + function cleanAssistantOptimisticServerCandidate(value) { + const candidate = String(value || "") + .trim() + .replace(/^[`"'“”‘’([{<\s]+/g, "") + .replace(/[`"'“”‘’)\]}>.,!?;:\s]+$/g, "") + .replace(/\s+/g, " ") + .trim(); + if (!candidate) return ""; + if (/^(?:open|show|goto|go to|navigate|launch|new tab|tab|popup|pop up|menu|page|screen|section|area|window|server|servers|bot|instance)$/i.test(candidate)) { + return ""; + } + return candidate; + } + + function deriveOptimisticAssistantServerRouteCandidate(requestedServer, section) { + const raw = String(requestedServer || "").trim(); + if (!raw) return ""; + + const candidates = []; + const seen = new Set(); + const pushCandidate = (value) => { + const candidate = cleanAssistantOptimisticServerCandidate(value); + if (!candidate) return; + const key = candidate.toLowerCase(); + if (seen.has(key)) return; + seen.add(key); + candidates.push(candidate); + }; + + const quoted = raw.match(/["'`“”]([^"'`“”]{1,120})["'`“”]/); + if (quoted?.[1]) pushCandidate(quoted[1]); + + const wrappedMatches = Array.from(raw.matchAll(/[\(\[]([^()\[\]]{1,120})[\)\]]/g)); + wrappedMatches.forEach((match) => pushCandidate(match?.[1])); + + const tailMatch = raw.match(/\b(?:in|for|on|at)\s+([a-z0-9][a-z0-9 _.-]{0,80})$/i); + if (tailMatch?.[1]) pushCandidate(tailMatch[1]); + + const labeledMatch = raw.match(/\b(?:server|bot|instance)\s+([a-z0-9][a-z0-9 _.-]{0,80})$/i); + if (labeledMatch?.[1]) pushCandidate(labeledMatch[1]); + + const cleaned = raw + .replace(/\b(?:open|show|take me|go to|goto|navigate|bring me|launch|new tab|tab|popup|pop up|menu|page|screen|section|area|window)\b/gi, " ") + .replace(/\b(?:console|terminal|backups?|snapshots?|files?|activity|scheduler|tasks?|store|plugins?|versions?|resource(?:s| stats?)?|overview|info|details?|subdomains?|domains?|reinstall|ai help|assistant help)\b/gi, " ") + .replace(/\b(?:the|my|our|please|pls|now|right|right now|server|servers|srv|named|called|bot|instance)\b/gi, " ") + .replace(/\s+/g, " ") + .trim(); + pushCandidate(cleaned); + pushCandidate(raw); + + const normalizedSection = normalizeAssistantServerPageSectionValue(section); + return candidates.find((candidate) => { + const normalized = normalizeAssistantLookupPhrase(candidate); + if (!normalized || normalized === normalizedSection) return false; + if (/\b(?:open|show|goto|go to|navigate|bring me|launch|new tab|tab|popup|pop up|menu|page|screen|section|area|window|console|terminal|backups?|snapshots?|files?|activity|scheduler|tasks?|store|plugins?|versions?|resource(?:s| stats?)?|overview|info|details?|subdomains?|domains?|reinstall|ai help|assistant help)\b/.test(normalized)) { + return false; + } + return normalized.split(" ").some(Boolean); + }) || ""; + } + + function getAssistantServerPageSectionLabel(section) { + const normalized = normalizeAssistantServerPageSectionValue(section); + const labels = { + console: "console", + info: "info", + files: "files", + activity: "activity", + backups: "backups", + scheduler: "scheduler", + store: "store", + resource_stats: "resource stats", + subdomains: "subdomains", + reinstall: "reinstall", + ai_help: "AI help", + }; + return labels[normalized] || "server page"; + } + + function normalizeAssistantSettingsActionValue(value) { + const text = normalizeAssistantLookupPhrase(value); + if (!text) return ""; + if (/\b(pgadmin|postgres setup|postgresql setup)\b/.test(text)) return "pgadmin_setup"; + if (/\b(mongodb|mongo setup)\b/.test(text)) return "mongodb_setup"; + if (/\b(create|new|add)\b.*\buser\b/.test(text)) return "create_user"; + if (/\bbranding\b/.test(text)) return "branding"; + if (/\blogin watermark\b|\bwatermark\b/.test(text)) return "login_watermark"; + if (/\blogin background\b/.test(text)) return "login_background"; + if (/\b(alert|announcement|banner|global alert)\b/.test(text)) return "alert"; + if (/\b(admin quick action|quick action admin|admin action)\b/.test(text)) return "quick_action_admin"; + if (/\b(user quick action|quick action user|user action)\b/.test(text)) return "quick_action_user"; + if (/\b(database setup|setup database|set up database|phpmyadmin|mysql setup)\b/.test(text)) return "database_setup"; + if (/\bcaptcha\b/.test(text)) return "captcha"; + if (/\bmaintenance\b/.test(text)) return "maintenance"; + if (/\b(create|new|add)\b.*\bnode\b/.test(text)) return "create_node"; + if (/\b(create|new|add)\b.*\btemplate\b/.test(text)) return "create_template"; + if ((/\b(add|create|new)\b/.test(text) || /\bpopup\b|\bmodal\b/.test(text)) && /\bwebhook\b/.test(text)) return "add_webhook"; + return ""; + } + + function inferAssistantSettingsPanelFromActionValue(action) { + const normalized = String(action || "").trim(); + if (!normalized) return ""; + if (["branding", "login_watermark", "login_background"].includes(normalized)) return "customization"; + if (["create_user"].includes(normalized)) return "account"; + if (["captcha", "maintenance"].includes(normalized)) return "security"; + if (["database_setup", "pgadmin_setup", "mongodb_setup"].includes(normalized)) return "databases"; + if (["create_node"].includes(normalized)) return "nodes"; + if (["create_template"].includes(normalized)) return "templates"; + if (["add_webhook"].includes(normalized)) return "webhooks"; + if (["alert", "quick_action_admin", "quick_action_user"].includes(normalized)) return "customization"; + return ""; + } + + function normalizeAssistantSettingsPanelValue(value) { + const text = normalizeAssistantLookupPhrase(value); + if (!text) return ""; + if (/\b(panel info|panelinfo)\b/.test(text)) return "panelinfo"; + if (/\b(customization|customisation|appearance|look|theme|style|branding)\b/.test(text)) return "customization"; + if (/\b(account|accounts?|users?|user management)\b/.test(text)) return "account"; + if (/\b(security|captcha|maintenance)\b/.test(text)) return "security"; + if (/\b(databases?|database|db|mysql|postgres|postgresql|pgadmin|mongo|mongodb)\b/.test(text)) return "databases"; + if (/\b(nodes?|infrastructure)\b/.test(text)) return "nodes"; + if (/\b(templates?|docker templates?)\b/.test(text)) return "templates"; + if (/\b(servers?|instances?)\b/.test(text)) return "servers"; + if (/\b(webhooks?|discord)\b/.test(text)) return "webhooks"; + if (/\b(preferences?|general settings?|settings home)\b/.test(text)) return "preferences"; + return ""; + } + + function getAssistantSettingsPanelLabel(panel) { + const normalized = normalizeAssistantSettingsPanelValue(panel); + const labels = { + preferences: "Preferences", + customization: "Customization", + account: "Account", + security: "Security", + databases: "Databases", + nodes: "Nodes", + templates: "Templates", + servers: "Servers", + webhooks: "Webhooks", + panelinfo: "Panel Info", + }; + return labels[normalized] || "Settings"; + } + + function getAssistantSettingsActionLabel(action) { + const normalized = normalizeAssistantSettingsActionValue(action); + const labels = { + create_user: "Create User", + branding: "Branding", + login_watermark: "Login Watermark", + login_background: "Login Background", + alert: "Alerts", + quick_action_admin: "Admin Quick Actions", + quick_action_user: "User Quick Actions", + database_setup: "Database Setup", + pgadmin_setup: "pgAdmin Setup", + mongodb_setup: "MongoDB Setup", + captcha: "Captcha", + maintenance: "Maintenance", + create_node: "Create Node", + create_template: "Create Template", + add_webhook: "Add Webhook", + }; + return labels[normalized] || "that settings tool"; + } + + function buildAssistantServerPageUrl(serverName, section) { + const cleanName = String(serverName || "").trim(); + if (!cleanName) return ""; + const normalizedSection = normalizeAssistantServerPageSectionValue(section); + const basePath = `/server/${encodeURIComponent(cleanName)}`; + const queryActions = { + console: "", + info: "open-info", + files: "open-files", + activity: "open-activity", + backups: "open-backups", + scheduler: "open-scheduler", + store: "open-store", + resource_stats: "open-resource-stats", + subdomains: "open-subdomains", + reinstall: "open-reinstall", + ai_help: "open-ai-help", + }; + const assistantAction = queryActions[normalizedSection] || ""; + if (!assistantAction) return basePath; + return `${basePath}?assistantAction=${encodeURIComponent(assistantAction)}`; + } + + function appendAssistantNavigationLink(label, url, options = {}) { + const safeLabel = String(label || "").trim() || "Open link"; + const absoluteUrl = buildAssistantAbsoluteUrl(url); + if (!absoluteUrl) return false; + + const prefix = String(options.prefix || "").trim(); + const suffix = String(options.suffix || "").trim(); + const parts = [prefix, `${safeLabel}: ${absoluteUrl}`, suffix].filter(Boolean); + const message = parts.join("\n"); + setStatus("Assistant prepared a link.", "idle"); + appendAssistantFollowUp(message, { speak: !!options.speak }); + return true; + } + + function buildAssistantSettingsUrl(panel, action) { + const normalizedAction = normalizeAssistantSettingsActionValue(action); + const normalizedPanel = normalizeAssistantSettingsPanelValue(panel) || inferAssistantSettingsPanelFromActionValue(normalizedAction) || "preferences"; + const params = new URLSearchParams(); + params.set("panel", normalizedPanel); + if (normalizedAction) { + params.set("assistantAction", normalizedAction); + } + return `/settings?${params.toString()}`; + } + + async function waitForAssistantPowerObservation(serverName, action, options = {}) { + const target = String(serverName || "").trim(); + const normalizedAction = normalizeAssistantPowerAction(action); + if (!target || !normalizedAction || normalizedAction === "restart") { + return { confirmed: false, pending: true, contradictory: false, status: "" }; + } + + const attempts = Math.max(1, Number(options.attempts) || 4); + const delayMs = Math.max(250, Number(options.delayMs) || 1200); + let lastStatus = ""; + + for (let attempt = 0; attempt < attempts; attempt += 1) { + if (attempt > 0) { + await new Promise((resolve) => window.setTimeout(resolve, delayMs)); + } + try { + const directStatus = await fetchAssistantSingleServerStatus(target); + lastStatus = normalizeStatusLabel(directStatus?.status); + } catch { + } + + if (!lastStatus || lastStatus === "unknown") { + try { + const statuses = await fetchAssistantServerStatuses([target]); + lastStatus = normalizeStatusLabel(statuses?.[target]?.status) || lastStatus; + } catch { + } + } + + if ((normalizedAction === "start" && ["starting", "running", "online"].includes(lastStatus)) + || ((normalizedAction === "stop" || normalizedAction === "kill") && ["stopping", "stopped", "offline"].includes(lastStatus))) { + return { confirmed: true, pending: false, contradictory: false, status: lastStatus }; + } + } + + const pending = !lastStatus || ["unknown", "starting", "stopping"].includes(lastStatus); + return { + confirmed: false, + pending, + contradictory: !pending, + status: lastStatus, + }; + } + + function getAssistantPropertyValue(content, key) { + const propertyKey = String(key || "").trim(); + if (!propertyKey) return ""; + const lines = String(content || "").split(/\r?\n/); + for (const line of lines) { + if (extractAssistantPropertiesKey(line) === propertyKey) { + return extractAssistantPropertiesValue(line); + } + } + return ""; + } + + function scoreAssistantNodeLoad(stats, metric = "balanced") { + const cpu = normalizePercent(stats?.stats?.cpu?.percent); + const ram = normalizePercent(stats?.stats?.ram?.percent); + const disk = normalizePercent(stats?.stats?.disk?.percent); + let score = (cpu || 0) * 0.55 + (ram || 0) * 0.3 + (disk || 0) * 0.15; + if (metric === "cpu") score = cpu || 0; + else if (metric === "memory") score = ram || 0; + else if (metric === "disk") score = disk || 0; + if (stats?.online) score += 8; + return score; + } + + function scoreAssistantServerLoad(status, metric = "balanced") { + const stateLabel = normalizeStatusLabel(status?.status); + const cpu = normalizePercent(status?.cpu); + const memory = normalizePercent(status?.memory?.percent); + const disk = normalizePercent(status?.disk?.percent); + let score = (cpu || 0) * 0.62 + (memory || 0) * 0.28 + (disk || 0) * 0.1; + if (metric === "cpu") score = cpu || 0; + else if (metric === "memory") score = memory || 0; + else if (metric === "disk") score = disk || 0; + + if (stateLabel === "running") score += 12; + else if (stateLabel === "starting") score += 4; + else if (["stopped", "offline", "unknown", "installing"].includes(stateLabel)) score -= 35; + + if (status?.nodeOnline === false) score -= 50; + return score; + } + + function normalizeAssistantMetricList(value) { + const rawList = Array.isArray(value) ? value : [value]; + const seen = new Set(); + const metrics = []; + + rawList.forEach((entry) => { + const metric = String(entry || "").trim().toLowerCase(); + if (!["cpu", "memory", "disk"].includes(metric) || seen.has(metric)) return; + seen.add(metric); + metrics.push(metric); + }); + + return metrics; + } + + function formatAssistantMemoryAmount(valueMb) { + const amount = Number(valueMb); + if (!Number.isFinite(amount) || amount < 0) return null; + if (amount >= 1024) { + const gb = amount / 1024; + return `${gb >= 10 ? Math.round(gb) : gb.toFixed(1)} GB`; + } + return `${Math.round(amount)} MB`; + } + + function formatAssistantDiskAmount(valueGb) { + const amount = Number(valueGb); + if (!Number.isFinite(amount) || amount < 0) return null; + return `${amount >= 10 ? Math.round(amount) : amount.toFixed(1)} GB`; + } + + function buildAssistantNodeUsageDetail(nodeStats, includeMetrics = []) { + const metrics = normalizeAssistantMetricList(includeMetrics); + if (!metrics.length) return ""; + + const parts = []; + if (metrics.includes("cpu")) { + const cpu = normalizePercent(nodeStats?.stats?.cpu?.percent); + if (cpu !== null) parts.push(`${cpu}% CPU`); + } + if (metrics.includes("memory")) { + const used = formatAssistantMemoryAmount(nodeStats?.stats?.ram?.usedMb); + const total = formatAssistantMemoryAmount(nodeStats?.stats?.ram?.totalMb); + const percent = normalizePercent(nodeStats?.stats?.ram?.percent); + if (used && total) parts.push(`${used}/${total} RAM`); + else if (percent !== null) parts.push(`${percent}% RAM`); + } + if (metrics.includes("disk")) { + const used = formatAssistantDiskAmount(nodeStats?.stats?.disk?.usedGb); + const total = formatAssistantDiskAmount(nodeStats?.stats?.disk?.totalGb); + const percent = normalizePercent(nodeStats?.stats?.disk?.percent); + if (used && total) parts.push(`${used}/${total} disk`); + else if (percent !== null) parts.push(`${percent}% disk`); + } + + return parts.join(", "); + } + + function buildAssistantServerUsageDetail(status, includeMetrics = []) { + const metrics = normalizeAssistantMetricList(includeMetrics); + if (!metrics.length) return ""; + + const parts = []; + if (metrics.includes("cpu")) { + const cpu = normalizePercent(status?.cpu); + if (cpu !== null) parts.push(`${cpu}% CPU`); + } + if (metrics.includes("memory")) { + const used = formatAssistantMemoryAmount(status?.memory?.used); + const total = formatAssistantMemoryAmount(status?.memory?.total); + const percent = normalizePercent(status?.memory?.percent); + if (used && total) parts.push(`${used}/${total} RAM`); + else if (percent !== null) parts.push(`${percent}% RAM`); + } + if (metrics.includes("disk")) { + const used = formatAssistantDiskAmount(status?.disk?.used); + const total = formatAssistantDiskAmount(status?.disk?.total); + const percent = normalizePercent(status?.disk?.percent); + if (used && total) parts.push(`${used}/${total} disk`); + else if (percent !== null) parts.push(`${percent}% disk`); + } + + return parts.join(", "); + } + + function summarizeAssistantNodeLoad(nodeStats, metric = "balanced", includeMetrics = []) { + const label = String(nodeStats?.nodeName || nodeStats?.nodeId || "That node").trim() || "That node"; + const cpu = normalizePercent(nodeStats?.stats?.cpu?.percent); + const ram = normalizePercent(nodeStats?.stats?.ram?.percent); + const disk = normalizePercent(nodeStats?.stats?.disk?.percent); + const requestedMetrics = normalizeAssistantMetricList(includeMetrics); + const details = buildAssistantNodeUsageDetail( + nodeStats, + metric === "cpu" ? requestedMetrics.filter((entry) => entry !== "cpu") : requestedMetrics + ); + if (metric === "cpu" && cpu !== null) return `${label} is highest on CPU at ${cpu}%.${details ? ` It is using ${details}.` : ""}`; + if (metric === "memory" && ram !== null) return `${label} is highest on RAM at ${ram}%.${details ? ` It is using ${details}.` : ""}`; + if (metric === "disk" && disk !== null) return `${label} is highest on disk at ${disk}%.${details ? ` It is using ${details}.` : ""}`; + + const parts = []; + if (cpu !== null) parts.push(`${cpu}% CPU`); + if (ram !== null) parts.push(`${ram}% RAM`); + if (disk !== null && disk >= 80) parts.push(`${disk}% disk`); + const detailSuffix = buildAssistantNodeUsageDetail(nodeStats, requestedMetrics); + if (detailSuffix) { + return `${label} is busiest. It is using ${detailSuffix}.`; + } + if (parts.length) { + return `${label} is busiest: ${parts.join(", ")}.`; + } + return `${label} looks like the busiest node right now.`; + } + + function summarizeAssistantServerLoad(target, status, metric = "balanced", includeMetrics = []) { + const label = getReadableTargetLabel(target); + const cpu = normalizePercent(status?.cpu); + const memory = normalizePercent(status?.memory?.percent); + const disk = normalizePercent(status?.disk?.percent); + const requestedMetrics = normalizeAssistantMetricList(includeMetrics); + const details = buildAssistantServerUsageDetail( + status, + metric === "cpu" ? requestedMetrics.filter((entry) => entry !== "cpu") : requestedMetrics + ); + if (metric === "cpu" && cpu !== null) return `${label} is highest on CPU at ${cpu}%.${details ? ` It is using ${details}.` : ""}`; + if (metric === "memory" && memory !== null) return `${label} is highest on RAM at ${memory}%.${details ? ` It is using ${details}.` : ""}`; + if (metric === "disk" && disk !== null) return `${label} is highest on disk at ${disk}%.${details ? ` It is using ${details}.` : ""}`; + + const parts = []; + if (cpu !== null) parts.push(`${cpu}% CPU`); + if (memory !== null) parts.push(`${memory}% RAM`); + if (disk !== null && disk >= 80) parts.push(`${disk}% disk`); + const detailSuffix = buildAssistantServerUsageDetail(status, requestedMetrics); + if (detailSuffix) { + return `${label} is busiest. It is using ${detailSuffix}.`; + } + if (parts.length) { + return `${label} is busiest: ${parts.join(", ")}.`; + } + return `${label} looks like the busiest accessible server right now.`; + } + + function mergeAssistantServerLimitStatus(liveStatus, cachedStatus) { + const live = liveStatus && typeof liveStatus === "object" ? liveStatus : {}; + const cached = cachedStatus && typeof cachedStatus === "object" ? cachedStatus : {}; + return { + status: live.status || cached.status || "unknown", + nodeOnline: live.nodeOnline !== false && cached.nodeOnline !== false, + cpu: live.cpu ?? cached.cpu ?? null, + cpuLimit: live.cpuLimit ?? cached.cpuLimit ?? null, + memory: live.memory || cached.memory || null, + disk: live.disk || cached.disk || null, + uptime: live.uptime ?? cached.uptime ?? null, + }; + } + + function buildAssistantServerLimitsSummary(target, status, question = "") { + const label = getReadableTargetLabel(target); + const cpu = normalizePercent(status?.cpu); + const cpuLimitRaw = Number(status?.cpuLimit); + const cpuLimit = Number.isFinite(cpuLimitRaw) && cpuLimitRaw > 0 ? Math.round(cpuLimitRaw) : 100; + const cpuRemaining = cpu !== null ? Math.max(0, cpuLimit - cpu) : null; + + const memoryPercent = normalizePercent(status?.memory?.percent); + const memoryUsed = Number(status?.memory?.used); + const memoryTotal = Number(status?.memory?.total); + const memoryRemaining = Number.isFinite(memoryTotal) && Number.isFinite(memoryUsed) + ? Math.max(0, memoryTotal - memoryUsed) + : null; + + const diskPercent = normalizePercent(status?.disk?.percent); + const diskUsed = Number(status?.disk?.used); + const diskTotal = Number(status?.disk?.total); + const diskRemaining = Number.isFinite(diskTotal) && Number.isFinite(diskUsed) + ? Math.max(0, diskTotal - diskUsed) + : null; + + const warnings = []; + if (status?.nodeOnline === false) warnings.push("node_offline"); + if (cpu !== null && cpu >= Math.max(90, cpuLimit - 5)) warnings.push("cpu_high"); + if (memoryPercent !== null && memoryPercent >= 90) warnings.push("memory_high"); + if (diskPercent !== null && diskPercent >= 90) warnings.push("disk_high"); + + const parts = []; + if (cpu !== null) { + parts.push(cpuLimit && cpuLimit !== 100 + ? `${cpu}% CPU of ${cpuLimit}% limit` + : `${cpu}% CPU`); + } + const memoryUsedText = formatAssistantMemoryAmount(memoryUsed); + const memoryTotalText = formatAssistantMemoryAmount(memoryTotal); + const memoryRemainingText = formatAssistantMemoryAmount(memoryRemaining); + if (memoryUsedText && memoryTotalText) { + parts.push(`${memoryUsedText}/${memoryTotalText} RAM${memoryRemainingText ? `, about ${memoryRemainingText} left` : ""}`); + } else if (memoryPercent !== null) { + parts.push(`${memoryPercent}% RAM`); + } + const diskUsedText = formatAssistantDiskAmount(diskUsed); + const diskTotalText = formatAssistantDiskAmount(diskTotal); + const diskRemainingText = formatAssistantDiskAmount(diskRemaining); + if (diskUsedText && diskTotalText) { + parts.push(`${diskUsedText}/${diskTotalText} storage${diskRemainingText ? `, about ${diskRemainingText} left` : ""}`); + } else if (diskPercent !== null) { + parts.push(`${diskPercent}% storage`); + } + + let message = parts.length + ? `${label} is using ${parts.join(", ")}.` + : `I could only read partial limits data for ${label}.`; + + if (warnings.includes("node_offline")) { + message = `The node hosting ${label} looks offline right now.`; + } else if (warnings.includes("memory_high")) { + message += " RAM looks close to the limit."; + } else if (warnings.includes("disk_high")) { + message += " Storage looks close to full."; + } else if (warnings.includes("cpu_high")) { + message += " CPU looks close to saturation."; + } else if (parts.length) { + message += " Headroom looks okay."; + } + + const asksForProblemCheck = /\b(problem|issue|healthy|health|okay|ok|fine|good|bad|risk)\b/i.test(String(question || "")); + const needsConsoleCheck = asksForProblemCheck || warnings.some((entry) => entry !== "node_offline"); + if (needsConsoleCheck) { + message += " If you want, I can check the console logs next."; + } + + return { + message, + warnings, + needsConsoleCheck, + kind: warnings.length ? "warning" : "idle", + remaining: { + cpuPercent: cpuRemaining, + memoryMb: Number.isFinite(memoryRemaining) ? Math.round(memoryRemaining) : null, + diskGb: Number.isFinite(diskRemaining) ? Number(diskRemaining.toFixed(2)) : null, + }, + }; + } + + function buildAssistantPropertiesLine(key, value) { + return `${String(key || "").trim()}=${String(value ?? "").replace(/\r?\n/g, " ").trim()}`; + } + + function extractAssistantPropertiesKey(line) { + const text = String(line || ""); + const trimmed = text.replace(/^\s+/, ""); + if (!trimmed || /^[#!]/.test(trimmed)) return ""; + + let key = ""; + let escaping = false; + for (let index = 0; index < trimmed.length; index += 1) { + const char = trimmed[index]; + if (escaping) { + key += char; + escaping = false; + continue; + } + if (char === "\\") { + key += char; + escaping = true; + continue; + } + if (char === "=" || char === ":" || /\s/.test(char)) break; + key += char; + } + + return key.trim(); + } + + function extractAssistantPropertiesValue(line) { + const text = String(line || ""); + const propertyKey = extractAssistantPropertiesKey(text); + if (!propertyKey) return ""; + return text + .slice(text.indexOf(propertyKey) + propertyKey.length) + .replace(/^\s*[:=]?\s*/, "") + .trim(); + } + + function normalizeAssistantPropertyValueToken(value) { + const clean = String(value ?? "").trim(); + if (/^(true|on|enabled?|yes|da)$/i.test(clean)) return "true"; + if (/^(false|off|disabled?|no|nu)$/i.test(clean)) return "false"; + return clean; + } + + function updateAssistantPropertiesContent(content, key, value, options = {}) { + const propertyKey = String(key || "").trim(); + if (!propertyKey) { + throw new Error("A server.properties key is required."); + } + + const normalizedContent = typeof content === "string" ? content : ""; + const newline = normalizedContent.includes("\r\n") ? "\r\n" : "\n"; + const lines = normalizedContent.split(/\r?\n/); + const desiredLine = buildAssistantPropertiesLine(propertyKey, value); + const expectedCurrent = normalizeAssistantPropertyValueToken(options?.onlyIfCurrent); + const currentLine = lines.find((line) => extractAssistantPropertiesKey(line) === propertyKey); + const currentValue = currentLine ? extractAssistantPropertiesValue(currentLine) : ""; + + if (expectedCurrent) { + const normalizedCurrent = normalizeAssistantPropertyValueToken(currentValue); + if (!currentLine || normalizedCurrent !== expectedCurrent) { + return { + changed: false, + conditionMatched: false, + currentValue, + content: normalizedContent, + }; + } + } + + const updatedLines = []; + let replaced = false; + let changed = false; + + for (const line of lines) { + if (extractAssistantPropertiesKey(line) === propertyKey) { + if (!replaced) { + updatedLines.push(desiredLine); + replaced = true; + if (line !== desiredLine) changed = true; + } else { + changed = true; + } + continue; + } + updatedLines.push(line); + } + + if (!replaced) { + if (updatedLines.length && updatedLines[updatedLines.length - 1] === "") { + updatedLines.splice(updatedLines.length - 1, 0, desiredLine); + } else { + updatedLines.push(desiredLine); + } + changed = true; + } + + return { + changed, + conditionMatched: true, + currentValue, + content: updatedLines.join(newline), + }; + } + + async function fetchServerPermissions(serverName) { + return fetchJson(`/api/servers/${encodeURIComponent(serverName)}/permissions`, { cache: "no-store" }); + } + + function getAssistantPowerRequiredPermissions(action) { + const normalizedAction = normalizeAssistantPowerAction(action); + if (normalizedAction === "start") return ["server_start"]; + if (normalizedAction === "restart") return ["server_stop", "server_start"]; + if (normalizedAction === "stop" || normalizedAction === "kill") return ["server_stop"]; + return []; + } + + function canAssistantRunPowerAction(perms, action) { + const required = getAssistantPowerRequiredPermissions(action); + return required.every((perm) => !!perms?.[perm]); + } + + async function buildAccessibleAssistantPowerTargets(action) { + const servers = await fetchAccessibleServerDirectory(); + if (!servers.length) { + return { targets: [], skipped: [] }; + } + + const resolved = await mapWithConcurrency(servers, 6, async (target) => { + const nodeId = String(target?.nodeId || "").trim().toLowerCase(); + if (!nodeId || nodeId === "local") { + return { + skip: { + server: target.server, + displayName: getReadableTargetLabel(target), + reason: "not_attached_to_node", + }, + }; + } + + try { + const permissions = await fetchServerPermissions(target.server); + if (!canAssistantRunPowerAction(permissions?.perms, action)) { + return { + skip: { + server: target.server, + displayName: getReadableTargetLabel(target), + reason: "permission_denied", + }, + }; + } + } catch { + return { + skip: { + server: target.server, + displayName: getReadableTargetLabel(target), + reason: "permission_lookup_failed", + }, + }; + } + + return { target }; + }); + + return { + targets: resolved.map((item) => item?.target).filter(Boolean), + skipped: resolved.map((item) => item?.skip).filter(Boolean), + }; + } + + async function resolveMinecraftPropertyTargets(actionConfig) { + const explicitTargets = normalizeAssistantServerTargets( + actionConfig?.targets + || actionConfig?.servers + || actionConfig?.serverNames + || actionConfig?.target + || actionConfig?.server + ); + const candidates = explicitTargets.length + ? explicitTargets + : normalizeAssistantServerTargets(await fetchAccessibleServerNames()); + + if (!candidates.length) return []; + + const resolved = await mapWithConcurrency(candidates, 6, async (target) => { + if (target.template) { + return target.template === "minecraft" ? target : null; + } + + try { + const info = await fetchJson(`/api/server-info/${encodeURIComponent(target.server)}`, { cache: "no-store" }); + return String(info?.template || "").trim().toLowerCase() === "minecraft" + ? Object.assign({}, target, { template: "minecraft" }) + : null; + } catch { + return null; + } + }); + + return resolved.filter(Boolean); + } + + async function readAssistantLogSnapshot(serverName, options = {}) { + const includeMeta = !!options?.includeMeta; + if (typeof window.TextDecoder === "undefined" || typeof AbortController === "undefined") { + return includeMeta + ? { ok: false, status: 0, lines: [], error: "This browser cannot stream console output here." } + : []; + } + + const timeoutMs = Math.max(250, Number(options.timeoutMs) || 900); + const maxLines = Math.max(1, Number(options.maxLines) || 4); + const controller = new AbortController(); + const decoder = new window.TextDecoder("utf-8"); + const timer = window.setTimeout(() => controller.abort(), timeoutMs); + const lines = []; + let pending = ""; + + function extractLines(flush = false) { + pending = pending.replace(/\r\n/g, "\n"); + + while (true) { + const boundary = pending.indexOf("\n\n"); + if (boundary === -1) break; + + const chunk = pending.slice(0, boundary); + pending = pending.slice(boundary + 2); + const payload = chunk + .split("\n") + .filter((line) => line.startsWith("data:")) + .map((line) => line.slice(5).trimStart()) + .join("\n") + .trim(); + + if (!payload) continue; + + try { + const parsed = JSON.parse(payload); + const text = typeof parsed?.line === "string" + ? parsed.line + : typeof parsed === "string" + ? parsed + : ""; + if (text.trim()) lines.push(text.trim()); + } catch { + if (payload.trim()) lines.push(payload.trim()); + } + + if (lines.length >= maxLines) return; + } + + if (flush && pending.trim()) { + const tail = pending.trim(); + try { + const parsed = JSON.parse(tail); + const text = typeof parsed?.line === "string" + ? parsed.line + : typeof parsed === "string" + ? parsed + : ""; + if (text.trim()) lines.push(text.trim()); + } catch { + lines.push(tail); + } + pending = ""; + } + } + + try { + const response = await fetch(`/api/nodes/server/${encodeURIComponent(serverName)}/logs`, { + credentials: "include", + headers: { Accept: "text/event-stream" }, + signal: controller.signal, + cache: "no-store", + }); + if (!response.ok) { + let errorMessage = ""; + try { + const contentType = String(response.headers.get("content-type") || "").toLowerCase(); + if (contentType.includes("application/json")) { + const json = await response.json().catch(() => null); + errorMessage = String(json?.detail || json?.error || json?.message || "").trim(); + } else { + errorMessage = String(await response.text().catch(() => "")).trim(); + } + } catch { + } + + return includeMeta + ? { + ok: false, + status: response.status, + lines: [], + error: errorMessage, + } + : []; + } + if (!response.body) { + return includeMeta + ? { ok: false, status: response.status, lines: [], error: "No console stream was returned." } + : []; + } + + const reader = response.body.getReader(); + while (lines.length < maxLines) { + const chunk = await reader.read(); + if (chunk.done) break; + pending += decoder.decode(chunk.value || new Uint8Array(), { stream: true }); + extractLines(false); + } + } catch (error) { + if (error?.name !== "AbortError") { + return includeMeta + ? { + ok: false, + status: 0, + lines: [], + error: String(error?.message || "Console request failed.").trim(), + } + : []; + } + } finally { + window.clearTimeout(timer); + controller.abort(); + } + + extractLines(true); + const finalLines = lines.slice(0, maxLines); + return includeMeta + ? { ok: true, status: 200, lines: finalLines, error: "" } + : finalLines; + } + + function stripAssistantAnsiCodes(value) { + return String(value || "").replace(/\u001b\[[0-9;]*m/g, ""); + } + + function cleanAssistantConsoleLine(value) { + return stripAssistantAnsiCodes(value) + .replace(/\s+/g, " ") + .replace(/^\[[^\]]{1,40}\]\s*/g, "") + .replace(/^(?:info|warn|warning|error|debug|trace)\s*[:|-]\s*/i, "") + .trim(); + } + + function truncateAssistantConsoleLine(value, maxLength = 150) { + const clean = cleanAssistantConsoleLine(value); + if (clean.length <= maxLength) return clean; + return `${clean.slice(0, Math.max(20, maxLength - 3)).trim()}...`; + } + + function findAssistantConsoleEvidence(lines, pattern) { + const list = Array.isArray(lines) ? lines : []; + for (let index = list.length - 1; index >= 0; index -= 1) { + const line = cleanAssistantConsoleLine(list[index]); + if (!line) continue; + if (pattern.test(line.toLowerCase())) { + return truncateAssistantConsoleLine(line); + } + } + return ""; + } + + function pickAssistantLatestConsoleLine(lines) { + const list = Array.isArray(lines) ? lines : []; + for (let index = list.length - 1; index >= 0; index -= 1) { + const line = truncateAssistantConsoleLine(list[index]); + if (line) return line; + } + return ""; + } + + function inferAssistantConsoleIntent(question) { + const text = String(question || "").trim().toLowerCase(); + if (!text) return "diagnose"; + if (/\b(show|read|what(?:'s| is)? in|latest|tail|see|display)\b/.test(text)) return "show"; + return "diagnose"; + } + + function buildAssistantConsoleCheckSummary(target, logLines, context = {}) { + const label = getReadableTargetLabel(target); + const statusLabel = normalizeStatusLabel(context?.status?.status); + const intent = inferAssistantConsoleIntent(context?.question); + const lines = (Array.isArray(logLines) ? logLines : []).map(cleanAssistantConsoleLine).filter(Boolean); + const latestLine = pickAssistantLatestConsoleLine(lines); + + if (context?.status?.nodeOnline === false) { + return { kind: "warning", message: `Node looks offline for ${label}.` }; + } + + if (!lines.length) { + if (statusLabel && statusLabel !== "unknown") { + return { kind: statusLabel === "running" ? "idle" : "warning", message: `I could not read fresh console output for ${label}. It is ${statusLabel}.` }; + } + return { kind: "warning", message: `I could not read fresh console output for ${label}.` }; + } + + const rules = [ + { pattern: /you need to agree to the eula|eula\.txt|eula=false/, message: `Console shows EULA is not accepted on ${label}.` }, + { pattern: /out of memory|cannot allocate memory|oom|killed process/, message: `Console shows an out-of-memory crash on ${label}.` }, + { pattern: /address already in use|eaddrinuse|failed to bind|bind: address|port is already allocated/, message: `Console shows a port conflict on ${label}.` }, + { pattern: /no space left|disk quota exceeded|enospc/, message: `Console shows disk space is exhausted on ${label}.` }, + { pattern: /unsupportedclassversionerror|more recent version of the java runtime|class file version/, message: `Console shows a Java version mismatch on ${label}.` }, + { pattern: /failed to load plugin|could not load .*plugins|error occurred while enabling|paper plugin loader/, message: `Console shows a broken plugin on ${label}.` }, + { pattern: /permission denied|operation not permitted|eacces|eperm/, message: `Console shows a permission error on ${label}.` }, + { pattern: /cannot find module|module not found|no module named|missing dependency|could not resolve dependency/, message: `Console shows a missing module or dependency on ${label}.` }, + { pattern: /connection refused|timed out|timeout|failed to connect|could not connect/, message: `Console shows a connection failure on ${label}.` }, + { pattern: /yaml|toml|json|scannerexception|parsererror|syntax error|mapping values are not allowed/, message: `Console shows a config syntax error on ${label}.` }, + { pattern: /traceback|panic:|uncaught exception|fatal error|java\.lang\./, message: `${label} is crashing with an application exception.` }, + ]; + + for (const rule of rules) { + const evidence = findAssistantConsoleEvidence(lines, rule.pattern); + if (evidence) { + return { + kind: "warning", + message: `${rule.message}${evidence ? ` ${evidence}.` : ""}`, + }; + } + } + + if (intent === "show" && latestLine) { + return { kind: "idle", message: `Latest console on ${label}: ${latestLine}.` }; + } + + if (latestLine) { + const prefix = statusLabel === "running" + ? `Console on ${label} does not show a clear fault.` + : `Console on ${label} points to:`; + return { kind: statusLabel === "running" ? "idle" : "warning", message: `${prefix} ${latestLine}.` }; + } + + return { kind: "warning", message: `I could not find a clear console clue for ${label}.` }; + } + + function tailAssistantLines(content, maxLines = 18) { + const text = String(content || ""); + if (!text.trim()) return []; + return text + .replace(/\r\n/g, "\n") + .split("\n") + .map((line) => line.trim()) + .filter(Boolean) + .slice(-Math.max(1, Number(maxLines) || 18)); + } + + function buildAssistantLogFileCandidates(template) { + const normalizedTemplate = String(template || "").trim().toLowerCase(); + const candidates = [ + "logs/latest.log", + "latest.log", + "server.log", + "logs/server.log", + ]; + if (normalizedTemplate === "minecraft") { + candidates.unshift("logs/latest.log"); + candidates.push("crash-reports/latest.log"); + } + return [...new Set(candidates)]; + } + + async function readAssistantHistoricalLogSnapshot(serverName, template, maxLines = 18) { + const candidates = buildAssistantLogFileCandidates(template); + for (const filePath of candidates) { + try { + const fileData = await fetchJson(`/api/servers/${encodeURIComponent(serverName)}/files/read?path=${encodeURIComponent(filePath)}`, { + cache: "no-store", + }); + const lines = tailAssistantLines(fileData?.content, maxLines); + if (lines.length) { + return { path: filePath, lines }; + } + } catch { + } + } + + return { path: "", lines: [] }; + } + + function buildAssistantDiagnosis(target, context) { + const label = getReadableTargetLabel(target); + const statusLabel = normalizeStatusLabel(context?.status?.status); + const cpu = normalizePercent(context?.status?.cpu); + const memory = normalizePercent(context?.status?.memory?.percent); + const disk = normalizePercent(context?.status?.disk?.percent); + const activityEntries = Array.isArray(context?.activityEntries) ? context.activityEntries : []; + const recentActions = activityEntries.map((entry) => String(entry?.action || "").trim().toLowerCase()).filter(Boolean); + const logText = (Array.isArray(context?.logLines) ? context.logLines : []).join(" ").toLowerCase(); + const nodeCpu = normalizePercent(context?.nodeStats?.stats?.cpu?.percent); + const nodeRam = normalizePercent(context?.nodeStats?.stats?.ram?.percent); + const nodeDisk = normalizePercent(context?.nodeStats?.stats?.disk?.percent); + + if (context?.status?.nodeOnline === false || context?.nodeInfo?.nodeOnline === false) { + return { message: `Node looks offline for ${label}.`, kind: "warning" }; + } + + if (context?.eulaAccepted === false || /you need to agree to the eula|eula\.txt/.test(logText)) { + return { message: `EULA is not accepted on ${label} yet.`, kind: "warning" }; + } + + if (/out of memory|oom|cannot allocate memory|killed process/.test(logText) || memory !== null && memory >= 96) { + return { message: `Likely RAM issue on ${label}.`, kind: "warning" }; + } + + if (/address already in use|eaddrinuse|failed to bind|port is already allocated|bind: address/.test(logText)) { + return { message: `Likely port conflict on ${label}.`, kind: "warning" }; + } + + if (/no space left|disk quota exceeded|enospc/.test(logText) || disk !== null && disk >= 98) { + return { message: `Disk looks full on ${label}.`, kind: "warning" }; + } + + if (/unsupportedclassversionerror|has been compiled by a more recent version of the java runtime|class file version/.test(logText)) { + return { message: `Java looks mismatched on ${label}.`, kind: "warning" }; + } + + if (/failed to load plugin|could not load .*plugins|error occurred while enabling|paper plugin loader/i.test(logText)) { + return { message: `A plugin looks broken on ${label}.`, kind: "warning" }; + } + + if (/permission denied|operation not permitted|eacces|eperm/.test(logText)) { + return { message: `Looks like a file permission issue on ${label}.`, kind: "warning" }; + } + + if (/cannot find module|module not found|no module named|traceback|fatal error|panic:|uncaught exception|java\.lang\./.test(logText)) { + return { message: `${label} looks crashed by an app error.`, kind: "warning" }; + } + + if ((statusLabel === "stopped" || statusLabel === "offline") && recentActions.some((action) => /(?:^|_)(stop|kill)$/.test(action))) { + return { message: `${label} looks intentionally stopped.`, kind: "idle" }; + } + + const restartishCount = recentActions.filter((action) => /(?:^|_)(start|restart|kill)$/.test(action)).length; + if ((statusLabel === "starting" || statusLabel === "stopped" || statusLabel === "offline") && restartishCount >= 3) { + return { message: `${label} may be stuck in a restart loop.`, kind: "warning" }; + } + + if ((nodeRam !== null && nodeRam >= 96) || (nodeDisk !== null && nodeDisk >= 98) || (nodeCpu !== null && nodeCpu >= 98)) { + return { message: `The node hosting ${label} looks overloaded.`, kind: "warning" }; + } + + if (statusLabel === "running") { + if (cpu !== null && cpu >= 95) return { message: `${label} is up, but CPU is saturated.`, kind: "warning" }; + if (memory !== null && memory >= 92) return { message: `${label} is up, but RAM is nearly full.`, kind: "warning" }; + return { message: `${label} looks healthy right now.`, kind: "idle" }; + } + + if (statusLabel === "starting") { + return { message: `${label} is still starting.`, kind: "idle" }; + } + + if (statusLabel === "unknown") { + if (context?.noLogAccess) { + return { message: `I only have limited diagnostics for ${label} here.`, kind: "warning" }; + } + return { message: `I cannot read a clean status for ${label} yet.`, kind: "warning" }; + } + + return { + message: `${label} is ${statusLabel || "not healthy"} right now.`, + kind: statusLabel === "stopped" ? "idle" : "warning", + }; + } + + function buildBatchPropertiesSummary(key, value, updated, unchanged, failures, skipped, options = {}) { + const propertyKey = String(key || "").trim() || "that property"; + const valueText = String(value ?? "").trim(); + const onlyIfCurrent = String(options?.onlyIfCurrent || "").trim(); + const conditionSkipped = Array.isArray(options?.conditionSkipped) ? options.conditionSkipped : []; + const restartAfter = !!options?.restartAfter; + const restartSuccesses = Array.isArray(options?.restartSuccesses) ? options.restartSuccesses : []; + const restartFailures = Array.isArray(options?.restartFailures) ? options.restartFailures : []; + const restartSkipped = Array.isArray(options?.restartSkipped) ? options.restartSkipped : []; + const parts = []; + + if (updated.length) { + parts.push( + updated.length === 1 + ? `Updated ${propertyKey} on ${updated[0]}.` + : `Updated ${propertyKey} on ${updated.length} Minecraft servers.` + ); + } + + if (!updated.length && unchanged.length && !conditionSkipped.length) { + parts.push(`All targets already had ${propertyKey}=${valueText}.`); + } else if (unchanged.length) { + parts.push(`${unchanged.length} already matched.`); + } + + if (conditionSkipped.length) { + parts.push(`${conditionSkipped.length} skipped because ${propertyKey} was not ${onlyIfCurrent || "the expected value"}.`); + } + + if (failures.length) { + parts.push(`${failures.length} failed.`); + } + + if (skipped.length) { + parts.push(`${skipped.length} skipped.`); + } + + if (restartAfter) { + if (restartSuccesses.length) { + parts.push( + restartSuccesses.length === 1 + ? `Requested restart for ${restartSuccesses[0]}.` + : `Requested restart for ${restartSuccesses.length} servers.` + ); + } + + if (restartFailures.length) { + parts.push(`${restartFailures.length} restart${restartFailures.length === 1 ? "" : "s"} failed.`); + } + + if (restartSkipped.length) { + parts.push(`${restartSkipped.length} restart${restartSkipped.length === 1 ? "" : "s"} skipped.`); + } + } + + if (!parts.length) { + return `I could not update ${propertyKey}.`; + } + + return parts.join(" "); + } + + async function runFindBusiestNodeClientAction(actionConfig) { + try { + const metric = String(actionConfig?.metric || "balanced").trim().toLowerCase() || "balanced"; + const includeMetrics = normalizeAssistantMetricList(actionConfig?.includeMetrics); + let nodes = normalizeAssistantNodeTargets(actionConfig?.nodes || actionConfig?.nodeIds); + if (!nodes.length) { + nodes = await fetchKnownNodes(); + } + + if (!nodes.length) { + const message = "I could not find any nodes to inspect."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + const results = await mapWithConcurrency(nodes, 4, async (node) => { + try { + return await fetchJson(`/api/admin/nodes/${encodeURIComponent(node.id)}/stats`, { cache: "no-store" }); + } catch (error) { + return { ok: false, nodeId: node.id, nodeName: node.name, error: String(error?.message || "Request failed.").trim() }; + } + }); + + const adminDenied = results.some((entry) => /admin/i.test(String(entry?.error || ""))); + if (adminDenied) { + const message = "Node load is available only for admins."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + const onlineNodes = results.filter((entry) => entry?.ok && entry?.online); + if (!onlineNodes.length) { + const message = "I could not read live node stats right now."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + const busiest = onlineNodes + .slice() + .sort((left, right) => scoreAssistantNodeLoad(right, metric) - scoreAssistantNodeLoad(left, metric))[0]; + const summary = summarizeAssistantNodeLoad(busiest, metric, includeMetrics); + setStatus(summary, "idle"); + appendAssistantFollowUp(summary, { + speak: true, + sourceType: "busiest_node", + context: { + metric, + includeMetrics, + nodeId: busiest?.nodeId || null, + nodeName: busiest?.nodeName || null, + stats: busiest?.stats || null, + }, + }); + } catch (error) { + const rawMessage = String(error?.message || "Failed to inspect node load.").trim(); + const adminOnly = /not authorized|admin/i.test(rawMessage); + const message = adminOnly ? "Node load is available only for admins." : rawMessage; + setStatus(message, adminOnly ? "warning" : "error"); + appendAssistantFollowUp(message, { speak: true }); + } + } + + async function runFindBusiestServerClientAction(actionConfig) { + try { + const metric = String(actionConfig?.metric || "balanced").trim().toLowerCase() || "balanced"; + const includeMetrics = normalizeAssistantMetricList(actionConfig?.includeMetrics); + let targets = normalizeAssistantServerTargets( + actionConfig?.targets + || actionConfig?.servers + || actionConfig?.serverNames + || actionConfig?.target + || actionConfig?.server + ); + if (!targets.length) { + targets = normalizeAssistantServerTargets(await fetchAccessibleServerNames()); + } + + if (!targets.length) { + const message = "I could not find any accessible servers."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + const statuses = await fetchAssistantServerStatuses(targets.map((target) => target.server)); + const ranked = targets.map((target) => ({ + target, + status: statuses[target.server] || {}, + score: scoreAssistantServerLoad(statuses[target.server] || {}, metric), + })); + + const candidates = ranked.filter((entry) => entry.status && entry.status.nodeOnline !== false); + const busiest = (candidates.length ? candidates : ranked) + .slice() + .sort((left, right) => right.score - left.score)[0]; + + if (!busiest) { + const message = "I could not rank your servers right now."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + const detailedSummary = summarizeAssistantServerLoad(busiest.target, busiest.status, metric, includeMetrics); + setStatus(detailedSummary, "idle"); + appendAssistantFollowUp(detailedSummary, { + speak: true, + sourceType: "busiest_server", + context: { + metric, + includeMetrics, + server: busiest?.target?.server || null, + displayName: busiest?.target?.displayName || busiest?.target?.server || null, + status: busiest?.status || null, + }, + }); + } catch (error) { + const message = String(error?.message || "Failed to inspect server load.").trim(); + setStatus(message, "error"); + appendAssistantFollowUp(message, { speak: true }); + } + } + + async function runCheckServerLimitsClientAction(actionConfig) { + const query = String(actionConfig?.query || actionConfig?.server || "").trim(); + const question = String(actionConfig?.question || query).trim(); + if (!query) { + const message = "I need a server name for that limits check."; + setStatus(message, "warning"); + await appendAssistantFollowUp(message, { + speak: true, + ai: true, + sourceType: "server_limits_check", + context: { question }, + }); + return; + } + + setStatus("Finding the matching server limits...", "working"); + const servers = await fetchAccessibleServerDirectory(); + const resolved = resolveAssistantServerFromDirectory(servers, query); + if (!resolved.entry) { + const candidates = Array.isArray(resolved.candidates) && resolved.candidates.length + ? ` Try ${resolved.candidates.join(", ")}.` + : ""; + const message = `${resolved.error || "I could not match that server."}${candidates}`.trim(); + setStatus(message, "warning"); + await appendAssistantFollowUp(message, { + speak: true, + ai: true, + sourceType: "server_limits_check", + context: { + question, + query, + candidates: Array.isArray(resolved.candidates) ? resolved.candidates.slice(0, 8) : [], + }, + }); + return; + } + + setStatus(`Checking limits on ${getReadableTargetLabel(resolved.entry)}...`, "working"); + + try { + const [liveStatus, cachedStatus] = await Promise.all([ + fetchAssistantSingleServerStatus(resolved.entry.server).catch(() => null), + fetchAssistantCachedServerStatus(resolved.entry.server).catch(() => null), + ]); + + const mergedStatus = mergeAssistantServerLimitStatus(liveStatus, cachedStatus); + const summary = buildAssistantServerLimitsSummary(resolved.entry, mergedStatus, question); + setStatus(`Interpreting limits for ${getReadableTargetLabel(resolved.entry)}...`, "working"); + const finalReply = await appendAssistantFollowUp(summary.message, { + speak: true, + ai: true, + sourceType: "server_limits_check", + context: { + server: resolved.entry.server, + displayName: getReadableTargetLabel(resolved.entry), + question, + status: mergedStatus, + warnings: summary.warnings, + remaining: summary.remaining, + needsConsoleCheck: summary.needsConsoleCheck, + }, + }); + setStatus(finalReply || summary.message, summary.kind || "idle"); + } catch (error) { + const message = String(error?.message || `Failed to inspect the limits for ${getReadableTargetLabel(resolved.entry)}.`).trim(); + setStatus(message, "error"); + await appendAssistantFollowUp(message, { + speak: true, + ai: true, + sourceType: "server_limits_check", + context: { + server: resolved.entry.server, + displayName: getReadableTargetLabel(resolved.entry), + question, + error: message, + }, + }); + } + } + + async function runCheckServerConsoleClientAction(actionConfig) { + const query = String(actionConfig?.query || actionConfig?.server || "").trim(); + const question = String(actionConfig?.question || query).trim(); + if (!query) { + const message = "I need a server name for that console check."; + setStatus(message, "warning"); + await appendAssistantFollowUp(message, { + speak: true, + ai: true, + sourceType: "console_check", + context: { question }, + }); + return; + } + + setStatus("Finding the matching server console...", "working"); + const servers = await fetchAccessibleServerDirectory(); + const resolved = resolveAssistantServerFromDirectory(servers, query); + if (!resolved.entry) { + const candidates = Array.isArray(resolved.candidates) && resolved.candidates.length + ? ` Try ${resolved.candidates.join(", ")}.` + : ""; + const message = `${resolved.error || "I could not match that server."}${candidates}`.trim(); + setStatus(message, "warning"); + await appendAssistantFollowUp(message, { + speak: true, + ai: true, + sourceType: "console_check", + context: { + question, + query, + candidates: Array.isArray(resolved.candidates) ? resolved.candidates.slice(0, 8) : [], + }, + }); + return; + } + + setStatus(`Checking console on ${getReadableTargetLabel(resolved.entry)}...`, "working"); + + try { + const [statusResult, logResult] = await Promise.all([ + fetchAssistantSingleServerStatus(resolved.entry.server).catch(() => null), + readAssistantLogSnapshot(resolved.entry.server, { timeoutMs: 2200, maxLines: 80, includeMeta: true }), + ]); + + if (!logResult?.ok) { + const statusCode = Number(logResult?.status) || 0; + if (statusCode === 401 || statusCode === 403) { + const message = `You do not have permission to read the console on ${getReadableTargetLabel(resolved.entry)}.`; + setStatus(message, "warning"); + await appendAssistantFollowUp(message, { + speak: true, + ai: true, + sourceType: "console_check", + context: { + server: resolved.entry.server, + displayName: getReadableTargetLabel(resolved.entry), + question, + statusCode, + }, + }); + return; + } + + const detail = String(logResult?.error || "").trim(); + const message = detail + ? `I could not read the console on ${getReadableTargetLabel(resolved.entry)}. ${detail}` + : `I could not read the console on ${getReadableTargetLabel(resolved.entry)} right now.`; + setStatus(message, "warning"); + await appendAssistantFollowUp(message, { + speak: true, + ai: true, + sourceType: "console_check", + context: { + server: resolved.entry.server, + displayName: getReadableTargetLabel(resolved.entry), + question, + statusCode, + error: detail || "", + }, + }); + return; + } + + const summary = buildAssistantConsoleCheckSummary(resolved.entry, logResult.lines, { + status: statusResult, + question, + }); + setStatus(`Interpreting console output for ${getReadableTargetLabel(resolved.entry)}...`, "working"); + const finalReply = await appendAssistantFollowUp(summary.message, { + speak: true, + ai: true, + sourceType: "console_check", + context: { + server: resolved.entry.server, + displayName: getReadableTargetLabel(resolved.entry), + question, + status: statusResult, + logLines: Array.isArray(logResult.lines) ? logResult.lines.slice(-60) : [], + kind: summary.kind || "idle", + }, + }); + setStatus(finalReply || summary.message, summary.kind || "idle"); + } catch (error) { + const message = String(error?.message || `Failed to inspect the console for ${getReadableTargetLabel(resolved.entry)}.`).trim(); + setStatus(message, "error"); + await appendAssistantFollowUp(message, { + speak: true, + ai: true, + sourceType: "console_check", + context: { + server: resolved.entry.server, + displayName: getReadableTargetLabel(resolved.entry), + question, + error: message, + }, + }); + } + } + + async function runDiagnoseServerClientAction(actionConfig) { + const target = normalizeAssistantServerTarget(actionConfig?.target || actionConfig?.server || actionConfig); + if (!target) { + const message = "I need a server to diagnose."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + try { + setStatus(`Diagnosing ${getReadableTargetLabel(target)}...`, "working"); + + const [statusResult, infoResult, nodeInfoResult, activityResult, logLines] = await Promise.all([ + fetchJson(`/api/server/${encodeURIComponent(target.server)}/node-status`, { cache: "no-store" }).catch((error) => ({ error: error?.message || "status_failed" })), + fetchJson(`/api/server-info/${encodeURIComponent(target.server)}`, { cache: "no-store" }).catch(() => null), + fetchJson(`/api/nodes/server/${encodeURIComponent(target.server)}/info`, { cache: "no-store" }).catch(() => null), + actionConfig?.permissions?.activity_logs + ? fetchJson(`/api/server/${encodeURIComponent(target.server)}/activity?offset=0&limit=8`, { cache: "no-store" }).catch(() => ({ entries: [] })) + : Promise.resolve({ entries: [] }), + actionConfig?.permissions?.console_read + ? readAssistantLogSnapshot(target.server, { timeoutMs: 1400, maxLines: 8 }) + : Promise.resolve([]), + ]); + + if (statusResult?.error && /access denied|no access|not authenticated/i.test(String(statusResult.error))) { + const message = `I cannot inspect ${getReadableTargetLabel(target)} with this account.`; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + const template = String(infoResult?.template || actionConfig?.template || target.template || "").trim().toLowerCase(); + const nodeId = String(nodeInfoResult?.nodeId || infoResult?.nodeId || target.nodeId || "").trim(); + const [nodeStats, eulaResult, historicalLogs] = await Promise.all([ + nodeId + ? fetchJson(`/api/admin/nodes/${encodeURIComponent(nodeId)}/stats`, { cache: "no-store" }).catch(() => null) + : Promise.resolve(null), + template === "minecraft" && actionConfig?.permissions?.files_read + ? fetchJson(`/api/servers/${encodeURIComponent(target.server)}/files/read?path=${encodeURIComponent("eula.txt")}`, { cache: "no-store" }).catch(() => null) + : Promise.resolve(null), + actionConfig?.permissions?.files_read + ? readAssistantHistoricalLogSnapshot(target.server, template, 18) + : Promise.resolve({ path: "", lines: [] }), + ]); + const eulaAccepted = typeof eulaResult?.content === "string" + ? /(^|\n)\s*eula\s*=\s*true\s*($|\n)/i.test(eulaResult.content) + : null; + const mergedLogLines = Array.isArray(logLines) && logLines.length + ? logLines + : (Array.isArray(historicalLogs?.lines) ? historicalLogs.lines : []); + + const diagnosis = buildAssistantDiagnosis(target, { + status: statusResult, + info: infoResult, + nodeInfo: nodeInfoResult, + nodeStats, + eulaAccepted, + noLogAccess: !actionConfig?.permissions?.console_read && !actionConfig?.permissions?.files_read, + activityEntries: Array.isArray(activityResult?.entries) ? activityResult.entries : [], + logLines: mergedLogLines, + }); + setStatus(diagnosis.message, diagnosis.kind); + appendAssistantFollowUp(diagnosis.message, { speak: true }); + } catch (error) { + const message = String(error?.message || `Failed to diagnose ${getReadableTargetLabel(target)}.`).trim(); + setStatus(message, "error"); + appendAssistantFollowUp(message, { speak: true }); + } + } + + async function runBatchMinecraftPropertiesAction(actionConfig) { + const propertyKey = String(actionConfig?.key || actionConfig?.property || actionConfig?.propertyKey || "").trim(); + const propertyValue = actionConfig?.value ?? actionConfig?.propertyValue ?? ""; + const filePath = String(actionConfig?.path || "server.properties").trim() || "server.properties"; + const onlyIfCurrent = actionConfig?.onlyIfCurrent == null ? "" : String(actionConfig.onlyIfCurrent).trim(); + const restartAfter = !!actionConfig?.restartAfter; + const expectedValue = extractAssistantPropertiesValue(buildAssistantPropertiesLine(propertyKey, propertyValue)); + + if (!propertyKey) { + const message = "I need the server.properties key to update."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + try { + const targets = await resolveMinecraftPropertyTargets(actionConfig); + if (!targets.length) { + const message = "I could not find any accessible Minecraft servers."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + const updated = []; + const unchanged = []; + const conditionSkipped = []; + const failures = []; + const skipped = (Array.isArray(actionConfig?.skipped) ? actionConfig.skipped : []).map((entry) => getReadableTargetLabel(entry)); + const restartTargets = []; + const restartSuccesses = []; + const restartFailures = []; + const restartSkipped = []; + + for (let index = 0; index < targets.length; index += 1) { + const target = targets[index]; + const label = getReadableTargetLabel(target); + setStatus(`Updating ${propertyKey} on ${label} (${index + 1}/${targets.length})...`, "working"); + + try { + const permissions = await fetchServerPermissions(target.server); + const canRead = !!permissions?.perms?.files_read; + const canWrite = !!permissions?.perms?.files_create; + const canRestart = !!permissions?.perms?.server_start && !!permissions?.perms?.server_stop; + const writeToken = String(permissions?.actionTokens?.fileWrite || "").trim(); + + if (!canRead || !canWrite || !writeToken) { + skipped.push(label); + continue; + } + + let currentContent = ""; + try { + const fileData = await fetchJson(`/api/servers/${encodeURIComponent(target.server)}/files/read?path=${encodeURIComponent(filePath)}`, { + cache: "no-store", + }); + currentContent = typeof fileData?.content === "string" ? fileData.content : ""; + } catch (error) { + const detail = String(error?.message || "").trim().toLowerCase(); + if (!/file not found/.test(detail)) { + throw error; + } + } + + const nextFile = updateAssistantPropertiesContent(currentContent, propertyKey, propertyValue, { onlyIfCurrent }); + if (!nextFile.changed) { + if (onlyIfCurrent && nextFile.conditionMatched === false) { + conditionSkipped.push(label); + } else { + unchanged.push(label); + } + continue; + } + + await fetchJson(`/api/servers/${encodeURIComponent(target.server)}/files/write`, { + method: "PUT", + headers: { + "Content-Type": "application/json", + "x-action-token": writeToken, + }, + body: JSON.stringify({ + path: filePath, + content: nextFile.content, + }), + }); + + const readBack = await fetchJson(`/api/servers/${encodeURIComponent(target.server)}/files/read?path=${encodeURIComponent(filePath)}`, { + cache: "no-store", + }); + const verifiedContent = typeof readBack?.content === "string" ? readBack.content : ""; + if (getAssistantPropertyValue(verifiedContent, propertyKey) !== expectedValue) { + throw new Error(`The ${propertyKey} update could not be verified on ${label}.`); + } + + updated.push(label); + if (restartAfter) { + restartTargets.push({ target, label, canRestart }); + } + } catch (error) { + failures.push({ + label, + message: String(error?.message || "Request failed.").trim(), + }); + } + } + + if (restartAfter && restartTargets.length) { + for (let index = 0; index < restartTargets.length; index += 1) { + const item = restartTargets[index]; + setStatus(`Restarting ${item.label} (${index + 1}/${restartTargets.length})...`, "working"); + + if (!item.canRestart) { + restartSkipped.push({ label: item.label, reason: "permission_denied" }); + continue; + } + + try { + await requestAssistantPowerAction(item.target, "restart"); + restartSuccesses.push(item.label); + } catch (error) { + restartFailures.push({ + label: item.label, + message: String(error?.message || "Request failed.").trim(), + }); + } + } + } + + const summary = buildBatchPropertiesSummary(propertyKey, propertyValue, updated, unchanged, failures, skipped, { + onlyIfCurrent, + conditionSkipped, + restartAfter, + restartSuccesses, + restartFailures, + restartSkipped, + }); + setStatus(summary, failures.length || skipped.length || restartFailures.length || restartSkipped.length ? "warning" : "idle"); + appendAssistantFollowUp(summary, { speak: true }); + } catch (error) { + const message = String(error?.message || `Failed to update ${propertyKey}.`).trim(); + setStatus(message, "error"); + appendAssistantFollowUp(message, { speak: true }); + } + } + + async function requestAssistantPowerAction(target, action) { + const serverName = String(target?.server || target?.name || "").trim(); + if (!serverName) { + throw new Error("No server was selected."); + } + + const payload = { cmd: action }; + + const response = await fetch(`/api/nodes/server/${encodeURIComponent(serverName)}/action`, { + method: "POST", + credentials: "include", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(payload), + }); + const data = await response.json().catch(() => ({})); + + if (!response.ok || (data && data.ok === false)) { + throw new Error(data.detail || data.error || data.message || "Power action failed."); + } + + return data; + } + + function buildPowerActionSummary({ action, successes, failures, skipped, unconfirmed, pending }) { + const base = getPowerActionWord(action, "base"); + const successCount = Array.isArray(successes) ? successes.length : 0; + const failureCount = Array.isArray(failures) ? failures.length : 0; + const skippedCount = Array.isArray(skipped) ? skipped.length : 0; + const unconfirmedCount = Array.isArray(unconfirmed) ? unconfirmed.length : 0; + const pendingCount = Array.isArray(pending) ? pending.length : 0; + const sentences = []; + + if (successCount > 0) { + const targetText = successCount === 1 ? successes[0] : `${successCount} servers`; + sentences.push(`Requested ${base} for ${targetText}.`); + } + + if (pendingCount > 0) { + const firstPending = pending[0]; + const detail = firstPending?.label + ? ` ${firstPending.label} is still updating.` + : ""; + sentences.push(`Live status is still updating for ${pendingCount === 1 ? "1 server" : `${pendingCount} servers`}.${detail}`); + } + + if (unconfirmedCount > 0) { + const firstPending = unconfirmed[0]; + const detail = firstPending?.label && firstPending?.status + ? ` ${firstPending.label} is still ${firstPending.status}.` + : ""; + sentences.push(`${unconfirmedCount} did not reflect the requested state yet.${detail}`); + } + + if (failureCount > 0) { + const firstFailure = failures[0]; + const detail = firstFailure?.label + ? ` First failed: ${firstFailure.label}${firstFailure.message ? ` (${firstFailure.message})` : ""}.` + : ""; + sentences.push(`${failureCount} failed.${detail}`); + } + + if (skippedCount > 0) { + const permissionSkipped = skipped.some((item) => item?.reason === "permission_denied"); + const nodeSkipped = skipped.some((item) => item?.reason === "not_attached_to_node"); + let reasonText = ""; + if (permissionSkipped && nodeSkipped) reasonText = " due to permissions or missing node links"; + else if (permissionSkipped) reasonText = " due to permissions"; + else if (nodeSkipped) reasonText = " because they are not attached to nodes"; + sentences.push(`${skippedCount} skipped${reasonText}.`); + } + + if (!sentences.length) { + return `I couldn't ${base} any servers.`; + } + + return sentences.join(" "); + } + + async function runPowerServerClientAction(actionConfig) { + const action = normalizeAssistantPowerAction(actionConfig?.action); + const targets = Array.isArray(actionConfig?.targets) ? actionConfig.targets.filter((item) => item?.server || item?.name) : []; + const skipped = Array.isArray(actionConfig?.skipped) ? actionConfig.skipped : []; + + if (!action || !targets.length) { + const summary = buildPowerActionSummary({ action, successes: [], failures: [], skipped }); + setStatus(summary, "warning"); + if (skipped.length) { + appendAssistantFollowUp(summary, { speak: true }); + } + return; + } + + const successes = []; + const failures = []; + const unconfirmed = []; + const pending = []; + + for (let index = 0; index < targets.length; index += 1) { + const target = targets[index]; + const label = getPowerTargetLabel(target); + setStatus(`${capitalizeText(getPowerActionWord(action, "progressive"))} ${label} (${index + 1}/${targets.length})...`, "working"); + try { + await requestAssistantPowerAction(target, action); + successes.push(label); + const observation = await waitForAssistantPowerObservation(target.server, action); + if (!observation.confirmed) { + if (observation.pending) { + pending.push({ + label, + status: observation.status, + }); + } else { + unconfirmed.push({ + label, + status: observation.status, + }); + } + } + } catch (error) { + failures.push({ + label, + message: String(error?.message || "Request failed.").trim(), + }); + } + } + + const summary = buildPowerActionSummary({ action, successes, failures, skipped, unconfirmed, pending }); + const shouldAppendFollowUp = !!(failures.length || skipped.length || unconfirmed.length); + if (shouldAppendFollowUp) { + appendAssistantFollowUp(summary, { speak: true }); + } + + if (failures.length || skipped.length || unconfirmed.length) { + setStatus(summary, "warning"); + return; + } + + if (pending.length) { + setStatus(summary, "idle"); + return; + } + + if (targets.length === 1 && successes.length === 1) { + const message = `Requested ${getPowerActionWord(action, "base")} for ${successes[0]}.`; + setStatus(message, "idle"); + return; + } + + setStatus(summary, "idle"); + } + + async function runResolveAndPowerServerClientAction(actionConfig) { + const action = normalizeAssistantPowerAction(actionConfig?.action); + const query = String(actionConfig?.query || actionConfig?.server || "").trim(); + if (!action || !query) { + const message = "I need a server name for that power action."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + setStatus(`Finding the matching server for ${getPowerActionWord(action, "base")}...`, "working"); + const servers = await fetchAccessibleServerDirectory(); + const resolved = resolveAssistantServerFromDirectory(servers, query); + if (!resolved.entry) { + const candidates = Array.isArray(resolved.candidates) && resolved.candidates.length + ? ` Try ${resolved.candidates.join(", ")}.` + : ""; + const message = `${resolved.error || "I could not match that server."}${candidates}`.trim(); + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + try { + const permissions = await fetchServerPermissions(resolved.entry.server); + if (!canAssistantRunPowerAction(permissions?.perms, action)) { + const message = `You do not have permission to ${getPowerActionWord(action, "base")} ${getReadableTargetLabel(resolved.entry)}.`; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + } catch { + const message = `I could not verify power permissions for ${getReadableTargetLabel(resolved.entry)}.`; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + await runPowerServerClientAction({ + action, + targets: [resolved.entry], + skipped: [], + }); + } + + async function runOpenServerPageClientAction(actionConfig) { + const query = String(actionConfig?.query || actionConfig?.server || "").trim(); + const section = normalizeAssistantServerPageSectionValue(actionConfig?.section); + if (!query) { + const message = "I can't help with that server link right now."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: false }); + return false; + } + + const cachedServers = getCachedAccessibleServerDirectory(); + const cachedResolved = cachedServers.length + ? resolveAssistantServerFromDirectory(cachedServers, query) + : { entry: null }; + + if (cachedResolved.entry) { + const label = getReadableTargetLabel(cachedResolved.entry); + const url = buildAssistantServerPageUrl(cachedResolved.entry.server, section); + const sectionLabel = getAssistantServerPageSectionLabel(section); + const linkLabel = section === "console" + ? `Open ${label}` + : `Open ${sectionLabel} for ${label}`; + appendAssistantNavigationLink(linkLabel, url, { + prefix: "Tap the link below to open it in a new tab.", + speak: false, + }); + return true; + } + + setStatus(`Finding the matching server for ${getAssistantServerPageSectionLabel(section)}...`, "working"); + const servers = await fetchAccessibleServerDirectory(); + const resolved = resolveAssistantServerFromDirectory(servers, query); + if (!resolved.entry) { + const candidates = Array.isArray(resolved.candidates) && resolved.candidates.length + ? ` Try ${resolved.candidates.join(", ")}.` + : ""; + const message = `I can't help with that server link right now.${candidates}`.trim(); + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: false }); + return false; + } + + const label = getReadableTargetLabel(resolved.entry); + const url = buildAssistantServerPageUrl(resolved.entry.server, section); + if (!url) { + const message = `I could not open ${label} right now.`; + setStatus(message, "error"); + appendAssistantFollowUp(message, { speak: true }); + return false; + } + + const sectionLabel = getAssistantServerPageSectionLabel(section); + const linkLabel = section === "console" + ? `Open ${label}` + : `Open ${sectionLabel} for ${label}`; + appendAssistantNavigationLink(linkLabel, url, { + prefix: "Tap the link below to open it in a new tab.", + speak: false, + }); + return true; + } + + async function runOpenSettingsDestinationClientAction(actionConfig) { + const action = normalizeAssistantSettingsActionValue(actionConfig?.action); + const panel = normalizeAssistantSettingsPanelValue(actionConfig?.panel) || inferAssistantSettingsPanelFromActionValue(action); + if (!state.isAdmin) { + const message = "Only administrators can open settings tools."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return false; + } + if (!panel && !action) { + const message = "I can't help with that settings link right now."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: false }); + return false; + } + + const url = buildAssistantSettingsUrl(panel, action); + const linkLabel = action + ? `Open ${getAssistantSettingsActionLabel(action)}` + : `Open ${getAssistantSettingsPanelLabel(panel)}`; + appendAssistantNavigationLink(linkLabel, url, { + prefix: "Tap the link below to open it in a new tab.", + speak: false, + }); + return true; + } + + async function runPowerAccessibleServersClientAction(actionConfig) { + const action = normalizeAssistantPowerAction(actionConfig?.action); + if (!action) { + const message = "I need a valid power action."; + setStatus(message, "warning"); + appendAssistantFollowUp(message, { speak: true }); + return; + } + + setStatus(`Finding accessible servers to ${getPowerActionWord(action, "base")}...`, "working"); + const { targets, skipped } = await buildAccessibleAssistantPowerTargets(action); + await runPowerServerClientAction({ + action, + targets, + skipped, + }); + } + + async function runClientActions(actions) { + const report = { + handled: 0, + unknown: 0, + openedTabs: 0, + errors: [], + }; + if (!Array.isArray(actions) || !actions.length) return report; + + for (const action of actions) { + try { + if (action?.type === "power_servers") { + report.handled += 1; + await runPowerServerClientAction(action); + continue; + } + if (assistantActionMatches(action, ["assistant_power_accessible_servers", "power_accessible_servers"])) { + report.handled += 1; + await runPowerAccessibleServersClientAction(action); + continue; + } + if (assistantActionMatches(action, ["assistant_resolve_power_server", "resolve_power_server"])) { + report.handled += 1; + await runResolveAndPowerServerClientAction(action); + continue; + } + if (assistantActionMatches(action, ["assistant_open_server_page", "open_server_page"])) { + report.handled += 1; + await runOpenServerPageClientAction(action); + continue; + } + if (assistantActionMatches(action, ["assistant_open_settings_destination", "open_settings_destination"])) { + report.handled += 1; + await runOpenSettingsDestinationClientAction(action); + continue; + } + if (assistantActionMatches(action, ["find_busiest_node", "assistant_find_busiest_node", "busiest_node"])) { + report.handled += 1; + await runFindBusiestNodeClientAction(action); + continue; + } + if (assistantActionMatches(action, ["find_busiest_server", "assistant_find_busiest_server", "busiest_server"])) { + report.handled += 1; + await runFindBusiestServerClientAction(action); + continue; + } + if (assistantActionMatches(action, ["check_server_console", "assistant_check_server_console", "server_console_check"])) { + report.handled += 1; + await runCheckServerConsoleClientAction(action); + continue; + } + if (assistantActionMatches(action, ["check_server_limits", "assistant_check_server_limits", "server_limits_check"])) { + report.handled += 1; + await runCheckServerLimitsClientAction(action); + continue; + } + if (assistantActionMatches(action, ["diagnose_server", "assistant_diagnose_server", "server_diagnosis"])) { + report.handled += 1; + await runDiagnoseServerClientAction(action); + continue; + } + if (assistantActionMatches(action, [ + "update_minecraft_server_property", + "assistant_update_minecraft_server_property", + "update_minecraft_server_properties", + "assistant_update_minecraft_server_properties", + "batch_update_server_properties", + "batch_update_minecraft_property", + ])) { + report.handled += 1; + await runBatchMinecraftPropertiesAction(action); + continue; + } + if (action?.type === "open_account_flow") { + report.handled += 1; + const helper = window.ADPanelDashboardAccount; + if (!helper || typeof helper.openAccountFlow !== "function") { + setStatus("The account flow could not be opened here.", "error"); + report.errors.push("The account flow could not be opened here."); + continue; + } + await helper.openAccountFlow(action.flow); + continue; + } + if (action?.type === "open_create_server_modal") { + report.handled += 1; + const helper = window.ADPanelDashboardCreate; + if (!helper || typeof helper.openCreateModal !== "function") { + setStatus("The create server window could not be opened here.", "error"); + report.errors.push("The create server window could not be opened here."); + continue; + } + closeMenu(); + await helper.openCreateModal(); + continue; + } + if (action?.type === "confirm_delete_server") { + report.handled += 1; + openDeleteModal(action); + continue; + } + + report.unknown += 1; + } catch (error) { + const message = String(error?.message || "Browser action failed.").trim(); + report.errors.push(message); + setStatus(message, "error"); + appendAssistantFollowUp(message, { speak: true }); + } + } + + return report; + } + + async function confirmDeleteModal() { + if (!state.pendingDeleteServer || state.deletingServer) return; + + const serverName = String(state.pendingDeleteServer.server || "").trim(); + if (!serverName) return; + + state.deletingServer = true; + if (els.deleteConfirm) { + els.deleteConfirm.disabled = true; + els.deleteConfirm.innerHTML = 'Deleting...'; + } + setStatus(`Deleting ${serverName}...`, "working"); + + try { + const data = await fetchJson("/api/dashboard-assistant/confirm-delete", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + chatId: state.chatId, + server: serverName, + }), + }); + + applyBootstrap({ + configured: state.configured, + canConfigure: state.canConfigure, + allowNormalUsers: state.allowNormalUsers, + provider: data.provider || state.provider, + providers: data.providers || state.providers, + chat: data.chat, + messages: Array.isArray(data.messages) ? data.messages : [], + actionTokens: state.actionTokens, + }); + + closeDeleteModal(true); + const reply = String(data.reply || `Deleted ${serverName}.`).trim(); + setStatus("Assistant ready.", "idle"); + if (reply) { + const spoken = speakAssistantReply(reply); + if (!spoken) { + setVoiceState("Voice playback could not start automatically."); + } + } + } catch (error) { + setStatus(error.message || "Failed to delete that server.", "error"); + if (els.deleteConfirm) { + els.deleteConfirm.disabled = false; + els.deleteConfirm.innerHTML = 'Delete server'; + } + } finally { + state.deletingServer = false; + } + } + + async function submitMessage(rawMessage, options = {}) { + const normalize = !!options.normalize; + const message = normalize ? normalizeRecognizedTranscript(rawMessage) : String(rawMessage || "").trim(); + if (!message || state.requestInFlight) return false; + const now = Date.now(); + if ( + state.lastSubmittedTranscript && + message === state.lastSubmittedTranscript && + now - state.lastSubmittedAt < 4000 + ) { + return false; + } + state.recognitionFallbackTranscript = ""; + if (!state.configured) { + setStatus( + state.canConfigure + ? `Save a ${getProviderMeta(state.provider).label} API key before using the voice assistant.` + : "The administrator has not configured an AI provider yet.", + "warning" + ); + return false; + } + + const previousMessages = Array.from((els.messages && els.messages.children) || []).map((node) => node.cloneNode(true)); + const requestGeneration = state.chatGeneration; + state.bootstrapRequestId += 1; + state.requestInFlight = true; + state.lastSubmittedTranscript = message; + state.lastSubmittedAt = now; + if (messageLooksLikeAssistantServerPrefetchIntent(message)) { + warmAccessibleServerDirectory(); + } + stopSpeaking(); + updateButtons(); + setStatus("Assistant is working...", "working"); + setTranscriptPreview(normalize ? `You said: ${message}` : ""); + + if (els.messages) { + appendMessageToUi({ role: "user", content: message, created_at: new Date().toISOString() }); + } + + try { + const data = await fetchJson("/api/dashboard-assistant/chat", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + chatId: state.chatId, + message, + }), + }); + if (requestGeneration !== state.chatGeneration) { + return false; + } + const reply = String(data.reply || "").trim(); + const clientActions = Array.isArray(data.clientActions) ? data.clientActions : []; + const hasExecutionActions = clientActions.some((action) => isExecutionClientAction(action)); + const serverMessages = Array.isArray(data.messages) ? data.messages : []; + const lastServerAssistant = [...serverMessages].reverse().find((message) => message && message.role === "assistant"); + const serverAssistantReply = String(lastServerAssistant?.content || "").trim(); + const hasRenderedAssistant = !hasExecutionActions && !!serverAssistantReply && (!reply || serverAssistantReply === reply); + applyBootstrap({ + configured: state.configured, + canConfigure: state.canConfigure, + allowNormalUsers: state.allowNormalUsers, + provider: data.provider || state.provider, + providers: data.providers || state.providers, + chat: data.chat, + messages: hasRenderedAssistant ? serverMessages : [], + actionTokens: state.actionTokens, + }, { preserveRenderedMessages: hasExecutionActions || !hasRenderedAssistant }); + if (!hasRenderedAssistant && reply) { + appendMessageToUi({ role: "assistant", content: reply, created_at: new Date().toISOString() }); + state.lastAssistantReply = reply; + } + setTranscriptPreview(""); + const assistantMessagesBeforeActions = countAssistantMessagesInUi(); + const clientActionReport = await runClientActions(clientActions); + if (hasExecutionActions) { + if (clientActionReport.handled < 1) { + const message = clientActionReport.errors[0] || "Browser action could not start."; + setStatus(message, "error"); + appendAssistantFollowUp(message, { speak: true }); + } else if (reply && countAssistantMessagesInUi() === assistantMessagesBeforeActions) { + const spoken = speakAssistantReply(reply); + if (!spoken) { + setVoiceState("Voice playback could not start automatically."); + } + } + return true; + } + setStatus("Assistant ready.", "idle"); + if (reply) { + const spoken = speakAssistantReply(reply); + if (!spoken) { + setVoiceState("Voice playback could not start automatically."); + } + } + return true; + } catch (error) { + if (requestGeneration !== state.chatGeneration) { + return false; + } + if (els.messages) { + els.messages.innerHTML = ""; + previousMessages.forEach((node) => els.messages.appendChild(node)); + } + setStatus(error.message || "Assistant request failed.", "error"); + return false; + } finally { + state.requestInFlight = false; + updateButtons(); + if (!state.recording && !state.transcribing) { + setTranscriptPreview(""); + } + } + } + + async function submitTranscript(rawTranscript) { + return submitMessage(rawTranscript, { normalize: true }); + } + + async function submitTextMessage(event) { + event?.preventDefault(); + const value = String(els.textInput?.value || "").trim(); + if (!value) return; + const sent = await submitMessage(value, { normalize: false }); + if (sent && els.textInput) { + els.textInput.value = ""; + } + updateButtons(); + } + + async function uploadRecording(blob, mimeType, fallbackTranscript = "") { + const formData = new FormData(); + const extension = inferAudioExtension(mimeType || blob.type); + formData.append("audio", blob, `dashboard-assistant.${extension}`); + const language = getPreferredTranscriptionLanguage(); + if (language) { + formData.append("language", language); + } + formData.append("prompt", buildTranscriptionPrompt()); + state.transcribing = true; + updateButtons(); + setStatus("Transcribing your recording...", "transcribing"); + + try { + const response = await fetch("/api/dashboard-assistant/transcribe", { + method: "POST", + body: formData, + credentials: "include", + }); + const data = await response.json().catch(() => ({})); + if (!response.ok) { + throw new Error(data.error || "Transcription failed."); + } + await submitTranscript(data.transcript || ""); + } catch (error) { + const fallback = normalizeRecognizedTranscript(fallbackTranscript || state.recognitionFallbackTranscript); + if (fallback) { + setStatus("AI transcription failed, using the live speech transcript instead.", "warning"); + await submitTranscript(fallback); + return; + } + setStatus(error.message || "Voice transcription failed.", "error"); + } finally { + state.transcribing = false; + updateButtons(); + if (!state.requestInFlight && !state.recording) { + setStatus(state.configured ? "Voice assistant ready." : "No AI provider is configured.", state.configured ? "idle" : "warning"); + } + } + } + + function cleanupAudioGraph() { + try { + state.audioProcessorNode?.disconnect(); + } catch { + } + try { + state.audioSourceNode?.disconnect(); + } catch { + } + try { + state.audioMonitorGain?.disconnect(); + } catch { + } + state.audioFilterNodes.forEach((node) => { + try { + node?.disconnect?.(); + } catch { + } + }); + if (state.audioContext) { + state.audioContext.close().catch(() => {}); + } + state.audioProcessorNode = null; + state.audioSourceNode = null; + state.audioMonitorGain = null; + state.audioContext = null; + state.audioFilterNodes = []; + } + + function stopActiveStream() { + try { + state.mediaStream?.getTracks().forEach((track) => track.stop()); + } catch { + } + state.mediaStream = null; + } + + async function stopRecordingAndUpload() { + const currentSessionId = state.recordingSessionId; + if (state.recognitionMode && state.recognition && !hasCapturedAudioActive()) { + state.recognitionStopping = true; + state.recording = false; + updateButtons(); + setStatus("Finalizing transcript...", "working"); + setVoiceState("Finishing speech recognition..."); + try { + state.recognition.stop(); + } catch { + const transcript = getRecognitionTranscript(); + cleanupRecognition(); + if (transcript) { + await submitTranscript(transcript); + } else { + setStatus("I didn't catch that. Try speaking a little closer to the mic.", "warning"); + } + } + return; + } + + if (state.recognitionMode && state.recognition) { + state.recognitionFallbackTranscript = getRecognitionTranscript(); + state.recognitionStopping = true; + try { + state.recognition.stop(); + } catch { + cleanupRecognition(); + } + } + + if (state.mediaRecorder) { + state.recording = false; + updateButtons(); + state.mediaRecorder.stop(); + return; + } + + if (state.audioContext) { + state.recording = false; + updateButtons(); + const pcmChunks = state.pcmChunks.slice(); + const sampleRate = state.pcmSampleRate; + state.pcmChunks = []; + cleanupAudioGraph(); + stopActiveStream(); + + if (!pcmChunks.length) { + const fallback = normalizeRecognizedTranscript(state.recognitionFallbackTranscript); + if (fallback) { + await submitTranscript(fallback); + } else { + setStatus("The recording was empty.", "warning"); + } + return; + } + + const prepared = prepareSpeechPcm(pcmChunks, sampleRate); + if (!prepared.pcm.length) { + const fallback = normalizeRecognizedTranscript(state.recognitionFallbackTranscript); + if (fallback) { + await submitTranscript(fallback); + } else { + setStatus("The recording was too quiet to transcribe clearly.", "warning"); + } + return; + } + const wavBlob = encodeWavBlob(prepared.pcm, prepared.sampleRate); + if (currentSessionId === state.recordingSessionId) { + await uploadRecording(wavBlob, "audio/wav", state.recognitionFallbackTranscript); + } + } + } + + function createMicrophoneStartErrorMessage(error) { + const name = String(error?.name || "").toLowerCase(); + if (!window.isSecureContext && !isLocalhostHost()) { + return "Microphone access requires HTTPS or localhost. Safari will not prompt on plain HTTP."; + } + if (name === "notallowederror" || name === "securityerror") { + return "Microphone permission was denied. Check the browser site permissions and try again."; + } + if (name === "notfounderror") { + return "No microphone was found on this device."; + } + if (name === "notreadableerror" || name === "trackstarterror") { + return "The microphone is already in use by another app or tab."; + } + return error?.message || "Failed to start microphone recording."; + } + + function createRecognitionErrorMessage(errorCode) { + const code = String(errorCode || "").trim().toLowerCase(); + if (code === "not-allowed" || code === "service-not-allowed") { + return "Speech recognition permission was denied. Check the browser site permissions and try again."; + } + if (code === "audio-capture") { + return "The browser could not access a working microphone."; + } + if (code === "network") { + return "Live speech recognition failed because the browser recognition service was unavailable."; + } + if (code === "no-speech") { + return "No clear speech was detected. Try speaking a little closer to the microphone."; + } + return "Live speech recognition could not start in this browser."; + } + + function cleanupRecognition() { + if (state.recognition) { + state.recognition.onstart = null; + state.recognition.onresult = null; + state.recognition.onerror = null; + state.recognition.onend = null; + } + state.recognition = null; + state.recognitionMode = false; + state.recognitionFinalTranscript = ""; + state.recognitionInterimTranscript = ""; + state.recognitionStopping = false; + state.recognitionErrorMessage = ""; + state.recognitionPreviewOnly = false; + } + + async function applyPreferredTrackConstraints(stream) { + const track = stream?.getAudioTracks?.()[0]; + if (!track || typeof track.applyConstraints !== "function") return; + + try { + await track.applyConstraints({ + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true, + channelCount: 1, + sampleRate: TARGET_PCM_SAMPLE_RATE, + sampleSize: 16, + advanced: [ + { + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true, + voiceIsolation: true, + }, + ], + }); + } catch { + } + } + + async function startCapturedRecording() { + state.recordingSessionId += 1; + state.recognitionFallbackTranscript = ""; + state.recognitionFinalTranscript = ""; + state.recognitionInterimTranscript = ""; + state.recognitionErrorMessage = ""; + setTranscriptPreview(""); + + const stream = await navigator.mediaDevices.getUserMedia({ + audio: { + channelCount: { ideal: 1 }, + sampleRate: { ideal: TARGET_PCM_SAMPLE_RATE }, + sampleSize: { ideal: 16 }, + echoCancellation: true, + noiseSuppression: true, + autoGainControl: true, + voiceIsolation: true, + }, + }); + + await applyPreferredTrackConstraints(stream); + + const mode = chooseRecorderMode(); + if (mode === "media-recorder") { + await startMediaRecorder(stream); + return; + } + await startPcmRecorder(stream); + } + + async function startSpeechRecognition(options = {}) { + if (!supportsSpeechRecognition()) { + throw new Error("This browser does not support live speech recognition here."); + } + + const previewOnly = !!options.previewOnly; + const sessionId = Number(options.sessionId || state.recordingSessionId || 0); + + return new Promise((resolve, reject) => { + let started = false; + let settled = false; + const recognition = new SpeechRecognitionClass(); + + state.recognition = recognition; + state.recognitionMode = true; + state.recognitionFinalTranscript = ""; + state.recognitionInterimTranscript = ""; + state.recognitionStopping = false; + state.recognitionErrorMessage = ""; + state.recognitionPreviewOnly = previewOnly; + + recognition.lang = state.preferredSpeechLang || "en-US"; + recognition.continuous = true; + recognition.interimResults = true; + recognition.maxAlternatives = 5; + + recognition.onstart = () => { + started = true; + settled = true; + if (!previewOnly) { + state.recording = true; + updateButtons(); + setStatus("Listening live...", "recording"); + setVoiceState("Listening with live speech recognition..."); + setTranscriptPreview(""); + } else { + setVoiceState("Live speech preview is active."); + } + resolve(); + }; + + recognition.onresult = (event) => { + if (sessionId !== state.recordingSessionId) return; + const results = Array.from(event.results || []); + const finalParts = []; + const interimParts = []; + + results.forEach((result) => { + const transcript = pickBestRecognitionAlternative(result); + if (!transcript) return; + if (result.isFinal) { + finalParts.push(transcript); + } else { + interimParts.push(transcript); + } + }); + + state.recognitionFinalTranscript = finalParts.join(" ").trim(); + state.recognitionInterimTranscript = interimParts.join(" ").trim(); + + const preview = getRecognitionTranscript(); + + if (preview) { + state.recognitionFallbackTranscript = preview; + setTranscriptPreview(`Listening: ${preview}`); + setVoiceState("Speech detected. Tap again to send or keep talking."); + } + }; + + recognition.onerror = (event) => { + if (sessionId !== state.recordingSessionId) return; + const errorCode = String(event?.error || "").trim().toLowerCase(); + if (errorCode === "aborted" && state.recognitionStopping) { + return; + } + const message = createRecognitionErrorMessage(errorCode); + state.recognitionErrorMessage = message; + if (!started && !settled) { + settled = true; + cleanupRecognition(); + reject(new Error(message)); + } + }; + + recognition.onend = () => { + if (sessionId !== state.recordingSessionId) return; + const transcript = getRecognitionTranscript(); + const shouldSubmit = !!transcript; + const errorMessage = state.recognitionErrorMessage; + const stoppedByUser = state.recognitionStopping; + const previewOnlyMode = state.recognitionPreviewOnly; + const captureActive = hasCapturedAudioActive(); + if (transcript) { + state.recognitionFallbackTranscript = transcript; + } + + cleanupRecognition(); + if (!previewOnlyMode) { + state.recording = false; + updateButtons(); + } + + if (previewOnlyMode) { + if (errorMessage && !captureActive) { + setStatus(errorMessage, "error"); + setNotice(errorMessage); + } else if (errorMessage) { + setVoiceState(errorMessage); + } + return; + } + + if (shouldSubmit) { + setStatus("Speech recognized.", "working"); + void submitTranscript(transcript); + return; + } + + if (errorMessage) { + setStatus(errorMessage, "error"); + setNotice(errorMessage); + return; + } + + if (stoppedByUser) { + setStatus("I didn't catch that. Try speaking a little closer to the mic.", "warning"); + setVoiceState("No speech detected."); + } + }; + + try { + recognition.start(); + } catch (error) { + cleanupRecognition(); + reject(error); + } + }); + } + + function chooseRecorderMode() { + if (typeof MediaRecorder === "undefined") { + return "pcm"; + } + const preferredMimeTypes = [ + "audio/webm;codecs=opus", + "audio/webm", + "audio/mp4", + "audio/mp4;codecs=mp4a.40.2", + ]; + const supported = preferredMimeTypes.find((mimeType) => + typeof MediaRecorder.isTypeSupported === "function" ? MediaRecorder.isTypeSupported(mimeType) : false + ); + if (supported) { + state.mediaMimeType = supported; + if (supported.includes("webm")) return "media-recorder"; + } + return AudioContextClass ? "pcm" : "media-recorder"; + } + + async function startMediaRecorder(stream) { + const options = state.mediaMimeType ? { mimeType: state.mediaMimeType } : undefined; + const recorder = options ? new MediaRecorder(stream, options) : new MediaRecorder(stream); + const sessionId = state.recordingSessionId; + + state.mediaRecorder = recorder; + state.mediaChunks = []; + state.mediaStream = stream; + state.recording = true; + + recorder.addEventListener("dataavailable", (event) => { + if (event.data && event.data.size > 0) { + state.mediaChunks.push(event.data); + } + }); + + recorder.addEventListener("stop", async () => { + const mimeType = recorder.mimeType || state.mediaMimeType || "audio/webm"; + const blob = new Blob(state.mediaChunks, { type: mimeType }); + state.mediaChunks = []; + state.mediaRecorder = null; + stopActiveStream(); + + if (sessionId !== state.recordingSessionId) { + return; + } + + if (blob.size > 0) { + await uploadRecording(blob, mimeType, state.recognitionFallbackTranscript); + } else { + const fallback = normalizeRecognizedTranscript(state.recognitionFallbackTranscript); + if (fallback) { + await submitTranscript(fallback); + } else { + setStatus("The recording was empty.", "warning"); + } + } + }); + + recorder.start(); + updateButtons(); + setStatus("Listening...", "recording"); + setVoiceState("Recording voice input..."); + } + + async function startPcmRecorder(stream) { + if (!AudioContextClass) { + throw new Error("This browser cannot record audio here."); + } + + const audioContext = new AudioContextClass(); + if (audioContext.state === "suspended") { + await audioContext.resume().catch(() => {}); + } + + const sourceNode = audioContext.createMediaStreamSource(stream); + const highPass = audioContext.createBiquadFilter(); + const lowPass = audioContext.createBiquadFilter(); + const compressor = audioContext.createDynamicsCompressor(); + const processorNode = audioContext.createScriptProcessor(4096, 1, 1); + const monitorGain = audioContext.createGain(); + highPass.type = "highpass"; + highPass.frequency.value = 80; + lowPass.type = "lowpass"; + lowPass.frequency.value = 4600; + compressor.threshold.value = -24; + compressor.knee.value = 18; + compressor.ratio.value = 3; + compressor.attack.value = 0.003; + compressor.release.value = 0.25; + monitorGain.gain.value = 0; + + state.audioContext = audioContext; + state.audioSourceNode = sourceNode; + state.audioProcessorNode = processorNode; + state.audioMonitorGain = monitorGain; + state.audioFilterNodes = [highPass, lowPass, compressor]; + state.mediaStream = stream; + state.pcmChunks = []; + state.pcmSampleRate = audioContext.sampleRate; + state.recording = true; + + processorNode.onaudioprocess = (event) => { + const input = event.inputBuffer.getChannelData(0); + state.pcmChunks.push(new Float32Array(input)); + }; + + sourceNode.connect(highPass); + highPass.connect(lowPass); + lowPass.connect(compressor); + compressor.connect(processorNode); + processorNode.connect(monitorGain); + monitorGain.connect(audioContext.destination); + + updateButtons(); + setStatus("Listening...", "recording"); + setVoiceState("Recording voice input..."); + } + + async function toggleRecording() { + if (state.transcribing || state.requestInFlight) return; + if (!state.configured) { + setStatus(`Save a ${getProviderMeta(state.provider).label} key before using voice input.`, "warning"); + return; + } + + if (state.recording) { + await stopRecordingAndUpload(); + return; + } + + const capabilityIssue = getMicrophoneCapabilityIssue(); + if (capabilityIssue) { + setStatus(capabilityIssue, "error"); + setNotice(capabilityIssue); + return; + } + + primeSpeechSynthesis(); + stopSpeaking(); + + try { + try { + await startCapturedRecording(); + const activeSessionId = state.recordingSessionId; + if (supportsSpeechRecognition()) { + void startSpeechRecognition({ previewOnly: true, sessionId: activeSessionId }).catch(() => { + setVoiceState("Live speech preview is unavailable here. AI transcription will still be used."); + }); + } + return; + } catch (captureError) { + if (supportsSpeechRecognition()) { + await startSpeechRecognition(); + return; + } + throw captureError; + } + } catch (error) { + const message = createMicrophoneStartErrorMessage(error); + setStatus(message, "error"); + setNotice(message); + stopActiveStream(); + cleanupAudioGraph(); + cleanupRecognition(); + state.mediaRecorder = null; + state.mediaChunks = []; + state.pcmChunks = []; + state.recording = false; + updateButtons(); + } + } + + function bindEvents() { + els.trigger?.addEventListener("click", (event) => { + event.stopPropagation(); + if (!state.open) { + openMenu(); + return; + } + positionMenu(); + }); + + els.close?.addEventListener("click", closeMenu); + els.reset?.addEventListener("click", () => { void resetChat(); }); + els.configToggle?.addEventListener("click", () => { + if (!els.config) return; + els.config.hidden = !els.config.hidden; + updateButtons(); + positionMenu(); + }); + els.providerSelect?.addEventListener("change", () => { + state.provider = String(els.providerSelect.value || state.provider || "groq").trim().toLowerCase() || "groq"; + syncProviderUi(); + syncStoredTokenField(true); + updateTokenStateText(); + }); + els.userAccessToggle?.addEventListener("change", () => { + void saveAssistantAccessSetting(!!els.userAccessToggle?.checked); + }); + els.tokenForm?.addEventListener("submit", (event) => { void saveToken(event); }); + els.tokenInput?.addEventListener("focus", () => { + if (state.tokenFieldUsesStoredValue) { + els.tokenInput.select(); + } + }); + els.tokenInput?.addEventListener("keydown", (event) => { + const key = String(event.key || "").toLowerCase(); + if ((event.ctrlKey || event.metaKey) && (key === "c" || key === "x")) { + event.preventDefault(); + return; + } + if ( + state.tokenFieldUsesStoredValue + && !event.ctrlKey + && !event.metaKey + && !event.altKey + && (event.key.length === 1 || event.key === "Backspace" || event.key === "Delete") + ) { + clearStoredTokenFieldIfNeeded(); + } + }); + els.tokenInput?.addEventListener("paste", () => { + clearStoredTokenFieldIfNeeded(); + }); + els.tokenInput?.addEventListener("beforeinput", (event) => { + if (!state.tokenFieldUsesStoredValue) return; + const inputType = String(event.inputType || ""); + if (!inputType || inputType === "insertCompositionText") return; + clearStoredTokenFieldIfNeeded(); + }); + els.tokenInput?.addEventListener("input", () => { + const storedValue = getStoredTokenFieldValue(state.provider); + state.tokenFieldUsesStoredValue = !!storedValue && els.tokenInput.value === storedValue; + if (els.tokenInput) { + els.tokenInput.dataset.storedValue = state.tokenFieldUsesStoredValue ? "1" : ""; + } + }); + els.tokenInput?.addEventListener("copy", (event) => { + event.preventDefault(); + }); + els.tokenInput?.addEventListener("cut", (event) => { + event.preventDefault(); + }); + els.tokenInput?.addEventListener("blur", () => { + if (!String(els.tokenInput?.value || "").trim()) { + syncStoredTokenField(false); + } + }); + els.composeForm?.addEventListener("submit", (event) => { void submitTextMessage(event); }); + els.textInput?.addEventListener("input", updateButtons); + els.textInput?.addEventListener("keydown", (event) => { + if (event.key === "Enter" && !event.shiftKey) { + event.preventDefault(); + void submitTextMessage(event); + } + }); + els.menu?.addEventListener("click", (event) => { + event.stopPropagation(); + }); + + els.mic?.addEventListener("click", (event) => { + event.stopPropagation(); + void toggleRecording(); + }); + + let isSettingPtt = false; + let currentPttKey = localStorage.getItem("dashboardAssistantPttKey") || "None"; + if (els.pttBtn) { + els.pttBtn.textContent = currentPttKey === " " ? "Space" : currentPttKey; + els.pttBtn.addEventListener("click", () => { + isSettingPtt = true; + els.pttBtn.textContent = "Listening..."; + }); + } + + document.addEventListener("keydown", (event) => { + if (isSettingPtt) { + event.preventDefault(); + event.stopPropagation(); + currentPttKey = event.code; + localStorage.setItem("dashboardAssistantPttKey", currentPttKey); + els.pttBtn.textContent = event.code === "Space" ? "Space" : event.code; + isSettingPtt = false; + return; + } + + if (event.key === "Escape" && state.open && !isSettingPtt) return; + + if (currentPttKey && currentPttKey !== "None" && event.code === currentPttKey) { + const tagName = document.activeElement?.tagName?.toLowerCase(); + if (tagName === "input" || tagName === "textarea") return; + event.preventDefault(); + if (!state.recording && !state.requestInFlight && state.configured && !event.repeat && !state.transcribing) { + void toggleRecording(); + } + } + }); + + document.addEventListener("keyup", (event) => { + if (currentPttKey && currentPttKey !== "None" && event.code === currentPttKey) { + if (!isSettingPtt && state.recording) { + void toggleRecording(); + } + } + }); + els.replay?.addEventListener("click", (event) => { + event.stopPropagation(); + if (!state.lastAssistantReply) return; + primeSpeechSynthesis(); + const spoken = speakAssistantReply(state.lastAssistantReply); + if (!spoken) { + setVoiceState("Voice playback could not start automatically."); + } + }); + + els.deleteClose?.addEventListener("click", () => closeDeleteModal()); + els.deleteCancel?.addEventListener("click", () => closeDeleteModal()); + els.deleteConfirm?.addEventListener("click", () => { void confirmDeleteModal(); }); + els.deleteModal?.addEventListener("click", (event) => { + if (event.target === els.deleteModal) { + closeDeleteModal(); + } + }); + + document.addEventListener("click", (event) => { + if (!state.open || !els.menu || !els.trigger) return; + if (els.deleteModal?.classList.contains("show") && els.deleteModal.contains(event.target)) return; + if (els.menu.contains(event.target) || els.trigger.contains(event.target)) return; + closeMenu(); + }); + + + if (supportsSpeechSynthesis()) { + window.speechSynthesis.onvoiceschanged = () => { + if (state.lastAssistantReply && state.speaking) { + updateButtons(); + } + }; + } + + window.addEventListener("resize", positionMenu); + window.addEventListener("scroll", positionMenu, true); + window.addEventListener("beforeunload", () => { + stopSpeaking(); + stopActiveStream(); + cleanupAudioGraph(); + cleanupRecognition(); + }); + } + + function init() { + els.trigger = $("dashboardAssistantButton"); + els.menu = $("dashboardAssistantMenu"); + els.close = $("dashboardAssistantClose"); + els.reset = $("dashboardAssistantReset"); + els.configToggle = $("dashboardAssistantConfigToggle"); + els.status = $("dashboardAssistantStatus"); + els.config = $("dashboardAssistantConfig"); + els.notice = $("dashboardAssistantNotice"); + els.messages = $("dashboardAssistantMessages"); + els.composer = $("dashboardAssistantComposer"); + els.composeForm = $("dashboardAssistantComposerForm"); + els.textInput = $("dashboardAssistantTextInput"); + els.send = $("dashboardAssistantSend"); + els.mic = $("dashboardAssistantMic"); + els.replay = $("dashboardAssistantReplay"); + els.voiceState = $("dashboardAssistantVoiceState"); + els.speakingIndicator = $("dashboardAssistantSpeaking"); + els.transcript = $("dashboardAssistantTranscript"); + els.tokenForm = $("dashboardAssistantTokenForm"); + els.providerSelect = $("dashboardAssistantProviderSelect"); + els.tokenLabel = $("dashboardAssistantTokenLabel"); + els.tokenInput = $("dashboardAssistantTokenInput"); + els.saveToken = $("dashboardAssistantSaveToken"); + els.tokenState = $("dashboardAssistantTokenState"); + els.userAccessToggle = $("dashboardAssistantAllowUsersToggle"); + els.deleteModal = $("dashboardAssistantDeleteModal"); + els.deleteClose = $("dashboardAssistantDeleteClose"); + els.deleteCancel = $("dashboardAssistantDeleteCancel"); + els.deleteConfirm = $("dashboardAssistantDeleteConfirm"); + els.deleteName = $("dashboardAssistantDeleteName"); + els.deleteSubtitle = $("dashboardAssistantDeleteSubtitle"); + els.pttBtn = $("dashboardAssistantPttKeyBtn"); + + if (!els.trigger || !els.menu) return; + + bindEvents(); + syncProviderUi(); + syncStoredTokenField(true); + updateTokenStateText(); + syncAssistantAccessUi(); + updateButtons(); + setVoiceState( + supportsSpeechSynthesis() + ? "Voice replies are on." + : "Voice playback is not available in this browser." + ); + setStatus("Assistant ready.", "idle"); + if (getMicrophoneCapabilityIssue()) { + setNotice(getMicrophoneCapabilityIssue()); + } + } + + document.addEventListener("DOMContentLoaded", init); +})(); diff --git a/public/js/dashboard.js b/public/js/dashboard.js new file mode 100644 index 0000000..26a2f03 --- /dev/null +++ b/public/js/dashboard.js @@ -0,0 +1,3309 @@ +if (typeof globalThis === "undefined") window.globalThis = window; +window.addEventListener("securitypolicyviolation", (e) => { + console.log("[CSP]", e.violatedDirective, "blocked:", e.blockedURI, "sample:", e.sample); +}); + +function escapeHtml(s) { + return String(s).replace(/[&<>"']/g, function (m) { + return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]); + }); +} + +const PANEL_EWS_ICON_SIZE = "1.6rem"; + +function ensurePanelEwsSvgStyles() { + if (document.getElementById("panel-ews-svg-styles")) return; + const style = document.createElement("style"); + style.id = "panel-ews-svg-styles"; + style.textContent = ` + .panel-ews-svg { + width: ${PANEL_EWS_ICON_SIZE}; + height: ${PANEL_EWS_ICON_SIZE}; + display: block; + flex: 0 0 auto; + transition: transform 180ms ease; + } + + .quick-action.qa-anim-rotate:hover .panel-ews-svg { + transform: rotate(180deg); + } + `; + document.head.appendChild(style); +} + +function createPanelEwsSvg() { + const template = document.createElement("template"); + template.innerHTML = ` + + `.trim(); + return template.content.firstElementChild; +} + +function replaceLegacyPanelEwsIcons(root = document) { + ensurePanelEwsSvgStyles(); + root.querySelectorAll("i.fa-panel-ews").forEach((icon) => { + const svg = createPanelEwsSvg(); + const inlineStyle = icon.getAttribute("style"); + if (inlineStyle) svg.setAttribute("style", `${inlineStyle};width:${PANEL_EWS_ICON_SIZE};height:${PANEL_EWS_ICON_SIZE};display:block;`); + icon.replaceWith(svg); + }); +} + +window.addEventListener('DOMContentLoaded', () => { + replaceLegacyPanelEwsIcons(); + + const splash = document.getElementById('splash-screen'); + const splashImage = splash?.dataset.splashImage || window.__dashboardSplashImage || '/images/hello.webp'; + const splashKey = window.__dashboardSplashKey || `dashboard-splash-cache:${window.location.origin}:${splashImage}`; + + const removeSplash = () => { + if (splash && splash.isConnected) splash.remove(); + }; + + const hideSplash = () => { + if (!splash || !splash.isConnected) return; + splash.classList.add('hidden'); + window.setTimeout(removeSplash, 600); + }; + + const markSplashCached = () => { + try { + localStorage.setItem(splashKey, '1'); + } catch (_) { } + }; + + const isSplashCached = async () => { + try { + const response = await fetch(splashImage, { + cache: 'only-if-cached', + mode: 'same-origin' + }); + return response.ok; + } catch (_) { + return false; + } + }; + + const showSplashForFirstCacheMiss = () => { + if (!splash) return; + const displayTime = 5000; + const preload = new Image(); + let hideScheduled = false; + + const scheduleHide = () => { + if (hideScheduled) return; + hideScheduled = true; + markSplashCached(); + window.setTimeout(hideSplash, displayTime); + }; + + preload.decoding = 'async'; + preload.onload = scheduleHide; + preload.onerror = removeSplash; + preload.src = splashImage; + + if (preload.complete) { + scheduleHide(); + } + }; + + if (splash) { + const skipSplash = document.documentElement.classList.contains('skip-dashboard-splash'); + + if (skipSplash) { + removeSplash(); + } else { + isSplashCached() + .then((cached) => { + if (cached) { + markSplashCached(); + removeSplash(); + return; + } + showSplashForFirstCacheMiss(); + }) + .catch(showSplashForFirstCacheMiss); + } + } + + document.querySelectorAll('[data-scroll-target]').forEach(button => { + button.addEventListener('click', () => { + const targetId = button.getAttribute('data-scroll-target'); + const section = document.getElementById(targetId); + if (section) section.scrollIntoView({ behavior: 'smooth' }); + }); + }); + + document.querySelectorAll('.bot-card').forEach(card => { + const overlay = card.querySelector('[data-offline-overlay]'); + if (!overlay) return; + const nodeOffline = card.classList.contains('node-offline'); + overlay.style.display = nodeOffline ? 'flex' : 'none'; + card.classList.toggle('is-offline', nodeOffline); + }); + + function updateNodeOfflineStatus(name, nodeOnline) { + const card = document.querySelector(`.bot-card[data-name="${name.toLowerCase()}"]`); + if (!card) return; + const overlay = card.querySelector('[data-offline-overlay]'); + + if (nodeOnline) { + card.classList.remove('node-offline'); + card.classList.remove('is-offline'); + if (overlay) overlay.style.display = 'none'; + } else { + card.classList.add('node-offline'); + card.classList.add('is-offline'); + if (overlay) overlay.style.display = 'flex'; + } + } + window.updateNodeOfflineStatus = updateNodeOfflineStatus; + + + function formatBytes(mb) { + if (mb === null || mb === undefined) return null; + if (mb === 0) return '0 MB'; + if (mb >= 1024) return `${(mb / 1024).toFixed(1)} GB`; + return `${Math.round(mb)} MB`; + } + + function formatResourceLabel(usedMb, limitMb) { + const used = formatBytes(usedMb); + const limit = formatBytes(limitMb); + if (limitMb > 0) return `${used || '0 MB'}/${limit}`; + if (usedMb > 0) return used; + return 'N/A'; + } + + function updateCardFromResourceData(data) { + if (!data || !data.server) return; + const name = data.server.toLowerCase(); + const card = document.querySelector(`.bot-card[data-name="${name}"]`); + if (!card) return; + + const status = data.status; + if (status) { + const isOnline = status === 'running' || status === 'online'; + const isStopped = status === 'stopped' || status === 'exited'; + if (!isOnline && !isStopped && card.classList.contains('status-online')) { + } else { + card.classList.remove('status-online', 'status-stopped', 'status-unknown'); + const statusEl = card.querySelector('.bot-card__status'); + if (statusEl) statusEl.classList.remove('status-online', 'status-stopped', 'status-unknown'); + if (isOnline) { + card.classList.add('status-online'); + if (statusEl) statusEl.classList.add('status-online'); + } else if (isStopped) { + card.classList.add('status-stopped'); + if (statusEl) statusEl.classList.add('status-stopped'); + } else { + card.classList.add('status-unknown'); + if (statusEl) statusEl.classList.add('status-unknown'); + } + } + } + + if (data.nodeOnline === true && typeof window.updateNodeOfflineStatus === 'function') { + window.updateNodeOfflineStatus(data.server, true); + } + + if (data.memory != null) { + let usedMb = 0, limitMb = 0, pct = 0; + if (typeof data.memory === 'object') { + usedMb = data.memory.used || 0; + limitMb = data.memory.total || 0; + pct = data.memory.percent ?? (limitMb > 0 ? Math.min(100, Math.round((usedMb / limitMb) * 100)) : 0); + } else { + usedMb = data.memory; limitMb = 0; pct = 0; + } + const memLabel = card.querySelector('.bot-card__stat-icon--memory')?.closest('.bot-card__stat')?.querySelector('.bot-card__stat-chip span'); + const memProgress = card.querySelector('.bot-card__stat-icon--memory')?.closest('.bot-card__stat')?.querySelector('.bot-card__progress span'); + if (memLabel) memLabel.textContent = formatResourceLabel(usedMb, limitMb); + if (memProgress) { memProgress.style.width = `${Math.min(100, Math.max(0, pct))}%`; } + } + + if (data.disk != null) { + let usedMb = 0, limitMb = 0, pct = 0; + if (typeof data.disk === 'object') { + usedMb = (data.disk.used || 0) * 1024; + limitMb = (data.disk.total || 0) * 1024; + pct = data.disk.percent ?? (limitMb > 0 ? Math.min(100, Math.round((usedMb / limitMb) * 100)) : 0); + } else { + usedMb = data.disk; limitMb = 0; pct = 0; + } + const diskLabel = card.querySelector('.bot-card__stat-icon--disk')?.closest('.bot-card__stat')?.querySelector('.bot-card__stat-chip span'); + const diskProgress = card.querySelector('.bot-card__stat-icon--disk')?.closest('.bot-card__stat')?.querySelector('.bot-card__progress span'); + if (diskLabel) diskLabel.textContent = formatResourceLabel(usedMb, limitMb); + if (diskProgress) { diskProgress.style.width = `${Math.min(100, Math.max(0, pct))}%`; } + } + + if (data.cpu != null) { + const cpuMax = data.cpuLimit || 100; + const cpuPct = Math.min(cpuMax, Math.max(0, data.cpu || 0)); + const cpuBarWidth = cpuMax > 0 ? Math.min(100, (cpuPct / cpuMax) * 100) : 0; + const cpuLabel = card.querySelector('.bot-card__stat-icon--cpu')?.closest('.bot-card__stat')?.querySelector('.bot-card__stat-chip span'); + const cpuProgress = card.querySelector('.bot-card__stat-icon--cpu')?.closest('.bot-card__stat')?.querySelector('.bot-card__progress span'); + if (cpuLabel) cpuLabel.textContent = cpuPct > 0 ? `${cpuPct.toFixed(1)}%` : 'N/A'; + if (cpuProgress) cpuProgress.style.width = `${cpuBarWidth}%`; + } + } + + let _dashResourceSocket = null; + let _dashResourceSubscribed = false; + window._dashResourceSocket = null; + + function getDashboardServerNames() { + return Array.from(document.querySelectorAll('[data-bot-card]')) + .map(c => c.dataset.name) + .filter(Boolean); + } + + function subscribeDashboardResources(socket) { + if (!socket || !socket.connected) return; + const names = getDashboardServerNames(); + if (!names.length) return; + socket.emit('resources:subscribe-bulk', { servers: names }); + _dashResourceSubscribed = true; + } + + function unsubscribeDashboardResources(socket) { + if (!socket) return; + socket.emit('resources:unsubscribe-all'); + _dashResourceSubscribed = false; + } + + function initDashboardResourceSocket() { + if (!window.io) return; + const socket = window.io({ + transports: ['websocket', 'polling'], + reconnection: true, + reconnectionDelay: 1000, + reconnectionDelayMax: 5000 + }); + _dashResourceSocket = socket; + window._dashResourceSocket = socket; + + socket.on('connect', () => { + subscribeDashboardResources(socket); + }); + + socket.on('disconnect', () => { + _dashResourceSubscribed = false; + }); + + socket.on('resources:data', updateCardFromResourceData); + + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + unsubscribeDashboardResources(socket); + } else { + subscribeDashboardResources(socket); + } + }); + + window.addEventListener('beforeunload', () => { + unsubscribeDashboardResources(socket); + }); + } + + initDashboardResourceSocket(); + + document.querySelectorAll('[data-href]').forEach(el => { + el.addEventListener('click', (event) => { + const href = el.getAttribute('data-href'); + if (!href) return; + const target = el.getAttribute('data-target'); + if (target === '_blank') { + window.open(href, '_blank'); + } 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, '\\"')}")`); + }); + + document.querySelectorAll('.bot-card__progress span[data-pct]').forEach(span => { + span.style.width = (span.dataset.pct || '0') + '%'; + }); + + const searchInput = document.getElementById('searchBots'); + const botGrid = document.querySelector('[data-bot-grid]'); + const emptyStateTemplate = document.getElementById('empty-state'); + const dashPagination = document.getElementById('dashPagination'); + + function navigateDashboard(page, search) { + const params = new URLSearchParams(); + if (page && page > 1) params.set('page', String(page)); + if (search) params.set('search', search); + const qs = params.toString(); + window.location.href = '/' + (qs ? '?' + qs : ''); + } + + function updateBotVisibility() { + if (dashPagination) { + clearTimeout(_searchTimer); + _searchTimer = setTimeout(() => navigateDashboard(1, (searchInput?.value || '').trim()), 500); + return; + } + const term = (searchInput?.value || '').trim().toLowerCase(); + const botCards = Array.from(botGrid.querySelectorAll('[data-bot-card]')); + let visible = 0; + botCards.forEach(card => { + const name = card.getAttribute('data-name'); + const match = !term || name.includes(term); + card.classList.toggle('is-hidden', !match); + if (match) visible++; + }); + const existing = botGrid.querySelector('.empty-state'); + if (visible === 0) { + if (!existing) { + const clone = emptyStateTemplate.content.cloneNode(true); + botGrid.appendChild(clone); + } + } else if (existing) existing.remove(); + } + let _searchTimer; + searchInput?.addEventListener('input', () => { + clearTimeout(_searchTimer); + _searchTimer = setTimeout(updateBotVisibility, dashPagination ? 500 : 150); + }); + if (!dashPagination) updateBotVisibility(); + + const urlParams = new URLSearchParams(window.location.search); + if (searchInput && urlParams.get('search')) { + searchInput.value = urlParams.get('search'); + } + + if (dashPagination) { + dashPagination.querySelectorAll('button[data-dash-page]').forEach(btn => { + btn.addEventListener('click', () => { + const p = parseInt(btn.dataset.dashPage, 10); + if (p >= 1) navigateDashboard(p, (searchInput?.value || '').trim()); + }); + }); + } + + const topBar = document.getElementById('topBar'); + const spacer = document.getElementById('topbar-spacer'); + function measureExpandedHeight() { + const hadCompact = topBar.classList.contains('top-bar--compact'); + topBar.classList.remove('top-bar--compact'); + const h = Math.ceil(topBar.getBoundingClientRect().height); + if (hadCompact) topBar.classList.add('top-bar--compact'); + return h; + } + let expandedHeight = measureExpandedHeight(); + spacer.style.height = expandedHeight + 'px'; + let resizeRAF = null; + window.addEventListener('resize', () => { + if (resizeRAF) cancelAnimationFrame(resizeRAF); + resizeRAF = requestAnimationFrame(() => { + expandedHeight = measureExpandedHeight(); + spacer.style.height = expandedHeight + 'px'; + }); + }); + new ResizeObserver(() => { + expandedHeight = measureExpandedHeight(); + spacer.style.height = expandedHeight + 'px'; + fitHero(); + }).observe(topBar); + + function fitHero() { + const hero = document.querySelector('.hero'); + if (!hero) return; + + hero.style.minHeight = ''; + hero.style.marginBottom = ''; + + if (document.querySelector('.quick-actions')) return; + + const rect = hero.getBoundingClientRect(); + const scrollTop = window.scrollY || document.documentElement.scrollTop; + const absTop = rect.top + scrollTop; + const heroHeight = hero.offsetHeight; + const totalContentHeight = absTop + heroHeight; + const viewHeight = window.innerHeight; + + const diff = viewHeight - totalContentHeight; + + if (diff > 0) { + hero.style.marginBottom = `${diff + 32}px`; + } + } + + window.addEventListener('resize', fitHero); + fitHero(); + + let lastY = window.scrollY || 0, ticking = false, pinnedTimeout = null; + function onScrollTick() { + const y = window.scrollY || 0, d = y - lastY; + if (y > 36) topBar.classList.add('top-bar--compact'); else topBar.classList.remove('top-bar--compact'); + if (y <= 24) { + topBar.classList.remove('top-bar--hidden', 'top-bar--pinned'); + lastY = y; ticking = false; return; + } + if (Math.abs(d) > 4) { + if (d > 0 && y > 120) { + topBar.classList.add('top-bar--hidden'); topBar.classList.remove('top-bar--pinned'); + } else if (d < 0) { + topBar.classList.remove('top-bar--hidden'); topBar.classList.add('top-bar--pinned'); + if (pinnedTimeout) clearTimeout(pinnedTimeout); + pinnedTimeout = setTimeout(() => topBar.classList.remove('top-bar--pinned'), 900); + } + } + lastY = y; ticking = false; + } + window.addEventListener('scroll', () => { + if (!ticking) { + requestAnimationFrame(onScrollTick); + ticking = true; + } + }, { passive: true }); + if ((window.scrollY || 0) > 36) topBar.classList.add('top-bar--compact'); else topBar.classList.remove('top-bar--compact'); + topBar.classList.remove('top-bar--hidden'); + + function deleteAllClientCookies() { + const cookies = document.cookie ? document.cookie.split('; ') : []; + for (const cookie of cookies) { + const eqPos = cookie.indexOf('='); + const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; + document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/`; + document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=${location.hostname}`; + const parts = location.hostname.split('.'); + for (let i = 0; i < parts.length - 1; i++) { + const dom = '.' + parts.slice(i).join('.'); + document.cookie = `${name}=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/;domain=${dom}`; + } + } + } + document.getElementById('logoutBtn')?.addEventListener('click', async (e) => { + e.preventDefault(); + try { + deleteAllClientCookies(); + await fetch('/logout', { method: 'POST', credentials: 'include' }); + location.href = '/login'; + } catch { + alert('Failed to log out'); + } + }); + + const accountBtn = document.getElementById('accountBtn'); + const accountBackBtn = document.getElementById('accountBackBtn'); + const accountPage = document.getElementById('accountPage'); + const mainContent = document.getElementById('mainContent'); + const footerEl = document.getElementById('upload'); + + async function showAccountPage() { + if (!accountPage) return; + + if (window.location.hash !== '#account') { + window.history.pushState(null, null, '#account'); + } + + if (mainContent) mainContent.style.display = 'none'; + if (footerEl) footerEl.style.display = 'none'; + + accountPage.style.display = 'block'; + + try { + const res = await fetch('/api/account', { credentials: 'include' }); + if (!res.ok) throw new Error('Failed to load account'); + const data = await res.json(); + + const usernameEl = document.getElementById('accountUsername'); + const emailEl = document.getElementById('accountEmail'); + const usernameValEl = document.getElementById('accountUsernameValue'); + const emailValEl = document.getElementById('accountEmailValue'); + const roleValEl = document.getElementById('accountRoleValue'); + const idValEl = document.getElementById('accountIdValue'); + const avatarImgEl = document.getElementById('accountAvatarImg'); + const statusTextEl = document.getElementById('accountStatusText'); + const cooldownEl = document.getElementById('usernameCooldown'); + + const badgeClass = data.isAdmin ? 'admin' : 'user'; + const badgeText = data.isAdmin ? 'Admin' : 'User'; + + if (usernameEl) usernameEl.innerHTML = `${escapeHtml(data.username)} `; + if (emailEl) emailEl.textContent = data.email; + if (usernameValEl) usernameValEl.textContent = data.username; + if (emailValEl) emailValEl.textContent = data.email; + if (roleValEl) roleValEl.textContent = data.isAdmin ? 'Administrator' : 'Standard User'; + if (idValEl) idValEl.textContent = data.userId || 'N/A'; + if (avatarImgEl && data.avatarUrl) avatarImgEl.src = data.avatarUrl; + if (statusTextEl) statusTextEl.textContent = data.status || 'Available'; + + window._accountData = data; + + if (cooldownEl && data.usernameChangeCooldown) { + const days = Math.ceil(data.usernameChangeCooldown / (24 * 60 * 60 * 1000)); + cooldownEl.textContent = `You can change your username again in ${days} day${days !== 1 ? 's' : ''}`; + cooldownEl.style.display = 'block'; + } else if (cooldownEl) { + cooldownEl.style.display = 'none'; + } + } catch (err) { + console.error('[account] Failed to load:', err); + } + + window.scrollTo({ top: 0, behavior: 'smooth' }); + } + + function hideAccountPage() { + if (!accountPage) return; + + if (window.location.hash === '#account') { + history.pushState("", document.title, window.location.pathname + window.location.search); + } + + accountPage.style.display = 'none'; + + if (mainContent) mainContent.style.display = ''; + if (footerEl) footerEl.style.display = ''; + + window.scrollTo({ top: 0, behavior: 'smooth' }); + } + + const avatarWrapper = document.getElementById('accountAvatarWrapper'); + const avatarFileInput = document.getElementById('avatarFileInput'); + + avatarWrapper?.addEventListener('click', () => { + avatarFileInput?.click(); + }); + + avatarFileInput?.addEventListener('change', async (e) => { + const file = e.target.files?.[0]; + if (!file) return; + + if (file.size > 5 * 1024 * 1024) { + alert('File too large. Maximum size is 5MB.'); + return; + } + + const formData = new FormData(); + formData.append('avatar', file); + + try { + const res = await fetch('/api/account/avatar/upload', { + method: 'POST', + credentials: 'include', + body: formData + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Failed to upload avatar'); + + const avatarImgEl = document.getElementById('accountAvatarImg'); + if (avatarImgEl) avatarImgEl.src = data.avatarUrl; + + const headerAvatarImg = document.querySelector('.account-btn-avatar'); + if (headerAvatarImg) headerAvatarImg.src = data.avatarUrl; + } catch (err) { + alert('Failed to upload avatar: ' + err.message); + } + + e.target.value = ''; + }); + + const usernameEditBtn = document.getElementById('usernameEditBtn'); + const usernameSaveBtn = document.getElementById('usernameSaveBtn'); + const usernameCancelBtn = document.getElementById('usernameCancelBtn'); + const usernameInput = document.getElementById('usernameInput'); + const usernameValEl = document.getElementById('accountUsernameValue'); + + usernameEditBtn?.addEventListener('click', () => { + if (usernameInput && usernameValEl) { + usernameInput.value = usernameValEl.textContent || ''; + usernameValEl.style.display = 'none'; + usernameInput.style.display = 'block'; + usernameEditBtn.style.display = 'none'; + usernameSaveBtn.style.display = 'inline-flex'; + usernameCancelBtn.style.display = 'inline-flex'; + usernameInput.focus(); + } + }); + + usernameCancelBtn?.addEventListener('click', () => { + usernameValEl.style.display = 'inline'; + usernameInput.style.display = 'none'; + usernameEditBtn.style.display = 'inline-flex'; + usernameSaveBtn.style.display = 'none'; + usernameCancelBtn.style.display = 'none'; + }); + + usernameSaveBtn?.addEventListener('click', async () => { + const newUsername = usernameInput?.value?.trim(); + if (!newUsername || newUsername.length < 3) { + alert('Username must be at least 3 characters'); + return; + } + + usernameSaveBtn.disabled = true; + try { + const res = await fetch('/api/account/username', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ username: newUsername }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Failed to update username'); + + if (usernameValEl) usernameValEl.textContent = newUsername; + const usernameEl = document.getElementById('accountUsername'); + if (usernameEl && window._accountData) { + const badgeClass = window._accountData.isAdmin ? 'admin' : 'user'; + const badgeText = window._accountData.isAdmin ? 'Admin' : 'User'; + usernameEl.innerHTML = `${escapeHtml(newUsername)} `; + } + + usernameCancelBtn?.click(); + } catch (err) { + alert(err.message); + } finally { + usernameSaveBtn.disabled = false; + } + }); + + const statusEditBtn = document.getElementById('statusEditBtn'); + const statusModal = document.getElementById('statusModal'); + const statusModalClose = document.getElementById('statusModalClose'); + const statusCancelBtn = document.getElementById('statusCancelBtn'); + const statusSaveBtn = document.getElementById('statusSaveBtn'); + const statusInput = document.getElementById('statusInput'); + const statusDuration = document.getElementById('statusDuration'); + const statusError = document.getElementById('statusError'); + const statusTextEl = document.getElementById('accountStatusText'); + + statusEditBtn?.addEventListener('click', () => { + if (statusInput) statusInput.value = statusTextEl?.textContent || ''; + statusModal?.classList.add('show'); + }); + + statusModalClose?.addEventListener('click', () => { + statusModal?.classList.remove('show'); + }); + + statusCancelBtn?.addEventListener('click', () => { + statusModal?.classList.remove('show'); + }); + + statusModal?.addEventListener('click', (e) => { + if (e.target === statusModal) statusModal.classList.remove('show'); + }); + + statusSaveBtn?.addEventListener('click', async () => { + const text = statusInput?.value?.trim() || 'Available'; + const durationVal = statusDuration?.value; + const expiresAt = durationVal === 'never' ? null : Date.now() + parseInt(durationVal || '86400000'); + + statusSaveBtn.disabled = true; + if (statusError) statusError.classList.remove('show'); + + try { + const res = await fetch('/api/me/status', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ text, expiresAt }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Failed to update status'); + + if (statusTextEl) statusTextEl.textContent = text; + + statusModal?.classList.remove('show'); + } catch (err) { + if (statusError) { + statusError.textContent = err.message; + statusError.classList.add('show'); + } + } finally { + statusSaveBtn.disabled = false; + } + }); + + accountBtn?.addEventListener('click', showAccountPage); + accountBackBtn?.addEventListener('click', hideAccountPage); + + if (window.location.hash === '#account') { + showAccountPage(); + } + + window.addEventListener('hashchange', () => { + if (window.location.hash === '#account') { + showAccountPage(); + } else { + hideAccountPage(); + } + }); + + function activateAccountTab(tabName) { + const normalized = tabName === 'credentials' ? 'credentials' : 'info'; + document.querySelectorAll('.account-tab').forEach((tab) => { + tab.classList.toggle('active', tab.dataset.accountTab === normalized); + }); + document.querySelectorAll('.account-tab-content').forEach((content) => { + content.classList.remove('active'); + }); + const tabId = normalized === 'info' ? 'accountInfoTab' : 'accountCredentialsTab'; + document.getElementById(tabId)?.classList.add('active'); + } + + document.querySelectorAll('.account-tab').forEach(tab => { + tab.addEventListener('click', () => { + activateAccountTab(tab.dataset.accountTab); + }); + }); + + const twofaModal = document.getElementById('twofaModal'); + const change2faBtn = document.getElementById('change2faBtn'); + const twofaModalClose = document.getElementById('twofaModalClose'); + const twofaCancelBtn = document.getElementById('twofaCancelBtn'); + const twofaConfirmBtn = document.getElementById('twofaConfirmBtn'); + const currentCodeInput = document.getElementById('currentCodeInput'); + const newCodeInput = document.getElementById('newCodeInput'); + const qrCodeSection = document.getElementById('qrCodeSection'); + const confirmSection = document.getElementById('confirmSection'); + const newQrCode = document.getElementById('newQrCode'); + const newSecretDisplay = document.getElementById('newSecretDisplay'); + const twofaError = document.getElementById('twofaError'); + const twofaSuccess = document.getElementById('twofaSuccess'); + + let pendingNewSecret = null; + let twoFaModalStep = 1; + + function resetTwofaModal() { + twoFaModalStep = 1; + pendingNewSecret = null; + if (currentCodeInput) currentCodeInput.value = ''; + if (newCodeInput) newCodeInput.value = ''; + if (qrCodeSection) qrCodeSection.style.display = 'none'; + if (confirmSection) confirmSection.style.display = 'none'; + if (twofaError) twofaError.classList.remove('show'); + if (twofaSuccess) twofaSuccess.classList.remove('show'); + if (twofaConfirmBtn) { + twofaConfirmBtn.textContent = 'Verify Current Code'; + twofaConfirmBtn.disabled = false; + twofaConfirmBtn.style.display = ''; + } + if (twofaCancelBtn) twofaCancelBtn.textContent = 'Cancel'; + + const twofaStep1 = document.getElementById('twofaStep1'); + if (twofaStep1) twofaStep1.style.display = ''; + const twofaForgotLink = document.getElementById('twofaForgotLink'); + if (twofaForgotLink) twofaForgotLink.style.display = ''; + + const qrStepNum = qrCodeSection?.querySelector('.twofa-step-num'); + const confirmStepNum = confirmSection?.querySelector('.twofa-step-num'); + if (qrStepNum) qrStepNum.textContent = '2'; + if (confirmStepNum) confirmStepNum.textContent = '3'; + } + + function showTwofaError(msg) { + if (twofaError) { + twofaError.textContent = msg; + twofaError.classList.add('show'); + } + } + + function hideTwofaError() { + if (twofaError) twofaError.classList.remove('show'); + } + + change2faBtn?.addEventListener('click', () => { + resetTwofaModal(); + twofaModal?.classList.add('show'); + }); + + twofaModalClose?.addEventListener('click', () => { + twofaModal?.classList.remove('show'); + }); + + twofaCancelBtn?.addEventListener('click', () => { + twofaModal?.classList.remove('show'); + }); + + twofaModal?.addEventListener('click', (e) => { + if (e.target === twofaModal) twofaModal.classList.remove('show'); + }); + + twofaConfirmBtn?.addEventListener('click', async () => { + hideTwofaError(); + + if (twoFaModalStep === 1) { + const currentCode = currentCodeInput?.value.trim() || ''; + if (!currentCode || currentCode.length !== 6 || !/^\d+$/.test(currentCode)) { + showTwofaError('Please enter a valid 6-digit code'); + return; + } + + twofaConfirmBtn.disabled = true; + twofaConfirmBtn.textContent = 'Verifying...'; + + try { + const res = await fetch('/api/account/2fa/generate', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ currentCode }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Verification failed'); + + pendingNewSecret = data.newSecret; + if (newQrCode) newQrCode.src = data.qrCodeUrl; + if (newSecretDisplay) newSecretDisplay.textContent = data.newSecret; + + if (qrCodeSection) qrCodeSection.style.display = 'block'; + if (confirmSection) confirmSection.style.display = 'block'; + twoFaModalStep = 2; + twofaConfirmBtn.textContent = 'Confirm New 2FA'; + twofaConfirmBtn.disabled = false; + } catch (err) { + showTwofaError(err.message); + twofaConfirmBtn.textContent = 'Verify Current Code'; + twofaConfirmBtn.disabled = false; + } + } else if (twoFaModalStep === 2) { + const newCode = newCodeInput?.value.trim() || ''; + if (!newCode || newCode.length !== 6 || !/^\d+$/.test(newCode)) { + showTwofaError('Please enter a valid 6-digit code from your new authenticator'); + return; + } + + twofaConfirmBtn.disabled = true; + twofaConfirmBtn.textContent = 'Updating...'; + + try { + const res = await fetch('/api/account/2fa/confirm', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ newCode, newSecret: pendingNewSecret }) + }); + + 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 (twofaCancelBtn) twofaCancelBtn.textContent = 'Done'; + + setTimeout(() => { + twofaModal?.classList.remove('show'); + resetTwofaModal(); + }, 2000); + } catch (err) { + showTwofaError(err.message); + twofaConfirmBtn.textContent = 'Confirm New 2FA'; + twofaConfirmBtn.disabled = false; + } + } + }); + + [currentCodeInput, newCodeInput].forEach(input => { + input?.addEventListener('input', (e) => { + e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6); + }); + }); + + const passwordModal = document.getElementById('passwordModal'); + const changePasswordBtn = document.getElementById('changePasswordBtn'); + const passwordModalClose = document.getElementById('passwordModalClose'); + const passwordCancelBtn = document.getElementById('passwordCancelBtn'); + const passwordConfirmBtn = document.getElementById('passwordConfirmBtn'); + const currentPasswordInput = document.getElementById('currentPasswordInput'); + const password2faInput = document.getElementById('password2faInput'); + const newPasswordInput = document.getElementById('newPasswordInput'); + const confirmPasswordInput = document.getElementById('confirmPasswordInput'); + const passwordStep1 = document.getElementById('passwordStep1'); + const passwordStep2 = document.getElementById('passwordStep2'); + const passwordError = document.getElementById('passwordError'); + const passwordSuccess = document.getElementById('passwordSuccess'); + + let passwordModalStep = 1; + + function resetPasswordModal() { + passwordModalStep = 1; + if (currentPasswordInput) currentPasswordInput.value = ''; + if (password2faInput) password2faInput.value = ''; + if (newPasswordInput) newPasswordInput.value = ''; + if (confirmPasswordInput) confirmPasswordInput.value = ''; + if (passwordStep1) passwordStep1.style.display = 'block'; + if (passwordStep2) passwordStep2.style.display = 'none'; + if (passwordError) passwordError.classList.remove('show'); + if (passwordSuccess) passwordSuccess.classList.remove('show'); + if (passwordConfirmBtn) { + passwordConfirmBtn.textContent = 'Verify'; + passwordConfirmBtn.disabled = false; + passwordConfirmBtn.style.display = ''; + } + if (passwordCancelBtn) passwordCancelBtn.textContent = 'Cancel'; + } + + function showPasswordError(msg) { + if (passwordError) { + passwordError.textContent = msg; + passwordError.classList.add('show'); + } + } + + function hidePasswordError() { + if (passwordError) passwordError.classList.remove('show'); + } + + changePasswordBtn?.addEventListener('click', () => { + resetPasswordModal(); + passwordModal?.classList.add('show'); + }); + + passwordModalClose?.addEventListener('click', () => { + passwordModal?.classList.remove('show'); + }); + + passwordCancelBtn?.addEventListener('click', () => { + passwordModal?.classList.remove('show'); + }); + + passwordModal?.addEventListener('click', (e) => { + if (e.target === passwordModal) passwordModal.classList.remove('show'); + }); + + passwordConfirmBtn?.addEventListener('click', async () => { + hidePasswordError(); + + if (passwordModalStep === 1) { + const currentPw = currentPasswordInput?.value || ''; + const code = password2faInput?.value.trim() || ''; + + if (!currentPw) { + showPasswordError('Please enter your current password'); + return; + } + if (!code || code.length !== 6 || !/^\d+$/.test(code)) { + showPasswordError('Please enter a valid 6-digit 2FA code'); + return; + } + + passwordConfirmBtn.disabled = true; + passwordConfirmBtn.textContent = 'Verifying...'; + + try { + const res = await fetch('/api/account/password/verify', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: code }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Verification failed'); + + passwordStep1.style.display = 'none'; + passwordStep2.style.display = 'block'; + passwordModalStep = 2; + passwordConfirmBtn.textContent = 'Change Password'; + passwordConfirmBtn.disabled = false; + } catch (err) { + showPasswordError(err.message); + passwordConfirmBtn.textContent = 'Verify'; + passwordConfirmBtn.disabled = false; + } + } else if (passwordModalStep === 2) { + const newPw = newPasswordInput?.value || ''; + const confirmPw = confirmPasswordInput?.value || ''; + + if (!newPw || newPw.length < 8) { + showPasswordError('Password must be at least 8 characters'); + return; + } + if (newPw !== confirmPw) { + showPasswordError('Passwords do not match'); + return; + } + + passwordConfirmBtn.disabled = true; + passwordConfirmBtn.textContent = 'Updating...'; + + try { + const res = await fetch('/api/account/password/change', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ + currentPassword: currentPasswordInput?.value || '', + twoFactorCode: password2faInput?.value.trim() || '', + newPassword: newPw + }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Failed to change password'); + + if (passwordSuccess) passwordSuccess.classList.add('show'); + passwordConfirmBtn.style.display = 'none'; + if (passwordCancelBtn) passwordCancelBtn.textContent = 'Done'; + + setTimeout(() => { + passwordModal?.classList.remove('show'); + resetPasswordModal(); + }, 2000); + } catch (err) { + showPasswordError(err.message); + passwordConfirmBtn.textContent = 'Change Password'; + passwordConfirmBtn.disabled = false; + } + } + }); + + password2faInput?.addEventListener('input', (e) => { + e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6); + }); + + document.querySelectorAll('.password-toggle-eye').forEach(btn => { + const targetId = btn.dataset.target; + const input = document.getElementById(targetId); + + if (input) { + input.addEventListener('input', () => { + btn.style.display = input.value.length > 0 ? 'block' : 'none'; + }); + + btn.addEventListener('click', () => { + const isPassword = input.type === 'password'; + input.type = isPassword ? 'text' : 'password'; + btn.querySelector('i').className = isPassword ? 'fa-solid fa-eye-slash' : 'fa-solid fa-eye'; + }); + } + }); + + const emailModal = document.getElementById('emailModal'); + const changeEmailBtn = document.getElementById('changeEmailBtn'); + const emailModalClose = document.getElementById('emailModalClose'); + const emailCancelBtn = document.getElementById('emailCancelBtn'); + const emailConfirmBtn = document.getElementById('emailConfirmBtn'); + const emailPasswordInput = document.getElementById('emailPasswordInput'); + const email2faInput = document.getElementById('email2faInput'); + const newEmailInput = document.getElementById('newEmailInput'); + const emailStep1 = document.getElementById('emailStep1'); + const emailStep2 = document.getElementById('emailStep2'); + const emailError = document.getElementById('emailError'); + const emailSuccess = document.getElementById('emailSuccess'); + + let emailModalStep = 1; + + function resetEmailModal() { + emailModalStep = 1; + if (emailPasswordInput) emailPasswordInput.value = ''; + if (email2faInput) email2faInput.value = ''; + if (newEmailInput) newEmailInput.value = ''; + if (emailStep1) emailStep1.style.display = 'block'; + if (emailStep2) emailStep2.style.display = 'none'; + if (emailError) emailError.classList.remove('show'); + if (emailSuccess) emailSuccess.classList.remove('show'); + if (emailConfirmBtn) { + emailConfirmBtn.textContent = 'Verify'; + emailConfirmBtn.disabled = false; + emailConfirmBtn.style.display = ''; + } + if (emailCancelBtn) emailCancelBtn.textContent = 'Cancel'; + } + + function showEmailError(msg) { + if (emailError) { + emailError.textContent = msg; + emailError.classList.add('show'); + } + } + + function hideEmailError() { + if (emailError) emailError.classList.remove('show'); + } + + changeEmailBtn?.addEventListener('click', () => { + resetEmailModal(); + emailModal?.classList.add('show'); + }); + + emailModalClose?.addEventListener('click', () => { + emailModal?.classList.remove('show'); + }); + + emailCancelBtn?.addEventListener('click', () => { + emailModal?.classList.remove('show'); + }); + + emailModal?.addEventListener('click', (e) => { + if (e.target === emailModal) emailModal.classList.remove('show'); + }); + + emailConfirmBtn?.addEventListener('click', async () => { + hideEmailError(); + + if (emailModalStep === 1) { + const currentPw = emailPasswordInput?.value || ''; + const code = email2faInput?.value.trim() || ''; + + if (!currentPw) { + showEmailError('Please enter your password'); + return; + } + if (!code || code.length !== 6 || !/^\d+$/.test(code)) { + showEmailError('Please enter a valid 6-digit 2FA code'); + return; + } + + emailConfirmBtn.disabled = true; + emailConfirmBtn.textContent = 'Verifying...'; + + try { + const res = await fetch('/api/account/email/verify', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: code }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Verification failed'); + + emailStep1.style.display = 'none'; + emailStep2.style.display = 'block'; + emailModalStep = 2; + emailConfirmBtn.textContent = 'Change Email'; + emailConfirmBtn.disabled = false; + } catch (err) { + showEmailError(err.message); + emailConfirmBtn.textContent = 'Verify'; + emailConfirmBtn.disabled = false; + } + } else if (emailModalStep === 2) { + const newEmail = newEmailInput?.value.trim() || ''; + + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!newEmail || !emailRegex.test(newEmail)) { + showEmailError('Please enter a valid email address'); + return; + } + + emailConfirmBtn.disabled = true; + emailConfirmBtn.textContent = 'Updating...'; + + try { + const res = await fetch('/api/account/email/change', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ + currentPassword: emailPasswordInput?.value || '', + twoFactorCode: email2faInput?.value.trim() || '', + newEmail: newEmail + }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Failed to change email'); + + if (emailSuccess) emailSuccess.classList.add('show'); + emailConfirmBtn.style.display = 'none'; + if (emailCancelBtn) emailCancelBtn.textContent = 'Done'; + + const accountEmailEl = document.getElementById('accountEmail'); + const accountEmailValueEl = document.getElementById('accountEmailValue'); + if (accountEmailEl) accountEmailEl.textContent = newEmail; + if (accountEmailValueEl) accountEmailValueEl.textContent = newEmail; + + setTimeout(() => { + emailModal?.classList.remove('show'); + resetEmailModal(); + }, 2000); + } catch (err) { + showEmailError(err.message); + emailConfirmBtn.textContent = 'Change Email'; + emailConfirmBtn.disabled = false; + } + } + }); + + email2faInput?.addEventListener('input', (e) => { + e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6); + }); + + document.querySelectorAll('.email-toggle-eye').forEach(btn => { + const targetId = btn.dataset.target; + const input = document.getElementById(targetId); + + if (input) { + input.addEventListener('input', () => { + btn.style.display = input.value.length > 0 ? 'block' : 'none'; + }); + + btn.addEventListener('click', () => { + const isPassword = input.type === 'password'; + input.type = isPassword ? 'text' : 'password'; + btn.querySelector('i').className = isPassword ? 'fa-solid fa-eye-slash' : 'fa-solid fa-eye'; + }); + } + }); + + const recoveryModal = document.getElementById('recoveryModal'); + const recoveryModalClose = document.getElementById('recoveryModalClose'); + const recoveryCancelBtn = document.getElementById('recoveryCancelBtn'); + const recoveryConfirmBtn = document.getElementById('recoveryConfirmBtn'); + const recoveryCodeInput = document.getElementById('recoveryCodeInput'); + const recoveryError = document.getElementById('recoveryError'); + + let recoveryReturnTo = null; + + function showRecoveryError(msg) { + if (recoveryError) { + recoveryError.textContent = msg; + recoveryError.classList.add('show'); + } + } + + function hideRecoveryError() { + if (recoveryError) recoveryError.classList.remove('show'); + } + + function resetRecoveryModal() { + if (recoveryCodeInput) recoveryCodeInput.value = ''; + hideRecoveryError(); + if (recoveryConfirmBtn) { + recoveryConfirmBtn.textContent = 'Verify Code'; + recoveryConfirmBtn.disabled = false; + } + recoveryReturnTo = null; + } + + function openRecoveryModal(returnTo) { + resetRecoveryModal(); + recoveryReturnTo = returnTo; + recoveryModal?.classList.add('show'); + } + + async function openAccountFlow(flow) { + await showAccountPage(); + activateAccountTab('credentials'); + + switch (flow) { + case 'change_password': + resetPasswordModal(); + passwordModal?.classList.add('show'); + return true; + case 'change_email': + resetEmailModal(); + emailModal?.classList.add('show'); + return true; + case 'change_2fa': + resetTwofaModal(); + twofaModal?.classList.add('show'); + return true; + case 'recover_password': + openRecoveryModal('password'); + return true; + case 'recover_email': + openRecoveryModal('email'); + return true; + case 'recover_2fa': + openRecoveryModal('twofa'); + return true; + default: + return false; + } + } + + window.ADPanelDashboardAccount = { + showAccountPage, + hideAccountPage, + activateAccountTab, + openAccountFlow, + }; + + document.getElementById('twofaForgotLink')?.addEventListener('click', () => { + twofaModal?.classList.remove('show'); + openRecoveryModal('twofa'); + }); + + document.getElementById('passwordForgotLink')?.addEventListener('click', () => { + passwordModal?.classList.remove('show'); + openRecoveryModal('password'); + }); + + document.getElementById('emailForgotLink')?.addEventListener('click', () => { + emailModal?.classList.remove('show'); + openRecoveryModal('email'); + }); + + recoveryModalClose?.addEventListener('click', () => { + recoveryModal?.classList.remove('show'); + }); + + recoveryCancelBtn?.addEventListener('click', () => { + recoveryModal?.classList.remove('show'); + }); + + recoveryModal?.addEventListener('click', (e) => { + if (e.target === recoveryModal) recoveryModal.classList.remove('show'); + }); + + recoveryCodeInput?.addEventListener('input', (e) => { + e.target.value = e.target.value.toUpperCase().replace(/[^A-Z0-9]/g, '').slice(0, 8); + }); + + recoveryConfirmBtn?.addEventListener('click', async () => { + hideRecoveryError(); + + const code = recoveryCodeInput?.value.trim().toUpperCase() || ''; + if (!code || code.length !== 8) { + showRecoveryError('Please enter a valid 8-character recovery code'); + return; + } + + recoveryConfirmBtn.disabled = true; + recoveryConfirmBtn.textContent = 'Verifying...'; + + try { + const res = await fetch('/api/account/recovery/verify', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify({ recoveryCode: code }) + }); + + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Invalid recovery code'); + + recoveryModal?.classList.remove('show'); + + if (recoveryReturnTo === 'twofa') { + try { + const genRes = await fetch('/api/account/2fa/generate-recovery', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include' + }); + const genData = await genRes.json(); + if (!genRes.ok) throw new Error(genData.error || 'Failed to generate new 2FA'); + + resetTwofaModal(); + pendingNewSecret = genData.newSecret; + if (newQrCode) newQrCode.src = genData.qrCodeUrl; + if (newSecretDisplay) newSecretDisplay.textContent = genData.newSecret; + + const twofaStep1 = document.getElementById('twofaStep1'); + if (twofaStep1) twofaStep1.style.display = 'none'; + + if (qrCodeSection) qrCodeSection.style.display = 'block'; + if (confirmSection) confirmSection.style.display = 'block'; + + const qrStepNum = qrCodeSection?.querySelector('.twofa-step-num'); + const confirmStepNum = confirmSection?.querySelector('.twofa-step-num'); + if (qrStepNum) qrStepNum.textContent = '1'; + if (confirmStepNum) confirmStepNum.textContent = '2'; + + twoFaModalStep = 2; + if (twofaConfirmBtn) twofaConfirmBtn.textContent = 'Confirm New 2FA'; + twofaModal?.classList.add('show'); + } catch (err) { + alert('Failed to generate 2FA: ' + err.message); + } + } else if (recoveryReturnTo === 'password') { + resetPasswordModal(); + if (passwordStep1) passwordStep1.style.display = 'none'; + if (passwordStep2) passwordStep2.style.display = 'block'; + document.getElementById('passwordForgotLink').style.display = 'none'; + passwordModalStep = 2; + if (passwordConfirmBtn) passwordConfirmBtn.textContent = 'Change Password'; + passwordModal?.classList.add('show'); + } else if (recoveryReturnTo === 'email') { + resetEmailModal(); + if (emailStep1) emailStep1.style.display = 'none'; + if (emailStep2) emailStep2.style.display = 'block'; + document.getElementById('emailForgotLink').style.display = 'none'; + emailModalStep = 2; + if (emailConfirmBtn) emailConfirmBtn.textContent = 'Change Email'; + emailModal?.classList.add('show'); + } + } catch (err) { + showRecoveryError(err.message); + recoveryConfirmBtn.textContent = 'Verify Code'; + recoveryConfirmBtn.disabled = false; + } + }); + + const createBtns = [ + document.getElementById('createBtn'), + document.getElementById('createBtnHero'), + document.getElementById('createBtnFooter') + ].filter(Boolean); + const createModal = document.getElementById('createModal'); + const createClose = document.getElementById('createClose'); + const createCancel = document.getElementById('createCancel'); + const createConfirm = document.getElementById('createConfirm'); + const createSpinner = document.getElementById('createSpinner'); + const serverNameEl = document.getElementById('serverName'); + const templateGrid = document.getElementById('templateGrid'); + const templateInfo = document.getElementById('templateInfo'); + const nodeGrid = document.getElementById('nodeGrid'); + const summaryNameEl = document.getElementById('summaryServerName'); + const summaryTemplateEl = document.getElementById('summaryTemplateName'); + const summaryNodeEl = document.getElementById('summaryNodeName'); + const templateInfo2 = document.getElementById('templateInfo2'); + const forkModal = document.getElementById('forkModal'); + const forkClose = document.getElementById('forkClose'); + const forkBack = document.getElementById('forkBack'); + const forkConfirm = document.getElementById('forkConfirm'); + const forkSpinner = document.getElementById('forkSpinner'); + const forkGrid = document.getElementById('forkGrid'); + const forkInfo = document.getElementById('forkInfo'); + const portModal = document.getElementById('portModal'); + const portClose = document.getElementById('portClose'); + const portBack = document.getElementById('portBack'); + const portConfirm = document.getElementById('portConfirm'); + const portSpinner = document.getElementById('portSpinner'); + const serverIpEl = document.getElementById('serverIp'); + const serverPortEl = document.getElementById('serverPort'); + const serverPortPreviewEl = document.getElementById('serverPortPreview'); + const portDefaultValueEl = document.getElementById('portDefaultValue'); + const portTitleTextEl = document.getElementById('portTitleText'); + const portSubtitleEl = document.getElementById('portSubtitle'); + const resourcesModal = document.getElementById('resourcesModal'); + const resourcesClose = document.getElementById('resourcesClose'); + const resourcesBack = document.getElementById('resourcesBack'); + const resourcesConfirm = document.getElementById('resourcesConfirm'); + const resourcesSpinner = document.getElementById('resourcesSpinner'); + const resourceRamEl = document.getElementById('resourceRam'); + const resourceCpuCoresEl = document.getElementById('resourceCpuCores'); + const resourceSwapEl = document.getElementById('resourceSwap'); + const resourceStorageEl = document.getElementById('resourceStorage'); + const resourceBackupsEl = document.getElementById('resourceBackups'); + const resourceMaxSchedulesEl = document.getElementById('resourceMaxSchedules'); + const resourceIoWeightEl = document.getElementById('resourceIoWeight'); + const resourceCpuWeightEl = document.getElementById('resourceCpuWeight'); + const resourcePidsLimitEl = document.getElementById('resourcePidsLimit'); + const resourceFileLimitEl = document.getElementById('resourceFileLimit'); + const resourceNetworkInboundLimitEl = document.getElementById('resourceNetworkInboundLimit'); + const resourceNetworkOutboundLimitEl = document.getElementById('resourceNetworkOutboundLimit'); + const resourceNetworkResetMinutesEl = document.getElementById('resourceNetworkResetMinutes'); + const nodeRamLimitEl = document.getElementById('nodeRamLimit'); + const nodeCpuLimitEl = document.getElementById('nodeCpuLimit'); + const nodeStorageLimitEl = document.getElementById('nodeStorageLimit'); + const liveNodeCapacityCache = new Map(); + const RESOURCE_NETWORK_LIMIT_MAX_MB = 1073741824; + const RESOURCE_NETWORK_RESET_MAX_MINUTES = 43200; + + function resolveNodeCacheKey(node) { + return String(node?.id || node?.uuid || node?.name || '').trim(); + } + + function configuredNodeCapacity(node) { + return { + ramMb: Math.max(0, Math.trunc(Number(node?.ram_mb || node?.buildConfig?.ram_mb || 0))), + cpuCores: Math.max(0, Number(node?.cpu_cores || node?.buildConfig?.cpu_cores || node?.buildConfig?.cpuCores || 0)), + diskGb: Math.max(0, Number(node?.disk_gb || node?.buildConfig?.disk_gb || node?.buildConfig?.diskGb || 0)) + }; + } + + function mergeNodeCapacityValue(configured, live, round, preferLive) { + const cfg = Number(configured); + const detected = Number(live); + let value = 0; + if (preferLive && Number.isFinite(detected) && detected > 0) value = detected; + else if (Number.isFinite(cfg) && cfg > 0 && Number.isFinite(detected) && detected > 0) value = Math.min(cfg, detected); + else if (Number.isFinite(detected) && detected > 0) value = detected; + else if (Number.isFinite(cfg) && cfg > 0) value = cfg; + return round ? Math.trunc(value) : value; + } + + function resolveEffectiveNodeCapacity(node, liveCapacity) { + const configured = configuredNodeCapacity(node); + const live = (liveCapacity && typeof liveCapacity === 'object') ? liveCapacity : {}; + return { + ramMb: mergeNodeCapacityValue(configured.ramMb, live.ramMb, true, true), + cpuCores: mergeNodeCapacityValue(configured.cpuCores, live.cpuCores, false), + diskGb: mergeNodeCapacityValue(configured.diskGb, live.diskGb, false) + }; + } + + function applyNodeCapacityToResourceModal(capacity) { + const ramMb = Number(capacity?.ramMb || 0); + const cpuCores = Number(capacity?.cpuCores || 0); + const diskGb = Number(capacity?.diskGb || 0); + const diskMb = diskGb > 0 ? Math.trunc(diskGb * 1024) : 0; + + if (nodeRamLimitEl) nodeRamLimitEl.textContent = ramMb > 0 ? `${ramMb.toLocaleString()} MB` : 'Unlimited'; + if (nodeCpuLimitEl) nodeCpuLimitEl.textContent = cpuCores > 0 ? `${cpuCores} cores` : 'Unlimited'; + if (nodeStorageLimitEl) nodeStorageLimitEl.textContent = diskMb > 0 ? (diskMb >= 1010 ? `${(diskMb / 1024).toFixed(2).replace(/\.?0+$/, '')} GB` : `${diskMb.toLocaleString()} MB`) : 'Unlimited'; + + if (resourceRamEl) { + if (ramMb > 0) resourceRamEl.max = ramMb; + else resourceRamEl.removeAttribute('max'); + } + if (resourceCpuCoresEl) { + if (cpuCores > 0) resourceCpuCoresEl.max = cpuCores; + else resourceCpuCoresEl.removeAttribute('max'); + } + if (resourceStorageEl) { + if (diskMb > 0) resourceStorageEl.max = diskMb; + else resourceStorageEl.removeAttribute('max'); + } + } + + async function fetchLiveNodeCapacity(node) { + const cacheKey = resolveNodeCacheKey(node); + if (!cacheKey) return null; + if (liveNodeCapacityCache.has(cacheKey)) return liveNodeCapacityCache.get(cacheKey); + + try { + const res = await fetch(`/api/admin/nodes/${encodeURIComponent(cacheKey)}/stats`, { cache: 'no-store' }); + const data = await res.json().catch(() => ({})); + if (!res.ok || !data.ok || !data.online || !data.stats) return null; + + const liveCapacity = { + ramMb: Math.max(0, Math.trunc(Number(data.stats?.ram?.totalMb || 0))), + cpuCores: Math.max(0, Number(data.stats?.cpu?.cores || 0)), + diskGb: Math.max(0, Number(data.stats?.disk?.totalGb || 0)) + }; + liveNodeCapacityCache.set(cacheKey, liveCapacity); + return liveCapacity; + } catch { + return null; + } + } + + async function getEffectiveNodeCapacity(node) { + const liveCapacity = await fetchLiveNodeCapacity(node); + return resolveEffectiveNodeCapacity(node, liveCapacity); + } + + if (resourceStorageEl) { + resourceStorageEl.addEventListener('input', () => { + const hint = resourceStorageEl.closest('.enterprise-field')?.querySelector('.enterprise-hint'); + if (!hint) return; + const val = parseInt(resourceStorageEl.value, 10); + if (!isNaN(val) && val > 0) { + const display = val >= 1010 ? (val / 1024).toFixed(2).replace(/\.?0+$/, '') + ' GB' : val + ' MB'; + hint.textContent = `Maximum disk space: ${display}`; + } else { + hint.textContent = 'Maximum disk space. Leave empty to use the node allocation.'; + } + }); + } + + function readOptionalIntegerRange(input, label, min, max) { + const raw = input && input.value != null ? String(input.value).trim() : ''; + if (!raw) return null; + if (!/^\d+$/.test(raw)) { + throw new Error(`${label} must be a whole number.`); + } + const value = Number(raw); + if (!Number.isSafeInteger(value) || value < min || value > max) { + throw new Error(`${label} must be between ${min} and ${max}.`); + } + return value; + } + + const startupModal = document.getElementById('startupModal'); + const startupClose = document.getElementById('startupClose'); + const startupBack = document.getElementById('startupBack'); + const startupConfirm = document.getElementById('startupConfirm'); + const startupSpinner = document.getElementById('startupSpinner'); + const startupCommandEl = document.getElementById('startupCommand'); + const startupCommandSourceEl = document.getElementById('startupCommandSource'); + const startupCommandErrorEl = document.getElementById('startupCommandError'); + + const importModal = document.getElementById('importModal'); + const importClose = document.getElementById('importClose'); + const importBack = document.getElementById('importBack'); + const importSkip = document.getElementById('importSkip'); + const importConfirm = document.getElementById('importConfirm'); + const importSpinner = document.getElementById('importSpinner'); + const importUrlEl = document.getElementById('importUrl'); + const importProgressContainer = document.getElementById('importProgressContainer'); + const importProgressFill = document.getElementById('importProgressFill'); + const importPercent = document.getElementById('importPercent'); + const importDownloaded = document.getElementById('importDownloaded'); + const importTotal = document.getElementById('importTotal'); + + const MC_VERSION = "1.21.8"; + const MC_FORKS = [ + { id: "paper", name: "Paper", desc: "Optimized performance with plugin support" }, + { id: "pufferfish", name: "Pufferfish", desc: "TPS-focused optimizations" }, + { id: "vanilla", name: "Vanilla", desc: "Standard Minecraft experience" }, + { id: "purpur", name: "Purpur", desc: "Paper fork with extra settings" } + ]; + + let templates = []; + let nodes = []; + let selectedTemplateId = null; + let selectedForkId = null; + let selectedNodeId = "local"; + let portBackTarget = "create"; + let selectedStartupCommand = ""; + let selectedStartupCommandMode = ""; + let selectedImportUrl = ""; + + const BUILTIN_TEMPLATES = ['minecraft', 'nodejs']; + const MAX_SERVER_NAME_LENGTH = 40; + + function isBuiltinTemplate(templateId) { + return BUILTIN_TEMPLATES.includes((templateId || '').toLowerCase()); + } + + function sanitizeName(s) { + s = (s || '').trim(); + s = s.replace(/\s+/g, '-').replace(/[^a-zA-Z0-9\-_]/g, ''); + return s.slice(0, MAX_SERVER_NAME_LENGTH) || ''; + } + + function getTemplateMeta(t) { + const id = ((t && t.id) || '').toString().toLowerCase(); + if (id.includes('minecraft') || id === 'mc') { + return { icon: 'fa-solid fa-cube', badge: 'Minecraft' }; + } + if (id.includes('node') || id.includes('discord')) { + return { icon: 'fa-brands fa-node-js', badge: 'Node.js' }; + } + if (id.includes('python') || id.includes('py')) { + return { icon: 'fa-brands fa-python', badge: 'Python' }; + } + if (id.includes('proxy') || id.includes('web') || id.includes('http')) { + return { icon: 'fa-solid fa-cloud', badge: 'Web' }; + } + return { icon: 'fa-solid fa-server', badge: 'Generic' }; + } + + function getDefaultPortForTemplate(templateId) { + const id = (templateId || '').toString().toLowerCase(); + if (!id) return 25565; + 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; + return 8080; + } + + function coercePositiveNumber(value) { + const numeric = Number(value); + return Number.isFinite(numeric) && numeric > 0 ? numeric : 0; + } + + function sanitizePortInputValue(value) { + return String(value ?? '').replace(/[^\d]/g, '').slice(0, 5); + } + + function parseStrictPortValue(value) { + const str = String(value ?? '').trim(); + if (!/^[1-9]\d{0,4}$/.test(str)) return null; + const port = Number(str); + if (!Number.isInteger(port) || port < 1 || port > 65535) return null; + return port; + } + + function getSelectedNode() { + if (!selectedNodeId || selectedNodeId === 'local') return null; + return (nodes || []).find(x => + (x.uuid === selectedNodeId) || + (x.id === selectedNodeId) || + (x.name === selectedNodeId) + ) || null; + } + + async function verifySelectedNodePortAvailable(portVal) { + const node = getSelectedNode(); + if (!node || !portVal) return true; + try { + const nodeId = encodeURIComponent(node.uuid || node.id || node.name || selectedNodeId); + const res = await fetch(`/api/nodes/${nodeId}/ports/check?port=${encodeURIComponent(String(portVal))}`); + const data = await res.json().catch(() => ({})); + if (res.ok && data && data.available === false) { + alert(data.detail || data.error || `Port ${portVal} is already in use on this node.`); + return false; + } + } catch (_) { + } + return true; + } + + function bindStrictPortInput(input) { + if (!input) return; + input.setAttribute('inputmode', 'numeric'); + input.addEventListener('input', () => { + const sanitized = sanitizePortInputValue(input.value); + if (input.value !== sanitized) input.value = sanitized; + }); + } + + function getDefaultStartupVolumes(templateId, docker) { + const configured = Array.isArray(docker?.volumes) + ? docker.volumes.map((entry) => String(entry || '').trim()).filter(Boolean) + : []; + if (configured.length) return configured; + const normalizedTemplateId = String(templateId || '').trim().toLowerCase(); + if (['nodejs', 'discord-bot', 'python', 'runtime'].includes(normalizedTemplateId)) { + return ['{DATA_DIR}:/app']; + } + return ['{DATA_DIR}:/data']; + } + + function getDefaultStartFileForTemplate(templateId) { + const normalizedTemplateId = String(templateId || '').trim().toLowerCase(); + if (normalizedTemplateId === 'minecraft') return 'server.jar'; + if (normalizedTemplateId === 'python') return 'main.py'; + if (normalizedTemplateId === 'nodejs' || normalizedTemplateId === 'discord-bot') return 'index.js'; + return ''; + } + + function getDefaultContainerDataDir(templateId, docker) { + const volumes = getDefaultStartupVolumes(templateId, docker); + const first = String(volumes[0] || '').trim(); + if (first.includes(':')) { + const parts = first.split(':'); + if (parts[1]) return parts[1].trim(); + } + const normalizedTemplateId = String(templateId || '').trim().toLowerCase(); + return ['nodejs', 'discord-bot', 'python', 'runtime'].includes(normalizedTemplateId) ? '/app' : '/data'; + } + + function getDefaultRuntimeCommand(templateId, docker) { + const explicit = String(docker?.command || '').trim(); + if (explicit) return explicit; + const normalizedTemplateId = String(templateId || '').trim().toLowerCase(); + const dataDir = getDefaultContainerDataDir(normalizedTemplateId, docker); + const startFile = getDefaultStartFileForTemplate(normalizedTemplateId); + if (normalizedTemplateId === 'minecraft') { + return `java -Xms128M -Xmx{RAM_MB}M -jar ${dataDir}/${startFile || 'server.jar'} nogui`; + } + if (normalizedTemplateId === 'python') { + return `python ${dataDir}/${startFile || 'main.py'}`; + } + if (normalizedTemplateId === 'nodejs' || normalizedTemplateId === 'discord-bot') { + return `node ${dataDir}/${startFile || 'index.js'}`; + } + return ''; + } + + const RUNTIME_PROCESS_BLOCKED_EXECUTABLES = new Set([ + 'sh', '/bin/sh', 'bash', '/bin/bash', 'ash', '/bin/ash', 'dash', '/bin/dash', 'zsh', '/bin/zsh', 'ksh', '/bin/ksh', + ]); + const RUNTIME_PROCESS_BLOCKED_CONTAINER_EXECUTABLES = new Set([ + 'docker', 'docker-compose', 'podman', 'podman-compose', 'nerdctl', 'ctr', + ]); + const RUNTIME_PROCESS_ENV_WRAPPERS = new Set(['env']); + const RUNTIME_PROCESS_BLOCKED_TOKENS = new Set([ + '&&', '||', '|', ';', '&', '>', '>>', '<', '<<', '2>', '2>>', '2>&1', '|&', + ]); + + function parseRuntimeProcessArgsInput(value) { + const input = String(value || ''); + const args = []; + let current = ''; + let quote = ''; + let escape = false; + for (let i = 0; i < input.length; i += 1) { + const ch = input[i]; + if (escape) { + current += ch; + escape = false; + continue; + } + if (ch === '\\') { + escape = true; + continue; + } + if (quote) { + if (ch === quote) quote = ''; + else current += ch; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + continue; + } + if (/\s/.test(ch)) { + if (current) { + args.push(current); + current = ''; + } + continue; + } + current += ch; + } + if (current) args.push(current); + return args; + } + + function getRuntimeProcessExecutableBaseNameInput(value) { + const raw = String(value || '').trim(); + if (!raw) return ''; + let candidate = raw; + if (/\s/.test(candidate)) { + const nestedArgs = parseRuntimeProcessArgsInput(candidate); + if (nestedArgs.length) candidate = String(nestedArgs[0] || '').trim(); + } + const normalized = candidate.toLowerCase().replace(/\\/g, '/'); + const parts = normalized.split('/').filter(Boolean); + return parts.pop() || normalized; + } + + function isRuntimeEnvAssignmentTokenInput(value) { + const token = String(value || '').trim(); + if (!token || token.startsWith('-')) return false; + const eqIdx = token.indexOf('='); + if (eqIdx <= 0) return false; + return /^[A-Za-z_][A-Za-z0-9_]*$/.test(token.slice(0, eqIdx)); + } + + function resolveRuntimeProcessExecutableArgsInput(args) { + const parts = Array.isArray(args) ? args : []; + if (!parts.length) return { execName: '', index: -1 }; + let index = 0; + while (index < parts.length) { + const token = String(parts[index] || '').trim(); + if (!token) { + index += 1; + continue; + } + const execName = getRuntimeProcessExecutableBaseNameInput(token); + if (RUNTIME_PROCESS_ENV_WRAPPERS.has(execName)) { + index += 1; + while (index < parts.length) { + const envToken = String(parts[index] || '').trim(); + if (!envToken) { + index += 1; + continue; + } + if (envToken === '--') { + index += 1; + break; + } + if (envToken.startsWith('-') || isRuntimeEnvAssignmentTokenInput(envToken)) { + index += 1; + continue; + } + break; + } + continue; + } + return { execName, index }; + } + return { execName: '', index: -1 }; + } + + function validateRuntimeContainerLauncherInput(args) { + const { execName } = resolveRuntimeProcessExecutableArgsInput(args); + if (RUNTIME_PROCESS_BLOCKED_CONTAINER_EXECUTABLES.has(execName)) { + return 'Container runtime CLI commands like "docker run" are not allowed here. Configure image, ports, volumes, env, and the in-container process separately.'; + } + return null; + } + + function isBlockedRuntimeShellExecutableInput(value) { + const execName = getRuntimeProcessExecutableBaseNameInput(value); + return RUNTIME_PROCESS_BLOCKED_EXECUTABLES.has(execName); + } + + function isRuntimeShellWrapperArgsInput(args, execIndex) { + if (!Array.isArray(args) || execIndex < 0 || execIndex >= args.length) return false; + if (!isBlockedRuntimeShellExecutableInput(args[execIndex])) return false; + const flags = String(args[execIndex + 1] || '').trim().toLowerCase(); + return flags.startsWith('-') && flags.includes('c'); + } + + function validateRuntimeProcessCommandInput(value) { + const command = String(value || '').trim(); + if (!command) return null; + if (command.length > 4000) return 'Process command is too long.'; + if (command.includes('\n')) return 'Process command must be a single line.'; + if (command.includes('`') || command.includes('$(')) { + return 'Shell expansions are not allowed in process commands.'; + } + const args = parseRuntimeProcessArgsInput(command); + if (!args.length) return 'Process command is empty.'; + const { execName: resolvedExecName, index: execIndex } = resolveRuntimeProcessExecutableArgsInput(args); + const containerRuntimeError = validateRuntimeContainerLauncherInput(args); + if (containerRuntimeError) return containerRuntimeError; + if (isBlockedRuntimeShellExecutableInput(resolvedExecName || args[0]) && isRuntimeShellWrapperArgsInput(args, execIndex)) { + return 'Shell wrappers like sh -c or bash -lc are not allowed. Provide the executable and arguments directly.'; + } + for (const arg of args) { + const token = String(arg || '').trim(); + if (RUNTIME_PROCESS_BLOCKED_TOKENS.has(token)) { + return `Shell control operator "${token}" is not allowed in process commands.`; + } + } + return null; + } + + function buildDefaultStartupCommandForTemplate(template) { + if (!template || !template.docker) return ''; + return getDefaultRuntimeCommand(template.id, template.docker); + } + + function setStartupCommandSource(message) { + if (!startupCommandSourceEl) return; + startupCommandSourceEl.textContent = String(message || 'Using startup command from template.').trim(); + } + + function setStartupCommandValidationError(message) { + const text = String(message || '').trim(); + if (startupCommandEl) startupCommandEl.setAttribute('aria-invalid', text ? 'true' : 'false'); + if (!startupCommandErrorEl) return; + startupCommandErrorEl.textContent = text; + startupCommandErrorEl.hidden = !text; + } + + function findTemplateById(templateId) { + const id = String(templateId || '').trim(); + if (!id) return null; + return (templates || []).find(t => String(t?.id || '').trim() === id) || null; + } + + 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 === 'image-inspect') { + return imageRef + ? `Detected from Docker image inspect (${imageRef}).` + : 'Detected from Docker image inspect.'; + } + if (normalized === 'template-command') return 'Using process command defined by this template.'; + if (normalized === 'template-default') return 'Using template default process command.'; + return 'Using auto-detected process command.'; + } + + function quoteStartupArg(arg) { + const value = String(arg || ''); + if (!value) return '""'; + if (!/[\s"'\\]/.test(value)) return value; + return `"${value.replace(/(["\\])/g, '\\$1')}"`; + } + + function joinStartupArgs(args) { + if (!Array.isArray(args)) return ''; + return args + .map((item) => String(item || '').trim()) + .filter(Boolean) + .map(quoteStartupArg) + .join(' ') + .trim(); + } + + function isShellEntrypoint(entrypoint) { + if (!Array.isArray(entrypoint) || entrypoint.length < 2) return false; + const first = String(entrypoint[0] || '').trim().toLowerCase(); + const base = first.split('/').filter(Boolean).pop() || first; + const shellLike = ['sh', 'bash', 'ash', 'dash', 'zsh', 'ksh'].includes(base); + if (!shellLike) return false; + const flags = String(entrypoint[1] || '').trim(); + return flags.startsWith('-') && flags.includes('c'); + } + + function isLikelyPathOnlyStartup(command) { + const args = parseRuntimeProcessArgsInput(String(command || '').trim()); + if (args.length !== 1) return false; + const token = String(args[0] || '').trim(); + if (!token.startsWith('/')) return false; + const lower = token.toLowerCase(); + if (lower.includes('entrypoint')) return true; + if (lower.endsWith('.sh') || lower.endsWith('.bash')) return true; + return false; + } + + function pickInspectEnvStartupCommand(envObj) { + if (!envObj || typeof envObj !== 'object' || Array.isArray(envObj)) return ''; + const env = {}; + Object.entries(envObj).forEach(([k, v]) => { + env[String(k || '').trim().toUpperCase()] = String(v ?? '').trim(); + }); + const candidates = [ + 'STARTUP', 'SERVER_START_CMD', 'START_CMD', 'START_COMMAND', + 'RUN_CMD', 'APP_START_CMD', 'LAUNCH_CMD', 'COMMAND', 'CMD' + ]; + for (const key of candidates) { + const val = String(env[key] || '').trim(); + if (!val) continue; + if (val.includes('${') || val.includes('{{')) continue; + if (val.startsWith('$')) continue; + return val; + } + return ''; + } + + function inferStartupFromInspectMeta(template, inspectMeta, fallbackCommand, options = {}) { + const allowUnsafe = !!options.allowUnsafe; + + function chooseCandidate(candidate) { + const value = String(candidate || '').trim(); + if (!value) return ''; + if (allowUnsafe) return value; + const err = validateRuntimeProcessCommandInput(value); + if (err) return ''; + return value; + } + + const entrypoint = Array.isArray(inspectMeta?.entrypoint) + ? inspectMeta.entrypoint.map((item) => String(item || '').trim()).filter(Boolean) + : []; + const cmd = Array.isArray(inspectMeta?.cmd) + ? inspectMeta.cmd.map((item) => String(item || '').trim()).filter(Boolean) + : []; + const workingDir = String(inspectMeta?.workingDir || '').trim() || '/'; + + const envStartup = pickInspectEnvStartupCommand(inspectMeta?.env); + if (envStartup) { + const candidate = chooseCandidate(envStartup); + if (candidate) return candidate; + } + + if (isShellEntrypoint(entrypoint)) { + if (cmd.length) { + const shellCmd = cmd.join(' ').trim(); + const candidate = chooseCandidate(shellCmd); + if (candidate) return candidate; + } + if (entrypoint.length > 2) { + const inlineShell = entrypoint.slice(2).join(' ').trim(); + const candidate = chooseCandidate(inlineShell); + if (candidate) return candidate; + } + } + + const assembled = joinStartupArgs([...(entrypoint || []), ...(cmd || [])]); + const assembledCandidate = chooseCandidate(assembled); + if (assembledCandidate) return assembledCandidate; + + const templateId = String(template?.id || '').trim().toLowerCase(); + const imageName = String(template?.docker?.image || '').trim().toLowerCase(); + const startFile = getDefaultStartFileForTemplate(templateId); + const normalizedDir = workingDir === '/' ? '/app' : workingDir; + + let heuristic = ''; + if (templateId.includes('node') || imageName.includes('node')) { + heuristic = `node ${normalizedDir}/${startFile || 'index.js'}`; + } else if (templateId.includes('python') || imageName.includes('python')) { + heuristic = `python ${normalizedDir}/${startFile || 'main.py'}`; + } else if (templateId.includes('minecraft') || imageName.includes('minecraft') || imageName.includes('java')) { + heuristic = 'java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui'; + } + + if (heuristic) { + const candidate = chooseCandidate(heuristic); + if (candidate) return candidate; + } + + const fallback = String(fallbackCommand || '').trim(); + const fallbackCandidate = chooseCandidate(fallback); + if (fallbackCandidate) return fallbackCandidate; + + if (allowUnsafe) { + if (assembled) return assembled; + if (entrypoint.length) return joinStartupArgs(entrypoint); + if (cmd.length) return cmd.join(' ').trim(); + if (fallback) return fallback; + } + + return ''; + } + + function isWrapperEntrypointOnlyCommand(command, inspectMeta) { + if (!isLikelyPathOnlyStartup(command)) return false; + const cmd = Array.isArray(inspectMeta?.cmd) + ? inspectMeta.cmd.map((item) => String(item || '').trim()).filter(Boolean) + : []; + return cmd.length === 0; + } + + function startupCommandCacheKey(templateId, nodeId) { + return `${String(templateId || '').trim().toLowerCase()}::${String(nodeId || '').trim().toLowerCase()}`; + } + + const startupCommandCache = new Map(); + + function setStartupCommandLoading(visible) { + if (!startupSpinner) return; + startupSpinner.classList.toggle('visible', Boolean(visible)); + } + + async function resolveStartupCommandForSelection(options = {}) { + const templateId = String(options.templateId ?? selectedTemplateId ?? '').trim(); + const nodeId = String(options.nodeId ?? selectedNodeId ?? 'local').trim() || 'local'; + const forceRefresh = !!options.forceRefresh; + const showLoading = !!options.showLoading; + setStartupCommandValidationError(''); + + const template = findTemplateById(templateId); + if (!template) { + selectedStartupCommand = ''; + if (startupCommandEl && startupModal?.classList.contains('show')) startupCommandEl.value = ''; + setStartupCommandSource('No template selected yet.'); + setStartupCommandLoading(false); + return ''; + } + + const templateDefinedCommand = String(template?.docker?.command || '').trim(); + const templateADPanelStartup = String( + template?.docker?.adpanelStartup || + template?.docker?.adpanel_startup || + template?.docker?.pterodactylStartup || + template?.docker?.pterodactyl_startup || + '' + ).trim(); + if (startupCommandEl) startupCommandEl.readOnly = false; + if (templateADPanelStartup) { + selectedStartupCommand = templateADPanelStartup; + selectedStartupCommandMode = 'adpanel-startup'; + if (startupCommandEl && startupModal?.classList.contains('show')) { + startupCommandEl.value = selectedStartupCommand; + startupCommandEl.readOnly = true; + } + setStartupCommandValidationError(''); + setStartupCommandSource('Using ADPanel STARTUP from this template. Edit it in template settings if needed.'); + setStartupCommandLoading(false); + return selectedStartupCommand; + } + selectedStartupCommandMode = ''; + const fallbackCommand = buildDefaultStartupCommandForTemplate(template); + const candidate = String(templateDefinedCommand || fallbackCommand || '').trim(); + const commandError = validateRuntimeProcessCommandInput(candidate); + + selectedStartupCommand = commandError ? '' : candidate; + if (startupCommandEl && startupModal?.classList.contains('show')) { + startupCommandEl.value = selectedStartupCommand; + } + + if (selectedStartupCommand) { + setStartupCommandSource(templateDefinedCommand + ? 'Using startup command defined in this template.' + : 'Using default startup command for this template.'); + } else { + setStartupCommandSource(commandError + ? `Template startup command is invalid (${commandError}). Set the process command manually.` + : 'Leave empty to use the Docker image default ENTRYPOINT/CMD, or set a process command manually.'); + } + + if (!templateDefinedCommand) { + const cacheKey = startupCommandCacheKey(templateId, nodeId); + try { + setStartupCommandLoading(showLoading); + let detected = null; + if (!forceRefresh && startupCommandCache.has(cacheKey)) { + detected = startupCommandCache.get(cacheKey); + } else { + const response = await fetch('/api/templates/startup-command', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ templateId, nodeId }) + }); + const data = await response.json().catch(() => ({})); + detected = { ok: response.ok && data?.ok, data, status: response.status }; + startupCommandCache.set(cacheKey, detected); + } + + if (detected?.ok) { + const data = detected.data || {}; + 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 (String(selectedTemplateId || '').trim() !== templateId || activeNodeId !== nodeId) { + return selectedStartupCommand; + } + selectedStartupCommand = detectedCommand; + selectedStartupCommandMode = String(data.source || '').trim().toLowerCase() === 'adpanel-startup' + ? 'adpanel-startup' + : ''; + if (startupCommandEl && startupModal?.classList.contains('show')) { + startupCommandEl.value = selectedStartupCommand; + startupCommandEl.readOnly = selectedStartupCommandMode === 'adpanel-startup'; + } + setStartupCommandSource(startupCommandSourceLabel(data.source, data.imageRef)); + return selectedStartupCommand; + } + } else if (!selectedStartupCommand && detected?.data) { + const detail = String(detected.data.detail || detected.data.error || '').trim(); + if (detail) setStartupCommandSource(`Could not auto-detect startup command (${detail}). Set it manually.`); + } + } catch { + if (!selectedStartupCommand) { + setStartupCommandSource('Could not auto-detect startup command from Docker image. Set it manually.'); + } + } finally { + setStartupCommandLoading(false); + } + } + + return selectedStartupCommand; + } + + function openCreate() { + createModal.classList.add('show'); + createModal.setAttribute('aria-hidden', 'false'); + + selectedTemplateId = null; + selectedForkId = null; + selectedNodeId = 'local'; + portBackTarget = 'create'; + selectedStartupCommand = ''; + selectedImportUrl = ''; + + if (serverNameEl) serverNameEl.value = ''; + if (templateGrid) templateGrid.innerHTML = '
    Loading templates…
    '; + if (templateInfo) templateInfo.textContent = 'No template chosen'; + + if (nodeGrid) nodeGrid.innerHTML = '
    Loading nodes…
    '; + + if (summaryNameEl) summaryNameEl.textContent = '—'; + if (summaryTemplateEl) summaryTemplateEl.textContent = '—'; + if (summaryNodeEl) summaryNodeEl.textContent = 'Local node'; + if (templateInfo2) templateInfo2.textContent = ''; + setStartupCommandSource('Using startup command from template.'); + + fetchTemplates(); + fetchNodes(); + } + + function closeCreate() { + createModal.classList.remove('show'); + createModal.setAttribute('aria-hidden', 'true'); + } + + window.ADPanelDashboardCreate = { + openCreateModal() { + openCreate(); + return true; + }, + closeCreateModal() { + closeCreate(); + return true; + }, + }; + + createBtns.forEach(btn => btn.addEventListener('click', openCreate)); + createClose?.addEventListener('click', closeCreate); + createCancel?.addEventListener('click', closeCreate); + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && createModal?.classList.contains('show')) closeCreate(); + }); + + async function fetchTemplates() { + try { + const r = await fetch('/api/templates'); + if (!r.ok) throw new Error('Failed to load templates'); + const data = await r.json(); + templates = (data && data.templates) || []; + } catch (e) { + templates = [ + { id: 'minecraft', name: 'Minecraft', description: 'Minecraft server (fork selection in the next step).' }, + { id: 'discord-bot', name: 'Discord Bot', description: 'Node 20 runtime (mount /app).' }, + { id: 'vanilla', name: 'Empty', description: 'Alpine base (sleep).' }, + ]; + } + renderTemplates(); + } + + async function fetchNodes() { + try { + const r = await fetch('/api/nodes'); + const data = await r.json(); + nodes = (data && data.nodes) ? data.nodes : []; + } catch (e) { + nodes = []; + } + renderNodes(); + } + + function renderTemplates() { + if (!templateGrid) return; + templateGrid.innerHTML = ''; + + if (!templates.length) { + const empty = document.createElement('div'); + empty.className = 'enterprise-hint'; + empty.textContent = 'No templates available.'; + templateGrid.appendChild(empty); + return; + } + + templates.forEach(t => { + const card = document.createElement('button'); + card.type = 'button'; + card.className = 'enterprise-template-item'; + card.setAttribute('role', 'option'); + card.setAttribute('aria-selected', 'false'); + + const meta = getTemplateMeta(t); + + card.innerHTML = ` +
    + +
    +
    ${escapeHtml(t.name)}
    + `; + card.addEventListener('click', () => { + selectedTemplateId = t.id; + selectedStartupCommand = buildDefaultStartupCommandForTemplate(t) || ''; + [...templateGrid.children].forEach(c => { + c.classList.remove('selected'); + c.setAttribute('aria-selected', 'false'); + }); + card.classList.add('selected'); + card.setAttribute('aria-selected', 'true'); + if (templateInfo) templateInfo.textContent = t.name; + if (summaryTemplateEl) summaryTemplateEl.textContent = t.name; + if (templateInfo2) templateInfo2.textContent = t.description || ''; + if (startupCommandEl && startupModal?.classList.contains('show')) { + startupCommandEl.value = selectedStartupCommand; + } + void resolveStartupCommandForSelection({ + templateId: selectedTemplateId, + nodeId: selectedNodeId, + forceRefresh: false, + showLoading: startupModal?.classList.contains('show') + }); + }); + templateGrid.appendChild(card); + }); + } + + function renderNodes() { + if (!nodeGrid) return; + nodeGrid.innerHTML = ''; + + if (!nodes.length) { + const empty = document.createElement('div'); + empty.className = 'enterprise-hint'; + empty.textContent = 'No remote nodes configured. Using local node.'; + nodeGrid.appendChild(empty); + if (summaryNodeEl) summaryNodeEl.textContent = 'Local node'; + return; + } + + const autoNode = nodes.find(n => n && n.online) || nodes[0]; + if ((!selectedNodeId || selectedNodeId === 'local') && autoNode) { + selectedNodeId = autoNode.uuid || autoNode.id || autoNode.name || selectedNodeId; + } + + nodes.forEach(n => { + const online = !!n.online; + const nodeValue = n.uuid || n.id || n.name; + const el = document.createElement('button'); + el.type = 'button'; + el.className = 'enterprise-node-item'; + el.setAttribute('role', 'option'); + el.setAttribute('aria-selected', 'false'); + el.innerHTML = ` +
    + +
    +
    +
    ${escapeHtml(n.name || n.uuid)}
    +
    ${online ? '● Online' : '○ Offline'} · ${escapeHtml(n.address || 'No address')}
    +
    + `; + el.addEventListener('click', () => { + selectedNodeId = nodeValue; + [...nodeGrid.children].forEach(c => { + c.classList.remove('selected'); + c.setAttribute('aria-selected', 'false'); + }); + el.classList.add('selected'); + el.setAttribute('aria-selected', 'true'); + const label = n.name || n.uuid; + if (summaryNodeEl) summaryNodeEl.textContent = online ? label : `${label} (offline)`; + }); + + if (nodeValue && selectedNodeId === nodeValue) { + el.classList.add('selected'); + el.setAttribute('aria-selected', 'true'); + const label = n.name || n.uuid; + if (summaryNodeEl) summaryNodeEl.textContent = online ? label : `${label} (offline)`; + } + + nodeGrid.appendChild(el); + }); + + } + + function openForkModal() { + if (!forkModal) return; + if (forkGrid) forkGrid.innerHTML = ''; + selectedForkId = null; + if (forkInfo) forkInfo.textContent = 'Select a fork to continue.'; + + MC_FORKS.forEach(f => { + const card = document.createElement('button'); + card.type = 'button'; + card.className = 'enterprise-fork-item'; + card.setAttribute('role', 'option'); + card.setAttribute('aria-selected', 'false'); + card.innerHTML = ` +
    + +
    +
    ${escapeHtml(f.name)}
    +
    ${escapeHtml(f.desc)}
    + `; + card.addEventListener('click', () => { + selectedForkId = f.id; + [...forkGrid.children].forEach(c => { + c.classList.remove('selected'); + c.setAttribute('aria-selected', 'false'); + }); + card.classList.add('selected'); + card.setAttribute('aria-selected', 'true'); + if (forkInfo) forkInfo.textContent = f.name + ' selected'; + }); + forkGrid.appendChild(card); + }); + + forkModal.classList.add('show'); + forkModal.setAttribute('aria-hidden', 'false'); + } + + function closeForkModal() { + forkModal.classList.remove('show'); + forkModal.setAttribute('aria-hidden', 'true'); + } + + forkClose?.addEventListener('click', closeForkModal); + forkBack?.addEventListener('click', () => { + closeForkModal(); + createModal.classList.add('show'); + createModal.setAttribute('aria-hidden', 'false'); + }); + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && forkModal?.classList.contains('show')) closeForkModal(); + }); + + function openPortModal(backFrom) { + portBackTarget = backFrom || 'create'; + + 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; + } + } + + serverPortEl.value = String(defPort); + if (portDefaultValueEl) portDefaultValueEl.textContent = String(defPort); + if (serverPortPreviewEl) serverPortPreviewEl.textContent = String(defPort); + } + + if (serverIpEl) { + 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'; + } + + const selectedTemplate = templates.find(t => t.id === selectedTemplateId); + const templateLabel = selectedTemplate ? selectedTemplate.name : 'server'; + 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)); + } + + portModal.classList.add('show'); + portModal.setAttribute('aria-hidden', 'false'); + } + + function closePortModal() { + portModal.classList.remove('show'); + portModal.setAttribute('aria-hidden', 'true'); + } + + portClose?.addEventListener('click', closePortModal); + portBack?.addEventListener('click', () => { + closePortModal(); + if (portBackTarget === 'fork') { + forkModal.classList.add('show'); + forkModal.setAttribute('aria-hidden', 'false'); + } else { + createModal.classList.add('show'); + createModal.setAttribute('aria-hidden', 'false'); + } + }); + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && portModal?.classList.contains('show')) closePortModal(); + }); + + bindStrictPortInput(serverPortEl); + if (serverPortEl && serverPortPreviewEl) { + serverPortEl.addEventListener('input', () => { + const raw = sanitizePortInputValue(serverPortEl.value); + if (serverPortEl.value !== raw) serverPortEl.value = raw; + serverPortPreviewEl.textContent = raw || (portDefaultValueEl ? portDefaultValueEl.textContent : '—'); + }); + } + + if (serverNameEl && summaryNameEl) { + serverNameEl.maxLength = MAX_SERVER_NAME_LENGTH; + serverNameEl.addEventListener('input', () => { + if (serverNameEl.value.length > MAX_SERVER_NAME_LENGTH) { + serverNameEl.value = serverNameEl.value.slice(0, MAX_SERVER_NAME_LENGTH); + } + const raw = serverNameEl.value.trim(); + summaryNameEl.textContent = raw || '—'; + }); + } + + createConfirm?.addEventListener('click', () => { + const raw = serverNameEl.value; + const name = sanitizeName(raw); + if (!name) { + alert('Please enter a valid name (letters, numbers, spaces, dashes, underscores).'); + return; + } + if (!selectedTemplateId) { + alert('Please choose a template.'); + 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 (selectedTemplateId === 'minecraft') { + closeCreate(); + openForkModal(); + return; + } + + closeCreate(); + openPortModal('create'); + }); + + forkConfirm?.addEventListener('click', () => { + if (!selectedForkId) { + alert('Please choose a fork.'); + return; + } + closeForkModal(); + openPortModal('fork'); + }); + + portConfirm?.addEventListener('click', async () => { + const portVal = parseStrictPortValue(serverPortEl?.value); + if (!portVal) { + alert('Invalid port. Choose a value between 1 and 65535.'); + 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; + } + } + } + + try { + if (portSpinner) portSpinner.classList.add('visible'); + if (portConfirm) portConfirm.disabled = true; + if (!(await verifySelectedNodePortAvailable(portVal))) return; + } finally { + if (portSpinner) portSpinner.classList.remove('visible'); + if (portConfirm) portConfirm.disabled = false; + } + + closePortModal(); + await openStartupModal(); + }); + + async function openStartupModal() { + if (!startupModal) return; + + startupModal.classList.add('show'); + startupModal.setAttribute('aria-hidden', 'false'); + setStartupCommandValidationError(''); + + await resolveStartupCommandForSelection({ + templateId: selectedTemplateId, + nodeId: selectedNodeId, + showLoading: true + }); + } + + function closeStartupModal() { + if (!startupModal) return; + startupModal.classList.remove('show'); + startupModal.setAttribute('aria-hidden', 'true'); + } + + startupClose?.addEventListener('click', closeStartupModal); + startupBack?.addEventListener('click', () => { + closeStartupModal(); + portModal.classList.add('show'); + portModal.setAttribute('aria-hidden', 'false'); + }); + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && startupModal?.classList.contains('show')) closeStartupModal(); + }); + + startupConfirm?.addEventListener('click', () => { + selectedStartupCommand = startupCommandEl ? startupCommandEl.value.trim() : ''; + const template = findTemplateById(selectedTemplateId); + const templateADPanelStartup = String( + template?.docker?.adpanelStartup || + template?.docker?.adpanel_startup || + template?.docker?.pterodactylStartup || + template?.docker?.pterodactyl_startup || + '' + ).trim(); + if (selectedStartupCommandMode === 'adpanel-startup' && selectedStartupCommand === templateADPanelStartup) { + setStartupCommandValidationError(''); + closeStartupModal(); + openImportModal(); + return; + } + selectedStartupCommandMode = ''; + const startupCommandError = validateRuntimeProcessCommandInput(selectedStartupCommand); + if (startupCommandError && selectedStartupCommand) { + setStartupCommandValidationError(startupCommandError); + setStartupCommandSource('This field accepts only the executable and arguments that run inside the container. Docker CLI startup commands are blocked by ADPanel.'); + startupCommandEl?.focus(); + return; + } + + setStartupCommandValidationError(''); + closeStartupModal(); + openImportModal(); + }); + + startupCommandEl?.addEventListener('input', () => { + selectedStartupCommandMode = ''; + if (startupCommandEl) startupCommandEl.readOnly = false; + const commandError = validateRuntimeProcessCommandInput(startupCommandEl.value); + setStartupCommandValidationError(commandError || ''); + }); + + const ALLOWED_ARCHIVE_EXTENSIONS = ['.zip', '.rar', '.7z', '.tar.gz', '.tgz', '.tar.bz2', '.tbz2']; + + function isValidArchiveUrl(url) { + if (!url) return true; + try { + const parsedUrl = new URL(url); + if (!['http:', 'https:'].includes(parsedUrl.protocol)) return false; + const pathname = parsedUrl.pathname.toLowerCase(); + return ALLOWED_ARCHIVE_EXTENSIONS.some(ext => pathname.endsWith(ext)); + } catch { + return false; + } + } + + function formatDownloadBytes(bytes) { + if (bytes === 0) return '0 B'; + const k = 1024; + const sizes = ['B', 'KB', 'MB', 'GB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; + } + + function openImportModal() { + if (!importModal) { + openResourcesModal(); + return; + } + + selectedImportUrl = ''; + if (importUrlEl) importUrlEl.value = ''; + if (importProgressContainer) importProgressContainer.style.display = 'none'; + if (importProgressFill) importProgressFill.style.width = '0%'; + if (importPercent) importPercent.textContent = '0%'; + if (importDownloaded) importDownloaded.textContent = '0 MB'; + if (importTotal) importTotal.textContent = '0 MB'; + + if (importConfirm) importConfirm.disabled = false; + if (importBack) importBack.disabled = false; + if (importSkip) importSkip.disabled = false; + if (importClose) importClose.disabled = false; + + importModal.classList.add('show'); + importModal.setAttribute('aria-hidden', 'false'); + } + + function closeImportModal() { + if (!importModal) return; + importModal.classList.remove('show'); + importModal.setAttribute('aria-hidden', 'true'); + } + + function setImportButtonsDisabled(disabled) { + if (importConfirm) importConfirm.disabled = disabled; + if (importBack) importBack.disabled = disabled; + if (importSkip) importSkip.disabled = disabled; + if (importClose) importClose.disabled = disabled; + } + + importClose?.addEventListener('click', () => { + closeImportModal(); + }); + + importBack?.addEventListener('click', () => { + closeImportModal(); + startupModal.classList.add('show'); + startupModal.setAttribute('aria-hidden', 'false'); + }); + + importSkip?.addEventListener('click', () => { + selectedImportUrl = ''; + closeImportModal(); + openResourcesModal(); + }); + + + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && importModal?.classList.contains('show')) { + closeImportModal(); + } + }); + + importConfirm?.addEventListener('click', async () => { + const url = importUrlEl ? importUrlEl.value.trim() : ''; + + if (!url) { + selectedImportUrl = ''; + closeImportModal(); + openResourcesModal(); + return; + } + + if (!isValidArchiveUrl(url)) { + alert('Invalid URL. Please enter a direct link to a .zip, .rar, .7z, or .tar.gz archive.'); + return; + } + + selectedImportUrl = url; + closeImportModal(); + openResourcesModal(); + }); + + function openResourcesModal() { + if (resourceRamEl) resourceRamEl.value = ''; + if (resourceCpuCoresEl) resourceCpuCoresEl.value = ''; + if (resourceSwapEl) resourceSwapEl.value = ''; + if (resourceStorageEl) resourceStorageEl.value = ''; + if (resourceBackupsEl) resourceBackupsEl.value = ''; + if (resourceMaxSchedulesEl) resourceMaxSchedulesEl.value = ''; + if (resourceIoWeightEl) resourceIoWeightEl.value = ''; + if (resourceCpuWeightEl) resourceCpuWeightEl.value = ''; + if (resourcePidsLimitEl) resourcePidsLimitEl.value = ''; + if (resourceFileLimitEl) resourceFileLimitEl.value = ''; + if (resourceNetworkInboundLimitEl) resourceNetworkInboundLimitEl.value = ''; + 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 }); + } + + resourcesModal.classList.add('show'); + resourcesModal.setAttribute('aria-hidden', 'false'); + } + + function closeResourcesModal() { + resourcesModal.classList.remove('show'); + resourcesModal.setAttribute('aria-hidden', 'true'); + } + + resourcesClose?.addEventListener('click', closeResourcesModal); + resourcesBack?.addEventListener('click', () => { + closeResourcesModal(); + openImportModal(); + }); + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && resourcesModal?.classList.contains('show')) closeResourcesModal(); + }); + + resourcesConfirm?.addEventListener('click', async () => { + const raw = serverNameEl.value; + const name = sanitizeName(raw); + if (!name) { + alert('Server name is missing or invalid.'); + return; + } + if (!selectedTemplateId) { + alert('Template is not chosen.'); + return; + } + if (selectedTemplateId === 'minecraft' && !selectedForkId) { + alert('Please choose a fork.'); + 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 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; + + 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); + if (!portVal) { + alert('Invalid port. Choose a value between 1 and 65535.'); + 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 (!(await verifySelectedNodePortAvailable(portVal))) { + return; + } + + try { + resourcesSpinner.classList.add('visible'); + resourcesConfirm.disabled = true; + + const displayName = raw.trim().replace(/[^a-zA-Z0-9 \-_.]/g, '').replace(/\s+/g, ' ').slice(0, 120); + const payload = { + name, + displayName: displayName || name, + templateId: selectedTemplateId, + nodeId: selectedNodeId, + hostPort: portVal + }; + if (selectedStartupCommand && selectedStartupCommandMode !== 'adpanel-startup') { + const payloadCommandError = validateRuntimeProcessCommandInput(selectedStartupCommand); + if (!payloadCommandError) { + payload.command = selectedStartupCommand; + } + } + + if (selectedTemplateId === 'minecraft') { + payload.mcFork = selectedForkId; + payload.mcVersion = MC_VERSION; + } + + if (selectedImportUrl) { + payload.importUrl = selectedImportUrl; + } + + const ramLimit = resourceRamEl && resourceRamEl.value ? parseInt(resourceRamEl.value, 10) : null; + const cpuCoresLimit = resourceCpuCoresEl && resourceCpuCoresEl.value ? parseFloat(resourceCpuCoresEl.value) : null; + const swapLimit = resourceSwapEl && resourceSwapEl.value !== '' ? parseInt(resourceSwapEl.value, 10) : null; + const storageLimit = resourceStorageEl && resourceStorageEl.value ? parseInt(resourceStorageEl.value, 10) : null; + const backupsLimit = resourceBackupsEl && resourceBackupsEl.value ? parseInt(resourceBackupsEl.value, 10) : null; + const maxSchedulesLimit = resourceMaxSchedulesEl && resourceMaxSchedulesEl.value ? parseInt(resourceMaxSchedulesEl.value, 10) : null; + const ioWeightLimit = readOptionalIntegerRange(resourceIoWeightEl, 'I/O Priority', 10, 1000); + const cpuWeightLimit = readOptionalIntegerRange(resourceCpuWeightEl, 'CPU Priority', 1, 1000); + const pidsLimit = readOptionalIntegerRange(resourcePidsLimitEl, 'Process Limit', 64, 4096); + const fileLimit = readOptionalIntegerRange(resourceFileLimitEl, 'File Limit', 1024, 1048576); + const networkInboundLimitMb = readOptionalIntegerRange(resourceNetworkInboundLimitEl, 'Inbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB); + const networkOutboundLimitMb = readOptionalIntegerRange(resourceNetworkOutboundLimitEl, 'Outbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB); + const networkResetMinutes = readOptionalIntegerRange(resourceNetworkResetMinutesEl, 'Reset Time', 1, RESOURCE_NETWORK_RESET_MAX_MINUTES); + + payload.resources = { + ramMb: ramLimit, + cpuCores: cpuCoresLimit, + swapMb: swapLimit, + storageMb: storageLimit, + backupsMax: backupsLimit, + maxSchedules: maxSchedulesLimit, + ioWeight: ioWeightLimit, + cpuWeight: cpuWeightLimit, + pidsLimit, + fileLimit, + networkInboundLimitMb, + networkOutboundLimitMb, + networkResetMinutes + }; + + const r = await fetch('/api/servers/create', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(payload) + }); + const j = await r.json().catch(() => ({})); + if (!r.ok || !j.ok) { + throw new Error( + (j && (j.detail || j.message || j.error)) + ? (j.detail || j.message || j.error) + : 'Create failed' + ); + } + + window.location.href = `/server/${encodeURIComponent(name)}`; + } catch (e) { + alert(e.message || 'Create failed'); + } finally { + resourcesSpinner.classList.remove('visible'); + resourcesConfirm.disabled = false; + } + }); +}); + +const serverStartTime = Number(document.body.dataset.serverStartTime) || Date.now(); +const uptimeDisplay = document.getElementById('uptimeDisplay'); +function formatTime(ms) { + const totalSeconds = Math.floor(ms / 1000); + const hours = Math.floor(totalSeconds / 3600); + const minutes = Math.floor((totalSeconds % 3600) / 60); + const seconds = totalSeconds % 60; + return `${hours}h ${minutes}m ${seconds}s`; +} +function updateUptime() { + if (uptimeDisplay) { + const now = Date.now(); + uptimeDisplay.textContent = formatTime(now - serverStartTime); + } +} +setInterval(updateUptime, 1000); +updateUptime(); + + +class DashboardStatusManager { + constructor() { + this.socket = null; + this.serverCards = new Map(); + this.statuses = new Map(); + this.connected = false; + } + + init() { + document.querySelectorAll('[data-bot-card]').forEach(card => { + const name = card.dataset.name; + if (name) this.serverCards.set(name.toLowerCase(), card); + }); + + if (this.serverCards.size === 0) return; + + if (window._dashResourceSocket) { + this.socket = window._dashResourceSocket; + this.connected = window._dashResourceSocket.connected; + this._attachListeners(); + if (this.connected) this.subscribe(); + } else { + this.connectSocket(); + } + } + + connectSocket() { + if (!window.io) return; + + this.socket = window.io({ + transports: ['websocket', 'polling'], + reconnection: true, + reconnectionDelay: 1000, + reconnectionDelayMax: 5000 + }); + + this._attachListeners(); + } + + _attachListeners() { + if (!this.socket) return; + + this.socket.on('connect', () => { + this.connected = true; + this.subscribe(); + }); + + this.socket.on('disconnect', () => { + this.connected = false; + }); + + this.socket.on('dashboard:initial', (data) => { + if (data.statuses) { + Object.entries(data.statuses).forEach(([name, status]) => { + this.updateServerCard(name, status); + }); + } + }); + + this.socket.on('server:status', (data) => { + this.updateServerCard(data.name, data); + }); + + this.socket.on('node:status', (data) => { + this.updateNodeIndicators(data.id, data); + }); + } + + subscribe() { + const serverNames = Array.from(this.serverCards.keys()); + this.socket.emit('dashboard:subscribe', { bots: serverNames }); + } + + updateServerCard(name, status) { + const cardName = String(name || '').toLowerCase(); + const card = this.serverCards.get(cardName); + if (!card) return; + + this.statuses.set(cardName, status); + + const statusEl = card.querySelector('.bot-card__status'); + if (statusEl) { + const normalized = this.normalizeStatus(status.status); + const allStatusClasses = ['status-online', 'status-stopped', 'status-unknown']; + card.classList.remove(...allStatusClasses); + statusEl.classList.remove(...allStatusClasses); + if (normalized === 'online') { + card.classList.add('status-online'); + statusEl.classList.add('status-online'); + } else if (normalized === 'stopped') { + card.classList.add('status-stopped'); + statusEl.classList.add('status-stopped'); + } else { + card.classList.add('status-unknown'); + statusEl.classList.add('status-unknown'); + } + } + + if ('nodeOnline' in status && typeof window.updateNodeOfflineStatus === 'function') { + window.updateNodeOfflineStatus(name, status.nodeOnline === true); + } + } + + updateNodeIndicators(nodeId, status) { + document.querySelectorAll(`[data-node-id="${nodeId}"]`).forEach(card => { + if (typeof window.updateNodeOfflineStatus === 'function') { + const name = card.dataset.name; + if (name) window.updateNodeOfflineStatus(name, status.online === true); + } + }); + } + + normalizeStatus(status) { + const raw = String(status || '').toLowerCase(); + if (['online', 'running', 'up', 'healthy'].some(t => raw.includes(t))) return 'online'; + if (raw.includes('unknown')) return null; + if (['offline', 'exited', 'stopped', 'down', 'dead', 'error'].some(t => raw.includes(t))) return 'stopped'; + if (!raw) return 'stopped'; + return null; + } + + destroy() { + if (this.socket) { + this.socket.emit('dashboard:unsubscribe'); + } + } +} + +window.dashboardStatus = new DashboardStatusManager(); +window.dashboardStatus.init(); diff --git a/public/js/resource-popup.js b/public/js/resource-popup.js new file mode 100644 index 0000000..9a2d5ca --- /dev/null +++ b/public/js/resource-popup.js @@ -0,0 +1,208 @@ +(() => { + const bot = document.documentElement.dataset.bot; + if (!bot) { + console.error("Bot name not found in dataset"); + return; + } + + const resMemoryLabel = document.getElementById('resMemoryLabel'); + const resMemoryBar = document.getElementById('resMemoryBar'); + const resDiskLabel = document.getElementById('resDiskLabel'); + const resDiskBar = document.getElementById('resDiskBar'); + const resCpuLabel = document.getElementById('resCpuLabel'); + const resCpuBar = document.getElementById('resCpuBar'); + const resNetworkInboundLabel = document.getElementById('resNetworkInboundLabel'); + const resNetworkOutboundLabel = document.getElementById('resNetworkOutboundLabel'); + const resUptimeLabel = document.getElementById('resUptimeLabel'); + + let resourceStatsUptimeInterval = null; + let lastFetchedUptime = null; + let uptimeFetchedAt = null; + let lastNetworkInboundBytes = 0; + let lastNetworkOutboundBytes = 0; + + const sio = window.io; + let socket; + if (typeof sio === 'function') { + try { socket = sio(); } catch { socket = null; } + } + if (!socket) { + console.error('Socket.IO not available for resource popup'); + return; + } + + function formatBytes(bytes, decimals = 2) { + if (!+bytes) return '0 B'; + const k = 1024; + const dm = decimals < 0 ? 0 : decimals; + const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`; + } + + function formatUptime(seconds) { + if (!seconds || seconds < 0) return '—'; + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + const mins = Math.floor((seconds % 3600) / 60); + const secs = Math.floor(seconds % 60); + const parts = []; + if (days > 0) parts.push(`${days}d`); + if (hours > 0) parts.push(`${hours}h`); + if (mins > 0) parts.push(`${mins}m`); + if (secs > 0 || parts.length === 0) parts.push(`${secs}s`); + return parts.join(' '); + } + + function readNetworkBytes(network, keys) { + if (!network || typeof network !== 'object') return null; + for (const key of keys) { + const value = Number(network[key]); + if (Number.isFinite(value) && value >= 0) return value; + } + return null; + } + + function onResourceData(data) { + if (!data || data.server !== bot) return; + const isRunning = data.status === 'running' || data.status === 'online'; + + if (data.memory && isRunning) { + let usedMb, limitMb, pct; + if (typeof data.memory === 'object') { + usedMb = data.memory.used || 0; + limitMb = data.memory.total || 0; + pct = data.memory.percent ?? (limitMb > 0 ? Math.min(100, Math.round((usedMb / limitMb) * 100)) : 0); + } else { + usedMb = data.memory; limitMb = 0; pct = 0; + } + resMemoryLabel.textContent = limitMb > 0 + ? `${formatBytes(usedMb * 1048576)} / ${formatBytes(limitMb * 1048576)} (${Math.round(pct)}%)` + : `${formatBytes(usedMb * 1048576)} / Unlimited`; + resMemoryBar.style.width = `${pct}%`; + } else { + resMemoryLabel.textContent = '—'; + resMemoryBar.style.width = '0%'; + } + + if (data.disk) { + let usedGb, limitGb, pct; + if (typeof data.disk === 'object') { + usedGb = data.disk.used || 0; + limitGb = data.disk.total || 0; + pct = data.disk.percent ?? (limitGb > 0 ? Math.min(100, Math.round((usedGb / limitGb) * 100)) : 0); + } else { + usedGb = data.disk / 1024; limitGb = 0; pct = 0; + } + resDiskLabel.textContent = limitGb > 0 + ? `${formatBytes(usedGb * 1073741824)} / ${formatBytes(limitGb * 1073741824)} (${Math.round(pct)}%)` + : `${formatBytes(usedGb * 1073741824)} / Unlimited`; + resDiskBar.style.width = `${pct}%`; + } else { + resDiskLabel.textContent = '—'; + resDiskBar.style.width = '0%'; + } + + if (data.cpu !== undefined && data.cpu !== null && isRunning) { + const cpuMax = data.cpuLimit || 100; + const cpuPct = Math.min(cpuMax, Math.round(data.cpu)); + const cpuBarWidth = cpuMax > 0 ? Math.min(100, (cpuPct / cpuMax) * 100) : 0; + resCpuLabel.textContent = `${cpuPct}% / ${Math.round(cpuMax)}%`; + resCpuBar.style.width = `${cpuBarWidth}%`; + } else { + resCpuLabel.textContent = '—'; + resCpuBar.style.width = '0%'; + } + + const network = data.network || null; + const inboundBytes = readNetworkBytes(network, ['inboundBytes', 'rxBytes', 'receivedBytes']); + const outboundBytes = readNetworkBytes(network, ['outboundBytes', 'txBytes', 'transmittedBytes']); + if (inboundBytes !== null) { + lastNetworkInboundBytes = Math.max(lastNetworkInboundBytes, inboundBytes); + if (resNetworkInboundLabel) resNetworkInboundLabel.textContent = formatBytes(lastNetworkInboundBytes); + } else if (resNetworkInboundLabel) { + resNetworkInboundLabel.textContent = '—'; + } + if (outboundBytes !== null) { + lastNetworkOutboundBytes = Math.max(lastNetworkOutboundBytes, outboundBytes); + if (resNetworkOutboundLabel) resNetworkOutboundLabel.textContent = formatBytes(lastNetworkOutboundBytes); + } else if (resNetworkOutboundLabel) { + resNetworkOutboundLabel.textContent = '—'; + } + + if (data.uptime && data.uptime > 0 && isRunning) { + lastFetchedUptime = data.uptime; + uptimeFetchedAt = Date.now(); + resUptimeLabel.textContent = formatUptime(data.uptime); + startUptimeCounter(); + } else { + lastFetchedUptime = null; + uptimeFetchedAt = null; + stopUptimeCounter(); + resUptimeLabel.textContent = isRunning ? 'Starting...' : 'Offline'; + } + } + + function startUptimeCounter() { + stopUptimeCounter(); + if (lastFetchedUptime === null || uptimeFetchedAt === null) return; + resourceStatsUptimeInterval = setInterval(() => { + if (lastFetchedUptime === null || uptimeFetchedAt === null) { + stopUptimeCounter(); + return; + } + const elapsed = Math.floor((Date.now() - uptimeFetchedAt) / 1000); + const currentUptime = lastFetchedUptime + elapsed; + resUptimeLabel.textContent = formatUptime(currentUptime); + }, 1000); + } + + function stopUptimeCounter() { + if (resourceStatsUptimeInterval) { + clearInterval(resourceStatsUptimeInterval); + resourceStatsUptimeInterval = null; + } + } + + let subscribed = false; + + function subscribe() { + if (subscribed) return; + subscribed = true; + socket.on('resources:data', onResourceData); + socket.emit('resources:subscribe', { server: bot }); + } + + function unsubscribe() { + if (!subscribed) return; + subscribed = false; + socket.off('resources:data', onResourceData); + socket.emit('resources:unsubscribe', { server: bot }); + stopUptimeCounter(); + } + + socket.on('connect', () => { + if (subscribed) { + subscribed = false; + subscribe(); + } else if (document.visibilityState !== 'hidden') { + subscribe(); + } + }); + + if (document.visibilityState !== 'hidden') { + if (socket.connected) subscribe(); + } + + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') { + unsubscribe(); + return; + } + subscribe(); + }); + + window.addEventListener('beforeunload', () => { + unsubscribe(); + }); +})(); diff --git a/public/js/settings.js b/public/js/settings.js new file mode 100644 index 0000000..d73697a --- /dev/null +++ b/public/js/settings.js @@ -0,0 +1,11608 @@ +const BG_KEY = 'ui-background'; +const ACCENT_KEY = 'ui-accent'; +const DENSITY_KEY = 'ui-density'; +const ANIM_KEY = 'ui-animations'; +const body = document.body; +const sidebarNav = document.getElementById('sidebarNav'); +const sections = document.querySelectorAll('.panel-section'); +const closeEscFixed = document.getElementById('closeEscFixed'); +const leftCol = document.getElementById('leftCol'); +const modalOverlay = document.getElementById('modalOverlay'); +const changeModal = document.getElementById('changeModal'); +const changePassCard = document.getElementById('changePassCard'); +const modalCancel = document.getElementById('modalCancel'); +const modalCancelBtn = document.getElementById('modalCancelBtn'); +const modalSave = document.getElementById('modalSave'); +const accountModalOverlay = document.getElementById('accountModalOverlay'); +const accountModal = document.getElementById('accountModal'); +const accountModalTitle = document.getElementById('accountModalTitle'); +const accountModalBody = document.getElementById('accountModalBody'); +const accountModalClose = document.getElementById('accountModalClose'); +const permModalOverlay = document.getElementById('permModalOverlay'); +const permModal = document.getElementById('permModal'); +const permModalTitle = document.getElementById('permModalTitle'); +const permModalBody = document.getElementById('permModalBody'); +const permCancel = document.getElementById('permCancel'); +const permCancelBtn = document.getElementById('permCancelBtn'); +const permSave = document.getElementById('permSave'); +const templatesFeedbackEl = document.getElementById('templatesFeedback'); +const templatesListEl = document.getElementById('templatesList'); +const openCreateTemplateBtn = document.getElementById('openCreateTemplate'); +const createTemplateOverlay = document.getElementById('createTemplateOverlay'); +const createTemplateModal = document.getElementById('createTemplateModal'); +const createTemplateModalTitle = document.getElementById('createTemplateModalTitle'); +const createTemplateModalSubtitle = document.getElementById('createTemplateModalSubtitle'); +const createTemplateCancel = document.getElementById('createTemplateCancel'); +const createTemplateClose = document.getElementById('createTemplateClose'); +const createTemplateSave = document.getElementById('createTemplateSave'); +const createTemplateFeedback = document.getElementById('createTemplateFeedback'); +const ct_id = document.getElementById('ct_id'); +const ct_name = document.getElementById('ct_name'); +const ct_description = document.getElementById('ct_description'); +const ct_template_image = document.getElementById('ct_template_image'); +const ct_default_port = document.getElementById('ct_default_port'); +const ct_image = document.getElementById('ct_image'); +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_import_json = document.getElementById('ct_import_json'); +const createTemplateImportBtn = document.getElementById('createTemplateImportBtn'); +const serversListEl = document.getElementById('serversList'); +const createServerBtn = document.getElementById('createServerBtn'); +const createServerNameInput = document.getElementById('createServerName'); +const serverTemplateOverlay = document.getElementById('serverTemplateOverlay'); +const serverTemplateModal = document.getElementById('serverTemplateModal'); +const serverTemplateTitle = document.getElementById('serverTemplateTitle'); +const serverTemplateSubtitle = document.getElementById('serverTemplateSubtitle'); +const serverTemplateList = document.getElementById('serverTemplateList'); +const serverTemplateFeedback = document.getElementById('serverTemplateFeedback'); +const serverTemplateCancel = document.getElementById('serverTemplateCancel'); +const serverTemplateClose = document.getElementById('serverTemplateClose'); +const serverTemplateDone = document.getElementById('serverTemplateDone'); +const accountsListEl = document.getElementById('accountsList'); +const accountsSearchInput = document.getElementById('accountsSearchInput'); +const nodesListEl = document.getElementById('nodesList'); +const openCreateNodeBtn = document.getElementById('openCreateNode'); +const createNodeOverlay = document.getElementById('createNodeOverlay'); +const createNodeModal = document.getElementById('createNodeModal'); +const createNodeClose = document.getElementById('createNodeClose'); +const createNodeCancel = document.getElementById('createNodeCancel'); +const createNodeSave = document.getElementById('createNodeSave'); +const createNodeFeedback = document.getElementById('createNodeFeedback'); +const cn_name = document.getElementById('cn_name'); +const cn_address = document.getElementById('cn_address'); +const cn_ram_gb = document.getElementById('cn_ram_gb'); +const cn_disk_gb = document.getElementById('cn_disk_gb'); +const cn_ports_range = document.getElementById('cn_ports_range'); +const cn_ports_list = document.getElementById('cn_ports_list'); +const cn_port_start = document.getElementById('cn_port_start'); +const cn_port_count = document.getElementById('cn_port_count'); +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'); +const cn_connection_help = document.getElementById('cn_connection_help'); +const cn_under_cloudflare = document.getElementById('cn_under_cloudflare'); +const cn_under_cloudflare_row = document.getElementById('cn_under_cloudflare_row'); +const nodeModalOverlay = document.getElementById('nodeModalOverlay'); +const ASSISTANT_SETTINGS_ACTION_EVENT = 'adpanel:assistant-open-settings-action'; + +function getRequestedAssistantSettingsAction() { + const params = new URLSearchParams(window.location.search || ''); + return String(params.get('assistantAction') || '').trim().toLowerCase(); +} + +function clearRequestedAssistantSettingsAction() { + const url = new URL(window.location.href); + if (!url.searchParams.has('assistantAction')) return; + url.searchParams.delete('assistantAction'); + const nextSearch = url.searchParams.toString(); + const nextUrl = `${url.pathname}${nextSearch ? `?${nextSearch}` : ''}${url.hash || ''}`; + try { + window.history.replaceState({}, '', nextUrl); + } catch { + } +} + +function dispatchAssistantSettingsAction(action) { + const normalized = String(action || '').trim().toLowerCase(); + if (!normalized) return false; + document.dispatchEvent(new CustomEvent(ASSISTANT_SETTINGS_ACTION_EVENT, { + detail: { action: normalized } + })); + return true; +} + +function clickAssistantSettingsButton(id) { + const button = document.getElementById(id); + if (!button) return false; + try { + button.focus?.(); + button.click(); + } catch { + button.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); + } + return true; +} + +function tryOpenRequestedAssistantSettingsAction(action) { + const normalized = String(action || '').trim().toLowerCase(); + if (!normalized) return false; + + switch (normalized) { + case 'create_user': + return clickAssistantSettingsButton('openCreateUserBtn'); + case 'branding': + return clickAssistantSettingsButton('openBrandingBtn'); + case 'login_watermark': + return clickAssistantSettingsButton('openLoginWatermarkBtn'); + case 'login_background': + return clickAssistantSettingsButton('openLoginBackgroundBtn'); + case 'alert': + return clickAssistantSettingsButton('openAlertModalBtn'); + case 'quick_action_admin': + return clickAssistantSettingsButton('addQuickActionBtn'); + case 'quick_action_user': + return clickAssistantSettingsButton('addUserQuickActionBtn'); + case 'database_setup': + if (typeof openSetupModal === 'function') { + openSetupModal(); + return true; + } + return false; + case 'create_node': + return clickAssistantSettingsButton('openCreateNode'); + case 'create_template': + return clickAssistantSettingsButton('openCreateTemplate'); + case 'add_webhook': + return clickAssistantSettingsButton('openAddWebhookBtn'); + case 'pgadmin_setup': + case 'mongodb_setup': + case 'captcha': + case 'maintenance': + return dispatchAssistantSettingsAction(normalized); + default: + return false; + } +} +const nodeModal = document.getElementById('nodeModal'); +const nodeModalClose = document.getElementById('nodeModalClose'); +const nodeModalCancelBtn = document.getElementById('nodeModalCancelBtn'); +const nm_title = document.getElementById('nm_title'); +const nm_subtitle = document.getElementById('nm_subtitle'); +const nm_tabs = nodeModal.querySelectorAll('.node-tabs .node-tab'); +const tab_build = document.getElementById('tab_build'); +const tab_linking = document.getElementById('tab_linking'); +const tab_deletion = document.getElementById('tab_deletion'); +const buildFooter = document.getElementById('buildFooter'); +const nm_name = document.getElementById('nm_name'); +const nm_address = document.getElementById('nm_address'); +const nm_cpu_cores = document.getElementById('nm_cpu_cores'); +const nm_ram_gb = document.getElementById('nm_ram_gb'); +const nm_disk_gb = document.getElementById('nm_disk_gb'); +const nm_ports_range = document.getElementById('nm_ports_range'); +const nm_ports_list = document.getElementById('nm_ports_list'); +const nm_port_start = document.getElementById('nm_port_start'); +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_configYml = document.getElementById('nm_configYml'); +const nm_copyConfig = document.getElementById('nm_copyConfig'); +const nm_downloadConfig = document.getElementById('nm_downloadConfig'); +const nm_showCmd = document.getElementById('nm_showCmd'); +const nm_cmd = document.getElementById('nm_cmd'); +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_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'); +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" +]; +const templateExportMap = new Map(); +const templateEditorState = { + mode: 'create', + editTemplateId: '' +}; +const ACL_PREFIX = 'acl:'; +const THEME_KEY = 'ui-theme'; +const UNSAVED_MODAL_MESSAGE = 'Ai modificari nesalvate intr-un popup. Daca reincarci pagina, acestea se vor pierde.'; +const TRACKED_MODAL_SELECTOR = '.modal-overlay'; +const TRACKABLE_MODAL_FIELD_SELECTOR = [ + 'input:not([type="hidden"]):not([type="button"]):not([type="submit"]):not([type="reset"]):not([disabled]):not([readonly])', + 'select:not([disabled]):not([readonly])', + 'textarea:not([disabled]):not([readonly])', + '[contenteditable="true"]' +].join(','); +const MODAL_MUTATION_CLICK_SELECTOR = '.icon-suggestion, .template-option-card, .port-remove, .pf-remove, [data-unsaved-action]'; +const modalUnsavedRecords = new WeakMap(); +const modalCustomStateReaders = new Map(); +let unsavedModalBeforeUnloadBound = false; + +function registerModalCustomStateReader(modalId, reader) { + if (!modalId || typeof reader !== 'function') return; + modalCustomStateReaders.set(modalId, reader); + observeTrackedModals(); +} + +function getModalUnsavedRecord(root) { + let record = modalUnsavedRecords.get(root); + if (!record) { + record = { + baseline: '', + dirty: false, + userInteracted: false, + pristineSyncTimer: null, + observer: null + }; + modalUnsavedRecords.set(root, record); + } + return record; +} + +function serializeDataset(dataset) { + if (!dataset) return ''; + const entries = Object.entries(dataset) + .filter(([, value]) => value !== undefined && value !== null && value !== '') + .sort(([a], [b]) => a.localeCompare(b)); + return entries.map(([key, value]) => `${key}=${String(value)}`).join('|'); +} + +function getModalFieldKey(el, index) { + const explicit = el.getAttribute('data-unsaved-key'); + if (explicit) return explicit; + if (el.id) return `#${el.id}`; + if (el.name) return `${el.tagName.toLowerCase()}:${el.name}:${index}`; + return `${el.tagName.toLowerCase()}:${el.type || 'value'}:${index}`; +} + +function hasHiddenAncestor(node, root) { + let current = node; + while (current && current !== root) { + if (current.hidden) return true; + const style = window.getComputedStyle(current); + if (style.display === 'none' || style.visibility === 'hidden') return true; + current = current.parentElement; + } + return false; +} + +function isTrackableFieldVisible(el, root) { + if (!el || !root) return false; + if (el.matches('[disabled], [readonly]')) return false; + if (el.tagName === 'INPUT' && el.type === 'file') { + return !!(el.files && el.files.length > 0) || !hasHiddenAncestor(el.parentElement || el, root); + } + return !hasHiddenAncestor(el, root); +} + +function serializeTrackableField(el, index) { + const key = getModalFieldKey(el, index); + const tag = el.tagName.toLowerCase(); + if (tag === 'input') { + const type = (el.type || 'text').toLowerCase(); + if (type === 'checkbox' || type === 'radio') { + return `${key}=${el.checked ? '1' : '0'}`; + } + if (type === 'file') { + const files = Array.from(el.files || []).map(file => `${file.name}:${file.size}:${file.lastModified}`); + return `${key}=${files.join(',')}`; + } + return `${key}=${el.value || ''}`; + } + if (tag === 'select' || tag === 'textarea') { + return `${key}=${el.value || ''}`; + } + return `${key}=${(el.textContent || '').trim()}`; +} + +function serializeMarkedModalState(el, index) { + const mode = (el.getAttribute('data-unsaved-state') || 'text').toLowerCase(); + const key = el.getAttribute('data-unsaved-key') || el.id || `state:${index}`; + let value = ''; + if (mode === 'html') { + value = (el.innerHTML || '').replace(/\s+/g, ' ').trim(); + } else if (mode === 'dataset') { + value = serializeDataset(el.dataset); + } else if (mode === 'value') { + value = typeof el.value === 'string' ? el.value : (el.textContent || '').trim(); + } else { + value = (el.textContent || '').replace(/\s+/g, ' ').trim(); + } + return `${key}=${value}`; +} + +function hasTrackableModalState(root) { + if (!root) return false; + return !!( + modalCustomStateReaders.has(root.id) || + root.querySelector(TRACKABLE_MODAL_FIELD_SELECTOR) || + root.querySelector('[data-unsaved-state]') + ); +} + +function isModalOpen(root) { + if (!root) return false; + if (root.classList.contains('show')) return true; + if (root.getAttribute('aria-hidden') === 'false') return true; + const style = window.getComputedStyle(root); + if (style.display === 'none' || style.visibility === 'hidden') return false; + return style.opacity !== '0'; +} + +function serializeModalState(root) { + if (!root) return ''; + const parts = []; + const innerModal = root.querySelector('.enterprise-modal'); + const rootDataset = serializeDataset(root.dataset); + if (rootDataset) parts.push(`root:${rootDataset}`); + if (innerModal && innerModal !== root) { + const modalDataset = serializeDataset(innerModal.dataset); + if (modalDataset) parts.push(`modal:${modalDataset}`); + } + Array.from(root.querySelectorAll(TRACKABLE_MODAL_FIELD_SELECTOR)) + .filter(el => isTrackableFieldVisible(el, root)) + .forEach((el, index) => { + parts.push(serializeTrackableField(el, index)); + }); + Array.from(root.querySelectorAll('[data-unsaved-state]')) + .forEach((el, index) => { + parts.push(serializeMarkedModalState(el, index)); + }); + const customReader = modalCustomStateReaders.get(root.id); + if (typeof customReader === 'function') { + try { + parts.push(`custom=${JSON.stringify(customReader())}`); + } catch (err) { + console.warn('[unsaved-modal-guard] Failed to serialize custom state for', root.id, err); + } + } + return parts.join('||'); +} + +function stopModalPristineSync(root) { + const record = getModalUnsavedRecord(root); + if (record.pristineSyncTimer) { + clearInterval(record.pristineSyncTimer); + record.pristineSyncTimer = null; + } +} + +function getDirtyOpenModals() { + return Array.from(document.querySelectorAll(TRACKED_MODAL_SELECTOR)) + .filter(root => hasTrackableModalState(root) && isModalOpen(root)) + .filter(root => getModalUnsavedRecord(root).dirty); +} + +function modalBeforeUnloadHandler(e) { + if (!getDirtyOpenModals().length) return; + e.preventDefault(); + e.returnValue = UNSAVED_MODAL_MESSAGE; + return UNSAVED_MODAL_MESSAGE; +} + +function updateUnsavedModalBeforeUnload() { + const shouldBind = getDirtyOpenModals().length > 0; + if (shouldBind && !unsavedModalBeforeUnloadBound) { + window.addEventListener('beforeunload', modalBeforeUnloadHandler); + unsavedModalBeforeUnloadBound = true; + } else if (!shouldBind && unsavedModalBeforeUnloadBound) { + window.removeEventListener('beforeunload', modalBeforeUnloadHandler); + unsavedModalBeforeUnloadBound = false; + } +} + +function syncModalBaseline(root) { + const record = getModalUnsavedRecord(root); + record.baseline = serializeModalState(root); + record.dirty = false; + updateUnsavedModalBeforeUnload(); +} + +function startModalPristineSync(root) { + if (!root || !hasTrackableModalState(root)) return; + const record = getModalUnsavedRecord(root); + record.userInteracted = false; + stopModalPristineSync(root); + syncModalBaseline(root); + record.pristineSyncTimer = window.setInterval(() => { + if (!isModalOpen(root)) { + stopModalPristineSync(root); + return; + } + if (record.userInteracted) { + stopModalPristineSync(root); + return; + } + record.baseline = serializeModalState(root); + record.dirty = false; + updateUnsavedModalBeforeUnload(); + }, 300); +} + +function resetModalUnsavedState(root) { + if (!root) return; + const record = getModalUnsavedRecord(root); + stopModalPristineSync(root); + record.baseline = ''; + record.dirty = false; + record.userInteracted = false; + updateUnsavedModalBeforeUnload(); +} + +function confirmDiscardModalChanges(root) { + if (!root || !hasTrackableModalState(root) || !isModalOpen(root)) return true; + if (!evaluateModalUnsavedState(root)) return true; + const ok = window.confirm(`${UNSAVED_MODAL_MESSAGE}\n\nInchizi fara sa salvezi?`); + if (ok) resetModalUnsavedState(root); + return ok; +} + +function evaluateModalUnsavedState(root) { + if (!root || !hasTrackableModalState(root)) return false; + const record = getModalUnsavedRecord(root); + const current = serializeModalState(root); + if (!record.baseline) { + record.baseline = current; + } + record.dirty = current !== record.baseline; + updateUnsavedModalBeforeUnload(); + return record.dirty; +} + +function handleModalUserInteraction(target) { + const root = target?.closest(TRACKED_MODAL_SELECTOR); + if (!root || !isModalOpen(root) || !hasTrackableModalState(root)) return; + const record = getModalUnsavedRecord(root); + record.userInteracted = true; + stopModalPristineSync(root); + window.setTimeout(() => { + if (isModalOpen(root)) evaluateModalUnsavedState(root); + }, 0); +} + +function observeTrackedModals() { + Array.from(document.querySelectorAll(TRACKED_MODAL_SELECTOR)).forEach(root => { + const record = getModalUnsavedRecord(root); + if (record.observer) return; + const observer = new MutationObserver(() => { + if (isModalOpen(root)) { + if (!record.userInteracted) startModalPristineSync(root); + } else { + resetModalUnsavedState(root); + } + }); + observer.observe(root, { + attributes: true, + attributeFilter: ['class', 'style', 'aria-hidden'], + childList: true, + subtree: true + }); + record.observer = observer; + if (isModalOpen(root)) startModalPristineSync(root); + }); +} + +document.addEventListener('input', (e) => handleModalUserInteraction(e.target), true); +document.addEventListener('change', (e) => handleModalUserInteraction(e.target), true); +document.addEventListener('click', (e) => { + const mutationTarget = e.target.closest(MODAL_MUTATION_CLICK_SELECTOR); + if (mutationTarget) handleModalUserInteraction(mutationTarget); +}, true); +observeTrackedModals(); + +function enforceDarkTheme() { + body.setAttribute('data-theme', 'dark'); + try { localStorage.setItem(THEME_KEY, 'dark'); } catch (e) { } + const savedThemeEl = document.getElementById('savedTheme'); + if (savedThemeEl) savedThemeEl.textContent = 'Dark'; + const themeDark = document.getElementById('themeDark'); + const themeLight = document.getElementById('themeLight'); + if (themeDark) themeDark.classList.add('active'); + if (themeLight) themeLight.classList.remove('active'); +} +enforceDarkTheme(); +function aclKey(email, server) { return `${ACL_PREFIX}${email}:${server}`; } +function getSavedPerms(email, server) { + try { const raw = localStorage.getItem(aclKey(email, server)); if (!raw) return null; const obj = JSON.parse(raw); if (obj && typeof obj === 'object') return obj; } catch (e) { } + return null; +} +function setSavedPerms(email, server, perms) { + try { localStorage.setItem(aclKey(email, server), JSON.stringify(perms || {})); } catch (e) { } +} +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; + 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'); + if (panel === 'servers') { + loadServers(); + } + if (panel === 'account') { + loadAccounts(); + } + if (panel === 'nodes') { + } + if (panel === 'templates') { + loadTemplates(); + } + if (panel === 'webhooks') { + if (typeof window._loadWebhooks === 'function') window._loadWebhooks(); + } + if (panel === 'panelinfo') { + loadPanelInfo(); + } +}); +function deleteAllClientCookies() { + const cookies = document.cookie.split("; "); + for (const cookie of cookies) { + const eqPos = cookie.indexOf("="); + const name = eqPos > -1 ? cookie.substr(0, eqPos) : cookie; + document.cookie = name + "=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/"; + } +} +document.getElementById("logoutBtn").addEventListener("click", async () => { + try { + deleteAllClientCookies(); + await fetch('/logout', { method: 'POST', credentials: 'include' }); + location.href = '/login'; + } catch (err) { + console.error(err); + alert('Failed to log out'); + } +}); +function goHome() { history.back(); } +closeEscFixed.addEventListener('click', goHome); +document.addEventListener('keydown', (e) => { if (e.key === 'Escape') goHome(); }); +const presets = [ + { id: 1, url: '/images/waves-digital.webp' }, + { id: 2, url: '/images/mountains.webp' }, + { id: 3, url: '/images/sunset.webp' }, + { id: 4, url: '/images/waves.png' } +]; +const thumbsEl = document.getElementById('thumbs'); +const bgPreview = document.getElementById('bgPreview'); +const colorPicker = document.getElementById('colorPicker'); +const hexInput = document.getElementById('hexInput'); +const colorDot = document.getElementById('colorDot'); +const applyColorBtn = document.getElementById('applyColorBtn'); +const bgHex = document.getElementById('bgHex'); +const uploadFile = document.getElementById('uploadFile'); +const urlInput = document.getElementById('urlInput'); +const useUrlBtn = document.getElementById('useUrlBtn'); +const densitySelect = document.getElementById('densitySelect'); +const animationsToggle = document.getElementById('animationsToggle'); +const accentPicker = document.getElementById('accentPicker'); +const savedBg = document.getElementById('savedBg'); +async function sendBackgroundToServer(obj) { + try { + const res = await fetch('/api/settings/background', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(obj) + }); + if (!res.ok) { + const err = await res.json().catch(() => ({ error: 'failed' })); + console.warn("Server returned error:", err); + } else { + console.log("Background updated on server"); + } + } catch (e) { + console.error("Failed to send background to server", e); + } +} +presets.forEach(p => { + const el = document.createElement('div'); + el.className = 'thumb'; + el.dataset.url = p.url; + el.innerHTML = `preset-${p.id}`; + el.addEventListener('click', () => selectThumb(el)); + thumbsEl.appendChild(el); +}); +function selectThumb(el) { + 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); +} +function setColor(hex) { + colorPicker.value = hex; + hexInput.value = hex; + colorDot.style.background = hex; + + hexInput.style.backgroundColor = hex; + const r = parseInt(hex.slice(1, 3), 16); + const g = parseInt(hex.slice(3, 5), 16); + const b = parseInt(hex.slice(5, 7), 16); + const brightness = (r * 299 + g * 587 + b * 114) / 1000; + hexInput.style.color = brightness > 128 ? '#000' : '#fff'; + hexInput.style.border = '1px solid rgba(0,0,0,0.1)'; + + bgPreview.style.backgroundImage = 'none'; + bgPreview.style.backgroundColor = hex; + bgHex.textContent = hex; + const obj = { type: 'color', value: hex }; + localStorage.setItem(BG_KEY, JSON.stringify(obj)); + updateSavedBgText(); + sendBackgroundToServer(obj); +} + + +if (colorDot && colorPicker) { + colorDot.addEventListener('click', () => { + colorPicker.click(); + }); +} + +if (hexInput && colorPicker) { + hexInput.addEventListener('click', () => { + colorPicker.click(); + }); + hexInput.style.cursor = 'pointer'; +} +const bgSaved = localStorage.getItem(BG_KEY); +if (bgSaved) { + 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; + } + } catch (e) { + console.warn('invalid bg saved'); + } +} 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' } +} +updateSavedBgText(); +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'); }); +const uploadBtn = document.getElementById('uploadBtn'); +if (uploadBtn && uploadFile) { + uploadBtn.addEventListener('click', () => uploadFile.click()); +} +uploadFile.addEventListener('change', async (e) => { + const file = e.target.files[0]; + if (!file) return; + const reader = new FileReader(); + 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 }); + }; + reader.readAsDataURL(file); +}); +useUrlBtn.addEventListener('click', async () => { + const url = urlInput.value.trim(); + 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); +}); + +if (colorDot && colorPicker) { + colorDot.addEventListener('click', () => { + colorPicker.click(); + }); +} + +const initDensity = localStorage.getItem(DENSITY_KEY) || 'comfortable'; +function applyDensity(d) { if (d === 'compact') body.classList.add('compact'); else body.classList.remove('compact'); const densityEl = document.getElementById('densitySelect'); if (densityEl) densityEl.value = d; } +applyDensity(initDensity); +const densitySelectEl = document.getElementById('densitySelect'); +if (densitySelectEl) densitySelectEl.addEventListener('change', (e) => { localStorage.setItem(DENSITY_KEY, e.target.value); applyDensity(e.target.value); }); +const initAnim = localStorage.getItem(ANIM_KEY); +const animationsToggleEl = document.getElementById('animationsToggle'); +if (animationsToggleEl) { + animationsToggleEl.checked = initAnim === null ? true : initAnim === 'true'; + function applyAnimations(enabled) { if (!enabled) body.classList.add('no-animations'); else body.classList.remove('no-animations'); } + applyAnimations(animationsToggleEl.checked); + animationsToggleEl.addEventListener('change', (e) => { localStorage.setItem(ANIM_KEY, e.target.checked); applyAnimations(e.target.checked); }); +} +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'); }); +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(); }); + +document.querySelectorAll('.password-toggle').forEach(btn => { + if (btn.dataset.listenerAdded) return; + btn.dataset.listenerAdded = 'true'; + btn.addEventListener('click', (e) => { + e.preventDefault(); + e.stopPropagation(); + const targetId = btn.dataset.target; + const input = targetId + ? document.getElementById(targetId) + : btn.parentElement?.querySelector('input'); + if (!input) return; + const icon = btn.querySelector('i'); + if (input.type === 'password') { + input.type = 'text'; + if (icon) icon.classList.replace('fa-eye', 'fa-eye-slash'); + btn.setAttribute('aria-label', 'Hide password'); + } else { + input.type = 'password'; + if (icon) icon.classList.replace('fa-eye-slash', 'fa-eye'); + btn.setAttribute('aria-label', 'Show password'); + } + }); +}); + +const newPasswordInput = document.getElementById('modalNew'); +const strengthIndicator = document.getElementById('passwordStrength'); +if (newPasswordInput && strengthIndicator) { + newPasswordInput.addEventListener('input', (e) => { + const val = e.target.value; + let strength = 'weak'; + if (val.length >= 12 && /[A-Z]/.test(val) && /[0-9]/.test(val) && /[^A-Za-z0-9]/.test(val)) { + strength = 'strong'; + } else if (val.length >= 10 && /[A-Z]/.test(val) && /[0-9]/.test(val)) { + strength = 'good'; + } else if (val.length >= 8) { + strength = 'fair'; + } + strengthIndicator.innerHTML = val ? `
    ` : ''; + }); +} + +modalSave.addEventListener('click', async () => { + const cur = document.getElementById('modalCurrent').value; + const nw = document.getElementById('modalNew').value; + const cf = document.getElementById('modalConfirm').value; + const twoFactorCode = document.getElementById('modalTwoFactor')?.value || ''; + const feedbackEl = document.getElementById('changePasswordFeedback'); + + const showFeedback = (msg, isError = false) => { + if (feedbackEl) { + feedbackEl.textContent = msg; + feedbackEl.className = 'node-feedback' + (isError ? ' error' : ' success'); + feedbackEl.style.display = msg ? 'block' : 'none'; + } + }; + + if (!cur || !nw || !cf) { + showFeedback('Please fill all fields', true); + return; + } + if (nw.length < 8) { + showFeedback('New password must be at least 8 characters', true); + return; + } + if (nw !== cf) { + showFeedback('Passwords do not match', true); + return; + } + + try { + modalSave.disabled = true; + modalSave.innerHTML = ' Updating...'; + + 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 }) + }); + const data = await res.json().catch(() => ({ error: 'Invalid server response' })); + + if (!res.ok) { + if (data.requires2FA) { + const twoFactorField = document.getElementById('twoFactorField'); + if (twoFactorField) twoFactorField.style.display = 'block'; + showFeedback('Please enter your 2FA code', true); + document.getElementById('modalTwoFactor')?.focus(); + } else { + showFeedback(data.error || 'Failed to change password', true); + } + return; + } + + showFeedback('Password changed successfully!', false); + + setTimeout(() => { + document.getElementById('modalCurrent').value = ''; + 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'; + modalOverlay.classList.remove('show'); changeModal.classList.remove('show'); + window.location.reload(); + }, 1500); + } catch (err) { + console.error(err); + showFeedback('Network error', true); + } finally { + modalSave.disabled = false; + modalSave.innerHTML = ' Update Password'; + } +}); +async function loadServers(page, search) { + if (typeof page === 'undefined') page = _serversPage; + if (typeof search === 'undefined') search = _serversSearch; + _serversPage = page; + _serversSearch = search; + const isFirstLoad = !serversListEl.querySelector('.server-row'); + if (isFirstLoad) { + serversListEl.innerHTML = `
    Loading…
    `; + } + 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()); + if (!res.ok) { + const err = await res.json().catch(() => ({ error: 'failed' })); + serversListEl.innerHTML = `
    Failed to load servers
    `; + console.warn(err); + return; + } + const data = await res.json(); + const items = Array.isArray(data.items) + ? data.items + : (Array.isArray(data.names) ? data.names.map(n => ({ name: n, isLocal: true, nodeId: null })) : []); + const total = Number(data.total || items.length); + const totalPages = Number(data.totalPages || 1); + renderServers(items); + renderServersPagination(page, totalPages, total); + } catch (e) { + console.error(e); + serversListEl.innerHTML = `
    Network error
    `; + } +} +function shortId(id) { + const s = String(id || ''); + return s.length > 8 ? s.slice(0, 8) : s || '—'; +} +function renderServers(list) { + if (!Array.isArray(list) || list.length === 0) { + serversListEl.innerHTML = `
    No servers found.
    `; + return; + } + serversListEl.innerHTML = ''; + list.forEach(item => { + const name = item.name || String(item); + 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 row = document.createElement('div'); + row.className = 'server-row clickable-card'; + row.dataset.name = name; + row.dataset.template = item?.template || ''; + row.dataset.nodeId = item?.nodeId ? String(item.nodeId) : ''; + row.innerHTML = ` +
    +
    +
    +
    ${escapeHtml(visibleName)}
    +
    + ${escapeHtml(chipText)} + Template: ${escapeHtml(templateLabel)} +
    +
    + + + + + +
    + `; + serversListEl.appendChild(row); + }); +} +function renderServersPagination(currentPage, totalPages, total) { + const el = document.getElementById('serversPagination'); + if (!el) return; + if (totalPages <= 1) { el.innerHTML = ''; return; } + const startItem = (currentPage - 1) * _serversLimit + 1; + const endItem = Math.min(currentPage * _serversLimit, total); + el.innerHTML = ` +
    + ${startItem}–${endItem} of ${total} servers +
    + + Page ${currentPage} / ${totalPages} + +
    +
    + `; + el.querySelectorAll('button[data-servers-page]').forEach(btn => { + btn.addEventListener('click', () => { + const p = parseInt(btn.dataset.serversPage, 10); + if (p >= 1 && p <= totalPages) loadServers(p); + }); + }); +} +function escapeHtml(s) { + return String(s).replace(/[&<>"']/g, function (m) { return ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[m]); }); +} + +const PANEL_EWS_ICON_SIZE = "1.6rem"; + +function isPanelEwsIcon(iconClass) { + return String(iconClass || "").split(/\s+/).includes("fa-panel-ews"); +} + +function ensurePanelEwsSvgStyles() { + if (document.getElementById("panel-ews-settings-styles")) return; + const style = document.createElement("style"); + style.id = "panel-ews-settings-styles"; + style.textContent = ` + .panel-ews-svg { + width: ${PANEL_EWS_ICON_SIZE}; + height: ${PANEL_EWS_ICON_SIZE}; + display: block; + flex: 0 0 auto; + transition: transform 180ms ease; + } + + .quick-action-item-icon .panel-ews-svg, + .quick-action-preview-card .panel-ews-svg, + .icon-preview .panel-ews-svg { + margin: 0 auto; + } + + .quick-action-preview-card.qa-anim-rotate:hover .panel-ews-svg { + transform: rotate(180deg); + } + `; + document.head.appendChild(style); +} + +function createPanelEwsSvg() { + const template = document.createElement("template"); + template.innerHTML = ` + + `.trim(); + return template.content.firstElementChild; +} + +function replaceLegacyPanelEwsIcons(root = document) { + ensurePanelEwsSvgStyles(); + root.querySelectorAll("i.fa-panel-ews").forEach((icon) => { + icon.replaceWith(createPanelEwsSvg()); + }); +} +const templateNameMap = new Map(); +const templatePickerState = { selected: '', selectedNorm: '', server: '', originalTemplate: '' }; +registerModalCustomStateReader('serverTemplateOverlay', () => ({ + server: templatePickerState.server || '', + selected: normalizeTemplateIdClient(templatePickerState.selected || ''), + original: templatePickerState.originalTemplate || '' +})); +function normalizeTemplateIdClient(tpl) { + const raw = (tpl || '').toString().trim().toLowerCase(); + if (!raw) return ''; + if (["discord-bot", "discord", "discord bot", "bot"].includes(raw)) return "discord-bot"; + if (["node", "nodejs", "node.js"].includes(raw)) return "nodejs"; + if (["python", "py"].includes(raw)) return "python"; + if (["mc", "minecraft"].includes(raw)) return "minecraft"; + return raw; +} +function updateTemplateNameMap(list) { + templateNameMap.clear(); + (Array.isArray(list) ? list : []).forEach(tpl => { + const norm = normalizeTemplateIdClient(tpl?.id); + if (norm) templateNameMap.set(norm, tpl?.name || tpl?.id || norm); + }); +} +function displayTemplateName(id) { + const norm = normalizeTemplateIdClient(id); + if (!norm) return 'No template'; + return templateNameMap.get(norm) || (id ? String(id) : norm); +} +function findServerRowByName(name) { + return Array.from(serversListEl.children || []).find(r => r.dataset && r.dataset.name === name) || null; +} +async function loadTemplates(page, search) { + if (!templatesListEl) return; + if (typeof page === 'undefined') page = _templatesPage; + if (typeof search === 'undefined') search = _templatesSearch; + _templatesPage = page; + _templatesSearch = search; + if (templatesFeedbackEl) templatesFeedbackEl.textContent = ''; + const isFirstLoad = !templatesListEl.querySelector('.template-card'); + if (isFirstLoad) { + templatesListEl.innerHTML = `
    Loading templates…
    `; + } + try { + const params = new URLSearchParams({ page: String(page), limit: String(_templatesLimit) }); + if (search) params.set('search', search); + const res = await fetch('/api/settings/templates?' + params.toString()); + if (!res.ok) { + const err = await res.json().catch(() => ({ error: 'failed' })); + templatesListEl.innerHTML = `
    Failed to load templates
    `; + if (templatesFeedbackEl) templatesFeedbackEl.textContent = err.error || 'Unable to load templates.'; + console.warn(err); + return; + } + const data = await res.json(); + const templates = Array.isArray(data.templates) ? data.templates : []; + const total = Number(data.total || templates.length); + const totalPages = Number(data.totalPages || 1); + updateTemplateNameMap(templates); + renderTemplates(templates); + renderTemplatesPagination(page, totalPages, total); + } catch (e) { + console.error(e); + templatesListEl.innerHTML = `
    Network error
    `; + } +} +function renderTemplates(list) { + if (!templatesListEl) return; + templateExportMap.clear(); + if (!Array.isArray(list) || list.length === 0) { + templatesListEl.innerHTML = `
    No templates found. Create one to get started.
    `; + return; + } + templatesListEl.innerHTML = ''; + list.forEach(tpl => { + const normalizedTemplateId = normalizeTemplateIdClient(tpl?.id); + if (normalizedTemplateId) { + templateExportMap.set(normalizedTemplateId, tpl); + } + + const encodedTemplateId = encodeURIComponent(tpl.id || ''); + const encodedTemplateName = encodeURIComponent(tpl.name || tpl.id || ''); + + const row = document.createElement('div'); + row.className = 'template-card clickable-card'; + row.innerHTML = ` +
    +
    +
    +
    +
    ${escapeHtml(tpl.name || tpl.id)}
    + ID: ${escapeHtml(tpl.id || '—')} +
    +
    ${escapeHtml(tpl.description || 'No description')}
    +
    + ${escapeHtml((tpl.docker && tpl.docker.image) ? tpl.docker.image : 'Custom image')} + ${escapeHtml((tpl.docker && tpl.docker.tag) ? tpl.docker.tag : 'latest')} +
    +
    +
    + + + +
    +
    + `; + templatesListEl.appendChild(row); + }); +} +function renderTemplatesPagination(currentPage, totalPages, total) { + const el = document.getElementById('templatesPagination'); + if (!el) return; + if (totalPages <= 1) { el.innerHTML = ''; return; } + const startItem = (currentPage - 1) * _templatesLimit + 1; + const endItem = Math.min(currentPage * _templatesLimit, total); + el.innerHTML = ` +
    + ${startItem}–${endItem} of ${total} templates +
    + + Page ${currentPage} / ${totalPages} + +
    +
    + `; + el.querySelectorAll('button[data-tpl-page]').forEach(btn => { + btn.addEventListener('click', () => { + const p = parseInt(btn.dataset.tplPage, 10); + if (p >= 1 && p <= totalPages) loadTemplates(p); + }); + }); +} +function openTemplateModal() { + createTemplateOverlay.classList.add('show'); + createTemplateModal.classList.add('show'); + createTemplateFeedback.textContent = ''; +} +function closeTemplateModal() { + createTemplateOverlay.classList.remove('show'); + createTemplateModal.classList.remove('show'); + createTemplateFeedback.textContent = ''; + if (templateEditorState.mode === 'edit') setTemplateModalMode('create'); +} + +function setTemplateModalMode(mode, template = null) { + const nextMode = mode === 'edit' ? 'edit' : 'create'; + templateEditorState.mode = nextMode; + templateEditorState.editTemplateId = nextMode === 'edit' ? String(template?.id || '').trim() : ''; + + if (createTemplateModal) createTemplateModal.dataset.mode = nextMode; + + if (nextMode === 'edit') { + if (createTemplateModalTitle) createTemplateModalTitle.textContent = 'Edit Template'; + if (createTemplateModalSubtitle) createTemplateModalSubtitle.textContent = 'Update this template and save your changes.'; + if (createTemplateSave) createTemplateSave.innerHTML = ' Save Template'; + if (ct_id) { + ct_id.readOnly = true; + ct_id.title = 'Template ID cannot be changed after creation.'; + } + return; + } + + if (createTemplateModalTitle) createTemplateModalTitle.textContent = 'New Template'; + if (createTemplateModalSubtitle) createTemplateModalSubtitle.textContent = 'Set up a reusable Docker template.'; + if (createTemplateSave) createTemplateSave.innerHTML = ' Create Template'; + if (ct_id) { + ct_id.readOnly = false; + ct_id.title = ''; + } +} + +function clearTemplateForm() { + if (ct_name) ct_name.value = ''; + if (ct_id) ct_id.value = ''; + if (ct_description) ct_description.value = ''; + if (ct_template_image) ct_template_image.value = ''; + if (ct_default_port) ct_default_port.value = ''; + if (ct_image) ct_image.value = ''; + if (ct_tag) ct_tag.value = 'latest'; + 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 = ''; + populateTemplateInstallForm(null); + if (ct_import_json) ct_import_json.value = ''; +} + +function populateTemplateForm(template) { + if (!template || typeof template !== 'object') return; + if (ct_name) ct_name.value = String(template.name || template.id || '').trim(); + if (ct_id) ct_id.value = String(template.id || '').trim(); + if (ct_description) ct_description.value = String(template.description || '').trim(); + if (ct_template_image) ct_template_image.value = String(template.templateImage || template.template_image || '').trim(); + 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(); + 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) + ? template.docker.env + : {}; + 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 = ''; +} + +function findTemplateForEditor(templateId) { + const normalizedId = normalizeTemplateIdClient(templateId); + if (!normalizedId) return null; + return templateExportMap.get(normalizedId) || null; +} + +function openTemplateEditModal(templateId) { + const selected = findTemplateForEditor(templateId); + if (!selected) { + if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Template data not available for editing. Please refresh the list.'; + return; + } + + populateTemplateForm(selected); + setTemplateModalMode('edit', selected); + if (createTemplateFeedback) createTemplateFeedback.textContent = ''; + openTemplateModal(); +} + +function sanitizeTemplateWorkdirInput(value) { + let workdir = String(value || '').trim(); + if (!workdir) return ''; + workdir = workdir.replace(/\\/g, '/').replace(/\/+/g, '/'); + if (workdir.length > 1) workdir = workdir.replace(/\/+$/, ''); + return workdir; +} + +function validateTemplateWorkdirInput(value) { + const workdir = sanitizeTemplateWorkdirInput(value); + if (!workdir) return ''; + if (!workdir.startsWith('/')) return 'Workdir must be an absolute Linux path (example: /app).'; + if (workdir.includes('..')) return 'Workdir must not include path traversal segments.'; + if (!/^\/[A-Za-z0-9._\-/]+$/.test(workdir)) { + return 'Workdir may only include letters, numbers, "/", ".", "_" and "-".'; + } + return ''; +} + +function parseTemplateEnvJsonInput(value) { + const raw = String(value || '').trim(); + if (!raw) return {}; + const parsed = JSON.parse(raw); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error('Environment JSON must be an object.'); + } + const out = {}; + Object.entries(parsed).forEach(([key, val]) => { + const envKey = String(key || '').trim(); + if (envKey) out[envKey] = String(val ?? ''); + }); + return out; +} + +function parseTemplateDefaultPort(value) { + const raw = String(value || '').trim(); + if (!raw) return null; + const port = Number.parseInt(raw, 10); + if (!Number.isInteger(port) || port < 1 || port > 65535) { + throw new Error('Default port must be between 1 and 65535.'); + } + return port; +} + +function slugifyTemplateId(value) { + return String(value || 'custom') + .trim() + .toLowerCase() + .replace(/[^a-z0-9_-]+/g, '-') + .replace(/^-+|-+$/g, '') + .slice(0, 60) || 'custom'; +} + +function splitDockerImageAndTag(ref) { + const raw = String(ref || '').trim(); + if (!raw) return { image: '', tag: 'latest' }; + const slash = raw.lastIndexOf('/'); + const colon = raw.lastIndexOf(':'); + if (colon > slash) { + return { image: raw.slice(0, colon), tag: raw.slice(colon + 1) || 'latest' }; + } + return { image: raw, tag: 'latest' }; +} + +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); + if (mountError) throw new Error(`Install mount path: ${mountError}`); + const runtimeError = validateTemplateWorkdirInput(install.runtimePath); + if (runtimeError) throw new Error(`Runtime mount path: ${runtimeError}`); + + return install; +} + +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(); +} + +function adpanelEggToTemplatePayload(payload) { + const dockerImages = payload.docker_images && typeof payload.docker_images === 'object' && !Array.isArray(payload.docker_images) + ? Object.values(payload.docker_images).filter(Boolean) + : []; + const dockerRef = String(dockerImages[0] || payload.docker_image || '').trim(); + const { image, tag } = splitDockerImageAndTag(dockerRef); + const installation = payload.scripts && payload.scripts.installation && typeof payload.scripts.installation === 'object' + ? payload.scripts.installation + : null; + + const env = {}; + (Array.isArray(payload.variables) ? payload.variables : []).forEach(variable => { + const key = String(variable?.env_variable || '').trim(); + if (!key) return; + env[key] = String(variable?.default_value ?? ''); + }); + + const startup = String(payload.startup || '').trim(); + if (startup) env.STARTUP = startup; + + const portCandidate = Number.parseInt(env.SERVER_PORT || env.PORT || env.SRCDS_PORT || '', 10); + const defaultPort = Number.isInteger(portCandidate) && portCandidate > 0 && portCandidate <= 65535 + ? portCandidate + : (startup.includes('27015') || env.SRCDS_APPID ? 27015 : 8080); + + return { + template_name: String(payload.name || '').trim(), + template_id: slugifyTemplateId(payload.name || payload.id || 'custom-template'), + description: String(payload.description || '').trim(), + docker_image: image, + docker_tag: tag, + startup: '', + adpanelStartup: 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, + }; +} + +function applyTemplateJsonImport(payload) { + if (!payload || typeof payload !== 'object' || Array.isArray(payload)) { + throw new Error('Invalid JSON format.'); + } + + if (payload.meta?.version || payload.scripts?.installation || payload.docker_images) { + payload = adpanelEggToTemplatePayload(payload); + } + + const requiredKeys = [ + 'template_name', + 'template_id', + 'docker_image' + ]; + + for (const key of requiredKeys) { + if (!Object.prototype.hasOwnProperty.call(payload, key)) { + throw new Error(`Missing required field in JSON: ${key}`); + } + } + + const templateName = String(payload.template_name || '').trim(); + const templateId = String(payload.template_id || '').trim(); + 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( + payload.adpanelStartup || + payload.adpanel_startup || + payload.pterodactylStartup || + payload.pterodactyl_startup || + '' + ).trim(); + const templateImage = String(payload.image || '').trim(); + const workdir = sanitizeTemplateWorkdirInput(payload.workdir); + const defaultPort = payload.defaultPort || payload.default_port || ''; + const env = payload.env && typeof payload.env === 'object' && !Array.isArray(payload.env) ? payload.env : {}; + const install = payload.install || payload.installation || null; + + if (!templateName || !templateId || !dockerImage) { + throw new Error('JSON must include non-empty template_name, template_id and docker_image.'); + } + + const startupCommandError = validateRuntimeProcessCommandInput(startup); + if (startupCommandError) { + throw new Error(startupCommandError); + } + const workdirError = validateTemplateWorkdirInput(workdir); + if (workdirError) { + throw new Error(workdirError); + } + + if (ct_name) ct_name.value = templateName; + if (ct_id) { + if (templateEditorState.mode === 'edit' && templateEditorState.editTemplateId) { + ct_id.value = templateEditorState.editTemplateId; + } else { + ct_id.value = templateId; + } + } + if (ct_description) ct_description.value = description; + 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; + 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) : ''; + if (ct_env_json) ct_env_json.value = Object.keys(env).length ? JSON.stringify(env, null, 2) : ''; + populateTemplateInstallForm(install); +} + +[createTemplateCancel, createTemplateClose, createTemplateOverlay].forEach(el => { + if (!el) return; + el.addEventListener('click', (e) => { + if (e.target === el || el === createTemplateCancel || el === createTemplateClose) { + closeTemplateModal(); + } + }); +}); +if (openCreateTemplateBtn) { + openCreateTemplateBtn.addEventListener('click', () => { + setTemplateModalMode('create'); + clearTemplateForm(); + openTemplateModal(); + }); +} + +if (createTemplateImportBtn && ct_import_json) { + createTemplateImportBtn.addEventListener('click', () => { + ct_import_json.click(); + }); + + ct_import_json.addEventListener('change', async () => { + const file = ct_import_json.files && ct_import_json.files[0] ? ct_import_json.files[0] : null; + if (!file) return; + + try { + if (!String(file.name || '').toLowerCase().endsWith('.json')) { + throw new Error('Only .json files are accepted.'); + } + const raw = await file.text(); + const parsed = JSON.parse(raw); + applyTemplateJsonImport(parsed); + const actionWord = templateEditorState.mode === 'edit' ? 'Save' : 'Create'; + createTemplateFeedback.textContent = `Template JSON imported successfully. Review and click ${actionWord}.`; + } catch (err) { + createTemplateFeedback.textContent = err?.message || 'Invalid template JSON.'; + } finally { + ct_import_json.value = ''; + } + }); +} + +if (createTemplateSave) { + createTemplateSave.addEventListener('click', async () => { + const isEditMode = templateEditorState.mode === 'edit'; + const id = (ct_id.value || '').trim(); + const name = (ct_name.value || '').trim(); + const description = (ct_description.value || '').trim(); + const templateImage = (ct_template_image.value || '').trim(); + const defaultPortInput = ct_default_port?.value || ''; + const image = (ct_image.value || '').trim(); + const tag = (ct_tag.value || '').trim(); + const startupCommand = (ct_startup_command?.value || '').trim(); + const workdirInput = ct_workdir?.value || ''; + const workdir = sanitizeTemplateWorkdirInput(workdirInput); + const adpanelStartup = String(ct_adpanel_startup?.value || '').trim(); + let defaultPort = null; + let env = {}; + let install = null; + + if (isEditMode && !templateEditorState.editTemplateId) { + createTemplateFeedback.textContent = 'Missing template reference for edit mode. Reopen the edit popup.'; + return; + } + + if (!name || !id || !image) { + createTemplateFeedback.textContent = 'Please fill out name, id and docker image.'; + return; + } + + const startupCommandError = validateRuntimeProcessCommandInput(startupCommand); + if (startupCommandError) { + createTemplateFeedback.textContent = startupCommandError; + return; + } + + const workdirError = validateTemplateWorkdirInput(workdirInput); + if (workdirError) { + createTemplateFeedback.textContent = workdirError; + return; + } + + try { + defaultPort = parseTemplateDefaultPort(defaultPortInput); + env = parseTemplateEnvJsonInput(ct_env_json?.value || ''); + install = buildTemplateInstallFromForm(); + } catch (err) { + createTemplateFeedback.textContent = err?.message || 'Invalid template advanced settings.'; + return; + } + + try { + createTemplateSave.disabled = true; + createTemplateFeedback.textContent = isEditMode ? 'Updating template…' : 'Saving template…'; + const endpoint = isEditMode + ? `/api/settings/templates/${encodeURIComponent(templateEditorState.editTemplateId)}` + : '/api/settings/templates'; + const method = isEditMode ? 'PUT' : 'POST'; + const res = await fetch(endpoint, { + method, + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + id, + name, + description, + dockerImage: image, + dockerTag: tag, + templateImage, + defaultPort, + command: startupCommand, + dockerWorkdir: workdir, + env, + adpanelStartup, + install, + }) + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + if (!res.ok) { + createTemplateFeedback.textContent = data.error || 'Failed to save template'; + createTemplateSave.disabled = false; + return; + } + createTemplateFeedback.textContent = isEditMode ? 'Template updated!' : 'Template created!'; + setTimeout(() => { + closeTemplateModal(); + setTemplateModalMode('create'); + }, 400); + loadTemplates(_templatesPage, _templatesSearch); + } catch (e) { + console.error(e); + createTemplateFeedback.textContent = 'Network error while saving template'; + } finally { + createTemplateSave.disabled = false; + } + }); +} +async function deleteTemplate(templateId, templateName, btn) { + if (!templateId) return; + if (!confirm(`Delete template "${templateName || templateId}"? It cannot be undone.`)) return; + try { + if (btn) { + btn.disabled = true; + btn.innerHTML = ''; + } + const res = await fetch(`/api/settings/templates/${encodeURIComponent(templateId)}`, { method: 'DELETE' }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + const serversMsg = Array.isArray(data.servers) && data.servers.length ? ` In use by: ${data.servers.join(', ')}` : ''; + if (templatesFeedbackEl) templatesFeedbackEl.textContent = (data.error || 'Failed to delete template.') + serversMsg; + return; + } + if (templatesFeedbackEl) templatesFeedbackEl.textContent = `Template "${templateName || templateId}" deleted.`; + loadTemplates(); + } catch (err) { + console.error(err); + if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Network error while deleting template.'; + } finally { + if (btn) { + btn.disabled = false; + btn.innerHTML = ''; + } + } +} + +function sanitizeExportFilenamePart(value) { + const raw = String(value || '').trim().toLowerCase(); + const sanitized = raw.replace(/[^a-z0-9._-]+/g, '-').replace(/^-+|-+$/g, ''); + return sanitized || 'template'; +} + +function getTemplateExportFilename(templateId, templateName) { + const basename = sanitizeExportFilenamePart(templateId || templateName || 'template'); + return `${basename}.json`; +} + +function cloneTemplateForExport(template) { + if (!template || typeof template !== 'object') return null; + try { + return JSON.parse(JSON.stringify(template)); + } catch { + return { ...template }; + } +} + +function triggerJsonDownload(filename, content) { + const blob = new Blob([content], { type: 'application/json;charset=utf-8' }); + const url = URL.createObjectURL(blob); + const anchor = document.createElement('a'); + anchor.href = url; + anchor.download = filename; + document.body.appendChild(anchor); + anchor.click(); + anchor.remove(); + URL.revokeObjectURL(url); +} + +function exportTemplate(templateId, templateName, btn) { + const normalizedId = normalizeTemplateIdClient(templateId); + if (!normalizedId) { + if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Invalid template id for export.'; + return; + } + + const selected = templateExportMap.get(normalizedId); + const template = cloneTemplateForExport(selected); + if (!template) { + if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Template data not available for export.'; + return; + } + + const originalHtml = btn ? btn.innerHTML : ''; + try { + if (btn) { + btn.disabled = true; + btn.innerHTML = ''; + } + const payload = [template]; + const filename = getTemplateExportFilename(templateId, templateName); + const jsonContent = `${JSON.stringify(payload, null, 2)}\n`; + triggerJsonDownload(filename, jsonContent); + if (templatesFeedbackEl) { + templatesFeedbackEl.textContent = `Template "${templateName || templateId}" exported successfully.`; + } + } catch (err) { + console.error(err); + if (templatesFeedbackEl) templatesFeedbackEl.textContent = 'Failed to export template JSON.'; + } finally { + if (btn) { + btn.disabled = false; + btn.innerHTML = originalHtml || ''; + } + } +} + +if (templatesListEl) { + templatesListEl.addEventListener('click', (e) => { + const editBtn = e.target.closest('.edit-template'); + if (editBtn) { + const id = decodeURIComponent(editBtn.dataset.id || ''); + openTemplateEditModal(id); + return; + } + + const exportBtn = e.target.closest('.export-template'); + if (exportBtn) { + const id = decodeURIComponent(exportBtn.dataset.id || ''); + const name = decodeURIComponent(exportBtn.dataset.name || '') || id; + exportTemplate(id, name, exportBtn); + return; + } + + const btn = e.target.closest('.delete-template'); + if (!btn) return; + const id = decodeURIComponent(btn.dataset.id || ''); + const name = decodeURIComponent(btn.dataset.name || '') || id; + deleteTemplate(id, name, btn); + }); +} +function closeServerTemplateModal() { + if (serverTemplateOverlay) serverTemplateOverlay.classList.remove('show'); + if (serverTemplateModal) serverTemplateModal.classList.remove('show'); + templatePickerState.selected = ''; + templatePickerState.selectedNorm = ''; + templatePickerState.server = ''; + templatePickerState.originalTemplate = ''; + if (serverTemplateModal) { + serverTemplateModal.dataset.server = ''; + serverTemplateModal.dataset.selected = ''; + } + if (serverTemplateList) serverTemplateList.innerHTML = ''; + if (serverTemplateFeedback) serverTemplateFeedback.textContent = ''; +} +function selectServerTemplate(id) { + const normalized = normalizeTemplateIdClient(id); + if (!normalized) return; + templatePickerState.selected = id; + templatePickerState.selectedNorm = normalized; + if (serverTemplateModal) serverTemplateModal.dataset.selected = id; + Array.from(serverTemplateList.querySelectorAll('.template-option-card')).forEach(card => { + const normCard = normalizeTemplateIdClient(card.dataset.id); + card.classList.toggle('active', normCard === normalized); + }); +} +function renderServerTemplateOptions(list, currentTemplate) { + if (!serverTemplateList) return; + const seen = new Set(); + const unique = []; + (Array.isArray(list) ? list : []).forEach(tpl => { + const norm = normalizeTemplateIdClient(tpl?.id); + if (!norm || seen.has(norm)) return; + seen.add(norm); + const canonicalId = tpl?.id || norm; + unique.push({ ...tpl, _norm: norm, _id: canonicalId }); + }); + if (unique.length === 0) { + serverTemplateList.innerHTML = `
    No templates available.
    `; + return; + } + serverTemplateList.innerHTML = ''; + unique.forEach(tpl => { + const card = document.createElement('div'); + card.className = 'template-option-card'; + card.dataset.id = tpl._id; + + const templateImage = tpl.template_image || tpl.templateImage || ''; + if (templateImage) { + card.style.setProperty('--template-bg', `url(${templateImage})`); + card.innerHTML = ` +
    +
    +
    ${escapeHtml(tpl.name || tpl.id)}
    +
    ${escapeHtml(tpl.description || 'No description')}
    +
    ${escapeHtml((tpl.docker && tpl.docker.image) ? tpl.docker.image : 'Custom image')}
    +
    + `; + card.style.cssText = `--bg-image: url('${templateImage.replace(/'/g, "\\'")}')`; + } else { + card.innerHTML = ` +
    +
    +
    ${escapeHtml(tpl.name || tpl.id)}
    +
    ${escapeHtml(tpl.description || 'No description')}
    +
    ${escapeHtml((tpl.docker && tpl.docker.image) ? tpl.docker.image : 'Custom image')}
    +
    + `; + } + + if (tpl._norm === normalizeTemplateIdClient(currentTemplate || templatePickerState.selected)) { + card.classList.add('active'); + templatePickerState.selected = tpl._id; + templatePickerState.selectedNorm = tpl._norm; + if (serverTemplateModal) serverTemplateModal.dataset.selected = tpl._id; + } + serverTemplateList.appendChild(card); + }); + if (!templatePickerState.selected && unique[0]) { + selectServerTemplate(unique[0]._id); + } +} +async function openServerTemplateModal(serverName, currentTemplate) { + if (!serverTemplateOverlay || !serverTemplateModal) return; + templatePickerState.server = serverName; + templatePickerState.selected = currentTemplate; + templatePickerState.selectedNorm = normalizeTemplateIdClient(currentTemplate); + templatePickerState.originalTemplate = normalizeTemplateIdClient(currentTemplate); + serverTemplateModal.dataset.server = serverName; + serverTemplateModal.dataset.selected = templatePickerState.selected || ''; + serverTemplateTitle.textContent = `Change template for ${serverName}`; + serverTemplateSubtitle.textContent = currentTemplate + ? `Current template: ${displayTemplateName(currentTemplate)}` + : 'Select a template to apply to this server.'; + serverTemplateOverlay.classList.add('show'); + serverTemplateModal.classList.add('show'); + if (serverTemplateList) serverTemplateList.innerHTML = `
    Loading templates…
    `; + if (serverTemplateFeedback) serverTemplateFeedback.textContent = ''; + try { + const res = await fetch('/api/settings/templates'); + const data = await res.json().catch(() => ({ templates: [] })); + if (!res.ok) { + if (serverTemplateFeedback) serverTemplateFeedback.textContent = data.error || 'Failed to load templates.'; + return; + } + const templates = Array.isArray(data.templates) ? data.templates : []; + updateTemplateNameMap(templates); + renderServerTemplateOptions(templates, currentTemplate); + } catch (err) { + console.error(err); + if (serverTemplateFeedback) serverTemplateFeedback.textContent = 'Network error while loading templates.'; + } +} +if (serverTemplateList) { + serverTemplateList.addEventListener('click', (e) => { + const card = e.target.closest('.template-option-card'); + if (!card) return; + selectServerTemplate(card.dataset.id); + }); +} +if (serverTemplateCancel) { + serverTemplateCancel.addEventListener('click', closeServerTemplateModal); +} +if (serverTemplateClose) { + serverTemplateClose.addEventListener('click', closeServerTemplateModal); +} +if (serverTemplateOverlay) { + // Click outside disabled — user must use close/cancel button +} +if (serverTemplateDone) { + serverTemplateDone.addEventListener('click', async () => { + const server = serverTemplateModal?.dataset?.server || ''; + const selected = templatePickerState.selected || serverTemplateModal?.dataset?.selected || ''; + const originalTemplate = templatePickerState.originalTemplate || ''; + if (!server) { + closeServerTemplateModal(); + return; + } + if (!selected) { + if (serverTemplateFeedback) serverTemplateFeedback.textContent = 'Select a template first.'; + return; + } + const selectedNorm = normalizeTemplateIdClient(selected); + if (selectedNorm === originalTemplate) { + closeServerTemplateModal(); + return; + } + const confirmMsg = `Changing template will REINSTALL the server "${server}". That means:\n\n` + + ` - All server files will be permanently deleted.\n\n` + + ` Are you sure you want to continue?`; + if (!confirm(confirmMsg)) return; + try { + serverTemplateDone.disabled = true; + if (serverTemplateCancel) serverTemplateCancel.disabled = true; + if (serverTemplateClose) serverTemplateClose.style.pointerEvents = 'none'; + serverTemplateDone.innerHTML = ' Reinstalling…'; + if (serverTemplateFeedback) { + serverTemplateFeedback.textContent = 'Stopping server and deleting files… This may take a few minutes.'; + serverTemplateFeedback.style.color = 'var(--warning, #f0ad4e)'; + } + const res = await fetch(`/api/settings/servers/${encodeURIComponent(server)}/template`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ templateId: selected }) + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + if (!res.ok) { + if (serverTemplateFeedback) { + serverTemplateFeedback.textContent = data.error || 'Failed to change template.'; + serverTemplateFeedback.style.color = 'var(--danger, #d9534f)'; + } + return; + } + if (serverTemplateFeedback) { + serverTemplateFeedback.textContent = 'Template changed and server reinstalled successfully!'; + serverTemplateFeedback.style.color = 'var(--success, #5cb85c)'; + } + const row = findServerRowByName(server); + if (row) { + row.dataset.template = selected; + const chip = row.querySelector('.template-chip'); + if (chip) chip.textContent = `Template: ${displayTemplateName(selected)}`; + } + setTimeout(() => { closeServerTemplateModal(); }, 1200); + } catch (err) { + console.error(err); + if (serverTemplateFeedback) { + serverTemplateFeedback.textContent = 'Network error while changing template. Please try again.'; + serverTemplateFeedback.style.color = 'var(--danger, #d9534f)'; + } + } finally { + serverTemplateDone.disabled = false; + if (serverTemplateCancel) serverTemplateCancel.disabled = false; + if (serverTemplateClose) serverTemplateClose.style.pointerEvents = ''; + serverTemplateDone.innerHTML = ' Done'; + } + }); +} +createServerBtn.addEventListener('click', async () => { + const raw = createServerNameInput.value.trim(); + if (!raw) return alert('Enter a server name'); + if (!/^[\w\-. ]{1,80}$/.test(raw)) return alert('Invalid name — allowed: letters, numbers, -, _, ., space'); + try { + createServerBtn.disabled = true; + createServerBtn.innerHTML = 'Creating...'; + const res = await fetch('/api/settings/servers', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ name: raw }) + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + if (!res.ok) { + alert(data.error || 'Failed to create server'); + createServerBtn.disabled = false; + createServerBtn.innerHTML = ' Create'; + return; + } + createServerNameInput.value = ''; + loadServers(); + } catch (err) { + console.error(err); + alert('Network error while creating server'); + } finally { + createServerBtn.disabled = false; + createServerBtn.innerHTML = ' Create'; + } +}); +serversListEl.addEventListener('click', async (e) => { + const resourceBtn = e.target.closest('.manage-resources'); + if (resourceBtn) { + const row = resourceBtn.closest('.server-row'); + const serverName = row?.dataset?.name || (resourceBtn.dataset.name ? decodeURIComponent(resourceBtn.dataset.name) : ''); + if (serverName) openResourcesModal(serverName); + return; + } + + const pfBtn = e.target.closest('.port-forward'); + if (pfBtn) { + const row = pfBtn.closest('.server-row'); + const serverName = row?.dataset?.name || (pfBtn.dataset.name ? decodeURIComponent(pfBtn.dataset.name) : ''); + if (serverName) openPortForwardModal(serverName); + return; + } + + const transferBtn = e.target.closest('.transfer-server'); + if (transferBtn) { + const row = transferBtn.closest('.server-row'); + const serverName = row?.dataset?.name || (transferBtn.dataset.name ? decodeURIComponent(transferBtn.dataset.name) : ''); + const currentNodeId = row?.dataset?.nodeId ? String(row.dataset.nodeId) : ''; + if (serverName) openTransferModal(serverName, currentNodeId); + return; + } + + const changeBtn = e.target.closest('.change-template'); + if (changeBtn) { + const row = changeBtn.closest('.server-row'); + const serverName = row?.dataset?.name || (changeBtn.dataset.name ? decodeURIComponent(changeBtn.dataset.name) : ''); + const currentTemplate = row?.dataset?.template || ''; + if (serverName) openServerTemplateModal(serverName, currentTemplate); + 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; + } +}); + +const transferModalOverlay = document.getElementById('transferModalOverlay'); +const transferModal = document.getElementById('transferModal'); +const transferModalTitle = document.getElementById('transferModalTitle'); +const transferModalSubtitle = document.getElementById('transferModalSubtitle'); +const transferModalClose = document.getElementById('transferModalClose'); +const transferCancel = document.getElementById('transferCancel'); +const transferFeedback = document.getElementById('transferFeedback'); +const transferNodeList = document.getElementById('transferNodeList'); +const transferProgress = document.getElementById('transferProgress'); +const transferProgressFill = document.getElementById('transferProgressFill'); +const transferProgressText = document.getElementById('transferProgressText'); + +let currentTransferServer = ''; +let transferPollTimer = null; + +function setTransferFeedback(msg, isError = false) { + if (!transferFeedback) return; + transferFeedback.textContent = msg || ''; + transferFeedback.className = 'node-feedback' + (isError ? ' error' : ''); +} + +function setTransferProgress(job) { + if (!transferProgress || !transferProgressFill || !transferProgressText) return; + if (!job) { + transferProgress.style.display = 'none'; + transferProgressFill.style.width = '0%'; + transferProgressText.textContent = ''; + return; + } + transferProgress.style.display = 'block'; + const pct = Math.max(0, Math.min(100, Number(job.percent || 0))); + transferProgressFill.style.width = `${pct}%`; + const status = job.status ? String(job.status) : 'running'; + transferProgressText.textContent = `${status}${job.message ? ' — ' + job.message : ''}`; +} + +function showTransferModal(show) { + if (!transferModalOverlay) return; + if (show) { + transferModalOverlay.setAttribute('aria-hidden', 'false'); + transferModalOverlay.classList.add('show'); + } else { + transferModalOverlay.setAttribute('aria-hidden', 'true'); + transferModalOverlay.classList.remove('show'); + currentTransferServer = ''; + setTransferFeedback(''); + setTransferProgress(null); + if (transferNodeList) transferNodeList.innerHTML = ''; + if (transferPollTimer) { + clearInterval(transferPollTimer); + transferPollTimer = null; + } + } +} + +async function fetchTransferJob(serverName) { + const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/transfer`, { cache: 'no-store' }); + if (!res.ok) return null; + const data = await res.json().catch(() => ({})); + return data.job || null; +} + +async function pollTransfer(serverName) { + try { + const job = await fetchTransferJob(serverName); + if (job) { + setTransferProgress(job); + if (job.status === 'error') setTransferFeedback(job.error || job.message || 'Transfer failed', true); + if (job.finishedAt) { + if (job.status === 'done') setTransferFeedback('Transfer complete.', false); + clearInterval(transferPollTimer); + transferPollTimer = null; + loadServers(); + } + } + } catch { } +} + +async function loadTransferNodes(serverName, currentNodeId) { + if (!transferNodeList) return; + transferNodeList.innerHTML = `
    Loading nodes…
    `; + try { + const res = await fetch('/api/nodes', { cache: 'no-store' }); + const data = await res.json().catch(() => ({ nodes: [] })); + if (!res.ok) throw new Error(data.error || 'Failed to load nodes'); + const nodes = Array.isArray(data.nodes) ? data.nodes : []; + transferNodeList.innerHTML = ''; + const filtered = nodes.filter(n => { + const id = String(n.id || '').trim(); + const uuid = String(n.uuid || '').trim(); + const name = String(n.name || '').trim(); + const anyId = String(id || uuid || name || '').trim(); + if (!anyId) return false; + if (currentNodeId && (String(currentNodeId) === id || String(currentNodeId) === uuid || String(currentNodeId) === name)) return false; + if (n.online !== true) return false; + return true; + }); + if (!filtered.length) { + transferNodeList.innerHTML = `
    No nodes available.
    `; + return; + } + filtered.forEach(n => { + const id = n.uuid || n.id || n.name; + const item = document.createElement('div'); + item.className = 'transfer-node-item'; + item.dataset.id = id; + item.innerHTML = ` +
    + +
    +
    ${escapeHtml(n.name || id)}
    +
    ${escapeHtml(n.address || '')} • API ${Number(n.api_port || 8080)}
    +
    +
    +
    + +
    + `; + item.querySelector('button')?.addEventListener('click', async (ev) => { + ev.stopPropagation(); + await startTransfer(serverName, id); + }); + item.addEventListener('click', async () => { + await startTransfer(serverName, id); + }); + transferNodeList.appendChild(item); + }); + } catch (e) { + console.error(e); + transferNodeList.innerHTML = `
    Failed to load nodes.
    `; + } +} + +async function startTransfer(serverName, targetNodeId) { + try { + setTransferFeedback('Starting transfer…'); + setTransferProgress({ status: 'preparing', percent: 0, message: 'Starting…' }); + const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/transfer`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ targetNodeId }) + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Failed to start transfer'); + if (data.job) setTransferProgress(data.job); + setTransferFeedback('Transfer in progress…'); + if (!transferPollTimer) { + transferPollTimer = setInterval(() => pollTransfer(serverName), 1500); + } + } catch (e) { + console.error(e); + setTransferFeedback(e.message || 'Failed to start transfer', true); + } +} + +async function openTransferModal(serverName, currentNodeId = '') { + currentTransferServer = serverName; + if (transferModalTitle) transferModalTitle.textContent = `Transfer: ${serverName}`; + if (transferModalSubtitle) transferModalSubtitle.textContent = 'Pick a destination node.'; + setTransferFeedback(''); + setTransferProgress(null); + showTransferModal(true); + await loadTransferNodes(serverName, currentNodeId); + const existing = await fetchTransferJob(serverName); + if (existing) { + setTransferProgress(existing); + if (!existing.finishedAt && !transferPollTimer) { + transferPollTimer = setInterval(() => pollTransfer(serverName), 1500); + } + } +} + +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 +} + +const resourcesModalOverlay = document.getElementById('resourcesModalOverlay'); +const resourcesModal = document.getElementById('resourcesModal'); +const resourcesModalTitle = document.getElementById('resourcesModalTitle'); +const resourcesModalSubtitle = document.getElementById('resourcesModalSubtitle'); +const resourcesModalClose = document.getElementById('resourcesModalClose'); +const resourcesCancel = document.getElementById('resourcesCancel'); +const resourcesSave = document.getElementById('resourcesSave'); +const resourcesFeedback = document.getElementById('resourcesFeedback'); +const resServerNameInput = document.getElementById('res_serverName'); +const resRenameServerBtn = document.getElementById('res_renameServer'); + +const resRamMb = document.getElementById('res_ramMb'); +const resCpuCores = document.getElementById('res_cpuCores'); +const resStorageMb = document.getElementById('res_storageMb'); +const resSwapMb = document.getElementById('res_swapMb'); +const resBackupsMax = document.getElementById('res_backupsMax'); +const resMaxSchedules = document.getElementById('res_maxSchedules'); +const resIoWeight = document.getElementById('res_ioWeight'); +const resCpuWeight = document.getElementById('res_cpuWeight'); +const resPidsLimit = document.getElementById('res_pidsLimit'); +const resFileLimit = document.getElementById('res_fileLimit'); +const resNetworkInboundLimitMb = document.getElementById('res_networkInboundLimitMb'); +const resNetworkOutboundLimitMb = document.getElementById('res_networkOutboundLimitMb'); +const resNetworkResetMinutes = document.getElementById('res_networkResetMinutes'); +const resUsageBar = document.getElementById('res_usageBar'); +const resUsageText = document.getElementById('res_usageText'); +const resPortsList = document.getElementById('res_portsList'); +const resNewPort = document.getElementById('res_newPort'); +const resAddPort = document.getElementById('res_addPort'); +const resStartupCommand = document.getElementById('res_startupCommand'); +const resStartupSection = document.getElementById('res_startupSection'); +const resStartupPreview = document.getElementById('res_startupPreview'); +const resCopyStartupCmd = document.getElementById('res_copyStartupCmd'); +const resStartupCommandHelp = document.getElementById('res_startupCommandHelp'); +const resJavaVersionField = document.getElementById('res_javaVersionField'); +const resJavaVersion = document.getElementById('res_javaVersion'); +const resJavaVersionHint = document.getElementById('res_javaVersionHint'); +if (resAddPort) resAddPort.setAttribute('data-unsaved-action', 'true'); +const RESOURCE_NETWORK_LIMIT_MAX_MB = 1073741824; +const RESOURCE_NETWORK_RESET_MAX_MINUTES = 43200; +const DEFAULT_MINECRAFT_JAVA_OPTIONS = Object.freeze(['8', '11', '17', '21', '22', '23', '24', '25', '26']); +const MINECRAFT_JAVA_MIN_VERSION = 8; +const MINECRAFT_JAVA_MAX_VERSION = 99; + +function formatStorageMb(mb) { + if (mb == null || isNaN(mb) || mb <= 0) return ''; + if (mb >= 1010) return (mb / 1024).toFixed(2).replace(/\.?0+$/, '') + ' GB'; + return Math.round(mb) + ' MB'; +} + +function readOptionalIntegerRange(input, label, min, max) { + const raw = input && input.value != null ? String(input.value).trim() : ''; + if (!raw) return null; + if (!/^\d+$/.test(raw)) { + throw new Error(`${label} must be a whole number.`); + } + const value = Number(raw); + if (!Number.isSafeInteger(value) || value < min || value > max) { + throw new Error(`${label} must be between ${min} and ${max}.`); + } + return value; +} + +if (resStorageMb) { + resStorageMb.addEventListener('input', () => { + const hint = resStorageMb.closest('.node-form-field')?.querySelector('.resource-hint'); + if (!hint) return; + const val = parseInt(resStorageMb.value, 10); + if (!isNaN(val) && val > 0) { + const display = formatStorageMb(val); + hint.textContent = `Disk space limit: ${display}`; + } else { + hint.textContent = 'Disk space limit for server files (e.g. 500 = 500 MB, 50000 = ~48.83 GB)'; + } + }); +} + +let currentResourcesServer = ''; +let currentResourcesRenameToken = ''; +let currentServerPorts = []; +let currentServerMainPort = null; +let originalServerMainPort = null; +let currentServerTemplate = ''; +let originalStartupCommand = ''; +let originalStartupCommandSource = ''; +let currentMinecraftJavaEnabled = false; +let originalMinecraftJavaVersion = ''; +registerModalCustomStateReader('resourcesModalOverlay', () => ({ + server: currentResourcesServer || '', + mainPort: currentServerMainPort ?? null, + ports: currentServerPorts.slice().map(Number).filter(Number.isFinite).sort((a, b) => a - b), + javaVersion: currentMinecraftJavaEnabled ? String(resJavaVersion?.value || '').trim() : '' +})); + +function showResourcesFeedback(msg, isError = false) { + if (!resourcesFeedback) return; + resourcesFeedback.textContent = msg; + resourcesFeedback.className = 'node-feedback' + (isError ? ' error' : ' success'); + resourcesFeedback.style.display = msg ? 'block' : 'none'; +} + +function clearResourcesFeedback() { + if (resourcesFeedback) { + resourcesFeedback.textContent = ''; + resourcesFeedback.style.display = 'none'; + } +} + +function renderStartupCommandPreview(command) { + if (!resStartupPreview) return; + const value = String(command || '').trim(); + if (!value) { + resStartupPreview.innerHTML = 'No startup command configured'; + return; + } + const escaped = value.replace(/&/g, '&').replace(//g, '>'); + resStartupPreview.innerHTML = '' + escaped + ''; +} + + + +function renderStartupCommandEditorState(command) { + renderStartupCommandPreview(command); + if (String(originalStartupCommandSource || '').trim().toLowerCase() === 'adpanel-startup') { + if (resStartupCommand) { + resStartupCommand.setAttribute('aria-invalid', 'false'); + resStartupCommand.readOnly = true; + } + return ''; + } + const error = validateRuntimeProcessCommandInput(command); + if (resStartupCommand) { + resStartupCommand.setAttribute('aria-invalid', error ? 'true' : 'false'); + } + return error; +} + + + +function normalizeMinecraftJavaVersionClient(value) { + const raw = String(value ?? '').trim().toLowerCase(); + if (!raw) return ''; + const match = raw.match(/^(\d{1,2})(?:\D.*)?$/); + if (!match) return ''; + const version = Number(match[1]); + if (!Number.isInteger(version) || version < MINECRAFT_JAVA_MIN_VERSION || version > MINECRAFT_JAVA_MAX_VERSION) return ''; + return String(version); +} + +function isMinecraftTemplateLikeClient(templateId, templateName) { + const normalizedTemplateId = normalizeTemplateIdClient(templateId); + if (normalizedTemplateId === 'minecraft') return true; + if (normalizedTemplateId.includes('minecraft')) return true; + return String(templateName || '').trim().toLowerCase().includes('minecraft'); +} + +function resetMinecraftJavaSelector() { + currentMinecraftJavaEnabled = false; + originalMinecraftJavaVersion = ''; + if (resJavaVersion) { + resJavaVersion.innerHTML = ''; + resJavaVersion.value = ''; + resJavaVersion.disabled = true; + } + if (resJavaVersionField) resJavaVersionField.hidden = true; + if (resJavaVersionHint) resJavaVersionHint.textContent = 'Runs this Minecraft server with the selected Eclipse Temurin JRE image.'; +} + +function renderMinecraftJavaSelector(data) { + resetMinecraftJavaSelector(); + if (!isMinecraftTemplateLikeClient(data?.template, data?.templateName)) return; + + const javaPayload = data?.minecraftJava && typeof data.minecraftJava === 'object' ? data.minecraftJava : null; + const rawOptions = Array.isArray(javaPayload?.options) && javaPayload.options.length + ? javaPayload.options + : DEFAULT_MINECRAFT_JAVA_OPTIONS.map((version) => ({ version, tag: `${version}-jre`, label: `Java ${version}` })); + const options = rawOptions + .map((option) => { + const version = normalizeMinecraftJavaVersionClient(option?.version || option?.value || option); + if (!version) return null; + return { + version, + tag: String(option?.tag || `${version}-jre`).trim(), + label: String(option?.label || `Java ${version}`).trim(), + }; + }) + .filter(Boolean); + if (!options.length || !resJavaVersion) return; + + const seen = new Set(); + resJavaVersion.innerHTML = ''; + for (const option of options) { + if (seen.has(option.version)) continue; + seen.add(option.version); + const opt = document.createElement('option'); + opt.value = option.version; + opt.textContent = `${option.label} (${option.tag})`; + resJavaVersion.appendChild(opt); + } + + const selected = normalizeMinecraftJavaVersionClient(data?.javaVersion || javaPayload?.selected) || + normalizeMinecraftJavaVersionClient(options.find((option) => option.version === '21')?.version) || + options[0].version; + resJavaVersion.value = selected; + resJavaVersion.disabled = false; + originalMinecraftJavaVersion = selected; + 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}`; + } +} + +function sanitizePortInputValue(value) { + return String(value ?? '').replace(/[^\d]/g, '').slice(0, 5); +} + +function parseStrictPortValue(value) { + const str = String(value ?? '').trim(); + if (!/^[1-9]\d{0,4}$/.test(str)) return null; + const port = Number(str); + if (!Number.isInteger(port) || port < 1 || port > 65535) return null; + return port; +} + +const RUNTIME_PROCESS_BLOCKED_EXECUTABLES = new Set([ + 'sh', '/bin/sh', 'bash', '/bin/bash', 'ash', '/bin/ash', 'dash', '/bin/dash', 'zsh', '/bin/zsh', 'ksh', '/bin/ksh', +]); +const RUNTIME_PROCESS_BLOCKED_CONTAINER_EXECUTABLES = new Set([ + 'docker', 'docker-compose', 'podman', 'podman-compose', 'nerdctl', 'ctr', +]); +const RUNTIME_PROCESS_ENV_WRAPPERS = new Set(['env']); +const RUNTIME_PROCESS_BLOCKED_TOKENS = new Set([ + '&&', '||', '|', ';', '&', '>', '>>', '<', '<<', '2>', '2>>', '2>&1', '|&', +]); + +function parseRuntimeProcessArgsInput(value) { + const input = String(value || ''); + const args = []; + let current = ''; + let quote = ''; + let escape = false; + for (let i = 0; i < input.length; i += 1) { + const ch = input[i]; + if (escape) { + current += ch; + escape = false; + continue; + } + if (ch === '\\') { + escape = true; + continue; + } + if (quote) { + if (ch === quote) quote = ''; + else current += ch; + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + continue; + } + if (/\s/.test(ch)) { + if (current) { + args.push(current); + current = ''; + } + continue; + } + current += ch; + } + if (current) args.push(current); + return args; +} + +function getRuntimeProcessExecutableBaseNameInput(value) { + const raw = String(value || '').trim(); + if (!raw) return ''; + let candidate = raw; + if (/\s/.test(candidate)) { + const nestedArgs = parseRuntimeProcessArgsInput(candidate); + if (nestedArgs.length) candidate = String(nestedArgs[0] || '').trim(); + } + const normalized = candidate.toLowerCase().replace(/\\/g, '/'); + const parts = normalized.split('/').filter(Boolean); + return parts.pop() || normalized; +} + +function isRuntimeEnvAssignmentTokenInput(value) { + const token = String(value || '').trim(); + if (!token || token.startsWith('-')) return false; + const eqIdx = token.indexOf('='); + if (eqIdx <= 0) return false; + return /^[A-Za-z_][A-Za-z0-9_]*$/.test(token.slice(0, eqIdx)); +} + +function resolveRuntimeProcessExecutableArgsInput(args) { + const parts = Array.isArray(args) ? args : []; + if (!parts.length) return { execName: '', index: -1 }; + let index = 0; + while (index < parts.length) { + const token = String(parts[index] || '').trim(); + if (!token) { + index += 1; + continue; + } + const execName = getRuntimeProcessExecutableBaseNameInput(token); + if (RUNTIME_PROCESS_ENV_WRAPPERS.has(execName)) { + index += 1; + while (index < parts.length) { + const envToken = String(parts[index] || '').trim(); + if (!envToken) { + index += 1; + continue; + } + if (envToken === '--') { + index += 1; + break; + } + if (envToken.startsWith('-') || isRuntimeEnvAssignmentTokenInput(envToken)) { + index += 1; + continue; + } + break; + } + continue; + } + return { execName, index }; + } + return { execName: '', index: -1 }; +} + +function validateRuntimeContainerLauncherInput(args) { + const { execName } = resolveRuntimeProcessExecutableArgsInput(args); + if (RUNTIME_PROCESS_BLOCKED_CONTAINER_EXECUTABLES.has(execName)) { + return 'Container runtime CLI commands like "docker run" are not allowed here. Configure image, ports, volumes, env, and the in-container process separately.'; + } + return null; +} + +function isBlockedRuntimeShellExecutableInput(value) { + const execName = getRuntimeProcessExecutableBaseNameInput(value); + return RUNTIME_PROCESS_BLOCKED_EXECUTABLES.has(execName); +} + +function isRuntimeShellWrapperArgsInput(args, execIndex) { + if (!Array.isArray(args) || execIndex < 0 || execIndex >= args.length) return false; + if (!isBlockedRuntimeShellExecutableInput(args[execIndex])) return false; + const flags = String(args[execIndex + 1] || '').trim().toLowerCase(); + return flags.startsWith('-') && flags.includes('c'); +} + +function validateRuntimeProcessCommandInput(value) { + const command = String(value || '').trim(); + if (!command) return null; + if (command.length > 4000) return 'Process command is too long.'; + if (command.includes('\n')) return 'Process command must be a single line.'; + if (command.includes('`') || command.includes('$(')) { + return 'Shell expansions are not allowed in process commands.'; + } + const args = parseRuntimeProcessArgsInput(command); + if (!args.length) return 'Process command is empty.'; + const { execName: resolvedExecName, index: execIndex } = resolveRuntimeProcessExecutableArgsInput(args); + const containerRuntimeError = validateRuntimeContainerLauncherInput(args); + if (containerRuntimeError) return containerRuntimeError; + if (isBlockedRuntimeShellExecutableInput(resolvedExecName || args[0]) && isRuntimeShellWrapperArgsInput(args, execIndex)) { + return 'Shell wrappers like sh -c or bash -lc are not allowed. Provide the executable and arguments directly.'; + } + for (const arg of args) { + const token = String(arg || '').trim(); + if (RUNTIME_PROCESS_BLOCKED_TOKENS.has(token)) { + return `Shell control operator "${token}" is not allowed in process commands.`; + } + } + return null; +} + +function bindStrictPortInput(input) { + if (!input) return; + input.setAttribute('inputmode', 'numeric'); + input.addEventListener('input', () => { + const sanitized = sanitizePortInputValue(input.value); + if (input.value !== sanitized) input.value = sanitized; + }); +} + +async function submitResourcesRename() { + if (!currentResourcesServer || !resServerNameInput) return; + + const requestedName = (resServerNameInput.value || '').trim(); + if (!requestedName) { + showResourcesFeedback('Enter a server name', true); + resServerNameInput.focus(); + return; + } + + if (requestedName === currentResourcesServer) { + showResourcesFeedback('Server name is already up to date.', false); + return; + } + + if (!currentResourcesRenameToken) { + showResourcesFeedback('Rename token missing. Reopen the modal and try again.', true); + return; + } + + const previousButtonHtml = resRenameServerBtn ? resRenameServerBtn.innerHTML : ''; + try { + if (resServerNameInput) resServerNameInput.disabled = true; + if (resRenameServerBtn) { + resRenameServerBtn.disabled = true; + resRenameServerBtn.innerHTML = ' Renaming...'; + } + if (resourcesSave) resourcesSave.disabled = true; + showResourcesFeedback('Renaming server…', false); + + const res = await fetch(`/api/settings/servers/${encodeURIComponent(currentResourcesServer)}/rename`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': currentResourcesRenameToken + }, + body: JSON.stringify({ newName: requestedName }) + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + if (!res.ok) { + throw new Error(data.error || 'Failed to rename server'); + } + + const nextName = data?.name || requestedName; + await loadServers(_serversPage, _serversSearch); + await openResourcesModal(nextName); + showResourcesFeedback(`Server renamed to ${nextName}.`, false); + } catch (err) { + console.error('[resources-rename]', err); + showResourcesFeedback(err.message || 'Rename failed', true); + if (resServerNameInput) { + resServerNameInput.disabled = false; + resServerNameInput.focus(); + resServerNameInput.select(); + } + if (resourcesSave) resourcesSave.disabled = false; + if (resRenameServerBtn) { + resRenameServerBtn.disabled = false; + resRenameServerBtn.innerHTML = previousButtonHtml || ' Rename'; + } + } +} + +function renderPortsList() { + if (!resPortsList) return; + resPortsList.innerHTML = ''; + + if (currentServerMainPort != null) { + const mainItem = document.createElement('div'); + mainItem.className = 'port-item port-item-primary'; + mainItem.innerHTML = ` + + + Primary + `; + resPortsList.appendChild(mainItem); + + const input = mainItem.querySelector('.port-edit-input'); + bindStrictPortInput(input); + input.addEventListener('change', () => { + const val = parseStrictPortValue(input.value); + if (!val) { + showResourcesFeedback('Main port must be between 1 and 65535', true); + input.value = currentServerMainPort; + return; + } + if (currentServerPorts.includes(val)) { + showResourcesFeedback(`Port ${val} is already used as an additional port`, true); + input.value = currentServerMainPort; + return; + } + clearResourcesFeedback(); + currentServerMainPort = val; + }); + } + + currentServerPorts.forEach((port, index) => { + const item = document.createElement('div'); + item.className = 'port-item'; + item.innerHTML = ` + + ${port} + + `; + resPortsList.appendChild(item); + }); +} + +function addPort() { + if (!resNewPort) return; + const portVal = resNewPort.value.trim(); + if (!portVal) { + showResourcesFeedback('Please enter a port number', true); + return; + } + const port = parseStrictPortValue(portVal); + if (!port) { + showResourcesFeedback('Port must be between 1 and 65535', true); + return; + } + if (currentServerMainPort != null && port === currentServerMainPort) { + showResourcesFeedback(`Port ${port} is already the primary server port`, true); + return; + } + if (currentServerPorts.includes(port)) { + showResourcesFeedback(`Port ${port} is already in the list`, true); + return; + } + currentServerPorts.push(port); + resNewPort.value = ''; + clearResourcesFeedback(); + renderPortsList(); +} + +function removePort(index) { + if (index >= 0 && index < currentServerPorts.length) { + const totalPorts = (currentServerMainPort != null ? 1 : 0) + currentServerPorts.length; + if (totalPorts <= 1) { + showResourcesFeedback('Cannot remove the last port — a server must have at least one port assigned.', true); + return; + } + clearResourcesFeedback(); + currentServerPorts.splice(index, 1); + renderPortsList(); + } +} + +function syncPortsToStartupCommand() { + renderStartupCommandEditorState(resStartupCommand?.value || ''); +} + +function parseDockerArgs(argsStr) { + const args = []; + let current = ''; + let inQuote = ''; + for (let i = 0; i < argsStr.length; i++) { + const ch = argsStr[i]; + if (inQuote) { + if (ch === inQuote) { inQuote = ''; continue; } + current += ch; + } else if (ch === '"' || ch === "'") { + inQuote = ch; + } else if (ch === ' ' || ch === '\t') { + if (current) { args.push(current); current = ''; } + } else { + current += ch; + } + } + if (current) args.push(current); + return args; +} + +if (resAddPort) resAddPort.addEventListener('click', addPort); +bindStrictPortInput(resNewPort); +if (resNewPort) { + resNewPort.addEventListener('keypress', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + addPort(); + } + }); +} +if (resPortsList) { + resPortsList.addEventListener('click', (e) => { + const removeBtn = e.target.closest('.port-remove'); + if (removeBtn) { + const index = parseInt(removeBtn.dataset.index, 10); + removePort(index); + } + }); +} + +async function openResourcesModal(serverName) { + currentResourcesServer = serverName; + currentResourcesRenameToken = ''; + currentServerPorts = []; + currentServerMainPort = null; + 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'); + } + + 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'; + } + } + } 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); + } + } 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); + } +} + +function closeResourcesModal() { + if (resourcesModalOverlay) { + resourcesModalOverlay.setAttribute('aria-hidden', 'true'); + resourcesModalOverlay.classList.remove('show'); + } + currentResourcesServer = ''; + currentResourcesRenameToken = ''; + currentServerMainPort = null; + originalServerMainPort = null; + originalStartupCommand = ''; + originalStartupCommandSource = ''; + if (resStartupCommand) resStartupCommand.readOnly = false; + resetMinecraftJavaSelector(); + clearResourcesFeedback(); +} + +async function saveResources() { + if (!currentResourcesServer) return; + + const resources = {}; + + const ramVal = resRamMb?.value?.trim(); + if (ramVal) { + const ram = parseInt(ramVal, 10); + if (!isNaN(ram) && ram >= 0) resources.ramMb = ram; + } + + const cpuVal = resCpuCores?.value?.trim(); + if (cpuVal) { + const cpu = parseFloat(cpuVal); + if (!isNaN(cpu) && cpu >= 0) resources.cpuCores = cpu; + } + + const storageVal = resStorageMb?.value?.trim(); + if (storageVal) { + const storage = parseInt(storageVal, 10); + if (!isNaN(storage) && storage >= 0) resources.storageMb = storage; + } + + const swapVal = resSwapMb?.value; + if (swapVal != null) { + const swap = parseInt(swapVal, 10); + if (!isNaN(swap)) resources.swapMb = swap; + } + + const backupsVal = resBackupsMax?.value?.trim(); + if (backupsVal) { + const backups = parseInt(backupsVal, 10); + if (!isNaN(backups) && backups >= 0) resources.backupsMax = backups; + } + + const maxSchedulesVal = resMaxSchedules?.value?.trim(); + if (maxSchedulesVal) { + const maxSched = parseInt(maxSchedulesVal, 10); + if (!isNaN(maxSched) && maxSched >= 0) resources.maxSchedules = maxSched; + } + + try { + const ioWeight = readOptionalIntegerRange(resIoWeight, 'I/O Priority', 10, 1000); + const cpuWeight = readOptionalIntegerRange(resCpuWeight, 'CPU Priority', 1, 1000); + const pidsLimit = readOptionalIntegerRange(resPidsLimit, 'Process Limit', 64, 4096); + const fileLimit = readOptionalIntegerRange(resFileLimit, 'File Limit', 1024, 1048576); + const networkInboundLimitMb = readOptionalIntegerRange(resNetworkInboundLimitMb, 'Inbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB); + const networkOutboundLimitMb = readOptionalIntegerRange(resNetworkOutboundLimitMb, 'Outbound Limit', 1, RESOURCE_NETWORK_LIMIT_MAX_MB); + const networkResetMinutesValue = readOptionalIntegerRange(resNetworkResetMinutes, 'Reset Time', 1, RESOURCE_NETWORK_RESET_MAX_MINUTES); + if (ioWeight != null) resources.ioWeight = ioWeight; + if (cpuWeight != null) resources.cpuWeight = cpuWeight; + if (pidsLimit != null) resources.pidsLimit = pidsLimit; + if (fileLimit != null) resources.fileLimit = fileLimit; + if (networkInboundLimitMb != null) resources.networkInboundLimitMb = networkInboundLimitMb; + else if (resNetworkInboundLimitMb) resources.networkInboundLimitMb = 0; + if (networkOutboundLimitMb != null) resources.networkOutboundLimitMb = networkOutboundLimitMb; + else if (resNetworkOutboundLimitMb) resources.networkOutboundLimitMb = 0; + if (networkResetMinutesValue != null) resources.networkResetMinutes = networkResetMinutesValue; + else if (resNetworkResetMinutes) resources.networkResetMinutes = 0; + } catch (err) { + showResourcesFeedback(err.message || 'Invalid resource value', true); + return; + } + + resources.ports = currentServerPorts.slice(); + + const requestBody = { resources }; + const startupCommand = String(resStartupCommand?.value || '').trim(); + const startupCommandError = renderStartupCommandEditorState(startupCommand); + if (startupCommandError) { + showResourcesFeedback(startupCommandError, true); + resStartupCommand?.focus(); + return; + } + if (String(originalStartupCommandSource || '').trim().toLowerCase() !== 'adpanel-startup' && startupCommand !== originalStartupCommand) { + requestBody.command = startupCommand; + } + + if (currentMinecraftJavaEnabled) { + const selectedJavaVersion = normalizeMinecraftJavaVersionClient(resJavaVersion?.value); + if (!selectedJavaVersion) { + showResourcesFeedback('Unsupported Minecraft Java version.', true); + resJavaVersion?.focus(); + return; + } + if (selectedJavaVersion !== originalMinecraftJavaVersion) { + requestBody.javaVersion = selectedJavaVersion; + } + } + + if (currentServerMainPort != null && currentServerMainPort !== originalServerMainPort) { + requestBody.mainPort = currentServerMainPort; + } + + if (resourcesSave) { + resourcesSave.disabled = true; + resourcesSave.innerHTML = ' Applying...'; + } + + try { + const res = await fetch(`/api/settings/servers/${encodeURIComponent(currentResourcesServer)}/resources`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(requestBody) + }); + + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + + if (!res.ok) { + showResourcesFeedback(data.error || 'Failed to update resources', true); + return; + } + + showResourcesFeedback('Resources updated! Server is restarting...', false); + + setTimeout(() => { + closeResourcesModal(); + }, 2000); + + } catch (err) { + console.error('[resources] Save error:', err); + showResourcesFeedback('Network error while saving resources', true); + } finally { + if (resourcesSave) { + resourcesSave.disabled = false; + resourcesSave.innerHTML = ' Apply & Restart'; + } + } +} + +if (resourcesModalClose) resourcesModalClose.addEventListener('click', closeResourcesModal); +if (resourcesCancel) resourcesCancel.addEventListener('click', closeResourcesModal); +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`; + } + }); +} +if (resServerNameInput) { + resServerNameInput.addEventListener('keydown', async (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + await submitResourcesRename(); + } + }); +} +if (resourcesModalOverlay) { + // Click outside disabled — user must use close/cancel button +} + +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && resourcesModalOverlay?.classList.contains('show')) { + closeResourcesModal(); + } +}); + +if (resCopyStartupCmd) { + resCopyStartupCmd.addEventListener('click', () => { + const cmd = resStartupCommand?.value?.trim() || resStartupPreview?.textContent?.trim() || ''; + if (cmd && cmd !== 'No startup command configured' && cmd !== 'Loading...') { + copyToClipboard(cmd).then(() => { + const icon = resCopyStartupCmd.querySelector('i'); + if (icon) { + icon.className = 'fa-solid fa-check'; + setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500); + } + }).catch(() => { }); + } + }); +} + +if (resStartupCommand) { + resStartupCommand.addEventListener('input', () => { + if (String(originalStartupCommandSource || '').trim().toLowerCase() === 'adpanel-startup') return; + renderStartupCommandEditorState(resStartupCommand.value); + }); +} + +const portForwardModalOverlay = document.getElementById('portForwardModalOverlay'); +const portForwardModal = document.getElementById('portForwardModal'); +const portForwardModalTitle = document.getElementById('portForwardModalTitle'); +const portForwardModalSubtitle = document.getElementById('portForwardModalSubtitle'); +const portForwardModalClose = document.getElementById('portForwardModalClose'); +const portForwardCancel = document.getElementById('portForwardCancel'); +const portForwardSave = document.getElementById('portForwardSave'); +const portForwardFeedback = document.getElementById('portForwardFeedback'); +const pfRulesList = document.getElementById('pf_rulesList'); +const pfNewPublicPort = document.getElementById('pf_newPublicPort'); +const pfNewInternalPort = document.getElementById('pf_newInternalPort'); +const pfAddRule = document.getElementById('pf_addRule'); +if (pfAddRule) pfAddRule.setAttribute('data-unsaved-action', 'true'); + +let currentPFServer = ''; +let currentPFRules = []; +let currentPFNodeAllocation = null; +let currentPFMainPort = null; +let currentPFAllocatedPorts = []; +registerModalCustomStateReader('portForwardModalOverlay', () => ({ + server: currentPFServer || '', + rules: currentPFRules + .map(rule => ({ + publicPort: Number(rule?.publicPort || 0), + internalPort: Number(rule?.internalPort || 0) + })) + .sort((a, b) => (a.internalPort - b.internalPort) || (a.publicPort - b.publicPort)) +})); + +function showPFFeedback(msg, isError = false) { + if (!portForwardFeedback) return; + portForwardFeedback.textContent = msg; + portForwardFeedback.className = 'node-feedback' + (isError ? ' error' : ' success'); + portForwardFeedback.style.display = msg ? 'block' : 'none'; +} + +function clearPFFeedback() { + if (portForwardFeedback) { + portForwardFeedback.textContent = ''; + portForwardFeedback.style.display = 'none'; + } +} + +function isPFPortInAllocation(port) { + if (!currentPFNodeAllocation) return true; + const p = Number(port); + if (!Number.isFinite(p) || p < 1 || p > 65535) return false; + const alloc = currentPFNodeAllocation; + if (alloc.mode === 'range') { + const start = Number(alloc.start || 0); + const count = Number(alloc.count || 0); + if (start <= 0 || count <= 0) return true; + return p >= start && p < start + count; + } + if (alloc.mode === 'list' && Array.isArray(alloc.ports)) { + if (alloc.ports.length === 0) return true; + return alloc.ports.includes(p); + } + return true; +} + +function populateInternalPortDropdown() { + if (!pfNewInternalPort) return; + pfNewInternalPort.innerHTML = ''; + const usedInternalPorts = new Set(currentPFRules.map(r => r.internalPort)); + for (const port of currentPFAllocatedPorts) { + if (!usedInternalPorts.has(port)) { + const opt = document.createElement('option'); + opt.value = port; + opt.textContent = port === currentPFMainPort ? `${port} (primary)` : String(port); + pfNewInternalPort.appendChild(opt); + } + } +} + +function renderPFRules() { + if (!pfRulesList) return; + pfRulesList.innerHTML = ''; + if (currentPFRules.length === 0) { + pfRulesList.innerHTML = '
    No port forward rules configured
    '; + populateInternalPortDropdown(); + return; + } + currentPFRules.forEach((rule, index) => { + const item = document.createElement('div'); + item.className = 'pf-rule-item'; + const isPrimary = rule.internalPort === currentPFMainPort; + item.innerHTML = ` +
    + ${rule.internalPort}${isPrimary ? ' (primary)' : ''} + + ${rule.publicPort} +
    + + `; + pfRulesList.appendChild(item); + }); + populateInternalPortDropdown(); +} + +function addPFRule() { + if (!pfNewPublicPort || !pfNewInternalPort) return; + const publicVal = pfNewPublicPort.value.trim(); + const internalVal = pfNewInternalPort.value; + if (!internalVal) { + showPFFeedback('Please select an internal server port', true); + return; + } + if (!publicVal) { + showPFFeedback('Please enter a public port', true); + return; + } + const publicPort = parseStrictPortValue(publicVal); + const internalPort = parseStrictPortValue(internalVal); + if (!publicPort) { + showPFFeedback('Public port must be between 1 and 65535', true); + return; + } + if (!internalPort) { + showPFFeedback('Invalid internal port selected', true); + return; + } + if (!isPFPortInAllocation(publicPort)) { + showPFFeedback(`Public port ${publicPort} is not in this node's allocated port range`, true); + return; + } + if (currentPFAllocatedPorts.includes(publicPort)) { + showPFFeedback(`Port ${publicPort} is already allocated to this server and cannot be used as a public forward`, true); + return; + } + if (currentPFRules.some(r => r.publicPort === publicPort)) { + showPFFeedback(`Public port ${publicPort} is already in use by another rule`, true); + return; + } + if (currentPFRules.some(r => r.internalPort === internalPort)) { + showPFFeedback(`Internal port ${internalPort} already has a forward rule`, true); + return; + } + currentPFRules.push({ publicPort, internalPort }); + pfNewPublicPort.value = ''; + pfNewInternalPort.value = ''; + clearPFFeedback(); + renderPFRules(); +} + +function removePFRule(index) { + if (index >= 0 && index < currentPFRules.length) { + currentPFRules.splice(index, 1); + clearPFFeedback(); + renderPFRules(); + } +} + +async function openPortForwardModal(serverName) { + currentPFServer = serverName; + currentPFRules = []; + currentPFNodeAllocation = null; + currentPFMainPort = null; + currentPFAllocatedPorts = []; + clearPFFeedback(); + + if (portForwardModalTitle) portForwardModalTitle.textContent = `Ports: ${serverName}`; + if (portForwardModalSubtitle) portForwardModalSubtitle.textContent = 'Map public ports to internal ones.'; + + if (pfNewPublicPort) pfNewPublicPort.value = ''; + if (pfNewInternalPort) pfNewInternalPort.value = ''; + renderPFRules(); + + if (portForwardModalOverlay) { + portForwardModalOverlay.setAttribute('aria-hidden', 'false'); + portForwardModalOverlay.classList.add('show'); + } + + try { + const res = await fetch(`/api/settings/servers/${encodeURIComponent(serverName)}/port-forwards`); + if (res.ok) { + const data = await res.json(); + if (Array.isArray(data.portForwards)) { + currentPFRules = data.portForwards.map(r => ({ + publicPort: Number(r.publicPort), + internalPort: Number(r.internalPort) + })); + } + if (data.nodeAllocation) { + currentPFNodeAllocation = data.nodeAllocation; + } + if (data.mainPort) { + currentPFMainPort = Number(data.mainPort); + } + if (Array.isArray(data.allocatedPorts)) { + currentPFAllocatedPorts = data.allocatedPorts.map(Number); + } + renderPFRules(); + } else { + const errData = await res.json().catch(() => ({})); + showPFFeedback(errData.error || 'Failed to load port forwarding config', true); + } + } catch (err) { + console.error('[port-forward] Failed to load:', err); + showPFFeedback('Failed to load port forwarding config', true); + } +} + +function closePortForwardModal() { + if (portForwardModalOverlay) { + portForwardModalOverlay.setAttribute('aria-hidden', 'true'); + portForwardModalOverlay.classList.remove('show'); + } + currentPFServer = ''; + currentPFRules = []; + currentPFNodeAllocation = null; + currentPFMainPort = null; + currentPFAllocatedPorts = []; + clearPFFeedback(); +} + +async function savePortForwards() { + if (!currentPFServer) return; + + for (const rule of currentPFRules) { + if (!isPFPortInAllocation(rule.publicPort)) { + showPFFeedback(`Public port ${rule.publicPort} is not in this node's allocated port range`, true); + return; + } + if (currentPFAllocatedPorts.includes(rule.publicPort)) { + showPFFeedback(`Port ${rule.publicPort} is allocated to this server and cannot be used as a public forward`, true); + return; + } + } + + if (portForwardSave) { + portForwardSave.disabled = true; + portForwardSave.innerHTML = ' Applying...'; + } + + try { + const res = await fetch(`/api/settings/servers/${encodeURIComponent(currentPFServer)}/port-forwards`, { + method: 'PATCH', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ portForwards: currentPFRules }) + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + if (!res.ok) { + showPFFeedback(data.error || 'Failed to update port forwards', true); + return; + } + showPFFeedback('Port forwards updated! Server is restarting...', false); + setTimeout(() => closePortForwardModal(), 2000); + } catch (err) { + console.error('[port-forward] Save error:', err); + showPFFeedback('Network error while saving port forwards', true); + } finally { + if (portForwardSave) { + portForwardSave.disabled = false; + portForwardSave.innerHTML = ' Apply & Restart'; + } + } +} + +if (portForwardModalClose) portForwardModalClose.addEventListener('click', closePortForwardModal); +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 +} +if (pfAddRule) pfAddRule.addEventListener('click', addPFRule); +if (pfNewPublicPort) { + pfNewPublicPort.addEventListener('keypress', (e) => { + if (e.key === 'Enter') { e.preventDefault(); addPFRule(); } + }); +} +if (pfRulesList) { + pfRulesList.addEventListener('click', (e) => { + const removeBtn = e.target.closest('.pf-remove'); + if (removeBtn) { + const index = parseInt(removeBtn.dataset.index, 10); + removePFRule(index); + } + }); +} +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && portForwardModalOverlay?.classList.contains('show')) { + closePortForwardModal(); + } +}); + +async function loadAccounts() { + accountsListEl.innerHTML = `
    Loading accounts…
    `; + try { + const res = await fetch('/api/settings/accounts'); + if (!res.ok) { + const err = await res.json().catch(() => ({ error: 'failed' })); + accountsListEl.innerHTML = `
    Failed to load accounts
    `; + console.warn(err); + return; + } + const data = await res.json(); + accountsListEl._accounts = data.accounts || []; + accountsListEl._bots = data.bots || []; + accountsListEl._actionTokens = data.actionTokens || {}; + renderAccounts(accountsListEl._accounts, accountsListEl._bots); + } catch (e) { + console.error(e); + accountsListEl.innerHTML = `
    Network error
    `; + } +} +function renderAccounts(accounts, bots, searchQuery = '') { + accountsListEl.innerHTML = ''; + + let filtered = Array.isArray(accounts) ? [...accounts] : []; + if (searchQuery && searchQuery.trim()) { + const q = searchQuery.trim().toLowerCase(); + filtered = filtered.filter(acc => + acc.email && acc.email.toLowerCase().includes(q) + ); + } + + filtered.sort((a, b) => { + const aAdmin = !!a?.admin; + const bAdmin = !!b?.admin; + if (aAdmin !== bAdmin) return aAdmin ? -1 : 1; + return String(a?.email || '').localeCompare(String(b?.email || '')); + }); + + if (!Array.isArray(filtered) || filtered.length === 0) { + if (searchQuery && searchQuery.trim()) { + accountsListEl.innerHTML = `
    No accounts matching "${escapeHtml(searchQuery)}"
    `; + } else { + accountsListEl.innerHTML = `
    No accounts found
    `; + } + return; + } + filtered.forEach(acc => { + const div = document.createElement('div'); + div.className = 'account-row'; + const isAdminAccount = !!acc.admin; + const accessLabel = isAdminAccount + ? 'admin account' + : ((Array.isArray(acc.servers) && acc.servers.length > 0) ? `${acc.servers.length} access` : 'no access'); + const accessControls = isAdminAccount ? '' : ` +
    + + Agent +
    + + `; + div.innerHTML = ` + +
    + ${accessControls} + + + +
    + `; + accountsListEl.appendChild(div); + }); +} + +if (accountsSearchInput) { + accountsSearchInput.addEventListener('input', (e) => { + const query = e.target.value; + const accounts = accountsListEl._accounts || []; + const bots = accountsListEl._bots || []; + renderAccounts(accounts, bots, query); + }); +} + +accountsListEl.addEventListener('click', async (e) => { + const manageBtn = e.target.closest('.manage-access'); + if (manageBtn) { + const enc = manageBtn.dataset.email; + if (!enc) return; + const email = decodeURIComponent(enc); + openManageAccessModal(email); + return; + } + + const changePassBtn = e.target.closest('.change-password-btn'); + if (changePassBtn) { + const enc = changePassBtn.dataset.email; + if (!enc) return; + const email = decodeURIComponent(enc); + openAdminChangePasswordModal(email); + 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 = ''; + } + return; + } +}); + +accountsListEl.addEventListener('change', async (e) => { + const toggle = e.target.closest('.agent-access-toggle'); + if (!toggle) return; + const enc = toggle.dataset.email; + if (!enc) return; + const email = decodeURIComponent(enc); + const enabled = toggle.checked; + try { + const res = await fetch(`/api/settings/accounts/${encodeURIComponent(email)}/agent-access`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': (accountsListEl._actionTokens || {}).setAgentAccess || '' + }, + body: JSON.stringify({ enabled }) + }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + alert(data.error || 'Failed to update agent access'); + toggle.checked = !enabled; + return; + } + const toast = document.createElement('div'); + toast.className = 'perm-success-toast'; + toast.innerHTML = ` Agent access ${enabled ? 'enabled' : 'disabled'}`; + document.body.appendChild(toast); + setTimeout(() => { toast.classList.add('show'); }, 10); + setTimeout(() => { + toast.classList.remove('show'); + setTimeout(() => toast.remove(), 300); + }, 2000); + } catch (err) { + console.error(err); + alert('Network error'); + toggle.checked = !enabled; + } +}); +async function openManageAccessModal(email) { + accountModalTitle.textContent = `Manage access for ${email}`; + accountModalBody.innerHTML = `
    Loading servers...
    `; + accountModalOverlay.classList.add('show'); + accountModal.classList.add('show'); + try { + const res = await fetch('/api/settings/accounts'); + if (!res.ok) { + const err = await res.json().catch(() => ({ error: 'failed' })); + accountModalBody.innerHTML = `

    Failed to load data

    `; + console.warn(err); + return; + } + const data = await res.json(); + const accounts = data.accounts || []; + const bots = data.bots || []; + const rec = accounts.find(a => String(a.email).toLowerCase() === String(email).toLowerCase()); + const userServers = rec ? (Array.isArray(rec.servers) ? rec.servers : []) : []; + if (!Array.isArray(bots) || bots.length === 0) { + accountModalBody.innerHTML = `

    No servers found

    `; + return; + } + const list = document.createElement('div'); + list.className = 'access-list'; + bots.forEach(b => { + const row = document.createElement('div'); + row.className = 'access-server-row'; + const left = document.createElement('div'); + left.className = 'access-server-left'; + left.innerHTML = `
    ${escapeHtml(b)}
    `; + let hasAccess = userServers.includes(b) || userServers.includes('all'); + const actions = document.createElement('div'); + actions.className = 'access-server-actions'; + if (hasAccess) { + const editBtn = document.createElement('button'); + editBtn.className = 'access-btn access-btn-edit'; + editBtn.title = `Edit permissions for ${escapeHtml(email)} on ${escapeHtml(b)}`; + editBtn.innerHTML = ` Edit`; + editBtn.addEventListener('click', () => { + const existing = getSavedPerms(email, b); + openPermsModal(email, b, () => openManageAccessModal(email), existing); + }); + const revokeBtn = document.createElement('button'); + revokeBtn.className = 'access-btn access-btn-revoke'; + revokeBtn.title = `Revoke access for ${escapeHtml(email)} on ${escapeHtml(b)}`; + revokeBtn.textContent = 'Revoke'; + revokeBtn.addEventListener('click', async () => { + revokeBtn.disabled = true; + try { + const r = await fetch(`/api/settings/accounts/${encodeURIComponent(email)}/remove`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': (accountsListEl._actionTokens || {}).removeAccess || '' + }, + body: JSON.stringify({ server: b }) + }); + if (!r.ok) { + const err = await r.json().catch(() => ({ error: 'failed' })); + alert(err.error || 'Failed to revoke access'); + revokeBtn.disabled = false; + } else { + setSavedPerms(email, b, {}); + openManageAccessModal(email); + } + } catch (err) { + console.error(err); + alert('Network error'); + revokeBtn.disabled = false; + } + }); + actions.appendChild(editBtn); + actions.appendChild(revokeBtn); + } else { + const addBtn = document.createElement('button'); + addBtn.className = 'access-btn access-btn-add'; + addBtn.innerHTML = ' Grant'; + addBtn.addEventListener('click', () => { + const remembered = getSavedPerms(email, b); + openPermsModal(email, b, () => openManageAccessModal(email), remembered); + }); + actions.appendChild(addBtn); + } + row.appendChild(left); + row.appendChild(actions); + list.appendChild(row); + }); + accountModalBody.innerHTML = ''; + accountModalBody.appendChild(list); + } catch (e) { + console.error(e); + accountModalBody.innerHTML = `

    Network error

    `; + } +} +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'); + } +}); +async function openPermsModal(email, server, onSaved, existingPerms) { + let serverPerms = null; + try { + const resp = await fetch(`/api/settings/accounts/${encodeURIComponent(email)}/perms?server=${encodeURIComponent(server)}`); + if (resp.ok) { + const data = await resp.json(); + if (data.ok && data.permissions) { + serverPerms = data.permissions; + } + } + } catch (e) { + console.error('Failed to fetch permissions from server:', e); + } + const permsToUse = serverPerms || existingPerms; + const isEdit = !!permsToUse && Object.keys(permsToUse).some(k => permsToUse[k]); + permModalTitle.textContent = isEdit + ? `Edit permissions for ${email} on ${server}` + : `Grant permissions for ${email} on ${server}`; + permModalBody.innerHTML = buildPermsFormHtml(permsToUse, !!serverPerms); + permModalOverlay.classList.add('show'); + permModal.classList.add('show'); + permModal.dataset.email = email; + permModal.dataset.server = server; + permModal.dataset.mode = isEdit ? 'edit' : 'add'; + permModal._onSaved = typeof onSaved === 'function' ? onSaved : null; + const selAll = document.getElementById('perm_all'); + const permInputs = Array.from(permModalBody.querySelectorAll('input[type="checkbox"].perm')); + selAll.checked = permInputs.length > 0 && permInputs.every(cb => cb.checked); + selAll.addEventListener('change', () => { + permInputs.forEach(cb => { cb.checked = selAll.checked; }); + }); + permInputs.forEach(cb => { + cb.addEventListener('change', () => { + selAll.checked = permInputs.length > 0 && permInputs.every(x => x.checked); + }); + }); +} +function closePermsModal() { + permModalOverlay.classList.remove('show'); + permModal.classList.remove('show'); + permModal.dataset.email = ''; + permModal.dataset.server = ''; + permModal.dataset.mode = ''; + permModal._onSaved = null; +} +function buildPermsFormHtml(existing, fromServer) { + const currentSummary = existing ? summarizePerms(existing) : null; + const permLabels = { + files_read: { label: 'Read files', icon: 'fa-file' }, + 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' }, + console_read: { label: 'Read console', icon: 'fa-terminal' }, + console_write: { label: 'Write to console', icon: 'fa-terminal' }, + server_stop: { label: 'Stop server', icon: 'fa-stop' }, + server_start: { label: 'Start server', icon: 'fa-play' }, + files_upload: { label: 'Upload files', icon: 'fa-upload' }, + files_create: { label: 'Create files/folders', icon: 'fa-folder-plus' }, + activity_logs: { label: 'View activity logs', icon: 'fa-clock-rotate-left' }, + backups_view: { label: 'View backups', icon: 'fa-box-archive' }, + backups_create: { label: 'Create backups', icon: 'fa-box-archive' }, + backups_delete: { label: 'Delete backups', icon: 'fa-trash-can' }, + scheduler_access: { label: 'Access scheduler', icon: 'fa-calendar-days' }, + scheduler_create: { label: 'Create schedules', icon: 'fa-calendar-plus' }, + scheduler_delete: { label: 'Delete schedules', icon: 'fa-calendar-xmark' }, + store_access: { label: 'Access store', icon: 'fa-store' }, + subdomain_show: { label: 'Subdomain Show', icon: 'fa-globe' }, + subdomain_add: { label: 'Subdomain Add', icon: 'fa-plus-circle' }, + server_reinstall: { label: 'Reinstall server', icon: 'fa-rotate' } + }; + const rows = PERM_KEYS.map((key) => { + const checked = existing ? !!existing[key] : (key === 'files_read'); + const perm = permLabels[key] || { label: key, icon: 'fa-circle' }; + return ` + + `; + }).join(''); + const info = fromServer + ? `
    + Current permissions: ${escapeHtml(currentSummary || 'None assigned')} +
    ` + : existing + ? `
    + Cached: ${escapeHtml(currentSummary)}. Toggle as needed. +
    ` + : `
    + Select the permissions you want to grant to this user. +
    `; + return ` + ${info} +
    + + ${rows} +
    + `; +} +permCancel.addEventListener('click', closePermsModal); +if (permCancelBtn) permCancelBtn.addEventListener('click', closePermsModal); +permModalOverlay.addEventListener('click', (e) => { if (e.target === permModalOverlay) closePermsModal(); }); +permSave.addEventListener('click', async () => { + const email = permModal.dataset.email || ''; + const server = permModal.dataset.server || ''; + if (!email || !server) { closePermsModal(); return; } + const permInputs = Array.from(permModalBody.querySelectorAll('input[type="checkbox"].perm')); + const selected = {}; + PERM_KEYS.forEach(k => selected[k] = false); + permInputs.forEach(cb => { + const key = cb.dataset.key; + selected[key] = !!cb.checked; + }); + const finalPerms = selected; + try { + permSave.disabled = true; + const res = await fetch(`/api/settings/accounts/${encodeURIComponent(email)}/grant-perms`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': (accountsListEl._actionTokens || {}).grantPerms || '' + }, + body: JSON.stringify({ server, permissions: finalPerms }) + }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + if (!res.ok) { + alert(data.error || 'Failed to grant permissions'); + return; + } + setSavedPerms(email, server, finalPerms); + const toast = document.createElement('div'); + toast.className = 'perm-success-toast'; + toast.innerHTML = ' Permissions saved successfully'; + document.body.appendChild(toast); + setTimeout(() => { toast.classList.add('show'); }, 10); + setTimeout(() => { + toast.classList.remove('show'); + setTimeout(() => toast.remove(), 300); + }, 2000); + closePermsModal(); + if (typeof permModal._onSaved === 'function') permModal._onSaved(); + } catch (e) { + console.error(e); + alert('Network error'); + } finally { + permSave.disabled = false; + } +}); +document.addEventListener('DOMContentLoaded', () => { + const WAIT_INTERVAL = 100; + const WAIT_TIMEOUT = 3000; + const sidebarSelector = '#sidebarNav'; + const pathnameDefaults = [ + { match: /^\/servers(?:\/|$)/i, panel: 'servers' }, + { match: /^\/settings(?:\/|$)/i, panel: 'preferences' } + ]; + function getRequestedPanel() { + 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); + const path = location.pathname || '/'; + for (const r of pathnameDefaults) { + if (r.match.test(path)) return r.panel; + } + return null; + } + function tryOpenPanel(panel) { + if (!panel) return false; + const btn = document.querySelector(`${sidebarSelector} button[data-panel="${panel}"]`); + if (btn) { + try { btn.focus?.(); btn.click(); } catch { btn.dispatchEvent(new MouseEvent('click', { bubbles: true, cancelable: true })); } + console.log(`[openPanel] opened panel: ${panel}`); + return true; + } + return false; + } + async function waitForSidebarAndOpen() { + const panel = getRequestedPanel(); + if (!panel) { console.log('[openPanel] no panel requested'); return; } + const start = Date.now(); + if (document.querySelector(sidebarSelector)) { if (tryOpenPanel(panel)) return; } + while (Date.now() - start < WAIT_TIMEOUT) { + const side = document.querySelector(sidebarSelector); + if (side) { if (tryOpenPanel(panel)) return; } + await new Promise(r => setTimeout(r, WAIT_INTERVAL)); + } + 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'); + console.log(`[openPanel] opened panel by id: ${panel}`); + } + } + async function maybeOpenAssistantRequestedAction() { + const action = getRequestedAssistantSettingsAction(); + if (!action) return; + await new Promise(resolve => setTimeout(resolve, 180)); + const handled = tryOpenRequestedAssistantSettingsAction(action); + if (!handled) { + console.warn(`[assistantSettings] failed to open action "${action}"`); + return; + } + clearRequestedAssistantSettingsAction(); + } + (async () => { + await waitForSidebarAndOpen(); + await maybeOpenAssistantRequestedAction(); + })(); +}); +async function fetchWithTimeout(url, opts = {}, ms = 2500) { + const ctrl = new AbortController(); + const t = setTimeout(() => ctrl.abort(), ms); + try { + const res = await fetch(url, { ...opts, signal: ctrl.signal }); + clearTimeout(t); + return res; + } catch (e) { + clearTimeout(t); + throw e; + } +} +function setNodeStatus(row, cls, label) { + const dot = row.querySelector('.status-dot'); + if (!dot) return; + dot.classList.remove('green', 'red', 'gray'); + dot.classList.add(cls); + if (label) dot.title = label; +} +function showCreateNodeModal(show) { + if (show) { + const restored = restoreCreateNodeDraft(); + if (!restored) { + createNodeConnectionTouched = false; + if (cn_under_cloudflare) cn_under_cloudflare.checked = false; + } + updateCreateNodeConnectionMode({ preferPanelHttps: true }); + createNodeOverlay.classList.add('show'); + createNodeModal.classList.add('show'); + } + else { + captureCreateNodeDraft(); + createNodeOverlay.classList.remove('show'); + createNodeModal.classList.remove('show'); + createNodeFeedback.textContent = ''; + } +} +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); }); +document.querySelectorAll('input[name="cn_ports_mode"]').forEach(r => { + r.addEventListener('change', () => { + const mode = document.querySelector('input[name="cn_ports_mode"]:checked').value; + cn_ports_range.style.display = (mode === 'range') ? 'grid' : 'none'; + cn_ports_list.style.display = (mode === 'list') ? 'block' : 'none'; + }); +}); +function bindEditPortsRadios() { + nodeModal.querySelectorAll('input[name="nm_ports_mode"]').forEach(r => { + r.addEventListener('change', () => { + const mode = nodeModal.querySelector('input[name="nm_ports_mode"]:checked').value; + nm_ports_range.style.display = (mode === 'range') ? 'grid' : 'none'; + nm_ports_list.style.display = (mode === 'list') ? 'block' : 'none'; + }); + }); +} +function parsePortsInput(mode, startEl, countEl, listEl) { + if (mode === 'range') { + const start = parseInt(startEl.value, 10); + const count = parseInt(countEl.value, 10); + if (!Number.isFinite(start) || start < 1 || start > 65535) throw new Error('Invalid start port'); + if (!Number.isFinite(count) || count < 1 || count > 1000) throw new Error('Invalid count'); + if (start + count - 1 > 65535) throw new Error('Port range exceeds 65535'); + return { mode: 'range', start, count }; + } else { + const raw = (listEl.value || '').trim(); + if (!raw) throw new Error('Provide at least one port'); + const parts = raw.split(',').map(s => parseInt(s.trim(), 10)).filter(n => Number.isFinite(n)); + const uniq = Array.from(new Set(parts)); + if (uniq.length === 0) throw new Error('No valid ports'); + if (uniq.length > 1000) throw new Error('Too many ports (max 1000)'); + if (uniq.some(p => p < 1 || p > 65535)) throw new Error('Ports must be 1..65535'); + return { mode: 'list', ports: uniq }; + } +} +function countPorts(alloc) { + if (!alloc) return 0; + if (alloc.mode === 'range') return Math.max(0, parseInt(alloc.count || 0, 10)); + if (alloc.mode === 'list' && Array.isArray(alloc.ports)) return alloc.ports.length; + return 0; +} +function portsSummary(alloc) { + if (!alloc) return '—'; + if (alloc.mode === 'range') return `range ${alloc.start}..${alloc.start + alloc.count - 1} (${alloc.count})`; + if (alloc.mode === 'list') return `${alloc.ports.length} ports`; + return '—'; +} +async function loadNodes(page, search) { + if (typeof page === 'undefined') page = _nodesPage; + if (typeof search === 'undefined') search = _nodesSearch; + _nodesPage = page; + _nodesSearch = search; + const isFirstLoad = !nodesListEl.querySelector('.node-row'); + if (isFirstLoad) { + nodesListEl.innerHTML = `
    Loading…
    `; + } + try { + const params = new URLSearchParams({ page: String(page), limit: String(_nodesLimit) }); + if (search) params.set('search', search); + const res = await fetch('/api/nodes?' + params.toString()); + if (!res.ok) { + nodesListEl.innerHTML = `
    Failed to load nodes
    `; + return; + } + const data = await res.json().catch(() => ({ nodes: [], total: 0, page: 1, totalPages: 1 })); + const nodes = Array.isArray(data.nodes) ? data.nodes : []; + const total = Number(data.total || nodes.length); + const totalPages = Number(data.totalPages || 1); + renderNodes(nodes); + renderNodesPagination(page, totalPages, total); + } catch (e) { + console.error(e); + nodesListEl.innerHTML = `
    Network error
    `; + } +} +let _nodesPage = 1; +let _nodesSearch = ''; +const _nodesLimit = 50; +let _serversPage = 1; +let _serversSearch = ''; +const _serversLimit = 50; +let _serversSearchTimer; +let _templatesPage = 1; +let _templatesSearch = ''; +const _templatesLimit = 50; +let _templatesSearchTimer; +let _nodesTimer; +let _nodesSearchTimer; +const nodesSearchInput = document.getElementById('nodesSearchInput'); +const nodesPaginationEl = document.getElementById('nodesPagination'); + +function stopNodesPolling() { clearInterval(_nodesTimer); _nodesTimer = null; } +function startNodesPolling() { + stopNodesPolling(); + _nodesTimer = setInterval(() => loadNodes(), 30000); +} + +document.querySelector('button[data-panel="nodes"]').addEventListener('click', () => { + _nodesPage = 1; + loadNodes(); + startNodesPolling(); +}); +sidebarNav.addEventListener('click', (e) => { + const btn = e.target.closest('button'); + if (btn && btn.dataset.panel !== 'nodes') stopNodesPolling(); +}); + +if (nodesSearchInput) { + nodesSearchInput.addEventListener('input', () => { + clearTimeout(_nodesSearchTimer); + _nodesSearchTimer = setTimeout(() => { + _nodesPage = 1; + loadNodes(1, nodesSearchInput.value.trim()); + }, 300); + }); +} + +const serversSearchInput = document.getElementById('serversSearchInput'); +if (serversSearchInput) { + serversSearchInput.addEventListener('input', () => { + clearTimeout(_serversSearchTimer); + _serversSearchTimer = setTimeout(() => { + _serversPage = 1; + loadServers(1, serversSearchInput.value.trim()); + }, 300); + }); +} + +const templatesSearchInput = document.getElementById('templatesSearchInput'); +if (templatesSearchInput) { + templatesSearchInput.addEventListener('input', () => { + clearTimeout(_templatesSearchTimer); + _templatesSearchTimer = setTimeout(() => { + _templatesPage = 1; + loadTemplates(1, templatesSearchInput.value.trim()); + }, 300); + }); +} + +function renderNodesPagination(currentPage, totalPages, total) { + if (!nodesPaginationEl) return; + if (totalPages <= 1) { nodesPaginationEl.innerHTML = ''; return; } + const startItem = (currentPage - 1) * _nodesLimit + 1; + const endItem = Math.min(currentPage * _nodesLimit, total); + nodesPaginationEl.innerHTML = ` +
    + ${startItem}–${endItem} of ${total} nodes +
    + + Page ${currentPage} / ${totalPages} + +
    +
    + `; + nodesPaginationEl.querySelectorAll('button[data-page]').forEach(btn => { + btn.addEventListener('click', () => { + const p = parseInt(btn.dataset.page, 10); + if (p >= 1 && p <= totalPages) loadNodes(p); + }); + }); +} + +function renderNodes(nodes) { + if (!nodes || nodes.length === 0) { + nodesListEl.innerHTML = ` +
    +
    ${_nodesSearch ? 'No nodes match your search.' : "You haven't created any node yet."}
    + ${!_nodesSearch ? '' : ''} +
    + `; + const emptyCreateBtn = nodesListEl.querySelector('[data-open-create-node]'); + if (emptyCreateBtn && openCreateNodeBtn) { + emptyCreateBtn.addEventListener('click', () => openCreateNodeBtn.click()); + } + return; + } + const frag = document.createDocumentFragment(); + const now = Date.now(); + for (let i = 0; i < nodes.length; i++) { + const n = nodes[i]; + const row = document.createElement('div'); + row.className = 'node-row'; + const nodeId = n.id || n.uuid || ''; + row.dataset.id = nodeId; + const lastSeen = Number(n.last_seen || n.lastSeen || n.lastHeartbeat || 0); + const fresh = lastSeen > 0 && (now - lastSeen) < 120000; + let statusClass = 'gray'; + let statusLabel = 'No recent heartbeat'; + if (n.online === false) { + statusClass = 'red'; + statusLabel = 'Offline'; + } + if (fresh || n.online === true) { + if (n.port_ok === false) { + statusClass = 'red'; + statusLabel = 'Heartbeat ok, port unreachable'; + } else if (n.port_ok === true) { + statusClass = 'green'; + statusLabel = 'Online'; + } else { + statusClass = 'gray'; + statusLabel = 'Checking…'; + } + } + const portCount = countPorts(n.ports); + row.innerHTML = ` +
    + +
    +
    +
    ${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}
    +
    +
    +
    + ID: ${escapeHtml(nodeId.toString())} + + + +
    + `; + row.querySelector('.open-node-update').addEventListener('click', (ev) => { + ev.stopPropagation(); + if (typeof window.openNodeUpdateModal === 'function') window.openNodeUpdateModal(nodeId); + }); + row.querySelector('.open-stats').addEventListener('click', (ev) => { ev.stopPropagation(); openNodeStatsModal(nodeId, n.name); }); + row.querySelector('.open-node').addEventListener('click', (ev) => { ev.stopPropagation(); openNodeModal(nodeId); }); + row.addEventListener('click', () => openNodeModal(nodeId)); + frag.appendChild(row); + } + nodesListEl.innerHTML = ''; + nodesListEl.appendChild(frag); +} +if (typeof window.io === 'function') { + try { + const _nodeStatusSocket = window.io(); + _nodeStatusSocket.on('node:status', (data) => { + if (!data || !data.id) return; + const row = nodesListEl.querySelector(`.node-row[data-id="${data.id}"]`); + if (!row) return; + if (data.online) { + setNodeStatus(row, 'green', 'Online'); + } else { + setNodeStatus(row, 'red', 'Offline / unreachable'); + } + }); + _nodeStatusSocket.emit('dashboard:subscribe', []); + } catch { } +} + +function isIPAddress(addr) { + if (!addr) return true; + if (/^\d{1,3}(\.\d{1,3}){3}$/.test(addr)) return true; + if (/^\[?[0-9a-fA-F:]+\]?$/.test(addr)) return true; + return false; +} +function extractHostname(value) { + const raw = String(value || '').trim(); + if (!raw) return ''; + if (/^https?:\/\//i.test(raw)) { + try { + return new URL(raw).hostname; + } catch { + return ''; + } + } + const withoutPath = raw.split(/[/?#]/)[0]; + if (withoutPath.startsWith('[')) { + const end = withoutPath.indexOf(']'); + return end > 0 ? withoutPath.slice(1, end) : withoutPath; + } + const colonCount = (withoutPath.match(/:/g) || []).length; + if (colonCount === 1) return withoutPath.split(':')[0]; + return withoutPath; +} +function isLoopbackHostname(hostname) { + const host = String(hostname || '').trim().toLowerCase(); + return host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]'; +} +function canUseHttpsForNodeAddress(address) { + const host = extractHostname(address); + return !!host && !isIPAddress(host) && !isLoopbackHostname(host); +} +function isNodeUnderCloudflare(node) { + const buildConfig = node && typeof node.buildConfig === 'object' ? node.buildConfig : {}; + return !!(node?.under_cloudflare || node?.cloudflare_proxy || buildConfig.under_cloudflare || buildConfig.cloudflare_proxy); +} +const CLOUDFLARE_HTTPS_EDGE_PORTS = new Set([443, 2053, 2083, 2087, 2096, 8443]); +function isCloudflareHttpsPort(port) { + const value = Number(port); + return Number.isInteger(value) && CLOUDFLARE_HTTPS_EDGE_PORTS.has(value); +} +function preferCloudflareDaemonPort(input) { + if (!input) return; + const current = parseInt(input.value || '8080', 10); + if (!isCloudflareHttpsPort(current)) input.value = '8443'; +} +function defaultNodeTlsPaths(node) { + if (!node || !node.ssl_enabled) return { cert: '', key: '' }; + const host = extractHostname(node.address || ''); + if (!canUseHttpsForNodeAddress(host) || !/^[a-z0-9.-]+$/i.test(host)) return { cert: '', key: '' }; + return { + cert: `/etc/letsencrypt/live/${host.toLowerCase()}/fullchain.pem`, + key: `/etc/letsencrypt/live/${host.toLowerCase()}/privkey.pem`, + }; +} +function isPanelOnHttpsDomain() { + const host = String(window.location.hostname || '').trim(); + return window.location.protocol === 'https:' && !!host && !isIPAddress(host) && !isLoopbackHostname(host); +} +function updateNodeConnectionCopy(checkbox, label, help, cloudflareToggle = null) { + const httpsEnabled = !!(checkbox && checkbox.checked); + const underCloudflare = !!(cloudflareToggle && cloudflareToggle.checked); + if (label) label.textContent = httpsEnabled ? 'HTTPS Connection' : 'HTTP Connection'; + if (help) { + if (!httpsEnabled) { + help.textContent = 'Communicate with this node over HTTP.'; + } else if (underCloudflare) { + help.textContent = 'Communicate with this node through Cloudflare over HTTPS.'; + } else { + help.textContent = "Communicate with this node over HTTPS (requires Let's Encrypt or custom SSL certificate on the node)."; + } + } +} +function updateCloudflareToggle(sslCheckbox, row, toggle) { + const show = !!(sslCheckbox && sslCheckbox.checked); + if (row) row.style.display = show ? '' : 'none'; + if (!show && toggle) toggle.checked = false; +} +let createNodeConnectionTouched = false; +let createNodeDraft = null; + +function getCheckedRadioValue(name, root = document) { + return root.querySelector(`input[name="${name}"]:checked`)?.value || ''; +} + +function setCheckedRadioValue(name, value, root = document) { + const el = root.querySelector(`input[name="${name}"][value="${value}"]`); + if (el) { + el.checked = true; + el.dispatchEvent(new Event('change')); + } +} + +function captureCreateNodeDraft() { + createNodeDraft = { + name: cn_name?.value || '', + address: cn_address?.value || '', + cpu_cores: cn_cpu_cores?.value || '', + ram_gb: cn_ram_gb?.value || '', + disk_gb: cn_disk_gb?.value || '', + ports_mode: getCheckedRadioValue('cn_ports_mode'), + port_start: cn_port_start?.value || '', + port_count: cn_port_count?.value || '', + 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, + }; +} + +function restoreCreateNodeDraft() { + if (!createNodeDraft) return false; + if (cn_name) cn_name.value = createNodeDraft.name; + if (cn_address) cn_address.value = createNodeDraft.address; + if (cn_cpu_cores) cn_cpu_cores.value = createNodeDraft.cpu_cores; + if (cn_ram_gb) cn_ram_gb.value = createNodeDraft.ram_gb; + if (cn_disk_gb) cn_disk_gb.value = createNodeDraft.disk_gb; + if (createNodeDraft.ports_mode) setCheckedRadioValue('cn_ports_mode', createNodeDraft.ports_mode); + if (cn_port_start) cn_port_start.value = createNodeDraft.port_start; + if (cn_port_count) cn_port_count.value = createNodeDraft.port_count; + 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; + return true; +} + +function resetCreateNodeForm() { + if (cn_name) cn_name.value = ''; + if (cn_address) cn_address.value = ''; + if (cn_cpu_cores) cn_cpu_cores.value = ''; + if (cn_ram_gb) cn_ram_gb.value = ''; + if (cn_disk_gb) cn_disk_gb.value = ''; + setCheckedRadioValue('cn_ports_mode', 'range'); + if (cn_port_start) cn_port_start.value = ''; + if (cn_port_count) cn_port_count.value = ''; + 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; + updateCreateNodeConnectionMode({ preferPanelHttps: true }); +} + +function updateCreateNodeConnectionMode(options = {}) { + if (!cn_ssl_row) return; + const address = String(cn_address?.value || '').trim(); + const addressAllowsHttps = canUseHttpsForNodeAddress(address); + const panelHttpsDomain = isPanelOnHttpsDomain(); + const shouldShow = addressAllowsHttps || (panelHttpsDomain && !address); + if (!shouldShow) { + cn_ssl_row.style.display = 'none'; + if (cn_ssl_enabled) cn_ssl_enabled.checked = false; + updateNodeConnectionCopy(cn_ssl_enabled, cn_connection_label, cn_connection_help, cn_under_cloudflare); + updateCloudflareToggle(cn_ssl_enabled, cn_under_cloudflare_row, cn_under_cloudflare); + return; + } + cn_ssl_row.style.display = ''; + if (options.preferPanelHttps && panelHttpsDomain && !createNodeConnectionTouched) { + if (cn_ssl_enabled) cn_ssl_enabled.checked = true; + } + updateNodeConnectionCopy(cn_ssl_enabled, cn_connection_label, cn_connection_help, cn_under_cloudflare); + updateCloudflareToggle(cn_ssl_enabled, cn_under_cloudflare_row, cn_under_cloudflare); +} +function updateEditNodeConnectionMode() { + if (!nm_ssl_row) return; + const address = String(nm_address?.value || '').trim(); + if (canUseHttpsForNodeAddress(address)) { + nm_ssl_row.style.display = ''; + } else { + nm_ssl_row.style.display = 'none'; + if (nm_ssl_enabled) nm_ssl_enabled.checked = false; + } + updateNodeConnectionCopy(nm_ssl_enabled, nm_connection_label, nm_connection_help, nm_under_cloudflare); + updateCloudflareToggle(nm_ssl_enabled, nm_under_cloudflare_row, nm_under_cloudflare); +} +if (cn_ssl_enabled) { + cn_ssl_enabled.addEventListener('change', () => { + createNodeConnectionTouched = true; + updateNodeConnectionCopy(cn_ssl_enabled, cn_connection_label, cn_connection_help, cn_under_cloudflare); + updateCloudflareToggle(cn_ssl_enabled, cn_under_cloudflare_row, cn_under_cloudflare); + }); +} +if (cn_under_cloudflare) { + cn_under_cloudflare.addEventListener('change', () => { + if (cn_under_cloudflare.checked) preferCloudflareDaemonPort(cn_daemon_port); + updateNodeConnectionCopy(cn_ssl_enabled, cn_connection_label, cn_connection_help, cn_under_cloudflare); + }); +} +if (cn_address && cn_ssl_row) { + cn_address.addEventListener('input', () => updateCreateNodeConnectionMode({ preferPanelHttps: true })); +} + +createNodeSave.addEventListener('click', async () => { + try { + createNodeFeedback.textContent = ''; + const name = cn_name.value.trim(); + const address = cn_address.value.trim(); + const cpu_cores = cn_cpu_cores ? parseInt(cn_cpu_cores.value, 10) : 0; + const ram_gb = parseInt(cn_ram_gb.value, 10); + const disk_gb = parseInt(cn_disk_gb.value, 10); + const mode = document.querySelector('input[name="cn_ports_mode"]:checked').value; + if (!name) throw new Error('Name required'); + if (!address) throw new Error('Address required'); + if (!Number.isFinite(ram_gb) || ram_gb < 1) throw new Error('Invalid RAM'); + if (!Number.isFinite(disk_gb) || disk_gb < 10) throw new Error('Invalid Disk'); + const ports = parsePortsInput(mode, cn_port_start, cn_port_count, cn_port_list); + const max_upload_mb = parseInt(cn_max_upload_mb?.value || '10240', 10); + 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)) { + 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 + }; + createNodeSave.disabled = true; + createNodeSave.innerHTML = 'Creating…'; + const res = await fetch('/api/nodes', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }); + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + if (!res.ok) { + createNodeFeedback.textContent = [data.error || 'Failed to create node', data.detail || ''].filter(Boolean).join('\n'); + createNodeSave.disabled = false; createNodeSave.innerHTML = ' Create Node'; + return; + } + showCreateNodeModal(false); + createNodeDraft = null; + resetCreateNodeForm(); + resetModalUnsavedState(createNodeOverlay); + await loadNodes(1, ''); + if (data.id || data.uuid) { + openNodeModal(data.id || data.uuid, true); + } + } catch (err) { + console.error(err); + createNodeFeedback.textContent = err.message || 'Error'; + } finally { + createNodeSave.disabled = false; + createNodeSave.innerHTML = ' Create Node'; + } +}); +function showNodeModal(show, options = {}) { + if (show) { + nodeModalOverlay.classList.add('show'); + nodeModal.classList.add('show'); + window.setTimeout(() => syncModalBaseline(nodeModalOverlay), 0); + return true; + } + if (!options.force && !confirmDiscardModalChanges(nodeModalOverlay)) return false; + nodeModalOverlay.classList.remove('show'); + nodeModal.classList.remove('show'); + resetModalUnsavedState(nodeModalOverlay); + return true; +} +nodeModalClose.addEventListener('click', () => showNodeModal(false)); +if (nodeModalCancelBtn) nodeModalCancelBtn.addEventListener('click', () => showNodeModal(false)); +nodeModalOverlay.addEventListener('click', (e) => { if (e.target === nodeModalOverlay) showNodeModal(false); }); +nm_tabs.forEach(btn => { + btn.addEventListener('click', () => { + nm_tabs.forEach(b => b.classList.remove('active')); btn.classList.add('active'); + const tab = btn.dataset.tab; + [tab_build, tab_linking, tab_deletion].forEach(p => p.classList.remove('active')); + if (tab === 'build') { tab_build.classList.add('active'); if (buildFooter) buildFooter.style.display = 'flex'; } + if (tab === 'linking') { tab_linking.classList.add('active'); if (buildFooter) buildFooter.style.display = 'none'; } + if (tab === 'deletion') { tab_deletion.classList.add('active'); if (buildFooter) buildFooter.style.display = 'none'; } + }); +}); +let CURRENT_NODE = null; +async function openNodeModal(id, focusLinking = false) { + try { + const res = await fetch(`/api/nodes/${encodeURIComponent(id)}`); + const node = await res.json(); + if (!res.ok) throw new Error(node.error || 'Failed to load node'); + CURRENT_NODE = node; + fillNodeModal(node, focusLinking); + showNodeModal(true); + } catch (e) { + alert(e.message || 'Failed to open node'); + } +} +function setRadio(name, value) { + const el = nodeModal.querySelector(`input[name="${name}"][value="${value}"]`); + if (el) { el.checked = true; el.dispatchEvent(new Event('change')); } +} +function fillNodeModal(node, focusLinking = false) { + nm_title.innerHTML = ` ${escapeHtml(node.name || 'Node')}`; + nm_subtitle.textContent = `${escapeHtml(node.address || '0.0.0.0')} • ${Number(node.cpu_cores || 0)} cores • ${(Number(node.ram_mb || 0) / 1024 | 0)} GB RAM`; + nm_name.value = node.name || ''; + nm_address.value = node.address || ''; + if (nm_cpu_cores) nm_cpu_cores.value = Number(node.cpu_cores || 0) || ''; + nm_ram_gb.value = (Number(node.ram_mb || 0) / 1024 | 0); + 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; + updateEditNodeConnectionMode(); + } + const alloc = node.ports || { mode: 'range', start: 25565, count: 10 }; + if (alloc.mode === 'list') { + setRadio('nm_ports_mode', 'list'); + nm_ports_range.style.display = 'none'; + nm_ports_list.style.display = 'block'; + nm_port_list.value = Array.isArray(alloc.ports) ? alloc.ports.join(',') : ''; + } else { + setRadio('nm_ports_mode', 'range'); + nm_ports_range.style.display = 'grid'; + nm_ports_list.style.display = 'none'; + nm_port_start.value = alloc.start || ''; + nm_port_count.value = alloc.count || ''; + } + bindEditPortsRadios(); + nm_configYml.value = generateNodeConfigYml(node); + nm_cmd.value = ''; + nm_cmd.style.display = 'none'; + nm_cmdActions.style.display = 'none'; + nm_tabs.forEach(b => b.classList.remove('active')); + [tab_build, tab_linking, tab_deletion].forEach(p => p.classList.remove('active')); + if (focusLinking) { + nodeModal.querySelector('.node-tab[data-tab="linking"]').classList.add('active'); + tab_linking.classList.add('active'); + if (buildFooter) buildFooter.style.display = 'none'; + } else { + nodeModal.querySelector('.node-tab[data-tab="build"]').classList.add('active'); + tab_build.classList.add('active'); + if (buildFooter) buildFooter.style.display = 'flex'; + } +} +function generateNodeConfigYml(node) { + const panelUrl = location.origin; + const uuid = node.uuid || node.id || ''; + const token_id = node.token_id || ''; + const token = node.token || ''; + const sslEnabled = !!node.ssl_enabled; + const tlsPaths = defaultNodeTlsPaths(node); + const yml = [ + `debug: false`, + `uuid: ${uuid}`, + `token_id: ${token_id}`, + `token: ${token}`, + `api:`, + ` host: 0.0.0.0`, + ` port: ${node.api_port || 8080}`, + ` ssl:`, + ` enabled: ${sslEnabled}`, + ` cert: "${tlsPaths.cert}"`, + ` key: "${tlsPaths.key}"`, + ` upload_limit: ${node.max_upload_mb || 10240}`, + `system:`, + ` data: /var/lib/node`, + ` sftp:`, + ` bind_port: ${node.sftp_port || 2022}`, + `allowed_mounts: []`, + `panel:`, + ` url: ${panelUrl}`, + ` node_id: ${node.id || node.uuid || ''}` + ].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`; +} +function legacyCopyToClipboard(text) { + return new Promise((resolve, reject) => { + const textArea = document.createElement("textarea"); + textArea.value = text; + textArea.style.position = "fixed"; + textArea.style.left = "-9999px"; + textArea.style.top = "0"; + document.body.appendChild(textArea); + textArea.focus(); + textArea.select(); + try { + const successful = document.execCommand('copy'); + if (successful) resolve(); + else reject(new Error('Copy failed')); + } catch (err) { + reject(err); + } finally { + document.body.removeChild(textArea); + } + }); +} + +function copyToClipboard(text) { + const value = String(text == null ? '' : text); + if (navigator.clipboard && navigator.clipboard.writeText) { + return navigator.clipboard.writeText(value).catch(() => legacyCopyToClipboard(value)); + } + return legacyCopyToClipboard(value); +} + +nm_copyConfig.addEventListener('click', () => { + copyToClipboard(nm_configYml.value || '').then(() => { nm_copyConfig.innerHTML = ''; setTimeout(() => nm_copyConfig.innerHTML = '', 1500); }); +}); +nm_downloadConfig.addEventListener('click', () => { + const blob = new Blob([nm_configYml.value || ''], { type: 'text/yaml' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; a.download = 'config.yml'; a.click(); + URL.revokeObjectURL(url); +}); +nm_showCmd.addEventListener('click', () => { + if (!CURRENT_NODE) return; + nm_cmd.value = generateOneTimeCommand(CURRENT_NODE); + nm_cmd.style.display = 'block'; + nm_cmdActions.style.display = 'flex'; +}); +nm_copyCmd.addEventListener('click', () => { + copyToClipboard(nm_cmd.value || '').then(() => { nm_copyCmd.innerHTML = ' Copied'; setTimeout(() => nm_copyCmd.innerHTML = ' Copy Command', 1500); }); +}); +if (nm_address && nm_ssl_row) { + nm_address.addEventListener('input', () => updateEditNodeConnectionMode()); +} +if (nm_ssl_enabled) { + nm_ssl_enabled.addEventListener('change', () => { + updateNodeConnectionCopy(nm_ssl_enabled, nm_connection_label, nm_connection_help, nm_under_cloudflare); + updateCloudflareToggle(nm_ssl_enabled, nm_under_cloudflare_row, nm_under_cloudflare); + }); +} +if (nm_under_cloudflare) { + nm_under_cloudflare.addEventListener('change', () => { + if (nm_under_cloudflare.checked) preferCloudflareDaemonPort(nm_daemon_port); + updateNodeConnectionCopy(nm_ssl_enabled, nm_connection_label, nm_connection_help, nm_under_cloudflare); + }); +} +nm_save.addEventListener('click', async () => { + if (!CURRENT_NODE) return; + try { + nm_save.disabled = true; nm_save.innerHTML = 'Saving…'; nm_saveFeedback.textContent = ''; + const name = nm_name.value.trim(); + const address = nm_address.value.trim(); + const cpu_cores = nm_cpu_cores ? parseInt(nm_cpu_cores.value, 10) : 0; + const ram_gb = parseInt(nm_ram_gb.value, 10); + const disk_gb = parseInt(nm_disk_gb.value, 10); + const mode = nodeModal.querySelector('input[name="nm_ports_mode"]:checked')?.value || 'range'; + if (!name) throw new Error('Name required'); + if (!address) throw new Error('Address required'); + if (!Number.isFinite(ram_gb) || ram_gb < 1) throw new Error('Invalid RAM'); + if (!Number.isFinite(disk_gb) || disk_gb < 10) throw new Error('Invalid Disk'); + const ports = parsePortsInput(mode, nm_port_start, nm_port_count, nm_port_list); + const max_upload_mb = parseInt(nm_max_upload_mb?.value || '10240', 10); + 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 res = await fetch(`/api/nodes/${encodeURIComponent(CURRENT_NODE.id || CURRENT_NODE.uuid)}`, { + method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error([data.error || 'Failed to save', data.detail || ''].filter(Boolean).join('\n')); + CURRENT_NODE = Object.assign({}, CURRENT_NODE, data, payload); + nm_configYml.value = generateNodeConfigYml(CURRENT_NODE); + nm_saveFeedback.textContent = 'Saved'; + syncModalBaseline(nodeModalOverlay); + await loadNodes(); + } catch (e) { + nm_saveFeedback.textContent = e.message || 'Error'; + } finally { + nm_save.disabled = false; nm_save.innerHTML = ' Save Changes'; + } +}); +nm_delete.addEventListener('click', async () => { + if (!CURRENT_NODE) return; + const ok = confirm(`Delete node "${CURRENT_NODE.name}"? This action is permanent.`); + if (!ok) 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 data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Failed to delete'); + nm_deleteFeedback.textContent = 'Deleted'; + showNodeModal(false, { force: true }); + await loadNodes(); + } catch (e) { + nm_deleteFeedback.textContent = e.message || 'Error'; + } finally { + nm_delete.disabled = false; + } +}); + +document.querySelectorAll('.toggle-pass').forEach(btn => { + const input = btn.parentElement.querySelector('input'); + const icon = btn.querySelector('i'); + + btn.addEventListener('click', () => { + const isPassword = input.type === 'password'; + input.type = isPassword ? 'text' : 'password'; + + icon.classList.toggle('fa-eye', !isPassword); + icon.classList.toggle('fa-eye-slash', isPassword); + }); +}); + +(function () { + const rateLimiterCard = document.getElementById('rateLimiterCard'); + const rateLimiterToggle = document.getElementById('rateLimiterToggle'); + const rateLimiterDetails = document.getElementById('rateLimiterDetails'); + const rateLimiterLimit = document.getElementById('rateLimiterLimit'); + const rateLimiterWindow = document.getElementById('rateLimiterWindow'); + const rateLimiterSave = document.getElementById('rateLimiterSave'); + const rateLimiterFeedback = document.getElementById('rateLimiterFeedback'); + const rateLimiterSummary = document.getElementById('rateLimiterSummary'); + + if (!rateLimiterCard) return; + + const rateLimiterSwitchLabel = rateLimiterCard.querySelector('.switch'); + if (rateLimiterSwitchLabel) { + rateLimiterSwitchLabel.addEventListener('click', (e) => e.stopPropagation()); + } + + let detailsOpen = false; + + function updateSummary() { + const limit = parseInt(rateLimiterLimit.value, 10) || 5; + const window = parseInt(rateLimiterWindow.value, 10) || 120; + rateLimiterSummary.textContent = `${limit} requests per ${window} seconds`; + } + + function showFeedback(msg, isError = false) { + rateLimiterFeedback.textContent = msg; + rateLimiterFeedback.style.color = isError ? '#ef4444' : '#22c55e'; + setTimeout(() => { rateLimiterFeedback.textContent = ''; }, 3000); + } + + let securityActionTokens = {}; + + async function loadSecuritySettings() { + try { + const res = await fetch('/api/settings/security'); + if (!res.ok) return; + const data = await res.json(); + rateLimiterToggle.checked = !!data.rate_limiting; + rateLimiterLimit.value = data.limit || 5; + rateLimiterWindow.value = data.window_seconds || 120; + securityActionTokens = data.actionTokens || {}; + updateSummary(); + } catch (e) { + console.error('Failed to load security settings:', e); + } + } + + async function saveSecuritySettings() { + const rate_limiting = rateLimiterToggle.checked; + const limit = parseInt(rateLimiterLimit.value, 10); + const window_seconds = parseInt(rateLimiterWindow.value, 10); + + if (!limit || limit < 1 || limit > 10000) { + showFeedback('Limit must be between 1 and 10000', true); + return; + } + if (!window_seconds || window_seconds < 1 || window_seconds > 86400) { + showFeedback('Window must be between 1 and 86400 seconds', true); + return; + } + + rateLimiterSave.disabled = true; + try { + const res = await fetch('/api/settings/security', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': securityActionTokens.updateSecurity || '' + }, + body: JSON.stringify({ rate_limiting, limit, window_seconds }) + }); + const data = await res.json(); + if (!res.ok) { + showFeedback(data.error || 'Failed to save', true); + } else { + showFeedback('Settings saved successfully!'); + await loadSecuritySettings(); + } + } catch (e) { + showFeedback('Network error', true); + } finally { + rateLimiterSave.disabled = false; + } + } + + rateLimiterCard.addEventListener('click', (e) => { + if (e.target.closest('.switch') || e.target.closest('input') || e.target.closest('button')) return; + detailsOpen = !detailsOpen; + rateLimiterDetails.style.display = detailsOpen ? 'block' : 'none'; + }); + + rateLimiterToggle.addEventListener('change', async () => { + await saveSecuritySettings(); + }); + + rateLimiterLimit.addEventListener('input', updateSummary); + rateLimiterWindow.addEventListener('input', updateSummary); + + rateLimiterSave.addEventListener('click', (e) => { + e.stopPropagation(); + saveSecuritySettings(); + }); + + [rateLimiterLimit, rateLimiterWindow].forEach(el => { + el.addEventListener('click', (e) => e.stopPropagation()); + }); + + loadSecuritySettings(); + + document.querySelector('button[data-panel="security"]')?.addEventListener('click', loadSecuritySettings); +})(); + +(function () { + const captchaCard = document.getElementById('captchaCard'); + if (!captchaCard) return; + + const captchaToggle = document.getElementById('captchaToggle'); + const captchaDetails = document.getElementById('captchaDetails'); + const captchaModalOverlay = document.getElementById('captchaModalOverlay'); + const captchaModal = document.getElementById('captchaModal'); + const captchaSiteKey = document.getElementById('captchaSiteKey'); + const captchaSecretKey = document.getElementById('captchaSecretKey'); + const captchaSecretToggle = document.getElementById('captchaSecretToggle'); + const captchaModalClose = document.getElementById('captchaModalClose'); + const captchaModalCancel = document.getElementById('captchaModalCancel'); + const captchaModalSave = document.getElementById('captchaModalSave'); + const captchaModalFeedback = document.getElementById('captchaModalFeedback'); + + const captchaSwitchLabel = captchaCard.querySelector('.switch'); + if (captchaSwitchLabel) { + captchaSwitchLabel.addEventListener('click', (e) => e.stopPropagation()); + } + + let captchaEnabled = false; + let isLoading = false; + let detailsOpen = false; + let pendingToggleState = null; + + function showFeedback(msg, isError = false) { + if (!captchaModalFeedback) return; + captchaModalFeedback.textContent = msg; + captchaModalFeedback.style.color = isError ? '#ef4444' : '#22c55e'; + if (msg) { + setTimeout(() => { + if (captchaModalFeedback) captchaModalFeedback.textContent = ''; + }, 4000); + } + } + + function openModal() { + if (!captchaModalOverlay || !captchaModal) return; + captchaSiteKey.value = ''; + captchaSecretKey.value = ''; + captchaSecretKey.type = 'password'; + if (captchaSecretToggle) { + const icon = captchaSecretToggle.querySelector('i'); + if (icon) icon.className = 'fa-solid fa-eye'; + } + showFeedback(''); + captchaModalOverlay.setAttribute('aria-hidden', 'false'); + captchaModalOverlay.style.display = 'flex'; + captchaModalOverlay.classList.add('show'); + void captchaModal.offsetWidth; + captchaModal.classList.add('show'); + setTimeout(() => captchaSiteKey.focus(), 100); + } + + document.addEventListener(ASSISTANT_SETTINGS_ACTION_EVENT, (event) => { + if (event?.detail?.action === 'captcha') { + openModal(); + } + }); + + function closeModal(revertToggle = false) { + if (!captchaModalOverlay) return; + const focusTarget = captchaToggle || document.body; + focusTarget.focus(); + setTimeout(() => { + captchaModalOverlay.setAttribute('aria-hidden', 'true'); + captchaModalOverlay.classList.remove('show'); + if (captchaModal) captchaModal.classList.remove('show'); + captchaModalOverlay.style.display = 'none'; + }, 10); + if (revertToggle && pendingToggleState !== null) { + captchaToggle.checked = !pendingToggleState; + } + pendingToggleState = null; + } + + function updateUI() { + if (captchaToggle) captchaToggle.checked = captchaEnabled; + if (captchaDetails) captchaDetails.style.display = captchaEnabled ? 'block' : 'none'; + } + + async function loadCaptchaStatus() { + if (isLoading) return; + isLoading = true; + try { + const res = await fetch('/api/settings/security'); + if (!res.ok) return; + const data = await res.json(); + captchaEnabled = !!data.captcha_enabled; + if (data.actionTokens) securityActionTokens = data.actionTokens; + updateUI(); + } catch (e) { + console.error('Failed to load captcha status:', e); + } finally { + isLoading = false; + } + } + + captchaToggle.addEventListener('change', async () => { + const newState = captchaToggle.checked; + pendingToggleState = newState; + + if (newState) { + openModal(); + } else { + if (!confirm('Are you sure you want to disable captcha? This will remove your configured keys.')) { + captchaToggle.checked = true; + pendingToggleState = null; + return; + } + + try { + const res = await fetch('/api/settings/captcha', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': securityActionTokens.updateCaptcha || '' + }, + body: JSON.stringify({ enabled: false }) + }); + const data = await res.json(); + if (!res.ok) { + alert(data.error || 'Failed to disable captcha'); + captchaToggle.checked = true; + } else { + captchaEnabled = false; + updateUI(); + await loadCaptchaStatus(); + } + } catch (e) { + alert('Network error'); + captchaToggle.checked = true; + } + pendingToggleState = null; + } + }); + + captchaCard.addEventListener('click', (e) => { + if (e.target.closest('.switch') || e.target.closest('input') || e.target.closest('button')) return; + if (!captchaEnabled) return; + detailsOpen = !detailsOpen; + if (captchaDetails) captchaDetails.style.display = detailsOpen ? 'block' : 'none'; + }); + + captchaModalCancel.addEventListener('click', () => closeModal(true)); + if (captchaModalClose) captchaModalClose.addEventListener('click', () => closeModal(true)); + + captchaModalOverlay.addEventListener('click', (e) => { + if (e.target === captchaModalOverlay) closeModal(true); + }); + + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && captchaModalOverlay.style.display === 'flex') { + closeModal(true); + } + }); + + if (captchaSecretToggle) { + captchaSecretToggle.addEventListener('click', () => { + const isPassword = captchaSecretKey.type === 'password'; + captchaSecretKey.type = isPassword ? 'text' : 'password'; + const icon = captchaSecretToggle.querySelector('i'); + if (icon) icon.className = isPassword ? 'fa-solid fa-eye-slash' : 'fa-solid fa-eye'; + }); + } + + captchaModalSave.addEventListener('click', async () => { + const siteKey = captchaSiteKey.value.trim(); + const secretKey = captchaSecretKey.value.trim(); + + if (!siteKey) { + showFeedback('Please enter your Site Key', true); + captchaSiteKey.focus(); + return; + } + if (siteKey.length < 10) { + showFeedback('Site Key appears to be invalid (too short)', true); + captchaSiteKey.focus(); + return; + } + if (!secretKey) { + showFeedback('Please enter your Secret Key', true); + captchaSecretKey.focus(); + return; + } + if (secretKey.length < 10) { + showFeedback('Secret Key appears to be invalid (too short)', true); + captchaSecretKey.focus(); + return; + } + + captchaModalSave.disabled = true; + showFeedback('Saving...'); + + try { + const res = await fetch('/api/settings/captcha', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': securityActionTokens.updateCaptcha || '' + }, + body: JSON.stringify({ site_key: siteKey, secret_key: secretKey, enabled: true }) + }); + const data = await res.json(); + + if (!res.ok) { + showFeedback(data.error || 'Failed to save', true); + } else { + captchaEnabled = true; + updateUI(); + closeModal(false); + await loadCaptchaStatus(); + if (data.note) { + setTimeout(() => alert(data.note), 100); + } + } + } catch (e) { + showFeedback('Network error', true); + } finally { + captchaModalSave.disabled = false; + } + }); + + const securityBtn = document.querySelector('button[data-panel="security"]'); + if (securityBtn) { + securityBtn.addEventListener('click', loadCaptchaStatus); + } + + const securityPanel = document.getElementById('security'); + if (securityPanel && securityPanel.classList.contains('active')) { + loadCaptchaStatus(); + } +})(); + +(function () { + const maintenanceCard = document.getElementById('maintenanceCard'); + if (!maintenanceCard) return; + + const maintenanceToggle = document.getElementById('maintenanceToggle'); + const maintenanceDetails = document.getElementById('maintenanceDetails'); + const maintenanceActiveBox = document.getElementById('maintenanceActiveBox'); + const maintenanceActiveText = document.getElementById('maintenanceActiveText'); + const maintenanceScheduledBox = document.getElementById('maintenanceScheduledBox'); + const maintenanceScheduledText = document.getElementById('maintenanceScheduledText'); + + const maintenanceModalOverlay = document.getElementById('maintenanceModalOverlay'); + const maintenanceModal = document.getElementById('maintenanceModal'); + const maintenanceModalClose = document.getElementById('maintenanceModalClose'); + const maintenanceModalCancel = document.getElementById('maintenanceModalCancel'); + const maintenanceModalSave = document.getElementById('maintenanceModalSave'); + const maintenanceModalFeedback = document.getElementById('maintenanceModalFeedback'); + const maintenanceImmediate = document.getElementById('maintenanceImmediate'); + const maintenanceScheduledRadio = document.getElementById('maintenanceScheduled'); + const maintenanceScheduleGroup = document.getElementById('maintenanceScheduleGroup'); + const maintenanceScheduleInput = document.getElementById('maintenanceScheduleInput'); + const maintenanceReasonInput = document.getElementById('maintenanceReasonInput'); + const maintenancePreAlertToggle = document.getElementById('maintenancePreAlertToggle'); + const maintenancePreAlertGroup = document.getElementById('maintenancePreAlertGroup'); + const maintenancePreAlertMessage = document.getElementById('maintenancePreAlertMessage'); + const maintenancePreAlertMinutes = document.getElementById('maintenancePreAlertMinutes'); + + const maintenanceSwitchLabel = maintenanceCard.querySelector('.switch'); + if (maintenanceSwitchLabel) { + maintenanceSwitchLabel.addEventListener('click', (e) => e.stopPropagation()); + } + + let maintenanceActionTokens = {}; + let detailsOpen = false; + let currentState = {}; + let pendingToggleState = null; + + function showFeedback(msg, isError = false) { + if (!maintenanceModalFeedback) return; + maintenanceModalFeedback.textContent = msg; + maintenanceModalFeedback.style.color = isError ? '#ef4444' : '#22c55e'; + if (msg) { + setTimeout(() => { + if (maintenanceModalFeedback) maintenanceModalFeedback.textContent = ''; + }, 4000); + } + } + + function formatDateTime(isoString) { + if (!isoString) return ''; + const d = new Date(isoString); + return d.toLocaleString(undefined, { + year: 'numeric', month: 'short', day: 'numeric', + hour: '2-digit', minute: '2-digit' + }); + } + + function updateUI() { + const isActive = currentState.is_active || currentState.enabled; + const isScheduled = !isActive && !!currentState.scheduled_at; + + maintenanceToggle.checked = isActive || isScheduled; + + if (isActive) { + maintenanceActiveBox.style.display = 'flex'; + const enabledBy = currentState.enabled_by || 'admin'; + const enabledAt = currentState.enabled_at ? formatDateTime(currentState.enabled_at) : ''; + maintenanceActiveText.textContent = 'Maintenance mode is active' + (enabledAt ? ' — enabled ' + enabledAt : '') + (enabledBy ? ' by ' + enabledBy : ''); + maintenanceDetails.style.display = 'block'; + detailsOpen = true; + } else { + maintenanceActiveBox.style.display = 'none'; + } + + if (isScheduled) { + maintenanceScheduledBox.style.display = 'flex'; + maintenanceScheduledText.textContent = 'Scheduled for ' + formatDateTime(currentState.scheduled_at); + maintenanceDetails.style.display = 'block'; + detailsOpen = true; + } else { + maintenanceScheduledBox.style.display = 'none'; + } + + if (!isActive && !isScheduled) { + maintenanceDetails.style.display = detailsOpen ? 'block' : 'none'; + } + } + + function openModal() { + if (!maintenanceModalOverlay || !maintenanceModal) return; + maintenanceImmediate.checked = true; + maintenanceScheduleGroup.style.display = 'none'; + maintenanceScheduleInput.value = ''; + maintenanceReasonInput.value = ''; + maintenancePreAlertToggle.checked = false; + maintenancePreAlertGroup.style.display = 'none'; + maintenancePreAlertMessage.value = ''; + maintenancePreAlertMinutes.value = '30'; + maintenanceModalSave.innerHTML = ' Enable Maintenance'; + showFeedback(''); + + const now = new Date(); + now.setMinutes(now.getMinutes() - now.getTimezoneOffset()); + maintenanceScheduleInput.min = now.toISOString().slice(0, 16); + + maintenanceModalOverlay.classList.add('show'); + maintenanceModal.classList.add('show'); + } + + document.addEventListener(ASSISTANT_SETTINGS_ACTION_EVENT, (event) => { + if (event?.detail?.action === 'maintenance') { + openModal(); + } + }); + + function closeModal(revertToggle = false) { + if (!maintenanceModalOverlay) return; + maintenanceModalOverlay.classList.remove('show'); + if (maintenanceModal) maintenanceModal.classList.remove('show'); + if (revertToggle && pendingToggleState !== null) { + maintenanceToggle.checked = !pendingToggleState; + } + pendingToggleState = null; + } + + async function loadMaintenanceState() { + try { + const res = await fetch('/api/settings/maintenance'); + if (!res.ok) return; + const data = await res.json(); + currentState = data; + maintenanceActionTokens = data.actionTokens || {}; + updateUI(); + } catch (e) { + console.error('Failed to load maintenance state:', e); + } + } + + maintenanceImmediate.addEventListener('change', () => { + maintenanceScheduleGroup.style.display = 'none'; + maintenanceModalSave.innerHTML = ' Enable Maintenance'; + }); + maintenanceScheduledRadio.addEventListener('change', () => { + maintenanceScheduleGroup.style.display = 'block'; + maintenanceModalSave.innerHTML = ' Schedule Maintenance'; + }); + + maintenancePreAlertToggle.addEventListener('change', () => { + maintenancePreAlertGroup.style.display = maintenancePreAlertToggle.checked ? 'block' : 'none'; + }); + + maintenanceToggle.addEventListener('change', async () => { + const newState = maintenanceToggle.checked; + pendingToggleState = newState; + + if (newState) { + openModal(); + } else { + if (!confirm('Are you sure you want to disable maintenance mode? All users will regain access immediately.')) { + maintenanceToggle.checked = true; + pendingToggleState = null; + return; + } + + try { + const res = await fetch('/api/settings/maintenance', { + method: 'DELETE', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': maintenanceActionTokens.disableMaintenance || '' + } + }); + const data = await res.json(); + if (!res.ok) { + alert(data.error || 'Failed to disable maintenance mode'); + maintenanceToggle.checked = true; + } else { + await loadMaintenanceState(); + } + } catch (e) { + alert('Network error'); + maintenanceToggle.checked = true; + } + pendingToggleState = null; + } + }); + + maintenanceCard.addEventListener('click', (e) => { + if (e.target.closest('.switch') || e.target.closest('input') || e.target.closest('button')) return; + detailsOpen = !detailsOpen; + if (maintenanceDetails) maintenanceDetails.style.display = detailsOpen ? 'block' : 'none'; + }); + + maintenanceModalCancel.addEventListener('click', () => closeModal(true)); + if (maintenanceModalClose) maintenanceModalClose.addEventListener('click', () => closeModal(true)); + maintenanceModalOverlay.addEventListener('click', (e) => { + if (e.target === maintenanceModalOverlay) closeModal(true); + }); + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && maintenanceModalOverlay.classList.contains('show')) { + closeModal(true); + } + }); + + maintenanceModalSave.addEventListener('click', async () => { + const isImmediate = maintenanceImmediate.checked; + const reason = maintenanceReasonInput.value.trim(); + const preAlertShow = maintenancePreAlertToggle.checked; + const preAlertMessage = maintenancePreAlertMessage.value.trim(); + const preAlertMinutes = parseInt(maintenancePreAlertMinutes.value, 10); + + if (!isImmediate) { + if (!maintenanceScheduleInput.value) { + showFeedback('Please select a date and time for the scheduled maintenance', true); + return; + } + const scheduledTime = new Date(maintenanceScheduleInput.value).getTime(); + if (isNaN(scheduledTime) || scheduledTime <= Date.now()) { + showFeedback('Scheduled time must be in the future', true); + return; + } + } + + if (preAlertShow) { + if (!preAlertMessage) { + showFeedback('Please enter an alert message', true); + maintenancePreAlertMessage.focus(); + return; + } + if (!preAlertMinutes || preAlertMinutes < 1) { + showFeedback('Please enter a valid number of minutes', true); + maintenancePreAlertMinutes.focus(); + return; + } + if (!isImmediate) { + const scheduledTime = new Date(maintenanceScheduleInput.value).getTime(); + const alertTime = scheduledTime - (preAlertMinutes * 60 * 1000); + if (alertTime <= Date.now()) { + showFeedback('The alert time (scheduled time minus minutes) is already in the past', true); + return; + } + } + } + + maintenanceModalSave.disabled = true; + showFeedback('Enabling maintenance mode...'); + + try { + const body = { + immediate: isImmediate, + reason: reason || null, + scheduled_at: !isImmediate ? new Date(maintenanceScheduleInput.value).toISOString() : null, + pre_alert_show: preAlertShow, + pre_alert_message: preAlertShow ? preAlertMessage : null, + pre_alert_minutes_before: preAlertShow ? preAlertMinutes : null + }; + + const res = await fetch('/api/settings/maintenance', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': maintenanceActionTokens.enableMaintenance || '' + }, + body: JSON.stringify(body) + }); + const data = await res.json(); + + if (!res.ok) { + showFeedback(data.error || 'Failed to enable maintenance mode', true); + } else { + closeModal(false); + await loadMaintenanceState(); + } + } catch (e) { + showFeedback('Network error', true); + } finally { + maintenanceModalSave.disabled = false; + } + }); + + const securityBtn = document.querySelector('button[data-panel="security"]'); + if (securityBtn) { + securityBtn.addEventListener('click', loadMaintenanceState); + } + + const securityPanel = document.getElementById('security'); + if (securityPanel && securityPanel.classList.contains('active')) { + loadMaintenanceState(); + } +})(); + +(function () { + const sessionsPanel = document.getElementById('sessions'); + if (!sessionsPanel) return; + + const sessionsBtn = document.querySelector('button[data-panel="sessions"]'); + const sessionsSearchInput = document.getElementById('sessionsSearchInput'); + const sessionsSummary = document.getElementById('sessionsSummary'); + const sessionsFeedback = document.getElementById('sessionsFeedback'); + const sessionsList = document.getElementById('sessionsList'); + const sessionsPagination = document.getElementById('sessionsPagination'); + const sessionsCountBadge = document.getElementById('sessionsCountBadge'); + const sessionsGraceBadge = document.getElementById('sessionsGraceBadge'); + + const sessionRevokeModalOverlay = document.getElementById('sessionRevokeModalOverlay'); + 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 PAGE_GROUP_SIZE = 6; + const sessionsState = { + actionTokens: {}, + items: [], + total: 0, + page: 1, + totalPages: 1, + search: '', + searchActive: false, + from: 0, + to: 0, + twoFactorEnabled: false, + graceExpiresAt: 0, + loading: false, + loadedOnce: false, + abortController: null, + searchTimer: null, + selectedSession: null, + graceTicker: null, + }; + + function showSessionsFeedback(message, isError = false) { + if (!sessionsFeedback) return; + sessionsFeedback.textContent = message || ''; + sessionsFeedback.style.color = isError ? '#f87171' : '#4ade80'; + if (message) { + window.clearTimeout(sessionsFeedback._timer); + sessionsFeedback._timer = window.setTimeout(() => { + sessionsFeedback.textContent = ''; + }, 4000); + } + } + + function showSessionRevokeModalFeedback(message, isError = false) { + if (!sessionRevokeModalFeedback) return; + sessionRevokeModalFeedback.textContent = message || ''; + sessionRevokeModalFeedback.style.display = message ? 'block' : 'none'; + sessionRevokeModalFeedback.style.color = isError ? '#f87171' : '#4ade80'; + } + + function showSuccessToast(message) { + const toast = document.createElement('div'); + toast.className = 'perm-success-toast'; + toast.innerHTML = ` ${escapeHtml(message || 'Done')}`; + document.body.appendChild(toast); + window.setTimeout(() => toast.classList.add('show'), 10); + window.setTimeout(() => { + toast.classList.remove('show'); + window.setTimeout(() => toast.remove(), 300); + }, 2200); + } + + function isGraceActive() { + return Number(sessionsState.graceExpiresAt || 0) > Date.now(); + } + + function isSessionsPanelActive() { + return !!sessionsPanel?.classList.contains('active'); + } + + function formatDateTime(value) { + const ts = Number(value || 0); + if (!ts) return 'Unknown'; + try { + return new Intl.DateTimeFormat(undefined, { + year: 'numeric', + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit', + }).format(new Date(ts)); + } catch { + return new Date(ts).toLocaleString(); + } + } + + function formatRelativeTime(value) { + const ts = Number(value || 0); + if (!ts) return 'unknown'; + + const diffMs = Date.now() - ts; + const diffMinutes = Math.round(diffMs / 60000); + if (Math.abs(diffMinutes) < 1) return 'just now'; + if (Math.abs(diffMinutes) < 60) return `${Math.abs(diffMinutes)}m ago`; + + const diffHours = Math.round(diffMinutes / 60); + if (Math.abs(diffHours) < 24) return `${Math.abs(diffHours)}h ago`; + + const diffDays = Math.round(diffHours / 24); + return `${Math.abs(diffDays)}d ago`; + } + + function describeUserAgent(userAgent) { + const ua = String(userAgent || '').trim(); + if (!ua) return 'Browser not detected'; + + const normalized = ua.toLowerCase(); + let browser = 'Browser'; + if (normalized.includes('edg/')) browser = 'Edge'; + else if (normalized.includes('opr/') || normalized.includes('opera')) browser = 'Opera'; + else if (normalized.includes('firefox/')) browser = 'Firefox'; + else if (normalized.includes('safari/') && !normalized.includes('chrome/')) browser = 'Safari'; + else if (normalized.includes('chrome/') || normalized.includes('crios/')) browser = 'Chrome'; + + let os = 'Unknown OS'; + if (normalized.includes('windows')) os = 'Windows'; + else if (normalized.includes('mac os x') || normalized.includes('macintosh')) os = 'macOS'; + else if (normalized.includes('android')) os = 'Android'; + else if (normalized.includes('iphone') || normalized.includes('ipad') || normalized.includes('ios')) os = 'iOS'; + else if (normalized.includes('linux')) os = 'Linux'; + + return `${browser} on ${os}`; + } + + function shortenSessionId(sessionId) { + const raw = String(sessionId || '').trim(); + if (!raw) return '—'; + if (raw.length <= 20) return raw; + return `${raw.slice(0, 10)}...${raw.slice(-8)}`; + } + + function syncGraceTicker() { + const shouldTick = isSessionsPanelActive() && isGraceActive(); + if (shouldTick && !sessionsState.graceTicker) { + sessionsState.graceTicker = window.setInterval(() => { + updateSessionsHeaderMeta(); + }, 1000); + return; + } + if (!shouldTick && sessionsState.graceTicker) { + window.clearInterval(sessionsState.graceTicker); + sessionsState.graceTicker = null; + } + } + + function updateSessionsHeaderMeta() { + if (sessionsCountBadge) { + sessionsCountBadge.textContent = `${sessionsState.total} active`; + } + + 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'); + } + } + syncGraceTicker(); + } + + function renderSessionsSummary() { + if (!sessionsSummary) return; + + if (sessionsState.loading && !sessionsState.loadedOnce) { + sessionsSummary.textContent = 'Loading active browser sessions...'; + return; + } + + if (sessionsState.searchActive) { + sessionsSummary.textContent = `${sessionsState.total} active session${sessionsState.total === 1 ? '' : 's'} matched "${sessionsState.search}"`; + return; + } + + if (!sessionsState.total) { + sessionsSummary.textContent = 'No active browser sessions found.'; + return; + } + + sessionsSummary.textContent = `${sessionsState.from}-${sessionsState.to} of ${sessionsState.total} active sessions`; + } + + function renderEmptySessionsState(message, iconClass = 'fa-solid fa-circle-info') { + if (!sessionsList) return; + sessionsList.innerHTML = ` +
    + + ${escapeHtml(message)} +
    + `; + } + + function renderSessionsList() { + if (!sessionsList) return; + + if (sessionsState.loading && !sessionsState.loadedOnce) { + renderEmptySessionsState('Loading active 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'); + } else { + renderEmptySessionsState('There are no active browser sessions right now.', 'fa-solid fa-window-restore'); + } + return; + } + + sessionsList.innerHTML = ''; + sessionsState.items.forEach((item) => { + const displayId = item.displayId || item.sessionId || ''; + const revokeToken = item.revokeToken || ''; + const row = document.createElement('div'); + row.className = 'session-row'; + row.innerHTML = ` +
    +
    + ${escapeHtml(shortenSessionId(displayId))} + ${escapeHtml(item.email || 'Unknown user')} +
    +
    + ${item.isCurrent ? ' Current session' : ''} + Last seen ${escapeHtml(formatRelativeTime(item.lastSeenAt))} + Expires ${escapeHtml(formatDateTime(item.expiresAt))} + ${escapeHtml(describeUserAgent(item.userAgent))} + ${item.ip ? ` ${escapeHtml(item.ip)}` : ''} +
    +
    +
    + +
    + `; + sessionsList.appendChild(row); + }); + } + + function getVisibleSessionPages(currentPage, totalPages) { + if (totalPages <= PAGE_GROUP_SIZE) { + return Array.from({ length: totalPages }, (_, index) => index + 1); + } + + if (currentPage < PAGE_GROUP_SIZE) { + return Array.from({ length: PAGE_GROUP_SIZE }, (_, index) => index + 1); + } + + const start = Math.floor((currentPage - PAGE_GROUP_SIZE) / PAGE_GROUP_SIZE) * PAGE_GROUP_SIZE + PAGE_GROUP_SIZE; + const end = Math.min(totalPages, start + PAGE_GROUP_SIZE); + const pages = []; + for (let page = start; page <= end; page += 1) { + pages.push(page); + } + return pages; + } + + function renderSessionsPagination() { + if (!sessionsPagination) return; + + if (sessionsState.searchActive || sessionsState.totalPages <= 1) { + sessionsPagination.innerHTML = ''; + return; + } + + const currentPage = Number(sessionsState.page || 1); + const totalPages = Number(sessionsState.totalPages || 1); + const visiblePages = getVisibleSessionPages(currentPage, totalPages); + + sessionsPagination.innerHTML = ` +
    + + ${visiblePages.map((page) => ` + + `).join('')} + +
    + `; + } + + async function loadSessions(page = sessionsState.page, search = sessionsState.search) { + if (sessionsState.abortController) { + sessionsState.abortController.abort(); + } + + sessionsState.abortController = new AbortController(); + sessionsState.loading = true; + sessionsState.page = Math.max(1, Number(page || 1)); + sessionsState.search = String(search || '').trim(); + renderSessionsSummary(); + renderSessionsList(); + + try { + const params = new URLSearchParams(); + params.set('page', String(Math.max(1, Number(page || 1)))); + if (sessionsState.search) { + params.set('search', sessionsState.search); + } + + const res = await fetch(`/api/settings/sessions?${params.toString()}`, { + signal: sessionsState.abortController.signal, + }); + const data = await res.json().catch(() => ({ error: 'Invalid server response' })); + + if (!res.ok) { + throw new Error(data.error || 'Failed to load sessions'); + } + + sessionsState.items = Array.isArray(data.items) ? data.items : []; + sessionsState.total = Number(data.total || 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) { + sessionsSearchInput.value = sessionsState.search; + } + + updateSessionsHeaderMeta(); + renderSessionsSummary(); + renderSessionsList(); + renderSessionsPagination(); + } 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); + } 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(), + }; + + if (sessionRevokeTargetSession) { + sessionRevokeTargetSession.textContent = shortenSessionId(sessionsState.selectedSession.displayId); + } + if (sessionRevokeTargetEmail) { + sessionRevokeTargetEmail.textContent = sessionsState.selectedSession.email || 'Unknown user'; + } + if (sessionRevokeTwoFactorInput) { + sessionRevokeTwoFactorInput.value = ''; + } + showSessionRevokeModalFeedback(''); + + if (sessionRevokeModalOverlay) { + sessionRevokeModalOverlay.setAttribute('aria-hidden', 'false'); + sessionRevokeModalOverlay.classList.add('show'); + } + if (sessionRevokeModal) { + sessionRevokeModal.classList.add('show'); + } + + window.setTimeout(() => { + sessionRevokeTwoFactorInput?.focus(); + }, 40); + } + + function closeSessionRevokeModal() { + sessionsState.selectedSession = null; + if (sessionRevokeModalOverlay) { + sessionRevokeModalOverlay.setAttribute('aria-hidden', 'true'); + sessionRevokeModalOverlay.classList.remove('show'); + } + if (sessionRevokeModal) { + sessionRevokeModal.classList.remove('show'); + } + 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; + } + } + + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = true; + sessionRevokeModalConfirm.innerHTML = ' Revoking...'; + } + + try { + const res = await fetch('/api/settings/sessions/revoke', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': sessionsState.actionTokens.revokeSession || '', + }, + body: JSON.stringify({ + revokeToken: trimmedRevokeToken, + twoFactorCode: requiresTwoFactor ? String(twoFactorCode || '').replace(/\s+/g, '') : 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.error === 'invalid or missing action token') { + await loadSessions(sessionsState.page, sessionsSearchInput?.value || ''); + } + if (data.code === 'session-action-expired') { + await loadSessions(sessionsState.page, sessionsSearchInput?.value || ''); + } + + if (modalVisible) { + showSessionRevokeModalFeedback(data.error || 'Failed to revoke session.', true); + } else { + showSessionsFeedback(data.error || 'Failed to revoke session.', true); + } + return; + } + + sessionsState.graceExpiresAt = Number(data.graceExpiresAt || 0); + updateSessionsHeaderMeta(); + closeSessionRevokeModal(); + + if (data.revokedCurrentSession) { + window.location.href = '/login'; + return; + } + + showSuccessToast(`Revoked ${data.targetEmail || trimmedEmail || 'session'}`); + await loadSessions(sessionsState.page, sessionsSearchInput?.value || ''); + } catch (err) { + console.error('[sessions] revoke failed', err); + if (modalVisible) { + showSessionRevokeModalFeedback(err.message || 'Network error while revoking session.', true); + } else { + showSessionsFeedback(err.message || 'Network error while revoking session.', true); + } + } finally { + if (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.disabled = false; + sessionRevokeModalConfirm.innerHTML = ' Revoke Session'; + } + } + } + + if (sessionsSearchInput) { + sessionsSearchInput.addEventListener('input', (event) => { + const nextValue = String(event.target.value || '').trim(); + window.clearTimeout(sessionsState.searchTimer); + sessionsState.searchTimer = window.setTimeout(() => { + loadSessions(1, nextValue); + }, 280); + }); + } + + if (sessionsPagination) { + sessionsPagination.addEventListener('click', (e) => { + const button = e.target.closest('button[data-sessions-page]'); + if (!button || button.disabled) return; + const nextPage = parseInt(button.dataset.sessionsPage, 10); + if (!nextPage || nextPage < 1 || nextPage > sessionsState.totalPages) return; + loadSessions(nextPage, sessionsSearchInput?.value || ''); + }); + } + + if (sessionsList) { + sessionsList.addEventListener('click', (e) => { + const button = e.target.closest('.session-revoke-btn'); + if (!button) return; + + const revokeToken = decodeURIComponent(button.dataset.revokeToken || ''); + const displayId = decodeURIComponent(button.dataset.sessionDisplay || ''); + const email = decodeURIComponent(button.dataset.sessionEmail || ''); + + if (!sessionsState.twoFactorEnabled) { + showSessionsFeedback('Enable 2FA before revoking sessions.', true); + return; + } + + if (isGraceActive()) { + revokeSession(revokeToken, email, '', displayId); + return; + } + + openSessionRevokeModal(revokeToken, displayId, email); + }); + } + + if (sessionRevokeModalClose) sessionRevokeModalClose.addEventListener('click', closeSessionRevokeModal); + if (sessionRevokeModalCancel) sessionRevokeModalCancel.addEventListener('click', closeSessionRevokeModal); + if (sessionRevokeModalOverlay) { + sessionRevokeModalOverlay.addEventListener('click', (e) => { + if (e.target === sessionRevokeModalOverlay) { + closeSessionRevokeModal(); + } + }); + } + 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 (sessionRevokeModalConfirm) { + sessionRevokeModalConfirm.addEventListener('click', () => { + if (!sessionsState.selectedSession) return; + revokeSession( + sessionsState.selectedSession.revokeToken, + sessionsState.selectedSession.email, + sessionRevokeTwoFactorInput?.value || '' + ); + }); + } + + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && sessionRevokeModalOverlay?.classList.contains('show')) { + closeSessionRevokeModal(); + } + }); + + if (sessionsBtn) { + sessionsBtn.addEventListener('click', () => { + loadSessions(sessionsState.searchActive ? 1 : sessionsState.page, sessionsSearchInput?.value || ''); + }); + } + + if (sessionsPanel?.classList.contains('active')) { + loadSessions(1, sessionsSearchInput?.value || ''); + } else { + updateSessionsHeaderMeta(); + renderSessionsSummary(); + } +})(); + +(function () { + 'use strict'; + + const DEFAULT_ADMIN_ACTIONS = [ + { id: 'default-admin-1', title: 'Manage account', icon: 'fa-solid fa-list-check', link: '/settings?panel=account', animation: 'default', newTab: false }, + { id: 'default-admin-2', title: 'Manage servers', icon: 'fa-solid fa-bars-progress', link: '/settings?panel=servers', animation: 'default', newTab: false }, + { id: 'default-admin-3', title: 'ADPanel Site', icon: 'fa-solid fa-globe', link: 'https://ad-panel.com', animation: 'default', newTab: true }, + ]; + + const DEFAULT_USER_ACTIONS = [ + { id: 'default-user-1', title: 'Manage account', icon: 'fa-solid fa-list-check', link: '/settings?panel=account', animation: 'default', newTab: false }, + ]; + + const MAX_QUICK_ACTIONS = 6; + let adminActions = []; + let userActions = []; + let editingActionId = null; + let editingType = 'admin'; + + const quickActionsList = document.getElementById('quickActionsList'); + const userQuickActionsList = document.getElementById('userQuickActionsList'); + const quickActionsEmpty = document.getElementById('quickActionsEmpty'); + const userQuickActionsEmpty = document.getElementById('userQuickActionsEmpty'); + const quickActionsCount = document.getElementById('quickActionsCount'); + const userQuickActionsCount = document.getElementById('userQuickActionsCount'); + const addQuickActionBtn = document.getElementById('addQuickActionBtn'); + const addUserQuickActionBtn = document.getElementById('addUserQuickActionBtn'); + + const quickActionModalOverlay = document.getElementById('quickActionModalOverlay'); + const quickActionModal = document.getElementById('quickActionModal'); + const quickActionModalTitle = document.getElementById('quickActionModalTitle'); + const quickActionModalClose = document.getElementById('quickActionModalClose'); + const quickActionCancel = document.getElementById('quickActionCancel'); + const quickActionSave = document.getElementById('quickActionSave'); + const quickActionFeedback = document.getElementById('quickActionFeedback'); + + const qaTitle = document.getElementById('qa_title'); + const qaLink = document.getElementById('qa_link'); + const qaIcon = document.getElementById('qa_icon'); + const qaAnimation = document.getElementById('qa_animation'); + const qaScale = document.getElementById('qa_scale'); + const qaScaleWrapper = document.getElementById('qa_scale_wrapper'); + const qaNewTab = document.getElementById('qa_newTab'); + + const quickActionPreview = document.getElementById('quickActionPreview'); + const previewIcon = document.getElementById('previewIcon'); + const previewTitle = document.getElementById('previewTitle'); + const iconInputPreview = document.getElementById('iconInputPreview'); + const iconSuggestions = document.getElementById('iconSuggestions'); + + if (!quickActionsList) return; + + loadQuickActions(); + + if (addQuickActionBtn) { + addQuickActionBtn.addEventListener('click', () => openQuickActionModal(null, 'admin')); + } + + if (addUserQuickActionBtn) { + addUserQuickActionBtn.addEventListener('click', () => openQuickActionModal(null, 'user')); + } + + if (quickActionModalClose) { + quickActionModalClose.addEventListener('click', closeQuickActionModal); + } + + if (quickActionCancel) { + quickActionCancel.addEventListener('click', closeQuickActionModal); + } + + if (quickActionModalOverlay) { + quickActionModalOverlay.addEventListener('click', (e) => { + if (e.target === quickActionModalOverlay) closeQuickActionModal(); + }); + } + + if (quickActionSave) { + quickActionSave.addEventListener('click', saveQuickAction); + } + + if (qaTitle) { + qaTitle.addEventListener('input', updatePreview); + } + + if (qaIcon) { + qaIcon.addEventListener('input', () => { + updateIconPreview(); + updatePreview(); + }); + } + + if (qaAnimation) { + qaAnimation.addEventListener('change', () => { + updateScaleInputVisibility(); + updatePreviewAnimation(); + }); + } + + if (qaScale) { + qaScale.addEventListener('input', updatePreviewAnimation); + } + + function updateScaleInputVisibility() { + if (qaAnimation.value === 'scale') { + qaScaleWrapper.style.display = 'block'; + } else { + qaScaleWrapper.style.display = 'none'; + } + } + + if (iconSuggestions) { + iconSuggestions.addEventListener('click', (e) => { + const btn = e.target.closest('.icon-suggestion'); + if (btn && qaIcon) { + const icon = btn.dataset.icon; + qaIcon.value = icon; + updateIconPreview(); + updatePreview(); + + iconSuggestions.querySelectorAll('.icon-suggestion').forEach(b => b.classList.remove('selected')); + btn.classList.add('selected'); + } + }); + } + + const customizationBtn = document.querySelector('button[data-panel="customization"]'); + if (customizationBtn) { + customizationBtn.addEventListener('click', loadQuickActions); + } + + async function loadQuickActions() { + try { + const res = await fetch('/api/settings/quick-actions'); + if (res.ok) { + const data = await res.json(); + if (data.actions && !Array.isArray(data.actions)) { + adminActions = data.actions.admin || DEFAULT_ADMIN_ACTIONS; + userActions = data.actions.user || DEFAULT_USER_ACTIONS; + } else { + adminActions = Array.isArray(data.actions) ? data.actions : DEFAULT_ADMIN_ACTIONS; + userActions = DEFAULT_USER_ACTIONS; + } + } else { + adminActions = DEFAULT_ADMIN_ACTIONS; + userActions = DEFAULT_USER_ACTIONS; + } + } catch (err) { + console.error('[quick-actions] Failed to load:', err); + adminActions = DEFAULT_ADMIN_ACTIONS; + userActions = DEFAULT_USER_ACTIONS; + } + renderQuickActions('admin'); + renderQuickActions('user'); + } + + function renderQuickActions(type = 'admin') { + const isUser = type === 'user'; + const actions = isUser ? userActions : adminActions; + const container = isUser ? userQuickActionsList : quickActionsList; + const emptyMsg = isUser ? userQuickActionsEmpty : quickActionsEmpty; + const countDisplay = isUser ? userQuickActionsCount : quickActionsCount; + const addBtn = isUser ? addUserQuickActionBtn : addQuickActionBtn; + + if (!container) return; + + if (actions.length === 0) { + container.innerHTML = ''; + if (emptyMsg) emptyMsg.style.display = 'flex'; + if (countDisplay) countDisplay.textContent = '0'; + return; + } + + if (emptyMsg) emptyMsg.style.display = 'none'; + if (countDisplay) countDisplay.textContent = String(actions.length); + + container.innerHTML = actions.map((action, index) => ` +
    +
    +
    + +
    +
    +
    ${escapeHtml(action.title || 'Untitled')}
    + +
    +
    +
    + + +
    +
    + `).join(''); + + replaceLegacyPanelEwsIcons(container); + + container.querySelectorAll('.quick-action-item-btn').forEach(btn => { + btn.addEventListener('click', (e) => { + e.stopPropagation(); + const actionType = btn.dataset.action; + const id = btn.dataset.id; + if (actionType === 'edit') { + const action = actions.find(a => (a.id || actions.indexOf(a)) == id); + if (action) openQuickActionModal(action, type); + } else if (actionType === 'delete') { + deleteQuickAction(id, type); + } + }); + }); + + if (addBtn) { + addBtn.disabled = actions.length >= MAX_QUICK_ACTIONS; + if (actions.length >= MAX_QUICK_ACTIONS) { + addBtn.title = 'Maximum of 6 quick actions reached'; + } else { + addBtn.title = isUser ? 'Add user action' : 'Add admin action'; + } + } + } + + function openQuickActionModal(action = null, type = 'admin') { + if (!quickActionModalOverlay) return; + + editingType = type; + editingActionId = action ? (action.id || null) : null; + + if (qaTitle) qaTitle.value = action?.title || ''; + if (qaLink) qaLink.value = action?.link || ''; + if (qaIcon) qaIcon.value = action?.icon || 'fa-solid fa-star'; + if (qaAnimation) qaAnimation.value = action?.animation || 'default'; + if (qaScale) qaScale.value = action?.scaleValue || 1.05; + if (qaNewTab) qaNewTab.checked = action?.newTab || false; + + updateScaleInputVisibility(); + + if (quickActionModalTitle) { + quickActionModalTitle.textContent = action ? 'Edit Quick Action' : 'Add Quick Action'; + } + + updateIconPreview(); + updatePreview(); + updatePreviewAnimation(); + + if (quickActionFeedback) { + quickActionFeedback.textContent = ''; + quickActionFeedback.className = 'node-feedback'; + } + + if (iconSuggestions) { + iconSuggestions.querySelectorAll('.icon-suggestion').forEach(b => b.classList.remove('selected')); + const currentIcon = qaIcon?.value || 'fa-solid fa-star'; + const matchBtn = iconSuggestions.querySelector(`[data-icon="${currentIcon}"]`); + if (matchBtn) matchBtn.classList.add('selected'); + } + + quickActionModalOverlay.setAttribute('aria-hidden', 'false'); + quickActionModalOverlay.classList.add('show'); + + setTimeout(() => qaTitle?.focus(), 100); + } + + function closeQuickActionModal() { + if (quickActionModalOverlay) { + quickActionModalOverlay.setAttribute('aria-hidden', 'true'); + quickActionModalOverlay.classList.remove('show'); + } + editingActionId = null; + } + + function updateIconPreview() { + const iconClass = qaIcon?.value || 'fa-solid fa-star'; + ensurePanelEwsSvgStyles(); + if (iconInputPreview) { + if (isPanelEwsIcon(iconClass)) { + iconInputPreview.innerHTML = ''; + iconInputPreview.appendChild(createPanelEwsSvg()); + } else { + iconInputPreview.innerHTML = ``; + } + } + if (quickActionPreview) { + const existingSvg = quickActionPreview.querySelector('.panel-ews-svg'); + let iconEl = quickActionPreview.querySelector('#previewIcon'); + if (isPanelEwsIcon(iconClass)) { + const svg = createPanelEwsSvg(); + if (iconEl) { + iconEl.replaceWith(svg); + } else if (existingSvg) { + existingSvg.replaceWith(svg); + } else { + quickActionPreview.insertBefore(svg, quickActionPreview.firstChild); + } + } else { + if (!iconEl) { + iconEl = document.createElement('i'); + iconEl.id = 'previewIcon'; + if (existingSvg) { + existingSvg.replaceWith(iconEl); + } else { + quickActionPreview.insertBefore(iconEl, quickActionPreview.firstChild); + } + } + iconEl.className = iconClass; + } + } + } + + function updatePreview() { + const title = qaTitle?.value || 'Action Title'; + if (previewTitle) { + previewTitle.textContent = title || 'Action Title'; + } + updateIconPreview(); + } + + function updatePreviewAnimation() { + const animation = qaAnimation?.value || 'default'; + if (quickActionPreview) { + quickActionPreview.className = 'quick-action-preview-card'; + if (animation !== 'default' && animation !== 'none') { + quickActionPreview.classList.add(`qa-anim-${animation}`); + + if (animation === 'scale') { + quickActionPreview.style.setProperty('--hover-scale', qaScale?.value || 1.05); + } else { + quickActionPreview.style.removeProperty('--hover-scale'); + } + } else { + quickActionPreview.style.removeProperty('--hover-scale'); + } + } + } + async function saveQuickAction() { + const title = qaTitle?.value?.trim(); + const link = qaLink?.value?.trim(); + const icon = qaIcon?.value || 'fa-solid fa-star'; + const animation = qaAnimation?.value || 'default'; + const scaleValue = qaScale?.value || 1.05; + const newTab = qaNewTab?.checked || false; + + if (!title) return showFeedback('Title is required', true); + if (!link) return showFeedback('Link is required', true); + + if (!icon) { + showFeedback('Icon is required', true); + qaIcon?.focus(); + return; + } + + if (!link.startsWith('/') && !link.startsWith('http://') && !link.startsWith('https://')) { + showFeedback('Link must start with / for internal links or http(s):// for external', true); + qaLink?.focus(); + return; + } + + const currentActions = editingType === 'user' ? userActions : adminActions; + if (!editingActionId && currentActions.length >= MAX_QUICK_ACTIONS) { + showFeedback('Maximum of 6 quick actions reached', true); + return; + } + + const actionData = { + id: editingActionId || `qa-${Date.now()}`, + title, + link, + icon, + animation, + scaleValue, + newTab + }; + + if (editingActionId) { + const index = currentActions.findIndex(a => a.id === editingActionId); + if (index !== -1) { + currentActions[index] = actionData; + } + } else { + currentActions.push(actionData); + } + + if (quickActionSave) { + quickActionSave.disabled = true; + quickActionSave.innerHTML = ' Saving...'; + } + + try { + const res = await fetch('/api/settings/quick-actions', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + admin: adminActions, + user: userActions + }) + }); + + if (!res.ok) { + const data = await res.json(); + showFeedback(data.error || 'Failed to save', true); + return; + } + + closeQuickActionModal(); + renderQuickActions(editingType); + } catch (err) { + console.error('[quick-actions] Save failed:', err); + showFeedback('Network error', true); + } finally { + if (quickActionSave) { + quickActionSave.disabled = false; + quickActionSave.innerHTML = ' Save Action'; + } + } + } + + async function deleteQuickAction(id, type) { + const isUser = type === 'user'; + const actions = isUser ? userActions : adminActions; + const action = actions.find(a => (a.id || actions.indexOf(a)) == id); + if (!action) return; + + const confirmDelete = confirm(`Delete quick action "${action.title}"?`); + if (!confirmDelete) return; + + const index = actions.findIndex(a => (a.id || actions.indexOf(a)) == id); + if (index !== -1) { + actions.splice(index, 1); + } + + try { + const res = await fetch('/api/settings/quick-actions', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + admin: adminActions, + user: userActions + }) + }); + + if (!res.ok) { + console.error('[quick-actions] Delete save failed'); + loadQuickActions(); + return; + } + + renderQuickActions(type); + } catch (err) { + console.error('[quick-actions] Delete failed:', err); + loadQuickActions(); + } + } + + function showFeedback(msg, isError = false) { + if (quickActionFeedback) { + quickActionFeedback.textContent = msg; + quickActionFeedback.className = 'node-feedback' + (isError ? ' error' : ' success'); + } + } + + function escapeHtml(str) { + if (!str) return ''; + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + function truncateLink(link) { + if (!link) return ''; + if (link.length <= 25) return link; + return link.substring(0, 22) + '...'; + } +})(); + +(function () { + 'use strict'; + + const phpmyadminToggle = document.getElementById('phpmyadminToggle'); + const phpmyadminDetails = document.getElementById('phpmyadminDetails'); + const phpmyadminStatus = document.getElementById('phpmyadminStatus'); + const phpmyadminCard = document.getElementById('phpmyadminCard'); + const dbUsersSection = document.getElementById('dbUsersSection'); + const dbUsersList = document.getElementById('dbUsersList'); + const dbTypeSection = document.getElementById('dbTypeSection'); + const dbTypeCurrent = document.getElementById('dbTypeCurrent'); + const phpmyadminAccessSection = document.getElementById('phpmyadminAccessSection'); + const phpmyadminUrl = document.getElementById('phpmyadminUrl'); + const copyPhpmyadminUrl = document.getElementById('copyPhpmyadminUrl'); + const openPhpmyadminUrl = document.getElementById('openPhpmyadminUrl'); + const addDbUserBtn = document.getElementById('addDbUserBtn'); + const changeDbTypeBtn = document.getElementById('changeDbTypeBtn'); + + const dbSetupModalOverlay = document.getElementById('dbSetupModalOverlay'); + const dbSetupModal = document.getElementById('dbSetupModal'); + const dbSetupModalClose = document.getElementById('dbSetupModalClose'); + const dbSetupCancel = document.getElementById('dbSetupCancel'); + const dbSetupSave = document.getElementById('dbSetupSave'); + const dbSetupFeedback = document.getElementById('dbSetupFeedback'); + const dbHost = document.getElementById('db_host'); + const dbPort = document.getElementById('db_port'); + const dbUsername = document.getElementById('db_username'); + const dbPassword = document.getElementById('db_password'); + + const dbUserModalOverlay = document.getElementById('dbUserModalOverlay'); + const dbUserModal = document.getElementById('dbUserModal'); + const dbUserModalTitle = document.getElementById('dbUserModalTitle'); + const dbUserModalClose = document.getElementById('dbUserModalClose'); + const dbUserCancel = document.getElementById('dbUserCancel'); + const dbUserSave = document.getElementById('dbUserSave'); + const dbUserFeedback = document.getElementById('dbUserFeedback'); + const dbuserUsername = document.getElementById('dbuser_username'); + const dbuserPassword = document.getElementById('dbuser_password'); + const dbUserPasswordStrength = document.getElementById('dbUserPasswordStrength'); + + const dbPassModalOverlay = document.getElementById('dbPassModalOverlay'); + const dbPassModal = document.getElementById('dbPassModal'); + const dbPassModalSubtitle = document.getElementById('dbPassModalSubtitle'); + const dbPassModalClose = document.getElementById('dbPassModalClose'); + const dbPassCancel = document.getElementById('dbPassCancel'); + const dbPassSave = document.getElementById('dbPassSave'); + const dbPassFeedback = document.getElementById('dbPassFeedback'); + const dbpassUsername = document.getElementById('dbpass_username'); + const dbpassPassword = document.getElementById('dbpass_password'); + const dbpassConfirm = document.getElementById('dbpass_confirm'); + const dbPassPasswordStrength = document.getElementById('dbPassPasswordStrength'); + + const dbChangeTypeModalOverlay = document.getElementById('dbChangeTypeModalOverlay'); + const dbChangeTypeModal = document.getElementById('dbChangeTypeModal'); + const dbChangeTypeModalClose = document.getElementById('dbChangeTypeModalClose'); + const dbChangeTypeCancel = document.getElementById('dbChangeTypeCancel'); + const dbChangeTypeSave = document.getElementById('dbChangeTypeSave'); + const dbChangeTypeFeedback = document.getElementById('dbChangeTypeFeedback'); + const dbChangeHost = document.getElementById('db_change_host'); + const dbChangePort = document.getElementById('db_change_port'); + const dbChangeUsername = document.getElementById('db_change_username'); + const dbChangePassword = document.getElementById('db_change_password'); + + let dbConfig = null; + let dbUsers = []; + let phpmyadminEnabled = false; + let dbActionTokens = {}; + window._dbActionTokens = dbActionTokens; + + function escapeHtmlDb(str) { + if (!str) return ''; + return String(str) + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); + } + + function checkPasswordStrength(password) { + if (!password) return ''; + let strength = 'weak'; + if (password.length >= 12 && /[A-Z]/.test(password) && /[0-9]/.test(password) && /[^A-Za-z0-9]/.test(password)) { + strength = 'strong'; + } else if (password.length >= 10 && /[A-Z]/.test(password) && /[0-9]/.test(password)) { + strength = 'good'; + } else if (password.length >= 8) { + strength = 'fair'; + } + return `
    `; + } + + function showDbFeedback(el, msg, isError = false) { + if (!el) return; + el.textContent = msg; + el.className = 'node-feedback' + (isError ? ' error' : ' success'); + el.style.display = msg ? 'block' : 'none'; + } + + function clearDbFeedback(el) { + if (el) { + el.textContent = ''; + el.style.display = 'none'; + } + } + + function openModal(overlay, modal) { + if (overlay) overlay.classList.add('show'); + if (modal) modal.classList.add('show'); + } + + function closeModal(overlay, modal) { + if (overlay) overlay.classList.remove('show'); + if (modal) modal.classList.remove('show'); + } + + function getDefaultPort(dbType) { + switch (dbType) { + case 'mysql': return 3306; + case 'postgresql': return 5432; + case 'mongodb': return 27017; + default: return 3306; + } + } + + function getDbTypeIcon(dbType) { + switch (dbType) { + case 'mysql': return 'fa-solid fa-database'; + case 'postgresql': return 'fa-solid fa-database'; + case 'mongodb': return 'fa-solid fa-leaf'; + default: return 'fa-solid fa-database'; + } + } + + async function loadDbConfig() { + try { + const res = await fetch('/api/settings/database'); + 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); + } + } + + function updateDbUI() { + if (!phpmyadminToggle) return; + + phpmyadminToggle.checked = phpmyadminEnabled; + + if (phpmyadminEnabled && dbConfig) { + if (phpmyadminDetails) phpmyadminDetails.style.display = 'block'; + + if (phpmyadminStatus) { + phpmyadminStatus.innerHTML = ` +
    + + phpMyAdmin is active and running +
    + `; + } + + if (dbUsersSection) dbUsersSection.style.display = 'block'; + renderDbUsers(); + + if (dbTypeSection) dbTypeSection.style.display = 'block'; + updateDbTypeDisplay(); + + if (phpmyadminAccessSection) { + phpmyadminAccessSection.style.display = 'block'; + if (phpmyadminUrl) phpmyadminUrl.textContent = 'Secure token access (click Open)'; + } + } else { + if (phpmyadminDetails) phpmyadminDetails.style.display = 'none'; + if (dbUsersSection) dbUsersSection.style.display = 'none'; + if (dbTypeSection) dbTypeSection.style.display = 'none'; + if (phpmyadminAccessSection) phpmyadminAccessSection.style.display = 'none'; + } + } + + function updateDbTypeDisplay() { + if (!dbTypeCurrent || !dbConfig) return; + + const icon = getDbTypeIcon(dbConfig.type); + const typeName = (dbConfig.type || 'mysql').charAt(0).toUpperCase() + (dbConfig.type || 'mysql').slice(1); + + dbTypeCurrent.innerHTML = ` +
    +
    +
    ${escapeHtmlDb(typeName)}
    +
    ${escapeHtmlDb(dbConfig.host || 'localhost')}:${dbConfig.port || getDefaultPort(dbConfig.type)}
    +
    + `; + } + + function renderDbUsers() { + if (!dbUsersList) return; + + if (!dbUsers || dbUsers.length === 0) { + dbUsersList.innerHTML = ` +
    + +

    No database users configured

    +
    + `; + return; + } + + dbUsersList.innerHTML = ''; + dbUsers.forEach(user => { + const row = document.createElement('div'); + row.className = 'db-user-row'; + row.innerHTML = ` +
    +
    +
    +
    ${escapeHtmlDb(user.username)}
    +
    ${user.createdAt ? 'Created ' + new Date(user.createdAt).toLocaleDateString() : ''}
    +
    +
    + + `; + dbUsersList.appendChild(row); + }); + } + + function openSetupModal() { + if (!dbSetupModalOverlay || !dbSetupModal) 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); + } + + 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'; + const port = parseInt(dbPort?.value || getDefaultPort(dbType), 10); + const username = dbUsername?.value?.trim(); + const password = dbPassword?.value; + + if (!username) { + showDbFeedback(dbSetupFeedback, 'Username is required', true); + return; + } + + if (!password) { + showDbFeedback(dbSetupFeedback, 'Password is required', true); + return; + } + + if (dbSetupSave) { + dbSetupSave.disabled = true; + dbSetupSave.innerHTML = ' Setting up...'; + } + + try { + const res = await fetch('/api/settings/database/setup', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens.setup || '' }, + body: JSON.stringify({ + type: dbType, + host, + port, + username, + password + }) + }); + + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + + if (!res.ok) { + showDbFeedback(dbSetupFeedback, data.error || 'Setup failed', true); + return; + } + + showDbFeedback(dbSetupFeedback, 'phpMyAdmin setup complete!', false); + phpmyadminEnabled = true; + await loadDbConfig(); + if (phpmyadminToggle) phpmyadminToggle.checked = true; + setTimeout(() => { + closeSetupModal(); + }, 800); + + } catch (err) { + console.error('[database] Setup error:', err); + showDbFeedback(dbSetupFeedback, 'Network error', true); + } finally { + if (dbSetupSave) { + dbSetupSave.disabled = false; + dbSetupSave.innerHTML = ' Setup & Enable'; + } + } + } + + function openUserModal() { + if (!dbUserModalOverlay || !dbUserModal) return; + + if (dbuserUsername) dbuserUsername.value = ''; + if (dbuserPassword) dbuserPassword.value = ''; + if (dbUserPasswordStrength) dbUserPasswordStrength.innerHTML = ''; + + clearDbFeedback(dbUserFeedback); + openModal(dbUserModalOverlay, dbUserModal); + } + + function closeUserModal() { + closeModal(dbUserModalOverlay, dbUserModal); + } + + async function saveDbUser() { + const username = dbuserUsername?.value?.trim(); + const password = dbuserPassword?.value; + + if (!username) { + showDbFeedback(dbUserFeedback, 'Username is required', true); + return; + } + + if (!password || password.length < 8) { + showDbFeedback(dbUserFeedback, 'Password must be at least 8 characters', true); + return; + } + + if (dbUserSave) { + dbUserSave.disabled = true; + dbUserSave.innerHTML = ' Creating...'; + } + + try { + const res = await fetch('/api/settings/database/users', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens.createUser || '' }, + body: JSON.stringify({ username, password }) + }); + + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + + if (!res.ok) { + showDbFeedback(dbUserFeedback, data.error || 'Failed to create user', true); + return; + } + + showDbFeedback(dbUserFeedback, 'User created successfully!', false); + + await loadDbConfig(); + + setTimeout(() => { + closeUserModal(); + }, 600); + + } catch (err) { + console.error('[database] Create user error:', err); + showDbFeedback(dbUserFeedback, 'Network error', true); + } finally { + if (dbUserSave) { + dbUserSave.disabled = false; + dbUserSave.innerHTML = ' Create User'; + } + } + } + + function openPasswordModal(username) { + if (!dbPassModalOverlay || !dbPassModal) return; + + if (dbpassUsername) dbpassUsername.value = username; + if (dbPassModalSubtitle) dbPassModalSubtitle.textContent = `Update password for ${username}`; + if (dbpassPassword) dbpassPassword.value = ''; + if (dbpassConfirm) dbpassConfirm.value = ''; + if (dbPassPasswordStrength) dbPassPasswordStrength.innerHTML = ''; + + clearDbFeedback(dbPassFeedback); + openModal(dbPassModalOverlay, dbPassModal); + } + + function closePasswordModal() { + closeModal(dbPassModalOverlay, dbPassModal); + } + + async function saveDbPassword() { + const username = dbpassUsername?.value; + const password = dbpassPassword?.value; + const confirm = dbpassConfirm?.value; + + if (!password || password.length < 8) { + showDbFeedback(dbPassFeedback, 'Password must be at least 8 characters', true); + return; + } + + if (password !== confirm) { + showDbFeedback(dbPassFeedback, 'Passwords do not match', true); + return; + } + + if (dbPassSave) { + dbPassSave.disabled = true; + dbPassSave.innerHTML = ' Updating...'; + } + + try { + const res = await fetch(`/api/settings/database/users/${encodeURIComponent(username)}/password`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens[`changePassword_${username}`] || '' }, + body: JSON.stringify({ password }) + }); + + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + + if (!res.ok) { + showDbFeedback(dbPassFeedback, data.error || 'Failed to update password', true); + return; + } + + showDbFeedback(dbPassFeedback, 'Password updated successfully!', false); + + setTimeout(() => { + closePasswordModal(); + }, 600); + + } catch (err) { + console.error('[database] Update password error:', err); + showDbFeedback(dbPassFeedback, 'Network error', true); + } finally { + if (dbPassSave) { + dbPassSave.disabled = false; + dbPassSave.innerHTML = ' Update Password'; + } + } + } + + async function deleteDbUser(username) { + if (!confirm(`Delete database user "${username}"? This cannot be undone.`)) return; + + try { + const res = await fetch(`/api/settings/database/users/${encodeURIComponent(username)}`, { + method: 'DELETE', + headers: { 'x-action-token': dbActionTokens[`deleteUser_${username}`] || '' } + }); + + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + + if (!res.ok) { + alert(data.error || 'Failed to delete user'); + return; + } + + await loadDbConfig(); + + } catch (err) { + console.error('[database] Delete user error:', err); + alert('Network error'); + } + } + + function openChangeTypeModal() { + if (!dbChangeTypeModalOverlay || !dbChangeTypeModal) return; + + if (dbChangeHost) dbChangeHost.value = 'localhost'; + if (dbChangePort) dbChangePort.value = ''; + if (dbChangeUsername) dbChangeUsername.value = ''; + if (dbChangePassword) dbChangePassword.value = ''; + + document.querySelectorAll('input[name="db_change_type"]').forEach(r => r.checked = false); + + clearDbFeedback(dbChangeTypeFeedback); + openModal(dbChangeTypeModalOverlay, dbChangeTypeModal); + } + + function closeChangeTypeModal() { + closeModal(dbChangeTypeModalOverlay, dbChangeTypeModal); + } + + async function saveDbTypeChange() { + const dbType = document.querySelector('input[name="db_change_type"]:checked')?.value; + const host = dbChangeHost?.value?.trim() || 'localhost'; + const port = parseInt(dbChangePort?.value || getDefaultPort(dbType), 10); + const username = dbChangeUsername?.value?.trim(); + const password = dbChangePassword?.value; + + if (!dbType) { + showDbFeedback(dbChangeTypeFeedback, 'Please select a database type', true); + return; + } + + if (!username) { + showDbFeedback(dbChangeTypeFeedback, 'Username is required', true); + return; + } + + if (!password) { + showDbFeedback(dbChangeTypeFeedback, 'Password is required', true); + return; + } + + if (!confirm('This will remove all existing database users and settings. Continue?')) { + return; + } + + if (dbChangeTypeSave) { + dbChangeTypeSave.disabled = true; + dbChangeTypeSave.innerHTML = ' Changing...'; + } + + try { + const res = await fetch('/api/settings/database/change-type', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': dbActionTokens.changeType || '' }, + body: JSON.stringify({ + type: dbType, + host, + port, + username, + password + }) + }); + + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + + if (!res.ok) { + showDbFeedback(dbChangeTypeFeedback, data.error || 'Failed to change database type', true); + return; + } + + showDbFeedback(dbChangeTypeFeedback, 'Database type changed successfully!', false); + + await loadDbConfig(); + + setTimeout(() => { + closeChangeTypeModal(); + }, 800); + + } catch (err) { + console.error('[database] Change type error:', err); + showDbFeedback(dbChangeTypeFeedback, 'Network error', true); + } finally { + if (dbChangeTypeSave) { + dbChangeTypeSave.disabled = false; + dbChangeTypeSave.innerHTML = ' Change Database'; + } + } + } + + async function togglePhpmyadmin(enabled) { + if (enabled && !phpmyadminEnabled) { + if (phpmyadminToggle) phpmyadminToggle.checked = false; + openSetupModal(); + return; + } + + if (!enabled && phpmyadminEnabled) { + if (!confirm('Disable phpMyAdmin? This will remove all database users and settings.')) { + if (phpmyadminToggle) phpmyadminToggle.checked = true; + return; + } + + const statusEl = document.getElementById('phpmyadminStatus'); + const detailsEl = document.getElementById('phpmyadminDetails'); + const accessSection = document.getElementById('phpmyadminAccessSection'); + const usersSection = document.getElementById('dbUsersSection'); + if (detailsEl) detailsEl.style.display = 'block'; + if (accessSection) accessSection.style.display = 'none'; + if (usersSection) usersSection.style.display = 'none'; + const progress = statusEl ? createDbDisableProgress(statusEl, [ + 'Disabling web access', + 'Removing configuration', + 'Saving settings' + ], 10, '#f89d21') : null; + + if (phpmyadminToggle) phpmyadminToggle.disabled = true; + + try { + const res = await fetch('/api/settings/database/disable', { + method: 'POST', + headers: { 'x-action-token': dbActionTokens.disable || '' } + }); + + const data = await res.json().catch(() => ({ error: 'Invalid response' })); + + if (!res.ok) { + if (progress) progress.finish(false, data.error || 'Failed to disable phpMyAdmin'); + if (phpmyadminToggle) { phpmyadminToggle.checked = true; phpmyadminToggle.disabled = false; } + return; + } + + if (progress) progress.finish(true, 'phpMyAdmin disabled successfully — refresh to update'); + + phpmyadminEnabled = false; + dbConfig = null; + dbUsers = []; + if (phpmyadminToggle) { phpmyadminToggle.checked = false; phpmyadminToggle.disabled = false; } + + } catch (err) { + console.error('[database] Disable error:', err); + if (progress) progress.finish(false, 'Network error — please try again'); + if (phpmyadminToggle) { phpmyadminToggle.checked = true; phpmyadminToggle.disabled = false; } + } + } + } + + if (phpmyadminToggle) { + phpmyadminToggle.addEventListener('change', (e) => { + togglePhpmyadmin(e.target.checked); + }); + } + + if (dbSetupModalClose) dbSetupModalClose.addEventListener('click', closeSetupModal); + if (dbSetupCancel) dbSetupCancel.addEventListener('click', closeSetupModal); + if (dbSetupModalOverlay) { + dbSetupModalOverlay.addEventListener('click', (e) => { + if (e.target === dbSetupModalOverlay) closeSetupModal(); + }); + } + if (dbSetupSave) dbSetupSave.addEventListener('click', saveDbSetup); + + document.querySelectorAll('input[name="db_type"]').forEach(radio => { + radio.addEventListener('change', (e) => { + if (dbPort) dbPort.value = getDefaultPort(e.target.value); + }); + }); + + document.querySelectorAll('input[name="db_change_type"]').forEach(radio => { + radio.addEventListener('change', (e) => { + if (dbChangePort) dbChangePort.value = getDefaultPort(e.target.value); + }); + }); + + if (addDbUserBtn) addDbUserBtn.addEventListener('click', openUserModal); + if (dbUserModalClose) dbUserModalClose.addEventListener('click', closeUserModal); + if (dbUserCancel) dbUserCancel.addEventListener('click', closeUserModal); + if (dbUserModalOverlay) { + dbUserModalOverlay.addEventListener('click', (e) => { + if (e.target === dbUserModalOverlay) closeUserModal(); + }); + } + if (dbUserSave) dbUserSave.addEventListener('click', saveDbUser); + + if (dbuserPassword) { + dbuserPassword.addEventListener('input', (e) => { + if (dbUserPasswordStrength) { + dbUserPasswordStrength.innerHTML = checkPasswordStrength(e.target.value); + } + }); + } + + if (dbPassModalClose) dbPassModalClose.addEventListener('click', closePasswordModal); + if (dbPassCancel) dbPassCancel.addEventListener('click', closePasswordModal); + if (dbPassModalOverlay) { + dbPassModalOverlay.addEventListener('click', (e) => { + if (e.target === dbPassModalOverlay) closePasswordModal(); + }); + } + if (dbPassSave) dbPassSave.addEventListener('click', saveDbPassword); + + if (dbpassPassword) { + dbpassPassword.addEventListener('input', (e) => { + if (dbPassPasswordStrength) { + dbPassPasswordStrength.innerHTML = checkPasswordStrength(e.target.value); + } + }); + } + + if (changeDbTypeBtn) changeDbTypeBtn.addEventListener('click', openChangeTypeModal); + if (dbChangeTypeModalClose) dbChangeTypeModalClose.addEventListener('click', closeChangeTypeModal); + if (dbChangeTypeCancel) dbChangeTypeCancel.addEventListener('click', closeChangeTypeModal); + if (dbChangeTypeModalOverlay) { + dbChangeTypeModalOverlay.addEventListener('click', (e) => { + if (e.target === dbChangeTypeModalOverlay) closeChangeTypeModal(); + }); + } + if (dbChangeTypeSave) dbChangeTypeSave.addEventListener('click', saveDbTypeChange); + + if (dbUsersList) { + dbUsersList.addEventListener('click', (e) => { + const editBtn = e.target.closest('.db-user-btn-edit'); + if (editBtn) { + const username = editBtn.dataset.username; + if (username) openPasswordModal(username); + return; + } + + const deleteBtn = e.target.closest('.db-user-btn-delete'); + if (deleteBtn) { + const username = deleteBtn.dataset.username; + if (username) deleteDbUser(username); + return; + } + }); + } + + // Helper: request a secure access token for database tools + async function requestDbAccessToken(service) { + try { + const res = await fetch('/api/settings/database/access-token', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ service }) + }); + const payload = await res.json().catch(() => ({})); + if (!res.ok) { + throw new Error(payload.error || 'Failed to get access token'); + } + return payload; + } catch (err) { + console.error('[db-proxy] Token request failed:', err); + return { error: err?.message || 'Failed to get access token' }; + } + } + window._requestDbAccessToken = requestDbAccessToken; + + if (copyPhpmyadminUrl) { + copyPhpmyadminUrl.addEventListener('click', async () => { + const originalHtml = copyPhpmyadminUrl.innerHTML; + copyPhpmyadminUrl.disabled = true; + copyPhpmyadminUrl.innerHTML = ''; + try { + const tokenData = await requestDbAccessToken('phpmyadmin'); + if (!tokenData || !tokenData.url) throw new Error(tokenData?.error || 'Failed to generate secure URL'); + const fullUrl = new URL(tokenData.url, window.location.origin).toString(); + await copyToClipboard(fullUrl); + copyPhpmyadminUrl.innerHTML = ''; + setTimeout(() => { + copyPhpmyadminUrl.disabled = false; + copyPhpmyadminUrl.innerHTML = originalHtml; + }, 1500); + } catch (err) { + console.error('[db-proxy] phpMyAdmin copy failed:', err); + copyPhpmyadminUrl.disabled = false; + copyPhpmyadminUrl.innerHTML = originalHtml; + alert(err?.message || 'Failed to copy secure URL. Please try again.'); + } + }); + } + + if (openPhpmyadminUrl) { + openPhpmyadminUrl.setAttribute('href', '/db-open/phpmyadmin'); + openPhpmyadminUrl.setAttribute('target', '_blank'); + openPhpmyadminUrl.setAttribute('rel', 'noopener noreferrer'); + } + + window.setupPasswordToggle = function (toggleId, inputId) { + const toggle = document.getElementById(toggleId); + const input = document.getElementById(inputId); + if (toggle && input && !toggle.dataset.listenerAdded) { + toggle.dataset.listenerAdded = 'true'; + toggle.addEventListener('click', (e) => { + e.preventDefault(); + e.stopPropagation(); + const icon = toggle.querySelector('i'); + if (input.type === 'password') { + input.type = 'text'; + if (icon) { + icon.classList.remove('fa-eye'); + icon.classList.add('fa-eye-slash'); + } + toggle.setAttribute('aria-label', 'Hide password'); + } else { + input.type = 'password'; + if (icon) { + icon.classList.remove('fa-eye-slash'); + icon.classList.add('fa-eye'); + } + toggle.setAttribute('aria-label', 'Show password'); + } + }); + } + } + + setupPasswordToggle('pgadmin_password_toggle', 'pgadmin_password'); + setupPasswordToggle('mongodb_password_toggle', 'mongodb_password'); + + const observer = new MutationObserver(() => { + setupPasswordToggle('pgadmin_password_toggle', 'pgadmin_password'); + setupPasswordToggle('mongodb_password_toggle', 'mongodb_password'); + }); + observer.observe(document.body, { childList: true, subtree: true }); + + const sidebarNav = document.getElementById('sidebarNav'); + if (sidebarNav) { + sidebarNav.addEventListener('click', (e) => { + const btn = e.target.closest('button'); + if (btn && btn.dataset.panel === 'databases') { + loadDbConfig(); + loadPgAdminStatus(); + loadMongoDBStatus(); + } + }); + } + + const databasesPanel = document.getElementById('databases'); + if (databasesPanel && databasesPanel.classList.contains('active')) { + loadDbConfig(); + loadPgAdminStatus(); + loadMongoDBStatus(); + } +})(); + +var _dbDisableGuard = null; +function _dbBeforeUnload(e) { e.preventDefault(); e.returnValue = ''; } +function _dbDisableGuardOn() { + if (!_dbDisableGuard) { + _dbDisableGuard = true; + window.addEventListener('beforeunload', _dbBeforeUnload); + } +} +function _dbDisableGuardOff() { + if (_dbDisableGuard) { + _dbDisableGuard = null; + window.removeEventListener('beforeunload', _dbBeforeUnload); + } +} + +function createDbDisableProgress(statusEl, steps, estimatedSecs, brandColor) { + const color = brandColor || '#f59e0b'; + const stepsHtml = steps.map((s, i) => + `
    ${s}
    ` + ).join(''); + + statusEl.innerHTML = ` +
    +
    + +
    +
    Disabling...
    +
    Estimated time: ~${estimatedSecs}s
    +
    +
    +
    +
    ${stepsHtml}
    +
    Elapsed: 0s
    +
    + `; + + _dbDisableGuardOn(); + + const barFill = statusEl.querySelector('.db-disable-bar-fill'); + const elapsedEl = statusEl.querySelector('.db-disable-elapsed'); + const stepEls = statusEl.querySelectorAll('.db-disable-step'); + let elapsed = 0; + let currentStep = 0; + + if (stepEls[0]) stepEls[0].classList.add('active'); + + const stepInterval = Math.floor(estimatedSecs / steps.length); + const timer = setInterval(() => { + elapsed++; + if (elapsedEl) elapsedEl.textContent = `Elapsed: ${elapsed}s`; + + const pct = Math.min(90, Math.round((elapsed / estimatedSecs) * 90)); + if (barFill) barFill.style.width = pct + '%'; + + const expectedStep = Math.min(steps.length - 1, Math.floor(elapsed / stepInterval)); + while (currentStep < expectedStep) { + if (stepEls[currentStep]) { + stepEls[currentStep].classList.remove('active'); + stepEls[currentStep].classList.add('done'); + stepEls[currentStep].querySelector('i').className = 'fa-solid fa-check'; + } + currentStep++; + if (stepEls[currentStep]) stepEls[currentStep].classList.add('active'); + } + }, 1000); + + return { + finish(success, message) { + clearInterval(timer); + _dbDisableGuardOff(); + stepEls.forEach(el => { + el.classList.remove('active'); + if (success) { + el.classList.add('done'); + el.querySelector('i').className = 'fa-solid fa-check'; + } + }); + if (barFill) barFill.style.width = '100%'; + if (success) { + setTimeout(() => { + statusEl.innerHTML = `
    ${message || 'Disabled successfully'}
    `; + }, 400); + } else { + statusEl.innerHTML = `
    ${message || 'Failed to disable'}
    `; + } + } + }; +} + +(function () { + 'use strict'; + + const pgadminToggle = document.getElementById('pgadminToggle'); + const pgadminStatus = document.getElementById('pgadminStatus'); + const pgadminAccessSection = document.getElementById('pgadminAccessSection'); + const pgadminUrl = document.getElementById('pgadminUrl'); + const copyPgadminUrl = document.getElementById('copyPgadminUrl'); + const openPgadminUrl = document.getElementById('openPgadminUrl'); + + const pgadminSetupModalOverlay = document.getElementById('pgadminSetupModalOverlay'); + const pgadminSetupModalClose = document.getElementById('pgadminSetupModalClose'); + const pgadminSetupCancel = document.getElementById('pgadminSetupCancel'); + const pgadminSetupSave = document.getElementById('pgadminSetupSave'); + const pgadminSetupFeedback = document.getElementById('pgadminSetupFeedback'); + const pgadminEmail = document.getElementById('pgadmin_email'); + const pgadminPassword = document.getElementById('pgadmin_password'); + const pgadminPasswordStrength = document.getElementById('pgadminPasswordStrength'); + + function showPgAdminFeedback(msg, isError = false) { + if (pgadminSetupFeedback) { + pgadminSetupFeedback.textContent = msg; + pgadminSetupFeedback.className = 'node-feedback' + (isError ? ' error' : ' success'); + pgadminSetupFeedback.style.display = msg ? 'block' : 'none'; + } + } + + function openPgAdminSetupModal() { + if (pgadminEmail) pgadminEmail.value = ''; + if (pgadminPassword) pgadminPassword.value = ''; + if (pgadminPasswordStrength) pgadminPasswordStrength.innerHTML = ''; + showPgAdminFeedback(''); + if (pgadminSetupModalOverlay) { + pgadminSetupModalOverlay.classList.add('show'); + pgadminSetupModalOverlay.setAttribute('aria-hidden', 'false'); + } + } + + document.addEventListener(ASSISTANT_SETTINGS_ACTION_EVENT, (event) => { + if (event?.detail?.action === 'pgadmin_setup') { + openPgAdminSetupModal(); + } + }); + + function closePgAdminSetupModal() { + if (pgadminSetupModalOverlay) { + pgadminSetupModalOverlay.classList.remove('show'); + pgadminSetupModalOverlay.setAttribute('aria-hidden', 'true'); + } + if (pgadminToggle && !pgadminToggle.dataset.wasEnabled) { + pgadminToggle.checked = false; + } + } + + window.loadPgAdminStatus = async function () { + if (!pgadminStatus) return; + pgadminStatus.innerHTML = '
    Checking status...
    '; + + try { + const res = await fetch('/api/settings/database/pgadmin/status'); + if (!res.ok) throw new Error('Failed to fetch status'); + const data = await res.json(); + + if (pgadminToggle) { + pgadminToggle.checked = data.enabled; + pgadminToggle.dataset.wasEnabled = data.enabled ? 'true' : ''; + } + + if (data.enabled && data.postgresRunning) { + if (pgadminUrl) pgadminUrl.textContent = 'Secure token access (click Open)'; + if (pgadminAccessSection) pgadminAccessSection.style.display = 'block'; + pgadminStatus.innerHTML = '
    PostgreSQL & pgAdmin4 running
    '; + } else if (data.installed) { + pgadminStatus.innerHTML = '
    PostgreSQL installed but not enabled
    '; + if (pgadminAccessSection) pgadminAccessSection.style.display = 'none'; + } else { + pgadminStatus.innerHTML = '
    Not installed - Enable to install
    '; + if (pgadminAccessSection) pgadminAccessSection.style.display = 'none'; + } + } catch (err) { + console.error('[pgadmin] Status error:', err); + pgadminStatus.innerHTML = '
    Error checking status
    '; + } + }; + + async function savePgAdminSetup() { + 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'; + const dbPort = document.getElementById('pgadmin_db_port')?.value?.trim() || '5432'; + + if (!email || !email.includes('@')) { + showPgAdminFeedback('Please enter a valid email address', true); + return; + } + + if (!password || password.length < 8) { + showPgAdminFeedback('Password must be at least 8 characters', true); + return; + } + + if (!dbUser || dbUser.length < 2) { + showPgAdminFeedback('Please enter a valid database username', true); + return; + } + + const progressContainer = document.getElementById('pgadminProgressContainer'); + const progressText = document.getElementById('pgadminProgressText'); + const progressPercent = document.getElementById('pgadminProgressPercent'); + const progressFill = document.getElementById('pgadminProgressFill'); + + if (progressContainer) progressContainer.style.display = 'block'; + if (progressText) progressText.textContent = 'Starting installation...'; + if (progressPercent) progressPercent.textContent = '0%'; + if (progressFill) progressFill.style.width = '0%'; + + if (pgadminSetupSave) { + pgadminSetupSave.disabled = true; + pgadminSetupSave.innerHTML = ' Installing...'; + } + if (pgadminSetupCancel) pgadminSetupCancel.disabled = true; + showPgAdminFeedback('', false); + + try { + const res = await fetch('/api/settings/database/pgadmin/setup', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': (window._dbActionTokens || {}).pgadminSetup || '' }, + body: JSON.stringify({ email, password, dbUser, dbHost, dbPort }) + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Setup failed'); + + const jobId = data.jobId; + const accessUrl = data.accessUrl; + + const pollProgress = async () => { + try { + const statusRes = await fetch(`/api/settings/database/install-progress/${jobId}`); + const status = await statusRes.json(); + + if (progressText) progressText.textContent = status.message || 'Installing...'; + if (progressPercent) progressPercent.textContent = `${status.progress || 0}%`; + if (progressFill) progressFill.style.width = `${status.progress || 0}%`; + + if (status.status === 'completed') { + if (progressContainer) progressContainer.style.display = 'none'; + if (pgadminSetupSave) { pgadminSetupSave.disabled = false; pgadminSetupSave.innerHTML = ' Install & Setup'; } + if (pgadminSetupCancel) pgadminSetupCancel.disabled = false; + showPgAdminFeedback('pgAdmin4 setup complete!', false); + + setTimeout(() => { + closePgAdminSetupModal(); + loadPgAdminStatus(); + + const toast = document.createElement('div'); + toast.className = 'perm-success-toast'; + toast.innerHTML = ` pgAdmin4 installed! Use the Open button for secure access.`; + document.body.appendChild(toast); + setTimeout(() => { toast.classList.add('show'); }, 10); + setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 4000); + }, 1000); + return; + } else if (status.status === 'failed') { + throw new Error(status.error || 'Installation failed'); + } else { + setTimeout(pollProgress, 2000); + } + } catch (pollErr) { + console.error('[pgadmin] Poll error:', pollErr); + showPgAdminFeedback('Installation failed: ' + pollErr.message, true); + if (progressContainer) progressContainer.style.display = 'none'; + if (pgadminToggle) pgadminToggle.checked = false; + if (pgadminSetupSave) { pgadminSetupSave.disabled = false; pgadminSetupSave.innerHTML = ' Install & Setup'; } + if (pgadminSetupCancel) pgadminSetupCancel.disabled = false; + } + }; + + setTimeout(pollProgress, 2000); + + } catch (err) { + console.error('[pgadmin] Setup error:', err); + showPgAdminFeedback('Setup failed: ' + err.message, true); + if (progressContainer) progressContainer.style.display = 'none'; + if (pgadminToggle) pgadminToggle.checked = false; + if (pgadminSetupSave) { pgadminSetupSave.disabled = false; pgadminSetupSave.innerHTML = ' Install & Setup'; } + if (pgadminSetupCancel) pgadminSetupCancel.disabled = false; + } + } + + async function disablePgAdmin() { + const pgadminDetails = document.getElementById('pgadminDetails'); + if (pgadminDetails) pgadminDetails.style.display = 'block'; + const progress = pgadminStatus ? createDbDisableProgress(pgadminStatus, [ + 'Stopping PostgreSQL service', + 'Stopping Apache service', + 'Removing Apache config', + 'Cleaning up nginx config', + 'Uninstalling pgAdmin4 packages', + 'Removing data directories', + 'Cleaning up apt sources', + 'Finalizing' + ], 60, '#336791') : null; + + if (pgadminToggle) pgadminToggle.disabled = true; + if (pgadminAccessSection) pgadminAccessSection.style.display = 'none'; + + try { + const res = await fetch('/api/settings/database/pgadmin/disable', { method: 'POST', headers: { 'x-action-token': (window._dbActionTokens || {}).pgadminDisable || '' } }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.error || 'Failed to disable'); + } + if (progress) progress.finish(true, 'pgAdmin4 disabled and uninstalled — refresh to update'); + } catch (err) { + console.error('[pgadmin] Disable error:', err); + if (progress) progress.finish(false, err.message || 'Failed to disable pgAdmin4'); + if (pgadminToggle) pgadminToggle.checked = true; + } finally { + if (pgadminToggle) pgadminToggle.disabled = false; + } + } + + if (pgadminToggle) { + pgadminToggle.addEventListener('change', (e) => { + if (e.target.checked) openPgAdminSetupModal(); + else disablePgAdmin(); + }); + } + + if (pgadminSetupModalClose) pgadminSetupModalClose.addEventListener('click', closePgAdminSetupModal); + if (pgadminSetupCancel) pgadminSetupCancel.addEventListener('click', closePgAdminSetupModal); + if (pgadminSetupModalOverlay) { + pgadminSetupModalOverlay.addEventListener('click', (e) => { + if (e.target === pgadminSetupModalOverlay) closePgAdminSetupModal(); + }); + } + if (pgadminSetupSave) pgadminSetupSave.addEventListener('click', savePgAdminSetup); + + if (pgadminPassword && pgadminPasswordStrength) { + pgadminPassword.addEventListener('input', (e) => { + const val = e.target.value; + let strength = 'weak'; + if (val.length >= 12 && /[A-Z]/.test(val) && /[0-9]/.test(val) && /[^A-Za-z0-9]/.test(val)) { + strength = 'strong'; + } else if (val.length >= 10 && /[A-Z]/.test(val) && /[0-9]/.test(val)) { + strength = 'good'; + } else if (val.length >= 8) { + strength = 'fair'; + } + pgadminPasswordStrength.innerHTML = val ? `
    ` : ''; + }); + } + + if (copyPgadminUrl) { + copyPgadminUrl.addEventListener('click', async () => { + const originalHtml = copyPgadminUrl.innerHTML; + copyPgadminUrl.disabled = true; + copyPgadminUrl.innerHTML = ''; + try { + const reqToken = window._requestDbAccessToken; + if (typeof reqToken !== 'function') throw new Error('Secure token service unavailable'); + const tokenData = await reqToken('pgadmin'); + if (!tokenData || !tokenData.url) throw new Error(tokenData?.error || 'Failed to generate secure URL'); + const fullUrl = new URL(tokenData.url, window.location.origin).toString(); + await copyToClipboard(fullUrl); + copyPgadminUrl.innerHTML = ''; + setTimeout(() => { + copyPgadminUrl.disabled = false; + copyPgadminUrl.innerHTML = originalHtml; + }, 1500); + } catch (err) { + console.error('[db-proxy] pgAdmin copy failed:', err); + copyPgadminUrl.disabled = false; + copyPgadminUrl.innerHTML = originalHtml; + alert(err?.message || 'Failed to copy secure URL. Please try again.'); + } + }); + } + + if (openPgadminUrl) { + openPgadminUrl.setAttribute('href', '/db-open/pgadmin'); + openPgadminUrl.setAttribute('target', '_blank'); + openPgadminUrl.setAttribute('rel', 'noopener noreferrer'); + } +})(); + +(function () { + 'use strict'; + + const mongodbToggle = document.getElementById('mongodbToggle'); + const mongodbStatus = document.getElementById('mongodbStatus'); + const mongodbAccessSection = document.getElementById('mongodbAccessSection'); + const mongodbConnString = document.getElementById('mongodbConnString'); + const copyMongodbUrl = document.getElementById('copyMongodbUrl'); + const mongodbConnPass = document.getElementById('mongodbConnPass'); + const toggleMongodbPassword = document.getElementById('toggleMongodbPassword'); + + const mongodbSetupModalOverlay = document.getElementById('mongodbSetupModalOverlay'); + const mongodbSetupModalClose = document.getElementById('mongodbSetupModalClose'); + const mongodbSetupCancel = document.getElementById('mongodbSetupCancel'); + const mongodbSetupSave = document.getElementById('mongodbSetupSave'); + const mongodbSetupFeedback = document.getElementById('mongodbSetupFeedback'); + const mongodbUsername = document.getElementById('mongodb_username'); + const mongodbPassword = document.getElementById('mongodb_password'); + const mongodbPasswordStrength = document.getElementById('mongodbPasswordStrength'); + const MONGODB_PASSWORD_CACHE_PREFIX = 'adpanel.mongodb.password.'; + let pendingMongoPassword = ''; + + function getMongoConnectionInfo() { + const urlWrapper = document.querySelector('.db-access-url-wrapper'); + const connUser = document.getElementById('mongodbConnUser'); + const connHost = document.getElementById('mongodbConnHost'); + const rawHost = (urlWrapper?.dataset.host || '').trim(); + const rawPort = (urlWrapper?.dataset.port || '').trim(); + const hostText = (connHost?.textContent || '').trim(); + const splitAt = hostText.lastIndexOf(':'); + const hostFromText = splitAt > -1 ? hostText.slice(0, splitAt) : hostText; + const portFromText = splitAt > -1 ? hostText.slice(splitAt + 1) : ''; + const username = (urlWrapper?.dataset.username || connUser?.textContent || 'admin').trim() || 'admin'; + const host = rawHost || hostFromText || 'localhost'; + const port = rawPort || portFromText || '27017'; + return { + urlWrapper, + username, + host, + port, + cacheKey: `${MONGODB_PASSWORD_CACHE_PREFIX}${username}@${host}:${port}` + }; + } + + function setMongoConnectionPassword(password, persist = true) { + const safePassword = typeof password === 'string' ? password : ''; + const { urlWrapper, cacheKey } = getMongoConnectionInfo(); + if (mongodbConnPass) mongodbConnPass.dataset.password = safePassword; + if (urlWrapper) urlWrapper.dataset.password = safePassword; + if (!persist) return; + try { + if (safePassword) localStorage.setItem(cacheKey, safePassword); + else localStorage.removeItem(cacheKey); + } catch { } + } + + function loadCachedMongoConnectionPassword() { + const { cacheKey } = getMongoConnectionInfo(); + try { + const cached = localStorage.getItem(cacheKey) || ''; + setMongoConnectionPassword(cached, false); + return cached; + } catch { + return ''; + } + } + + function ensureMongoConnectionPassword() { + const existing = mongodbConnPass?.dataset.password || ''; + if (existing) return existing; + const cached = loadCachedMongoConnectionPassword(); + if (cached) return cached; + const { username } = getMongoConnectionInfo(); + const entered = prompt(`Enter MongoDB password for "${username}" to use in the connection string:`); + if (!entered) return ''; + setMongoConnectionPassword(entered, true); + return entered; + } + + function hideMongoConnectionPassword() { + if (!mongodbConnPass) return; + mongodbConnPass.classList.add('blurred'); + mongodbConnPass.textContent = '••••••••'; + if (toggleMongodbPassword) { + toggleMongodbPassword.innerHTML = ''; + toggleMongodbPassword.title = 'Show password'; + } + } + + function showMongoConnectionPassword(password) { + if (!mongodbConnPass) return; + mongodbConnPass.classList.remove('blurred'); + mongodbConnPass.textContent = password; + if (toggleMongodbPassword) { + toggleMongodbPassword.innerHTML = ''; + toggleMongodbPassword.title = 'Hide password'; + } + } + + function showMongoDBFeedback(msg, isError = false) { + if (mongodbSetupFeedback) { + mongodbSetupFeedback.textContent = msg; + mongodbSetupFeedback.className = 'node-feedback' + (isError ? ' error' : ' success'); + mongodbSetupFeedback.style.display = msg ? 'block' : 'none'; + } + } + + function openMongoDBSetupModal() { + if (mongodbUsername) mongodbUsername.value = 'admin'; + if (mongodbPassword) mongodbPassword.value = ''; + if (mongodbPasswordStrength) mongodbPasswordStrength.innerHTML = ''; + showMongoDBFeedback(''); + if (mongodbSetupModalOverlay) { + mongodbSetupModalOverlay.classList.add('show'); + mongodbSetupModalOverlay.setAttribute('aria-hidden', 'false'); + } + } + + document.addEventListener(ASSISTANT_SETTINGS_ACTION_EVENT, (event) => { + if (event?.detail?.action === 'mongodb_setup') { + openMongoDBSetupModal(); + } + }); + + function closeMongoDBSetupModal() { + if (mongodbSetupModalOverlay) { + mongodbSetupModalOverlay.classList.remove('show'); + mongodbSetupModalOverlay.setAttribute('aria-hidden', 'true'); + } + if (mongodbToggle && !mongodbToggle.dataset.wasEnabled) { + mongodbToggle.checked = false; + } + } + + window.loadMongoDBStatus = async function () { + if (!mongodbStatus) return; + mongodbStatus.innerHTML = '
    Checking status...
    '; + + try { + const res = await fetch('/api/settings/database/mongodb/status'); + if (!res.ok) throw new Error('Failed to fetch status'); + const data = await res.json(); + + if (mongodbToggle) { + mongodbToggle.checked = data.enabled; + mongodbToggle.dataset.wasEnabled = data.enabled ? 'true' : ''; + } + + if (data.enabled && data.mongoRunning) { + const host = data.host === '0.0.0.0' ? window.location.hostname : (data.host || 'localhost'); + const port = data.port || '27017'; + + if (data.users && data.users[0]) { + const adminUser = data.users[0]; + const connUser = document.getElementById('mongodbConnUser'); + const connPass = document.getElementById('mongodbConnPass'); + const connHost = document.getElementById('mongodbConnHost'); + + if (connUser) connUser.textContent = adminUser.username; + if (connPass) { + hideMongoConnectionPassword(); + } + if (connHost) connHost.textContent = `${host}:${port}`; + + const urlWrapper = document.querySelector('.db-access-url-wrapper'); + if (urlWrapper) { + urlWrapper.dataset.username = adminUser.username || 'admin'; + urlWrapper.dataset.host = host; + urlWrapper.dataset.port = port; + } + if (pendingMongoPassword) { + setMongoConnectionPassword(pendingMongoPassword, true); + pendingMongoPassword = ''; + } else { + loadCachedMongoConnectionPassword(); + } + } + if (mongodbAccessSection) mongodbAccessSection.style.display = 'block'; + mongodbStatus.innerHTML = `
    MongoDB running on ${host}:${port}
    `; + if (typeof window.loadMongoDBUsers === 'function') window.loadMongoDBUsers(); + } else if (data.installed) { + mongodbStatus.innerHTML = '
    MongoDB installed but not enabled
    '; + if (mongodbAccessSection) mongodbAccessSection.style.display = 'none'; + } else { + mongodbStatus.innerHTML = '
    Not installed - Enable to install
    '; + if (mongodbAccessSection) mongodbAccessSection.style.display = 'none'; + } + } catch (err) { + console.error('[mongodb] Status error:', err); + mongodbStatus.innerHTML = '
    Error checking status
    '; + } + }; + + async function saveMongoDBSetup() { + 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'; + + if (!username || !/^[a-zA-Z0-9_-]+$/.test(username)) { + showMongoDBFeedback('Please enter a valid username (alphanumeric, _, - only)', true); + return; + } + + if (!password || password.length < 8) { + showMongoDBFeedback('Password must be at least 8 characters', true); + return; + } + + const progressContainer = document.getElementById('mongodbProgressContainer'); + const progressText = document.getElementById('mongodbProgressText'); + const progressPercent = document.getElementById('mongodbProgressPercent'); + const progressFill = document.getElementById('mongodbProgressFill'); + + if (progressContainer) progressContainer.style.display = 'block'; + if (progressText) progressText.textContent = 'Starting installation...'; + if (progressPercent) progressPercent.textContent = '0%'; + if (progressFill) progressFill.style.width = '0%'; + + if (mongodbSetupSave) { + mongodbSetupSave.disabled = true; + mongodbSetupSave.innerHTML = ' Installing...'; + } + if (mongodbSetupCancel) mongodbSetupCancel.disabled = true; + showMongoDBFeedback('', false); + + try { + const res = await fetch('/api/settings/database/mongodb/setup', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': (window._dbActionTokens || {}).mongodbSetup || '' }, + body: JSON.stringify({ username, password, host, port }) + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Setup failed'); + + const jobId = data.jobId; + + const pollProgress = async () => { + try { + const statusRes = await fetch(`/api/settings/database/install-progress/${jobId}`); + const status = await statusRes.json(); + + if (progressText) progressText.textContent = status.message || 'Installing...'; + if (progressPercent) progressPercent.textContent = `${status.progress || 0}%`; + if (progressFill) progressFill.style.width = `${status.progress || 0}%`; + + if (status.status === 'completed') { + if (progressContainer) progressContainer.style.display = 'none'; + if (mongodbSetupSave) { mongodbSetupSave.disabled = false; mongodbSetupSave.innerHTML = ' Install & Setup'; } + if (mongodbSetupCancel) mongodbSetupCancel.disabled = false; + showMongoDBFeedback('MongoDB setup complete!', false); + pendingMongoPassword = password; + + setTimeout(() => { + closeMongoDBSetupModal(); + loadMongoDBStatus(); + + const toast = document.createElement('div'); + toast.className = 'perm-success-toast'; + toast.innerHTML = ' MongoDB installed and ready!'; + document.body.appendChild(toast); + setTimeout(() => { toast.classList.add('show'); }, 10); + setTimeout(() => { toast.classList.remove('show'); setTimeout(() => toast.remove(), 300); }, 4000); + }, 1000); + return; + } else if (status.status === 'failed') { + throw new Error(status.error || 'Installation failed'); + } else { + setTimeout(pollProgress, 2000); + } + } catch (pollErr) { + console.error('[mongodb] Poll error:', pollErr); + showMongoDBFeedback('Installation failed: ' + pollErr.message, true); + if (progressContainer) progressContainer.style.display = 'none'; + if (mongodbToggle) mongodbToggle.checked = false; + if (mongodbSetupSave) { mongodbSetupSave.disabled = false; mongodbSetupSave.innerHTML = ' Install & Setup'; } + if (mongodbSetupCancel) mongodbSetupCancel.disabled = false; + } + }; + + setTimeout(pollProgress, 2000); + + } catch (err) { + console.error('[mongodb] Setup error:', err); + showMongoDBFeedback('Setup failed: ' + err.message, true); + if (progressContainer) progressContainer.style.display = 'none'; + if (mongodbToggle) mongodbToggle.checked = false; + if (mongodbSetupSave) { mongodbSetupSave.disabled = false; mongodbSetupSave.innerHTML = ' Install & Setup'; } + if (mongodbSetupCancel) mongodbSetupCancel.disabled = false; + } + } + + async function disableMongoDB() { + const mongodbStatus = document.getElementById('mongodbStatus'); + const mongodbDetails = document.getElementById('mongodbDetails'); + const mongodbAccessSection = document.getElementById('mongodbAccessSection'); + if (mongodbDetails) mongodbDetails.style.display = 'block'; + + const progress = mongodbStatus ? createDbDisableProgress(mongodbStatus, [ + 'Stopping MongoDB service', + 'Removing MongoDB packages', + 'Removing data and config', + 'Cleaning up apt sources', + 'Reloading system services', + 'Finalizing' + ], 90, '#00ed64') : null; + + if (mongodbToggle) mongodbToggle.disabled = true; + if (mongodbAccessSection) mongodbAccessSection.style.display = 'none'; + + try { + const res = await fetch('/api/settings/database/mongodb/disable', { method: 'POST', headers: { 'x-action-token': (window._dbActionTokens || {}).mongodbDisable || '' } }); + if (!res.ok) { + const data = await res.json().catch(() => ({})); + throw new Error(data.error || 'Failed to disable'); + } + if (progress) progress.finish(true, 'MongoDB disabled and removed — refresh to update'); + } catch (err) { + console.error('[mongodb] Disable error:', err); + if (progress) progress.finish(false, err.message || 'Failed to disable MongoDB'); + if (mongodbToggle) mongodbToggle.checked = true; + } finally { + if (mongodbToggle) mongodbToggle.disabled = false; + } + } + + if (mongodbToggle) { + mongodbToggle.addEventListener('change', (e) => { + if (e.target.checked) openMongoDBSetupModal(); + else disableMongoDB(); + }); + } + + if (mongodbSetupModalClose) mongodbSetupModalClose.addEventListener('click', closeMongoDBSetupModal); + if (mongodbSetupCancel) mongodbSetupCancel.addEventListener('click', closeMongoDBSetupModal); + if (mongodbSetupModalOverlay) { + mongodbSetupModalOverlay.addEventListener('click', (e) => { + if (e.target === mongodbSetupModalOverlay) closeMongoDBSetupModal(); + }); + } + if (mongodbSetupSave) mongodbSetupSave.addEventListener('click', saveMongoDBSetup); + + if (mongodbPassword && mongodbPasswordStrength) { + mongodbPassword.addEventListener('input', (e) => { + const val = e.target.value; + let strength = 'weak'; + if (val.length >= 12 && /[A-Z]/.test(val) && /[0-9]/.test(val) && /[^A-Za-z0-9]/.test(val)) { + strength = 'strong'; + } else if (val.length >= 10 && /[A-Z]/.test(val) && /[0-9]/.test(val)) { + strength = 'good'; + } else if (val.length >= 8) { + strength = 'fair'; + } + mongodbPasswordStrength.innerHTML = val ? `
    ` : ''; + }); + } + + if (mongodbConnPass) { + mongodbConnPass.addEventListener('click', () => { + const isBlurred = mongodbConnPass.classList.contains('blurred'); + if (isBlurred) { + const password = ensureMongoConnectionPassword(); + if (!password) return; + showMongoConnectionPassword(password); + } else if (!isBlurred) { + hideMongoConnectionPassword(); + } + }); + } + + if (toggleMongodbPassword && mongodbConnPass) { + toggleMongodbPassword.addEventListener('click', () => { + const isBlurred = mongodbConnPass.classList.contains('blurred'); + if (isBlurred) { + const password = ensureMongoConnectionPassword(); + if (!password) return; + showMongoConnectionPassword(password); + } else if (!isBlurred) { + hideMongoConnectionPassword(); + } + }); + } + + if (copyMongodbUrl) { + copyMongodbUrl.addEventListener('click', () => { + const urlWrapper = document.querySelector('.db-access-url-wrapper'); + if (!urlWrapper) return; + const username = urlWrapper.dataset.username || 'admin'; + let password = urlWrapper.dataset.password || ''; + if (!password) { + password = ensureMongoConnectionPassword(); + if (!password) return; + } + const host = urlWrapper.dataset.host || 'localhost'; + const port = urlWrapper.dataset.port || '27017'; + const encodedUser = encodeURIComponent(username); + const encodedPass = encodeURIComponent(password); + const fullUrl = `mongodb://${encodedUser}:${encodedPass}@${host}:${port}/?authSource=admin`; + + copyToClipboard(fullUrl).then(() => { + copyMongodbUrl.innerHTML = ''; + setTimeout(() => { copyMongodbUrl.innerHTML = ''; }, 1500); + }); + }); + } + + let mongodbActionTokens = {}; + window.loadMongoDBUsers = async function () { + try { + const res = await fetch('/api/settings/database/mongodb/users'); + const data = await res.json(); + + if (!data.ok || !data.enabled) return; + + mongodbActionTokens = data.actionTokens || {}; + + const portInfo = document.getElementById('mongodbPortInfo'); + const host = data.host === '0.0.0.0' ? window.location.hostname : (data.host || 'localhost'); + const port = data.port || '27017'; + if (portInfo) { + portInfo.textContent = `Database is running on ${host}:${port}`; + } + + const connUser = document.getElementById('mongodbConnUser'); + const connPass = document.getElementById('mongodbConnPass'); + const connHost = document.getElementById('mongodbConnHost'); + const urlWrapper = document.querySelector('.db-access-url-wrapper'); + + if (data.users && data.users[0]) { + const adminUser = data.users[0]; + if (connUser) connUser.textContent = adminUser.username; + if (connPass) { + hideMongoConnectionPassword(); + } + if (connHost) connHost.textContent = `${host}:${port}`; + if (urlWrapper) { + urlWrapper.dataset.username = adminUser.username || 'admin'; + urlWrapper.dataset.host = host; + urlWrapper.dataset.port = port; + } + if (pendingMongoPassword) { + setMongoConnectionPassword(pendingMongoPassword, true); + pendingMongoPassword = ''; + } else { + loadCachedMongoConnectionPassword(); + } + } else { + if (connUser) connUser.textContent = 'admin'; + if (connPass) { + hideMongoConnectionPassword(); + } + if (connHost) connHost.textContent = `${host}:${port}`; + } + + const usersList = document.getElementById('mongodbUsersList'); + if (!usersList) return; + + if (!data.users || data.users.length === 0) { + usersList.innerHTML = ` +
    + +

    No users found

    +
    + `; + return; + } + + usersList.innerHTML = data.users.map((user, idx) => { + const createdAt = user.createdAt ? new Date(user.createdAt).toLocaleDateString() : 'N/A'; + const isAdmin = idx === 0; + return ` +
    +
    +
    + +
    +
    +
    ${user.username}${isAdmin ? ' root' : ''}
    +
    Created ${createdAt}
    +
    +
    + +
    + `; + }).join(''); + + usersList.querySelectorAll('[data-action="change-password"]').forEach(btn => { + btn.addEventListener('click', () => { + const username = btn.getAttribute('data-username'); + window.changeMongoDBPassword(username); + }); + }); + + usersList.querySelectorAll('[data-action="delete-user"]').forEach(btn => { + btn.addEventListener('click', () => { + const username = btn.getAttribute('data-username'); + window.showDeleteUserModal(username); + }); + }); + } catch (err) { + console.error('[mongodb] Load users error:', err); + } + } + + const deleteModalOverlay = document.getElementById('mongodbDeleteUserModalOverlay'); + const deleteUsernameEl = document.getElementById('mongodbDeleteUsername'); + const deleteCancelBtn = document.getElementById('mongodbDeleteCancel'); + const deleteConfirmBtn = document.getElementById('mongodbDeleteConfirm'); + let pendingDeleteUsername = null; + + function openDeleteModal(username) { + pendingDeleteUsername = username; + if (deleteUsernameEl) deleteUsernameEl.textContent = username; + if (deleteModalOverlay) { + deleteModalOverlay.classList.add('show'); + deleteModalOverlay.setAttribute('aria-hidden', 'false'); + } + } + + function closeDeleteModal() { + if (deleteModalOverlay) { + deleteModalOverlay.classList.remove('show'); + deleteModalOverlay.setAttribute('aria-hidden', 'true'); + } + pendingDeleteUsername = null; + } + + window.showDeleteUserModal = openDeleteModal; + + if (deleteCancelBtn) { + deleteCancelBtn.addEventListener('click', closeDeleteModal); + } + + if (deleteModalOverlay) { + deleteModalOverlay.addEventListener('click', (e) => { + if (e.target === deleteModalOverlay) closeDeleteModal(); + }); + } + + if (deleteConfirmBtn) { + deleteConfirmBtn.addEventListener('click', async () => { + if (!pendingDeleteUsername) return; + + deleteConfirmBtn.disabled = true; + deleteConfirmBtn.innerHTML = ' Deleting...'; + + try { + const res = await fetch(`/api/settings/database/mongodb/users/${encodeURIComponent(pendingDeleteUsername)}`, { + method: 'DELETE', + headers: { 'x-action-token': mongodbActionTokens[`deleteUser_${pendingDeleteUsername}`] || '' } + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Delete failed'); + + closeDeleteModal(); + window.loadMongoDBUsers(); + } catch (err) { + alert('Failed to delete user: ' + err.message); + } finally { + deleteConfirmBtn.disabled = false; + deleteConfirmBtn.innerHTML = ' Delete User'; + } + }); + } + + window.deleteMongoDBUser = function (username) { + openDeleteModal(username); + }; + + window.changeMongoDBPassword = async function (username) { + const newPassword = prompt(`Enter new password for "${username}" (min 8 characters):`); + if (!newPassword) return; + if (newPassword.length < 8) { + alert('Password must be at least 8 characters'); + return; + } + + try { + const res = await fetch(`/api/settings/database/mongodb/users/${encodeURIComponent(username)}/password`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': mongodbActionTokens[`changePassword_${username}`] || '' }, + body: JSON.stringify({ password: newPassword }) + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Change password failed'); + alert('Password changed successfully'); + const currentConnUser = (document.getElementById('mongodbConnUser')?.textContent || '').trim() || 'admin'; + if (String(username || '').trim() === currentConnUser) { + setMongoConnectionPassword(newPassword, true); + hideMongoConnectionPassword(); + } + } catch (err) { + alert('Failed to change password: ' + err.message); + } + }; + + const mongodbUserModalOverlay = document.getElementById('mongodbUserModalOverlay'); + const mongodbUserModalClose = document.getElementById('mongodbUserModalClose'); + const mongodbUserCancel = document.getElementById('mongodbUserCancel'); + const mongodbUserSave = document.getElementById('mongodbUserSave'); + const mongodbNewUsername = document.getElementById('mongodb_new_username'); + const mongodbNewPassword = document.getElementById('mongodb_new_password'); + const mongodbUserFeedback = document.getElementById('mongodbUserFeedback'); + + function openMongodbUserModal() { + if (mongodbNewUsername) mongodbNewUsername.value = ''; + if (mongodbNewPassword) mongodbNewPassword.value = ''; + if (mongodbUserFeedback) mongodbUserFeedback.innerHTML = ''; + if (mongodbUserModalOverlay) { + mongodbUserModalOverlay.classList.add('show'); + mongodbUserModalOverlay.setAttribute('aria-hidden', 'false'); + } + } + + function closeMongodbUserModal() { + if (mongodbUserModalOverlay) { + mongodbUserModalOverlay.classList.remove('show'); + mongodbUserModalOverlay.setAttribute('aria-hidden', 'true'); + } + } + + function showMongodbUserFeedback(msg, isError = false) { + if (mongodbUserFeedback) { + mongodbUserFeedback.innerHTML = msg ? `` : ''; + } + } + + const createMongodbUserBtn = document.getElementById('createMongodbUser'); + if (createMongodbUserBtn) { + createMongodbUserBtn.addEventListener('click', openMongodbUserModal); + } + + if (mongodbUserModalClose) mongodbUserModalClose.addEventListener('click', closeMongodbUserModal); + if (mongodbUserCancel) mongodbUserCancel.addEventListener('click', closeMongodbUserModal); + if (mongodbUserModalOverlay) { + mongodbUserModalOverlay.addEventListener('click', (e) => { + if (e.target === mongodbUserModalOverlay) closeMongodbUserModal(); + }); + } + + if (mongodbUserSave) { + mongodbUserSave.addEventListener('click', async () => { + const username = mongodbNewUsername?.value?.trim(); + const password = mongodbNewPassword?.value; + + if (!username || !/^[a-zA-Z0-9_-]+$/.test(username)) { + showMongodbUserFeedback('Invalid username (alphanumeric, _, - only)', true); + return; + } + if (!password || password.length < 8) { + showMongodbUserFeedback('Password must be at least 8 characters', true); + return; + } + + mongodbUserSave.disabled = true; + mongodbUserSave.innerHTML = ' Creating...'; + showMongodbUserFeedback('', false); + + try { + const res = await fetch('/api/settings/database/mongodb/users', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': mongodbActionTokens.createUser || '' }, + body: JSON.stringify({ username, password }) + }); + const data = await res.json(); + if (!res.ok) throw new Error(data.error || 'Create failed'); + + showMongodbUserFeedback('User created successfully!', false); + setTimeout(() => { + closeMongodbUserModal(); + window.loadMongoDBUsers(); + }, 1000); + } catch (err) { + showMongodbUserFeedback('Failed: ' + err.message, true); + } finally { + mongodbUserSave.disabled = false; + mongodbUserSave.innerHTML = ' Create User'; + } + }); + } + + setupPasswordToggle('mongodb_new_password_toggle', 'mongodb_new_password'); + + const originalLoadMongoDBStatus = loadMongoDBStatus; + loadMongoDBStatus = async function () { + await originalLoadMongoDBStatus(); + window.loadMongoDBUsers(); + }; +})(); + +const adminChangePasswordOverlay = document.getElementById('adminChangePasswordOverlay'); +const adminChangePasswordModal = document.getElementById('adminChangePasswordModal'); +const adminChangePasswordTitle = document.getElementById('adminChangePasswordTitle'); +const adminChangePasswordSubtitle = document.getElementById('adminChangePasswordSubtitle'); +const adminChangePasswordClose = document.getElementById('adminChangePasswordClose'); +const adminChangePasswordCancelBtn = document.getElementById('adminChangePasswordCancelBtn'); +const adminChangePasswordSave = document.getElementById('adminChangePasswordSave'); +const adminChangePasswordFeedback = document.getElementById('adminChangePasswordFeedback'); +const adminNewPassword = document.getElementById('adminNewPassword'); +const adminConfirmPassword = document.getElementById('adminConfirmPassword'); +const adminPasswordStrength = document.getElementById('adminPasswordStrength'); + +let currentAdminChangePasswordEmail = ''; + +function showAdminPasswordFeedback(msg, isError = false) { + if (!adminChangePasswordFeedback) return; + adminChangePasswordFeedback.textContent = msg; + adminChangePasswordFeedback.className = 'node-feedback' + (isError ? ' error' : ' success'); + adminChangePasswordFeedback.style.display = msg ? 'block' : 'none'; +} + +function clearAdminPasswordFeedback() { + if (adminChangePasswordFeedback) { + adminChangePasswordFeedback.textContent = ''; + adminChangePasswordFeedback.style.display = 'none'; + } +} + +function openAdminChangePasswordModal(email) { + currentAdminChangePasswordEmail = email; + if (adminChangePasswordTitle) adminChangePasswordTitle.textContent = `Change password for ${email}`; + if (adminChangePasswordSubtitle) adminChangePasswordSubtitle.textContent = 'Set a new password for this user'; + if (adminNewPassword) adminNewPassword.value = ''; + if (adminConfirmPassword) adminConfirmPassword.value = ''; + if (adminPasswordStrength) adminPasswordStrength.innerHTML = ''; + clearAdminPasswordFeedback(); + + if (adminChangePasswordOverlay) { + adminChangePasswordOverlay.setAttribute('aria-hidden', 'false'); + adminChangePasswordOverlay.classList.add('show'); + } +} + +function closeAdminChangePasswordModal() { + if (adminChangePasswordOverlay) { + adminChangePasswordOverlay.setAttribute('aria-hidden', 'true'); + adminChangePasswordOverlay.classList.remove('show'); + } + currentAdminChangePasswordEmail = ''; + clearAdminPasswordFeedback(); +} + +async function saveAdminChangePassword() { + if (!currentAdminChangePasswordEmail) return; + + const newPassword = adminNewPassword?.value || ''; + const confirm = adminConfirmPassword?.value || ''; + + if (!newPassword || !confirm) { + showAdminPasswordFeedback('Please fill in all fields', true); + return; + } + + if (newPassword.length < 8) { + showAdminPasswordFeedback('Password must be at least 8 characters', true); + return; + } + + if (newPassword !== confirm) { + showAdminPasswordFeedback('Passwords do not match', true); + return; + } + + if (adminChangePasswordSave) { + adminChangePasswordSave.disabled = true; + adminChangePasswordSave.innerHTML = ' Updating...'; + } + + try { + const res = await fetch(`/api/settings/accounts/${encodeURIComponent(currentAdminChangePasswordEmail)}/change-password`, { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': (accountsListEl._actionTokens || {}).changePassword || '' + }, + body: JSON.stringify({ newPassword, confirm }) + }); + + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + showAdminPasswordFeedback(data.error || 'Failed to change password', true); + return; + } + + showAdminPasswordFeedback('Password changed successfully!', false); + + setTimeout(() => { + closeAdminChangePasswordModal(); + + const toast = document.createElement('div'); + toast.className = 'perm-success-toast'; + toast.innerHTML = ' Password changed successfully'; + document.body.appendChild(toast); + setTimeout(() => { toast.classList.add('show'); }, 10); + setTimeout(() => { + toast.classList.remove('show'); + setTimeout(() => toast.remove(), 300); + }, 2000); + }, 1000); + } catch (err) { + console.error('[admin-change-password]', err); + showAdminPasswordFeedback('Network error', true); + } finally { + if (adminChangePasswordSave) { + adminChangePasswordSave.disabled = false; + adminChangePasswordSave.innerHTML = ' Update Password'; + } + } +} + +if (adminChangePasswordClose) adminChangePasswordClose.addEventListener('click', closeAdminChangePasswordModal); +if (adminChangePasswordCancelBtn) adminChangePasswordCancelBtn.addEventListener('click', closeAdminChangePasswordModal); +if (adminChangePasswordSave) adminChangePasswordSave.addEventListener('click', saveAdminChangePassword); +if (adminChangePasswordOverlay) { + adminChangePasswordOverlay.addEventListener('click', (e) => { + if (e.target === adminChangePasswordOverlay) closeAdminChangePasswordModal(); + }); +} + +if (adminChangePasswordModal) { + adminChangePasswordModal.querySelectorAll('.password-toggle').forEach(btn => { + if (btn.dataset.listenerAdded) return; + btn.dataset.listenerAdded = 'true'; + btn.addEventListener('click', () => { + const wrap = btn.closest('.password-input-wrap'); + if (wrap) { + const input = wrap.querySelector('input'); + const icon = btn.querySelector('i'); + if (input && icon) { + if (input.type === 'password') { + input.type = 'text'; + icon.classList.replace('fa-eye', 'fa-eye-slash'); + } else { + input.type = 'password'; + icon.classList.replace('fa-eye-slash', 'fa-eye'); + } + } + } + }); + }); +} + +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && adminChangePasswordOverlay?.classList.contains('show')) { + closeAdminChangePasswordModal(); + } +}); + + +const qrOptionsModalOverlay = document.getElementById('qrOptionsModalOverlay'); +const qrOptionsModal = document.getElementById('qrOptionsModal'); +const qrOptionsModalClose = document.getElementById('qrOptionsModalClose'); +const qrOptionsUserEmail = document.getElementById('qrOptionsUserEmail'); +const resetUser2FABtn = document.getElementById('resetUser2FABtn'); +const resetUserRecoveryBtn = document.getElementById('resetUserRecoveryBtn'); + +const qrResetModalOverlay = document.getElementById('qrResetModalOverlay'); +const qrResetModal = document.getElementById('qrResetModal'); +const qrResetModalClose = document.getElementById('qrResetModalClose'); +const qrResetUserEmail = document.getElementById('qrResetUserEmail'); +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'); + +let currentQRResetEmail = ''; +let currentQRResetSecret = ''; +let currentQRResetIsAdmin = false; + +function openQROptionsModal(email, isAdmin = false) { + if (!qrOptionsModalOverlay) return; + currentQRResetEmail = email; + currentQRResetIsAdmin = !!isAdmin; + if (qrOptionsUserEmail) qrOptionsUserEmail.textContent = email; + if (resetUserRecoveryBtn) { + resetUserRecoveryBtn.style.display = currentQRResetIsAdmin ? 'none' : ''; + } + qrOptionsModalOverlay.setAttribute('aria-hidden', 'false'); + qrOptionsModalOverlay.classList.add('show'); +} + +function closeQROptionsModal() { + if (!qrOptionsModalOverlay) return; + qrOptionsModalOverlay.setAttribute('aria-hidden', 'true'); + qrOptionsModalOverlay.classList.remove('show'); +} + +function openQRResetModal() { + if (!qrResetModalOverlay) return; + if (qrResetUserEmail) qrResetUserEmail.textContent = `New QR for ${currentQRResetEmail}`; + if (qrResetLoading) qrResetLoading.style.display = 'block'; + if (qrResetContent) qrResetContent.style.display = 'none'; + if (qrResetError) qrResetError.style.display = 'none'; + qrResetModalOverlay.setAttribute('aria-hidden', 'false'); + qrResetModalOverlay.classList.add('show'); + + generateNewQRCode(); +} + +function closeQRResetModal() { + if (!qrResetModalOverlay) return; + qrResetModalOverlay.setAttribute('aria-hidden', 'true'); + qrResetModalOverlay.classList.remove('show'); + currentQRResetSecret = ''; +} + +async function generateNewQRCode() { + try { + const res = await fetch('/api/admin/user/reset-2fa', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': (accountsListEl._actionTokens || {}).reset2fa || '' + }, + credentials: 'include', + body: JSON.stringify({ email: currentQRResetEmail }) + }); + + const data = await res.json(); + + if (!res.ok) { + throw new Error(data.error || 'Failed to generate QR code'); + } + + 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; + + 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...'; + } + + 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')); + } finally { + if (qrResetDoneBtn) { + qrResetDoneBtn.disabled = false; + qrResetDoneBtn.innerHTML = ' Done'; + } + } +} + +if (qrOptionsModalClose) qrOptionsModalClose.addEventListener('click', closeQROptionsModal); +if (qrOptionsModalOverlay) { + qrOptionsModalOverlay.addEventListener('click', (e) => { + if (e.target === qrOptionsModalOverlay) closeQROptionsModal(); + }); +} + +if (resetUser2FABtn) { + resetUser2FABtn.addEventListener('click', () => { + closeQROptionsModal(); + openQRResetModal(); + }); +} + +if (qrResetModalClose) qrResetModalClose.addEventListener('click', closeQRResetModal); +if (qrResetModalOverlay) { + qrResetModalOverlay.addEventListener('click', (e) => { + if (e.target === qrResetModalOverlay) closeQRResetModal(); + }); +} + +if (qrResetDoneBtn) { + qrResetDoneBtn.addEventListener('click', confirmQRReset); +} + +if (accountsListEl) { + accountsListEl.addEventListener('click', (e) => { + const btn = e.target.closest('.qr-reset-btn'); + if (btn) { + const email = decodeURIComponent(btn.dataset.email || ''); + const isAdmin = btn.dataset.admin === '1'; + if (email) openQROptionsModal(email, isAdmin); + } + }); +} + + +const recoveryResetModalOverlay = document.getElementById('recoveryResetModalOverlay'); +const recoveryResetModal = document.getElementById('recoveryResetModal'); +const recoveryResetModalClose = document.getElementById('recoveryResetModalClose'); +const recoveryResetUserEmail = document.getElementById('recoveryResetUserEmail'); +const recoveryResetLoading = document.getElementById('recoveryResetLoading'); +const recoveryResetContent = document.getElementById('recoveryResetContent'); +const recoveryResetError = document.getElementById('recoveryResetError'); +const recoveryResetErrorText = document.getElementById('recoveryResetErrorText'); +const recoveryCodesList = document.getElementById('recoveryCodesList'); +const recoveryResetDoneBtn = document.getElementById('recoveryResetDoneBtn'); + +function openRecoveryResetModal() { + if (!recoveryResetModalOverlay) return; + if (recoveryResetUserEmail) recoveryResetUserEmail.textContent = `New codes for ${currentQRResetEmail}`; + if (recoveryResetLoading) recoveryResetLoading.style.display = 'block'; + if (recoveryResetContent) recoveryResetContent.style.display = 'none'; + if (recoveryResetError) recoveryResetError.style.display = 'none'; + recoveryResetModalOverlay.setAttribute('aria-hidden', 'false'); + recoveryResetModalOverlay.classList.add('show'); + + generateNewRecoveryCodes(); +} + +function closeRecoveryResetModal() { + if (!recoveryResetModalOverlay) return; + recoveryResetModalOverlay.setAttribute('aria-hidden', 'true'); + recoveryResetModalOverlay.classList.remove('show'); +} + +async function generateNewRecoveryCodes() { + try { + const res = await fetch('/api/admin/user/reset-recovery-codes', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': (accountsListEl._actionTokens || {}).resetRecoveryCodes || '' + }, + credentials: 'include', + body: JSON.stringify({ email: currentQRResetEmail }) + }); + + const data = await res.json(); + + if (!res.ok) { + throw new Error(data.error || 'Failed to generate recovery codes'); + } + + if (recoveryCodesList) { + recoveryCodesList.innerHTML = data.recoveryCodes.map((code, idx) => ` +
    + ${idx + 1}. ${code} +
    + `).join(''); + } + + if (recoveryResetLoading) recoveryResetLoading.style.display = 'none'; + if (recoveryResetContent) recoveryResetContent.style.display = 'block'; + if (recoveryResetError) recoveryResetError.style.display = 'none'; + + console.log('[admin] Recovery codes reset SUCCESS for', currentQRResetEmail); + + } catch (err) { + console.error('[admin] Recovery codes generation error:', err); + if (recoveryResetLoading) recoveryResetLoading.style.display = 'none'; + if (recoveryResetContent) recoveryResetContent.style.display = 'none'; + if (recoveryResetError) recoveryResetError.style.display = 'block'; + if (recoveryResetErrorText) recoveryResetErrorText.textContent = err.message || 'Failed to generate recovery codes'; + } +} + +if (recoveryResetModalClose) recoveryResetModalClose.addEventListener('click', closeRecoveryResetModal); +if (recoveryResetModalOverlay) { + recoveryResetModalOverlay.addEventListener('click', (e) => { + if (e.target === recoveryResetModalOverlay) closeRecoveryResetModal(); + }); +} + +if (recoveryResetDoneBtn) { + recoveryResetDoneBtn.addEventListener('click', closeRecoveryResetModal); +} + +if (resetUserRecoveryBtn) { + resetUserRecoveryBtn.addEventListener('click', () => { + closeQROptionsModal(); + openRecoveryResetModal(); + }); +} + +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape') { + if (recoveryResetModalOverlay?.classList.contains('show')) { + closeRecoveryResetModal(); + } else if (qrResetModalOverlay?.classList.contains('show')) { + closeQRResetModal(); + } else if (qrOptionsModalOverlay?.classList.contains('show')) { + closeQROptionsModal(); + } else if (createUserModalOverlay?.classList.contains('show')) { + closeCreateUserModal(); + } else if (userCredentialsModalOverlay?.classList.contains('show')) { + closeCredentialsModal(); + } + } +}); + + +const openCreateUserBtn = document.getElementById('openCreateUserBtn'); +const createUserModalOverlay = document.getElementById('createUserModalOverlay'); +const createUserModal = document.getElementById('createUserModal'); +const createUserModalClose = document.getElementById('createUserModalClose'); +const createUserCancelBtn = document.getElementById('createUserCancelBtn'); +const createUserSubmitBtn = document.getElementById('createUserSubmitBtn'); +const createUserRoleNormal = document.getElementById('createUserRoleNormal'); +const createUserRoleAdmin = document.getElementById('createUserRoleAdmin'); +const createUserEmail = document.getElementById('createUserEmail'); +const createUserPassword = document.getElementById('createUserPassword'); +const createUserPasswordConfirm = document.getElementById('createUserPasswordConfirm'); +const createUserAdminStepUp = document.getElementById('createUserAdminStepUp'); +const createAdminPassword = document.getElementById('createAdminPassword'); +const createAdminTwoFactor = document.getElementById('createAdminTwoFactor'); +const createUserError = document.getElementById('createUserError'); + +const userCredentialsModalOverlay = document.getElementById('userCredentialsModalOverlay'); +const userCredentialsModal = document.getElementById('userCredentialsModal'); +const credentialsModalClose = document.getElementById('credentialsModalClose'); +const credentialsUserEmail = document.getElementById('credentialsUserEmail'); +const credentialsUserRole = document.getElementById('credentialsUserRole'); +const credentialsQRCode = document.getElementById('credentialsQRCode'); +const credentialsSecret = document.getElementById('credentialsSecret'); +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 (createUserSubmitBtn) { + createUserSubmitBtn.innerHTML = createUserSelectedRole === 'admin' + ? ' Create Admin' + : ' Create User'; + } +} + +function openCreateUserModal() { + if (!createUserModalOverlay) return; + setCreateUserRole('user'); + if (createUserEmail) createUserEmail.value = ''; + if (createUserPassword) createUserPassword.value = ''; + if (createUserPasswordConfirm) createUserPasswordConfirm.value = ''; + if (createAdminPassword) createAdminPassword.value = ''; + if (createAdminTwoFactor) createAdminTwoFactor.value = ''; + if (createUserError) { + createUserError.style.display = 'none'; + createUserError.textContent = ''; + } + createUserModalOverlay.setAttribute('aria-hidden', 'false'); + createUserModalOverlay.classList.add('show'); + setTimeout(() => createUserEmail?.focus(), 100); +} + +function closeCreateUserModal() { + if (!createUserModalOverlay) return; + createUserModalOverlay.setAttribute('aria-hidden', 'true'); + createUserModalOverlay.classList.remove('show'); + if (createAdminPassword) createAdminPassword.value = ''; + if (createAdminTwoFactor) createAdminTwoFactor.value = ''; +} + +function showCreateUserError(msg) { + if (createUserError) { + createUserError.textContent = msg; + createUserError.style.display = 'block'; + } +} + +function getUtf8ByteLength(value) { + try { + return new TextEncoder().encode(String(value || '')).length; + } catch { + return unescape(encodeURIComponent(String(value || ''))).length; + } +} + +async function ensureCreateUserActionToken() { + if ((accountsListEl._actionTokens || {}).createUser) return true; + if (typeof loadAccounts === 'function') { + await loadAccounts(); + } + return !!((accountsListEl._actionTokens || {}).createUser); +} + +async function submitCreateUser() { + const email = createUserEmail?.value?.trim() || ''; + const password = createUserPassword?.value || ''; + const confirmPassword = createUserPasswordConfirm?.value || ''; + const role = createUserSelectedRole === 'admin' ? 'admin' : 'user'; + const adminPassword = createAdminPassword?.value || ''; + const adminTwoFactorCode = (createAdminTwoFactor?.value || '').replace(/\s+/g, ''); + + if (!email) { + showCreateUserError('Email is required'); + return; + } + if (!password) { + showCreateUserError('Password is required'); + return; + } + if (password.length < 12) { + showCreateUserError('Password must be at least 12 characters'); + return; + } + if (getUtf8ByteLength(password) > 72) { + showCreateUserError('Password must be 72 bytes or less'); + return; + } + if (password !== confirmPassword) { + showCreateUserError('Passwords do not match'); + return; + } + if (role === 'admin') { + if (!adminPassword) { + showCreateUserError('Your password is required'); + return; + } + if (!/^\d{6}$/.test(adminTwoFactorCode)) { + showCreateUserError('Enter a valid 6-digit 2FA code'); + return; + } + } + + if (createUserError) createUserError.style.display = 'none'; + + try { + if (createUserSubmitBtn) { + createUserSubmitBtn.disabled = true; + createUserSubmitBtn.innerHTML = ' Creating...'; + } + + const hasActionToken = await ensureCreateUserActionToken(); + if (!hasActionToken) { + throw new Error('Admin action token missing'); + } + + const res = await fetch('/api/admin/user/create', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + 'x-action-token': (accountsListEl._actionTokens || {}).createUser || '' + }, + credentials: 'include', + body: JSON.stringify({ + email, + password, + confirmPassword, + role, + adminPassword, + adminTwoFactorCode + }) + }); + + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + if (typeof loadAccounts === 'function') loadAccounts(); + throw new Error(data.error || 'Failed to create user'); + } + + lastCreatedUserCredentials = data; + closeCreateUserModal(); + openCredentialsModal(data); + + if (typeof loadAccounts === 'function') { + loadAccounts(); + } + + } catch (err) { + console.error('[admin] Create user error:', err); + showCreateUserError(err.message || 'Failed to create user'); + } finally { + if (createUserSubmitBtn) { + createUserSubmitBtn.disabled = false; + setCreateUserRole(createUserSelectedRole); + } + } +} + +function openCredentialsModal(data) { + if (!userCredentialsModalOverlay) return; + + if (credentialsUserEmail) credentialsUserEmail.textContent = data.email; + 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 (credentialsRecoveryCodes) { + credentialsRecoveryCodes.innerHTML = data.recoveryCodes.map((code, idx) => ` +
    + ${idx + 1}. ${code} +
    + `).join(''); + } + + userCredentialsModalOverlay.setAttribute('aria-hidden', 'false'); + userCredentialsModalOverlay.classList.add('show'); +} + +function closeCredentialsModal() { + if (!userCredentialsModalOverlay) return; + userCredentialsModalOverlay.setAttribute('aria-hidden', 'true'); + userCredentialsModalOverlay.classList.remove('show'); + lastCreatedUserCredentials = null; +} + +function downloadCredentials() { + if (!lastCreatedUserCredentials) return; + + const data = lastCreatedUserCredentials; + const role = data.role === 'admin' || data.admin === true ? 'Admin User' : 'Normal User'; + const content = `ADPanel User Credentials +======================== + +Email: ${data.email} +Role: ${role} + +2FA Secret: ${data.secret} + +Recovery Codes (each can only be used once): +${data.recoveryCodes.map((code, i) => ` ${i + 1}. ${code}`).join('\n')} + +IMPORTANT: Keep these credentials secure! +`; + + const blob = new Blob([content], { type: 'text/plain' }); + const url = URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = `adpanel-credentials-${data.email.replace('@', '_at_')}.txt`; + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + URL.revokeObjectURL(url); +} + +if (openCreateUserBtn) openCreateUserBtn.addEventListener('click', openCreateUserModal); +if (createUserRoleNormal) createUserRoleNormal.addEventListener('click', () => setCreateUserRole('user')); +if (createUserRoleAdmin) createUserRoleAdmin.addEventListener('click', () => setCreateUserRole('admin')); +if (createUserModalClose) createUserModalClose.addEventListener('click', closeCreateUserModal); +if (createUserCancelBtn) createUserCancelBtn.addEventListener('click', closeCreateUserModal); +if (createUserSubmitBtn) createUserSubmitBtn.addEventListener('click', submitCreateUser); +if (createAdminTwoFactor) { + createAdminTwoFactor.addEventListener('input', () => { + createAdminTwoFactor.value = createAdminTwoFactor.value.replace(/\D+/g, '').slice(0, 6); + }); +} +if (createUserModalOverlay) { + createUserModalOverlay.addEventListener('click', (e) => { + if (e.target === createUserModalOverlay) closeCreateUserModal(); + }); +} + +if (credentialsModalClose) credentialsModalClose.addEventListener('click', closeCredentialsModal); +if (credentialsDoneBtn) credentialsDoneBtn.addEventListener('click', closeCredentialsModal); +if (downloadCredentialsBtn) downloadCredentialsBtn.addEventListener('click', downloadCredentials); +if (userCredentialsModalOverlay) { + userCredentialsModalOverlay.addEventListener('click', (e) => { + if (e.target === userCredentialsModalOverlay) closeCredentialsModal(); + }); +} + +createUserModal?.querySelectorAll('.password-toggle').forEach(btn => { + if (btn.dataset.listenerAdded) return; + btn.dataset.listenerAdded = 'true'; + btn.addEventListener('click', () => { + const targetId = btn.dataset.target; + const input = document.getElementById(targetId); + const icon = btn.querySelector('i'); + if (input && icon) { + if (input.type === 'password') { + input.type = 'text'; + icon.classList.replace('fa-eye', 'fa-eye-slash'); + } else { + input.type = 'password'; + icon.classList.replace('fa-eye-slash', 'fa-eye'); + } + } + }); +}); + + +const openBrandingBtn = document.getElementById('openBrandingBtn'); +const brandingModalOverlay = document.getElementById('brandingModalOverlay'); +const brandingModal = document.getElementById('brandingModal'); +const brandingModalClose = document.getElementById('brandingModalClose'); +const brandingCancelBtn = document.getElementById('brandingCancelBtn'); +const brandingSaveBtn = document.getElementById('brandingSaveBtn'); +const brandingAppName = document.getElementById('brandingAppName'); +const brandingLogoFile = document.getElementById('brandingLogoFile'); +const brandingLogoUrl = document.getElementById('brandingLogoUrl'); +const brandingLogoSelectBtn = document.getElementById('brandingLogoSelectBtn'); +const brandingError = document.getElementById('brandingError'); +const logoTabUpload = document.getElementById('logoTabUpload'); +const logoTabUrl = document.getElementById('logoTabUrl'); +const logoUploadSection = document.getElementById('logoUploadSection'); +const logoUrlSection = document.getElementById('logoUrlSection'); +const logoPreviewUpload = document.getElementById('logoPreviewUpload'); +const logoPreviewImg = document.getElementById('logoPreviewImg'); +const logoFileName = document.getElementById('logoFileName'); + +let selectedLogoFile = null; + +function openBrandingModal() { + if (!brandingModalOverlay) return; + + selectedLogoFile = null; + if (brandingError) { + brandingError.style.display = 'none'; + brandingError.textContent = ''; + } + if (logoPreviewUpload) logoPreviewUpload.style.display = 'none'; + if (brandingLogoFile) brandingLogoFile.value = ''; + if (brandingLogoUrl) brandingLogoUrl.value = ''; + + loadCurrentBranding(); + + brandingModalOverlay.setAttribute('aria-hidden', 'false'); + brandingModalOverlay.classList.add('show'); +} + +function closeBrandingModal() { + if (!brandingModalOverlay) return; + brandingModalOverlay.setAttribute('aria-hidden', 'true'); + brandingModalOverlay.classList.remove('show'); +} + +async function loadCurrentBranding() { + try { + const res = await fetch('/api/admin/branding', { credentials: 'include' }); + if (res.ok) { + const data = await res.json(); + if (brandingAppName) brandingAppName.value = data.appName || ''; + if (data.logoUrl && brandingLogoUrl) { + brandingLogoUrl.value = data.logoUrl; + switchLogoTab('url'); + } + } + } catch (e) { + console.error('[branding] Failed to load current settings:', e); + } +} + +function switchLogoTab(tab) { + if (tab === 'upload') { + if (logoTabUpload) { + logoTabUpload.style.border = '1px solid rgba(99,102,241,0.5)'; + logoTabUpload.style.background = 'rgba(99,102,241,0.15)'; + logoTabUpload.style.color = '#a5b4fc'; + } + if (logoTabUrl) { + logoTabUrl.style.border = '1px solid rgba(255,255,255,0.1)'; + logoTabUrl.style.background = 'rgba(255,255,255,0.03)'; + logoTabUrl.style.color = 'rgba(255,255,255,0.6)'; + } + if (logoUploadSection) logoUploadSection.style.display = 'block'; + if (logoUrlSection) logoUrlSection.style.display = 'none'; + } else { + if (logoTabUrl) { + logoTabUrl.style.border = '1px solid rgba(99,102,241,0.5)'; + logoTabUrl.style.background = 'rgba(99,102,241,0.15)'; + logoTabUrl.style.color = '#a5b4fc'; + } + if (logoTabUpload) { + logoTabUpload.style.border = '1px solid rgba(255,255,255,0.1)'; + logoTabUpload.style.background = 'rgba(255,255,255,0.03)'; + logoTabUpload.style.color = 'rgba(255,255,255,0.6)'; + } + if (logoUploadSection) logoUploadSection.style.display = 'none'; + if (logoUrlSection) logoUrlSection.style.display = 'block'; + } +} + +function handleLogoFileSelect(e) { + const file = e.target.files?.[0]; + if (!file) return; + + selectedLogoFile = file; + + const reader = new FileReader(); + reader.onload = (evt) => { + if (logoPreviewImg) logoPreviewImg.src = evt.target.result; + if (logoFileName) logoFileName.textContent = file.name; + if (logoPreviewUpload) logoPreviewUpload.style.display = 'block'; + }; + reader.readAsDataURL(file); +} + +async function saveBranding() { + const appName = brandingAppName?.value?.trim(); + + if (!appName) { + if (brandingError) { + brandingError.textContent = 'App name is required'; + brandingError.style.display = 'block'; + } + return; + } + + if (brandingError) brandingError.style.display = 'none'; + + const body = { appName }; + + if (selectedLogoFile) { + const reader = new FileReader(); + const base64 = await new Promise((resolve) => { + reader.onload = (e) => resolve(e.target.result); + reader.readAsDataURL(selectedLogoFile); + }); + body.logoBase64 = base64; + body.logoFilename = selectedLogoFile.name; + } else if (brandingLogoUrl?.value?.trim()) { + body.logoUrl = brandingLogoUrl.value.trim(); + } + + try { + if (brandingSaveBtn) { + brandingSaveBtn.disabled = true; + brandingSaveBtn.innerHTML = ' Saving...'; + } + + const res = await fetch('/api/admin/branding/update', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify(body) + }); + + const data = await res.json(); + + if (!res.ok) { + throw new Error(data.error || 'Failed to update branding'); + } + + closeBrandingModal(); + alert('Branding updated successfully! Refresh the page to see changes.'); + + } catch (err) { + console.error('[branding] Save error:', err); + if (brandingError) { + brandingError.textContent = err.message || 'Failed to save branding'; + brandingError.style.display = 'block'; + } + } finally { + if (brandingSaveBtn) { + brandingSaveBtn.disabled = false; + brandingSaveBtn.innerHTML = ' Save Changes'; + } + } +} + +if (openBrandingBtn) openBrandingBtn.addEventListener('click', openBrandingModal); +if (brandingModalClose) brandingModalClose.addEventListener('click', closeBrandingModal); +if (brandingCancelBtn) brandingCancelBtn.addEventListener('click', closeBrandingModal); +if (brandingSaveBtn) brandingSaveBtn.addEventListener('click', saveBranding); +if (brandingModalOverlay) { + brandingModalOverlay.addEventListener('click', (e) => { + if (e.target === brandingModalOverlay) closeBrandingModal(); + }); +} + +if (logoTabUpload) logoTabUpload.addEventListener('click', () => switchLogoTab('upload')); +if (logoTabUrl) logoTabUrl.addEventListener('click', () => switchLogoTab('url')); + +if (brandingLogoSelectBtn) brandingLogoSelectBtn.addEventListener('click', () => brandingLogoFile?.click()); +if (brandingLogoFile) brandingLogoFile.addEventListener('change', handleLogoFileSelect); + +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && brandingModalOverlay?.classList.contains('show')) { + closeBrandingModal(); + } +}); + + +const DEFAULT_LOGIN_WATERMARK_URL = 'https://stalwart-pegasus-2c2ca4.netlify.app/watermark.webp'; +const openLoginWatermarkBtn = document.getElementById('openLoginWatermarkBtn'); +const loginWatermarkModalOverlay = document.getElementById('loginWatermarkModalOverlay'); +const loginWatermarkModalClose = document.getElementById('loginWatermarkModalClose'); +const loginWatermarkCancelBtn = document.getElementById('loginWatermarkCancelBtn'); +const loginWatermarkSaveBtn = document.getElementById('loginWatermarkSaveBtn'); +const loginWatermarkTabUpload = document.getElementById('loginWatermarkTabUpload'); +const loginWatermarkTabUrl = document.getElementById('loginWatermarkTabUrl'); +const loginWatermarkUploadSection = document.getElementById('loginWatermarkUploadSection'); +const loginWatermarkUrlSection = document.getElementById('loginWatermarkUrlSection'); +const loginWatermarkFile = document.getElementById('loginWatermarkFile'); +const loginWatermarkSelectBtn = document.getElementById('loginWatermarkSelectBtn'); +const loginWatermarkUrlInput = document.getElementById('loginWatermarkUrl'); +const loginWatermarkPreviewImg = document.getElementById('loginWatermarkPreviewImg'); +const loginWatermarkPreviewBadge = document.getElementById('loginWatermarkPreviewBadge'); +const loginWatermarkPreviewMeta = document.getElementById('loginWatermarkPreviewMeta'); +const loginWatermarkFeedback = document.getElementById('loginWatermarkFeedback'); +const loginWatermarkUploadMeta = document.getElementById('loginWatermarkUploadMeta'); +const initialLoginWatermarkSrc = document.querySelector('[data-login-watermark-image]')?.src || DEFAULT_LOGIN_WATERMARK_URL; + +let loginWatermarkSourceMode = 'upload'; +let selectedLoginWatermarkFile = null; +let loginWatermarkCurrentConfig = { + mode: 'url', + watermarkUrl: initialLoginWatermarkSrc, + externalUrl: initialLoginWatermarkSrc +}; + +function setLoginWatermarkFeedback(message, type = 'error') { + if (!loginWatermarkFeedback) return; + loginWatermarkFeedback.textContent = message || ''; + loginWatermarkFeedback.className = 'login-watermark-feedback'; + if (!message) { + loginWatermarkFeedback.style.display = 'none'; + return; + } + loginWatermarkFeedback.classList.add(type); + loginWatermarkFeedback.style.display = 'block'; +} + +function setLoginWatermarkPreview(src, badgeText, metaText) { + if (loginWatermarkPreviewImg && src) { + loginWatermarkPreviewImg.src = src; + } + if (loginWatermarkPreviewBadge) { + loginWatermarkPreviewBadge.textContent = badgeText || 'Current image'; + } + if (loginWatermarkPreviewMeta) { + loginWatermarkPreviewMeta.textContent = metaText || 'The login watermark keeps its current hardcoded size.'; + } +} + +function updateLoginWatermarkImages(src) { + if (!src) return; + document.querySelectorAll('[data-login-watermark-image]').forEach((img) => { + img.src = src; + }); +} + +function showLoginWatermarkToast(message) { + const toast = document.createElement('div'); + toast.className = 'perm-success-toast'; + toast.innerHTML = '' + escapeHtml(message || 'Login watermark updated'); + document.body.appendChild(toast); + requestAnimationFrame(() => toast.classList.add('show')); + setTimeout(() => { + toast.classList.remove('show'); + setTimeout(() => toast.remove(), 300); + }, 2800); +} + +function syncLoginWatermarkPreviewToCurrent() { + const currentUrl = loginWatermarkCurrentConfig.watermarkUrl || DEFAULT_LOGIN_WATERMARK_URL; + const currentMode = loginWatermarkCurrentConfig.mode === 'upload' ? 'Uploaded image' : 'Current image'; + const currentMeta = loginWatermarkCurrentConfig.mode === 'upload' + ? 'The login page is currently using an uploaded image. The watermark size and placement stay exactly the same.' + : 'The login page is currently using an image link. The watermark size and placement stay exactly the same.'; + setLoginWatermarkPreview(currentUrl, currentMode, currentMeta); +} + +function switchLoginWatermarkTab(mode) { + loginWatermarkSourceMode = mode === 'url' ? 'url' : 'upload'; + if (loginWatermarkTabUpload) loginWatermarkTabUpload.classList.toggle('active', loginWatermarkSourceMode === 'upload'); + if (loginWatermarkTabUrl) loginWatermarkTabUrl.classList.toggle('active', loginWatermarkSourceMode === 'url'); + if (loginWatermarkUploadSection) loginWatermarkUploadSection.style.display = loginWatermarkSourceMode === 'upload' ? 'block' : 'none'; + if (loginWatermarkUrlSection) loginWatermarkUrlSection.style.display = loginWatermarkSourceMode === 'url' ? 'block' : 'none'; + + if (loginWatermarkSourceMode === 'upload' && selectedLoginWatermarkFile) { + if (loginWatermarkUploadMeta) { + loginWatermarkUploadMeta.textContent = `Ready to upload: ${selectedLoginWatermarkFile.name}`; + } + return; + } + + if (loginWatermarkSourceMode === 'url' && loginWatermarkUrlInput?.value?.trim()) { + setLoginWatermarkPreview( + loginWatermarkUrlInput.value.trim(), + 'Link preview', + 'Previewing the image from this link. The login watermark dimensions remain untouched.' + ); + return; + } + + syncLoginWatermarkPreviewToCurrent(); +} + +async function loadCurrentLoginWatermark() { + try { + const res = await fetch('/api/admin/login-watermark', { credentials: 'include' }); + const data = await res.json(); + if (!res.ok) { + throw new Error(data.error || 'Failed to load login watermark'); + } + + loginWatermarkCurrentConfig = { + mode: data.mode || 'url', + watermarkUrl: data.watermarkUrl || DEFAULT_LOGIN_WATERMARK_URL, + externalUrl: data.externalUrl || '' + }; + + if (loginWatermarkUrlInput) { + loginWatermarkUrlInput.value = data.mode === 'upload' ? '' : (data.externalUrl || data.watermarkUrl || ''); + } + + if (loginWatermarkUploadMeta) { + loginWatermarkUploadMeta.textContent = data.mode === 'upload' + ? 'Currently using an uploaded image. Choose another file to replace it.' + : 'No local file selected yet. You can upload one anytime.'; + } + + switchLoginWatermarkTab(data.mode === 'upload' ? 'upload' : 'url'); + setLoginWatermarkFeedback(''); + } catch (err) { + console.error('[login-watermark] Failed to load current settings:', err); + loginWatermarkCurrentConfig = { + mode: 'url', + watermarkUrl: initialLoginWatermarkSrc, + externalUrl: initialLoginWatermarkSrc + }; + if (loginWatermarkUrlInput) loginWatermarkUrlInput.value = initialLoginWatermarkSrc; + if (loginWatermarkUploadMeta) loginWatermarkUploadMeta.textContent = 'No local file selected yet. You can upload one anytime.'; + switchLoginWatermarkTab('url'); + setLoginWatermarkFeedback('Could not load the current watermark. Saving a new one still works.', 'error'); + } +} + +function openLoginWatermarkModal() { + if (!loginWatermarkModalOverlay) return; + selectedLoginWatermarkFile = null; + if (loginWatermarkFile) loginWatermarkFile.value = ''; + if (loginWatermarkUploadMeta) loginWatermarkUploadMeta.textContent = ''; + setLoginWatermarkFeedback(''); + syncLoginWatermarkPreviewToCurrent(); + loginWatermarkModalOverlay.setAttribute('aria-hidden', 'false'); + loginWatermarkModalOverlay.classList.add('show'); + loadCurrentLoginWatermark(); +} + +function closeLoginWatermarkModal() { + if (!loginWatermarkModalOverlay) return; + loginWatermarkModalOverlay.setAttribute('aria-hidden', 'true'); + loginWatermarkModalOverlay.classList.remove('show'); +} + +function handleLoginWatermarkFileSelect(e) { + const file = e.target.files?.[0]; + if (!file) return; + + selectedLoginWatermarkFile = file; + if (loginWatermarkUploadMeta) { + loginWatermarkUploadMeta.textContent = `Selected file: ${file.name}`; + } + + const reader = new FileReader(); + reader.onload = (evt) => { + setLoginWatermarkPreview( + evt.target?.result || DEFAULT_LOGIN_WATERMARK_URL, + 'New upload', + 'This file will replace the login watermark image while keeping the current hardcoded dimensions.' + ); + }; + reader.readAsDataURL(file); +} + +function handleLoginWatermarkUrlPreview() { + const url = loginWatermarkUrlInput?.value?.trim(); + if (!url) { + syncLoginWatermarkPreviewToCurrent(); + return; + } + + setLoginWatermarkPreview( + url, + 'Link preview', + 'Previewing the image from this web link. The login watermark dimensions remain exactly as they are now.' + ); +} + +async function saveLoginWatermark() { + if (!loginWatermarkSaveBtn) return; + + const body = {}; + if (loginWatermarkSourceMode === 'upload' && selectedLoginWatermarkFile) { + const reader = new FileReader(); + const base64 = await new Promise((resolve) => { + reader.onload = (event) => resolve(event.target?.result || ''); + reader.readAsDataURL(selectedLoginWatermarkFile); + }); + body.watermarkBase64 = base64; + body.watermarkFilename = selectedLoginWatermarkFile.name; + } else if (loginWatermarkSourceMode === 'url' && loginWatermarkUrlInput?.value?.trim()) { + body.watermarkUrl = loginWatermarkUrlInput.value.trim(); + } + + try { + setLoginWatermarkFeedback(''); + loginWatermarkSaveBtn.disabled = true; + loginWatermarkSaveBtn.innerHTML = ' Saving...'; + + const res = await fetch('/api/admin/login-watermark', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify(body) + }); + + const data = await res.json(); + if (!res.ok) { + throw new Error(data.error || 'Failed to update login watermark'); + } + + loginWatermarkCurrentConfig = { + mode: data.mode || (loginWatermarkSourceMode === 'upload' ? 'upload' : 'url'), + watermarkUrl: data.watermarkUrl || DEFAULT_LOGIN_WATERMARK_URL, + externalUrl: data.externalUrl || '' + }; + updateLoginWatermarkImages(loginWatermarkCurrentConfig.watermarkUrl); + closeLoginWatermarkModal(); + showLoginWatermarkToast('Login watermark updated'); + } catch (err) { + console.error('[login-watermark] Save error:', err); + setLoginWatermarkFeedback(err.message || 'Failed to save login watermark', 'error'); + } finally { + loginWatermarkSaveBtn.disabled = false; + loginWatermarkSaveBtn.innerHTML = ' Save Watermark'; + } +} + +if (openLoginWatermarkBtn) openLoginWatermarkBtn.addEventListener('click', openLoginWatermarkModal); +if (loginWatermarkModalClose) loginWatermarkModalClose.addEventListener('click', closeLoginWatermarkModal); +if (loginWatermarkCancelBtn) loginWatermarkCancelBtn.addEventListener('click', closeLoginWatermarkModal); +if (loginWatermarkSaveBtn) loginWatermarkSaveBtn.addEventListener('click', saveLoginWatermark); +if (loginWatermarkTabUpload) loginWatermarkTabUpload.addEventListener('click', () => switchLoginWatermarkTab('upload')); +if (loginWatermarkTabUrl) loginWatermarkTabUrl.addEventListener('click', () => switchLoginWatermarkTab('url')); +if (loginWatermarkSelectBtn) loginWatermarkSelectBtn.addEventListener('click', () => loginWatermarkFile?.click()); +if (loginWatermarkFile) loginWatermarkFile.addEventListener('change', handleLoginWatermarkFileSelect); +if (loginWatermarkUrlInput) { + loginWatermarkUrlInput.addEventListener('input', () => { + if (loginWatermarkSourceMode === 'url') handleLoginWatermarkUrlPreview(); + }); + loginWatermarkUrlInput.addEventListener('change', handleLoginWatermarkUrlPreview); +} +if (loginWatermarkModalOverlay) { + loginWatermarkModalOverlay.addEventListener('click', (e) => { + if (e.target === loginWatermarkModalOverlay) closeLoginWatermarkModal(); + }); +} +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && loginWatermarkModalOverlay?.classList.contains('show')) { + closeLoginWatermarkModal(); + } +}); + + +const DEFAULT_LOGIN_BACKGROUND_URL = '/images/bgvid.webm'; +const openLoginBackgroundBtn = document.getElementById('openLoginBackgroundBtn'); +const loginBackgroundModalOverlay = document.getElementById('loginBackgroundModalOverlay'); +const loginBackgroundModalClose = document.getElementById('loginBackgroundModalClose'); +const loginBackgroundCancelBtn = document.getElementById('loginBackgroundCancelBtn'); +const loginBackgroundSaveBtn = document.getElementById('loginBackgroundSaveBtn'); +const loginBackgroundTabUpload = document.getElementById('loginBackgroundTabUpload'); +const loginBackgroundTabUrl = document.getElementById('loginBackgroundTabUrl'); +const loginBackgroundUploadSection = document.getElementById('loginBackgroundUploadSection'); +const loginBackgroundUrlSection = document.getElementById('loginBackgroundUrlSection'); +const loginBackgroundFile = document.getElementById('loginBackgroundFile'); +const loginBackgroundSelectBtn = document.getElementById('loginBackgroundSelectBtn'); +const loginBackgroundUrlInput = document.getElementById('loginBackgroundUrl'); +const loginBackgroundPreviewImg = document.getElementById('loginBackgroundPreviewImg'); +const loginBackgroundPreviewVideo = document.getElementById('loginBackgroundPreviewVideo'); +const loginBackgroundPreviewBadge = document.getElementById('loginBackgroundPreviewBadge'); +const loginBackgroundPreviewMeta = document.getElementById('loginBackgroundPreviewMeta'); +const loginBackgroundFeedback = document.getElementById('loginBackgroundFeedback'); +const loginBackgroundUploadMeta = document.getElementById('loginBackgroundUploadMeta'); + +const initialLoginBackgroundType = loginBackgroundPreviewImg?.classList.contains('is-visible') ? 'image' : 'video'; +const initialLoginBackgroundSrc = initialLoginBackgroundType === 'image' + ? (loginBackgroundPreviewImg?.currentSrc || loginBackgroundPreviewImg?.src || DEFAULT_LOGIN_BACKGROUND_URL) + : (loginBackgroundPreviewVideo?.currentSrc || loginBackgroundPreviewVideo?.src || DEFAULT_LOGIN_BACKGROUND_URL); + +let loginBackgroundSourceMode = 'upload'; +let selectedLoginBackgroundFile = null; +let loginBackgroundPreviewObjectUrl = null; +let loginBackgroundCurrentConfig = { + mode: 'upload', + mediaType: initialLoginBackgroundType, + backgroundUrl: initialLoginBackgroundSrc, + externalUrl: '', + mimeType: initialLoginBackgroundType === 'video' ? 'video/webm' : 'image/webp' +}; + +function setLoginBackgroundFeedback(message, type = 'error') { + if (!loginBackgroundFeedback) return; + loginBackgroundFeedback.textContent = message || ''; + loginBackgroundFeedback.className = 'login-watermark-feedback'; + if (!message) { + loginBackgroundFeedback.style.display = 'none'; + return; + } + loginBackgroundFeedback.classList.add(type); + loginBackgroundFeedback.style.display = 'block'; +} + +function clearLoginBackgroundPreviewObjectUrl() { + if (!loginBackgroundPreviewObjectUrl) return; + try { + URL.revokeObjectURL(loginBackgroundPreviewObjectUrl); + } catch (err) { + console.warn('[login-background] Failed to revoke preview URL:', err); + } + loginBackgroundPreviewObjectUrl = null; +} + +function safePlayLoginBackgroundPreview() { + if (!loginBackgroundPreviewVideo) return; + const playPromise = loginBackgroundPreviewVideo.play(); + if (playPromise && typeof playPromise.then === 'function') { + playPromise.catch(() => { }); + } +} + +function getLoginBackgroundExtension(value) { + try { + const pathname = new URL(value, window.location.origin).pathname.toLowerCase(); + if (!pathname.includes('.')) return ''; + return pathname.slice(pathname.lastIndexOf('.') + 1).replace(/[^a-z0-9]/g, ''); + } catch (err) { + return ''; + } +} + +function detectLoginBackgroundTypeFromUrl(value) { + const ext = getLoginBackgroundExtension(value); + if (['png', 'jpg', 'jpeg', 'webp', 'ico', 'svg'].includes(ext)) return 'image'; + if (['webm', 'mp4', 'ogg', 'ogv'].includes(ext)) return 'video'; + return null; +} + +function detectLoginBackgroundTypeFromFile(file) { + const fileType = String(file?.type || '').toLowerCase(); + if (fileType.startsWith('image/')) return 'image'; + if (fileType.startsWith('video/')) return 'video'; + return detectLoginBackgroundTypeFromUrl(file?.name || ''); +} + +function getLoginBackgroundMimeType(value, mediaType) { + const ext = getLoginBackgroundExtension(value); + if (mediaType === 'image') { + if (ext === 'png') return 'image/png'; + if (ext === 'jpg' || ext === 'jpeg') return 'image/jpeg'; + if (ext === 'webp') return 'image/webp'; + if (ext === 'ico') return 'image/x-icon'; + if (ext === 'svg') return 'image/svg+xml'; + return 'image/webp'; + } + + if (ext === 'mp4') return 'video/mp4'; + if (ext === 'ogg' || ext === 'ogv') return 'video/ogg'; + return 'video/webm'; +} + +function setLoginBackgroundPreview(src, mediaType, badgeText, metaText, mimeType) { + if (!loginBackgroundPreviewImg || !loginBackgroundPreviewVideo) return; + + loginBackgroundPreviewImg.classList.toggle('is-visible', mediaType === 'image'); + loginBackgroundPreviewVideo.classList.toggle('is-visible', mediaType === 'video'); + + if (mediaType === 'image') { + loginBackgroundPreviewVideo.pause(); + loginBackgroundPreviewVideo.removeAttribute('src'); + loginBackgroundPreviewVideo.load(); + loginBackgroundPreviewImg.src = src; + } else { + loginBackgroundPreviewImg.removeAttribute('src'); + loginBackgroundPreviewVideo.src = src; + if (mimeType) loginBackgroundPreviewVideo.dataset.mimeType = mimeType; + loginBackgroundPreviewVideo.load(); + safePlayLoginBackgroundPreview(); + } + + if (loginBackgroundPreviewBadge) { + loginBackgroundPreviewBadge.textContent = badgeText || (mediaType === 'image' ? 'Image' : 'Video'); + } + if (loginBackgroundPreviewMeta) { + loginBackgroundPreviewMeta.textContent = metaText || `Current ${mediaType}`; + } +} + +function showLoginBackgroundToast(message) { + const toast = document.createElement('div'); + toast.className = 'perm-success-toast'; + toast.innerHTML = '' + escapeHtml(message || 'Login background updated'); + document.body.appendChild(toast); + requestAnimationFrame(() => toast.classList.add('show')); + setTimeout(() => { + toast.classList.remove('show'); + setTimeout(() => toast.remove(), 300); + }, 2800); +} + +function syncLoginBackgroundPreviewToCurrent() { + setLoginBackgroundPreview( + loginBackgroundCurrentConfig.backgroundUrl || DEFAULT_LOGIN_BACKGROUND_URL, + loginBackgroundCurrentConfig.mediaType || 'video', + (loginBackgroundCurrentConfig.mediaType || 'video') === 'image' ? 'Image' : 'Video', + `Current ${(loginBackgroundCurrentConfig.mediaType || 'video') === 'image' ? 'image' : 'video'}`, + loginBackgroundCurrentConfig.mimeType || 'video/webm' + ); +} + +function switchLoginBackgroundTab(mode) { + loginBackgroundSourceMode = mode === 'url' ? 'url' : 'upload'; + if (loginBackgroundTabUpload) loginBackgroundTabUpload.classList.toggle('active', loginBackgroundSourceMode === 'upload'); + if (loginBackgroundTabUrl) loginBackgroundTabUrl.classList.toggle('active', loginBackgroundSourceMode === 'url'); + if (loginBackgroundUploadSection) loginBackgroundUploadSection.style.display = loginBackgroundSourceMode === 'upload' ? 'block' : 'none'; + if (loginBackgroundUrlSection) loginBackgroundUrlSection.style.display = loginBackgroundSourceMode === 'url' ? 'block' : 'none'; + + if (loginBackgroundSourceMode === 'upload' && selectedLoginBackgroundFile) { + const mediaType = detectLoginBackgroundTypeFromFile(selectedLoginBackgroundFile) || 'video'; + if (loginBackgroundUploadMeta) { + const mediaLabel = mediaType === 'image' ? 'Image' : 'Video'; + loginBackgroundUploadMeta.textContent = `${mediaLabel} ready: ${selectedLoginBackgroundFile.name}`; + } + if (loginBackgroundPreviewObjectUrl) { + setLoginBackgroundPreview( + loginBackgroundPreviewObjectUrl, + mediaType, + mediaType === 'image' ? 'Image' : 'Video', + `New ${mediaType}`, + selectedLoginBackgroundFile.type || getLoginBackgroundMimeType(selectedLoginBackgroundFile.name, mediaType) + ); + } + return; + } + + if (loginBackgroundSourceMode === 'url' && loginBackgroundUrlInput?.value?.trim()) { + handleLoginBackgroundUrlPreview(); + return; + } + + setLoginBackgroundFeedback(''); + syncLoginBackgroundPreviewToCurrent(); +} + +async function loadCurrentLoginBackground() { + try { + const res = await fetch('/api/admin/login-background', { credentials: 'include' }); + const data = await res.json(); + if (!res.ok) { + throw new Error(data.error || 'Failed to load login background'); + } + + loginBackgroundCurrentConfig = { + mode: data.mode || 'upload', + mediaType: data.mediaType || 'video', + backgroundUrl: data.backgroundUrl || DEFAULT_LOGIN_BACKGROUND_URL, + externalUrl: data.externalUrl || '', + mimeType: data.mimeType || 'video/webm' + }; + + if (loginBackgroundUrlInput) { + loginBackgroundUrlInput.value = data.mode === 'url' ? (data.externalUrl || data.backgroundUrl || '') : ''; + } + if (loginBackgroundUploadMeta) { + loginBackgroundUploadMeta.textContent = data.mode === 'upload' + ? `${data.mediaType === 'image' ? 'Image' : 'Video'} active` + : 'Ready for a local upload'; + } + + switchLoginBackgroundTab(data.mode || 'upload'); + setLoginBackgroundFeedback(''); + syncLoginBackgroundPreviewToCurrent(); + } catch (err) { + console.error('[login-background] Failed to load current settings:', err); + loginBackgroundCurrentConfig = { + mode: 'upload', + mediaType: initialLoginBackgroundType, + backgroundUrl: initialLoginBackgroundSrc, + externalUrl: '', + mimeType: initialLoginBackgroundType === 'video' ? 'video/webm' : 'image/webp' + }; + switchLoginBackgroundTab('upload'); + setLoginBackgroundFeedback('Could not load the current background.', 'error'); + syncLoginBackgroundPreviewToCurrent(); + } +} + +function openLoginBackgroundModal() { + if (!loginBackgroundModalOverlay) return; + selectedLoginBackgroundFile = null; + clearLoginBackgroundPreviewObjectUrl(); + if (loginBackgroundFile) loginBackgroundFile.value = ''; + if (loginBackgroundUploadMeta) loginBackgroundUploadMeta.textContent = ''; + setLoginBackgroundFeedback(''); + syncLoginBackgroundPreviewToCurrent(); + loginBackgroundModalOverlay.setAttribute('aria-hidden', 'false'); + loginBackgroundModalOverlay.classList.add('show'); + loadCurrentLoginBackground(); +} + +function closeLoginBackgroundModal() { + if (!loginBackgroundModalOverlay) return; + if (loginBackgroundPreviewVideo) { + loginBackgroundPreviewVideo.pause(); + } + clearLoginBackgroundPreviewObjectUrl(); + loginBackgroundModalOverlay.setAttribute('aria-hidden', 'true'); + loginBackgroundModalOverlay.classList.remove('show'); +} + +function handleLoginBackgroundFileSelect(e) { + const file = e.target.files?.[0]; + if (!file) return; + + const mediaType = detectLoginBackgroundTypeFromFile(file); + if (!mediaType) { + setLoginBackgroundFeedback('Choose a valid image or video file.', 'error'); + if (loginBackgroundFile) loginBackgroundFile.value = ''; + return; + } + + const maxBytes = mediaType === 'image' ? 5 * 1024 * 1024 : 40 * 1024 * 1024; + if (file.size > maxBytes) { + setLoginBackgroundFeedback(mediaType === 'image' ? 'Image must be under 5MB.' : 'Video must be under 40MB.', 'error'); + if (loginBackgroundFile) loginBackgroundFile.value = ''; + return; + } + + clearLoginBackgroundPreviewObjectUrl(); + loginBackgroundPreviewObjectUrl = URL.createObjectURL(file); + selectedLoginBackgroundFile = file; + + if (loginBackgroundUploadMeta) { + loginBackgroundUploadMeta.textContent = `${mediaType === 'image' ? 'Image' : 'Video'} selected: ${file.name}`; + } + + setLoginBackgroundFeedback(''); + setLoginBackgroundPreview( + loginBackgroundPreviewObjectUrl, + mediaType, + mediaType === 'image' ? 'Image' : 'Video', + `New ${mediaType}`, + file.type || getLoginBackgroundMimeType(file.name, mediaType) + ); +} + +function handleLoginBackgroundUrlPreview() { + const url = loginBackgroundUrlInput?.value?.trim(); + if (!url) { + setLoginBackgroundFeedback(''); + syncLoginBackgroundPreviewToCurrent(); + return; + } + + const mediaType = detectLoginBackgroundTypeFromUrl(url); + if (!mediaType) { + setLoginBackgroundFeedback('Use a direct image or video URL.', 'error'); + return; + } + + setLoginBackgroundFeedback(''); + setLoginBackgroundPreview( + url, + mediaType, + mediaType === 'image' ? 'Image' : 'Video', + `${mediaType === 'image' ? 'Image' : 'Video'} from web`, + getLoginBackgroundMimeType(url, mediaType) + ); +} + +async function saveLoginBackground() { + if (!loginBackgroundSaveBtn) return; + + const body = {}; + if (loginBackgroundSourceMode === 'upload') { + if (!selectedLoginBackgroundFile) { + setLoginBackgroundFeedback('Choose an image or video first.', 'error'); + return; + } + + const reader = new FileReader(); + const base64 = await new Promise((resolve) => { + reader.onload = (event) => resolve(event.target?.result || ''); + reader.readAsDataURL(selectedLoginBackgroundFile); + }); + body.backgroundBase64 = base64; + body.backgroundFilename = selectedLoginBackgroundFile.name; + } else { + const url = loginBackgroundUrlInput?.value?.trim(); + if (!url) { + setLoginBackgroundFeedback('Paste a media URL first.', 'error'); + return; + } + + const mediaType = detectLoginBackgroundTypeFromUrl(url); + if (!mediaType) { + setLoginBackgroundFeedback('Use a direct image or video URL.', 'error'); + return; + } + body.backgroundUrl = url; + } + + try { + setLoginBackgroundFeedback(''); + loginBackgroundSaveBtn.disabled = true; + loginBackgroundSaveBtn.innerHTML = ' Saving...'; + + const res = await fetch('/api/admin/login-background', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + credentials: 'include', + body: JSON.stringify(body) + }); + + const data = await res.json(); + if (!res.ok) { + throw new Error(data.error || 'Failed to update login background'); + } + + loginBackgroundCurrentConfig = { + mode: data.mode || loginBackgroundSourceMode, + mediaType: data.mediaType || 'video', + backgroundUrl: data.backgroundUrl || DEFAULT_LOGIN_BACKGROUND_URL, + externalUrl: data.externalUrl || '', + mimeType: data.mimeType || 'video/webm' + }; + + closeLoginBackgroundModal(); + showLoginBackgroundToast('Login background updated'); + } catch (err) { + console.error('[login-background] Save error:', err); + setLoginBackgroundFeedback(err.message || 'Failed to save login background', 'error'); + } finally { + loginBackgroundSaveBtn.disabled = false; + loginBackgroundSaveBtn.innerHTML = ' Save Background'; + } +} + +if (openLoginBackgroundBtn) openLoginBackgroundBtn.addEventListener('click', openLoginBackgroundModal); +if (loginBackgroundModalClose) loginBackgroundModalClose.addEventListener('click', closeLoginBackgroundModal); +if (loginBackgroundCancelBtn) loginBackgroundCancelBtn.addEventListener('click', closeLoginBackgroundModal); +if (loginBackgroundSaveBtn) loginBackgroundSaveBtn.addEventListener('click', saveLoginBackground); +if (loginBackgroundTabUpload) loginBackgroundTabUpload.addEventListener('click', () => switchLoginBackgroundTab('upload')); +if (loginBackgroundTabUrl) loginBackgroundTabUrl.addEventListener('click', () => switchLoginBackgroundTab('url')); +if (loginBackgroundSelectBtn) loginBackgroundSelectBtn.addEventListener('click', () => loginBackgroundFile?.click()); +if (loginBackgroundFile) loginBackgroundFile.addEventListener('change', handleLoginBackgroundFileSelect); +if (loginBackgroundUrlInput) { + loginBackgroundUrlInput.addEventListener('input', () => { + if (loginBackgroundSourceMode === 'url') handleLoginBackgroundUrlPreview(); + }); + loginBackgroundUrlInput.addEventListener('change', handleLoginBackgroundUrlPreview); +} +if (loginBackgroundModalOverlay) { + loginBackgroundModalOverlay.addEventListener('click', (e) => { + if (e.target === loginBackgroundModalOverlay) closeLoginBackgroundModal(); + }); +} +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && loginBackgroundModalOverlay?.classList.contains('show')) { + closeLoginBackgroundModal(); + } +}); + +const nodeStatsModalOverlay = document.getElementById('nodeStatsModalOverlay'); +const statsModalClose = document.getElementById('statsModalClose'); +const statsModalBody = document.getElementById('statsModalBody'); +const statsNodeNameEl = document.getElementById('statsNodeName'); +const statsImage = document.getElementById('nodeStatsImage'); + +if (statsImage) { + statsImage.addEventListener('error', () => { + if (!statsImage.src.includes('server.webp')) { + statsImage.src = '/images/server.webp'; + } + }); + if (statsImage.complete && statsImage.naturalHeight === 0) { + statsImage.src = '/images/server.webp'; + } +} + +let statsPollingInterval = null; +let currentStatsNodeId = null; + +function openNodeStatsModal(nodeId, nodeName) { + if (!nodeStatsModalOverlay) return; + currentStatsNodeId = nodeId; + if (statsNodeNameEl) statsNodeNameEl.textContent = 'Node name: ' + (nodeName || 'Loading...'); + nodeStatsModalOverlay.classList.add('show'); + document.body.style.overflow = 'hidden'; + + statsModalBody.innerHTML = ` +
    +
    + Loading statistics... +
    + `; + + fetchAndRenderStats(nodeId); + + statsPollingInterval = setInterval(() => { + if (currentStatsNodeId) fetchAndRenderStats(currentStatsNodeId); + }, 5000); +} + +function closeNodeStatsModal() { + if (!nodeStatsModalOverlay) return; + nodeStatsModalOverlay.classList.remove('show'); + document.body.style.overflow = ''; + + if (statsPollingInterval) { + clearInterval(statsPollingInterval); + statsPollingInterval = null; + } + currentStatsNodeId = null; +} + +async function fetchAndRenderStats(nodeId) { + try { + const res = await fetch(`/api/admin/nodes/${encodeURIComponent(nodeId)}/stats`); + const data = await res.json(); + + if (!data.ok || !data.online) { + renderOfflineStats(data.nodeName || nodeId, data.error); + return; + } + + renderStats(data); + } catch (err) { + console.error('[stats] Fetch error:', err); + renderOfflineStats(currentStatsNodeId, 'Connection error'); + } +} + +function renderOfflineStats(nodeName, error) { + statsNodeNameEl.textContent = 'Node name: ' + (nodeName || 'Node'); + statsModalBody.innerHTML = ` +
    +
    + +
    +
    Node Offline
    +
    ${escapeHtml(error || 'Unable to connect to this node')}
    +
    + `; +} + +function renderStats(data) { + const s = data.stats; + statsNodeNameEl.textContent = 'Node name: ' + (data.nodeName || 'Node'); + + const cpuClass = s.cpu.percent > 90 ? 'warning' : ''; + const ramClass = s.ram.freeMb < 100 ? 'critical' : s.ram.percent > 90 ? 'warning' : ''; + const diskClass = s.disk.freeGb < 1 ? 'critical' : s.disk.percent > 90 ? 'warning' : ''; + + let html = ''; + + if (data.warnings && data.warnings.length > 0) { + html += '
    '; + data.warnings.forEach(w => { + const icon = w.level === 'critical' ? 'fa-triangle-exclamation' : 'fa-circle-exclamation'; + html += ` +
    + + ${escapeHtml(w.message)} +
    + `; + }); + html += '
    '; + } + + html += ` +
    +
    +
    +
    + CPU Usage +
    +
    ${s.cpu.percent}%
    +
    +
    +
    +
    +
    +
    + 0% + 100% +
    +
    +
    +
    + Cores + ${s.cpu.cores || 'N/A'} +
    +
    +
    + `; + + html += ` +
    +
    +
    +
    + Memory Usage +
    +
    ${s.ram.percent}%
    +
    +
    +
    +
    +
    +
    + ${formatBytes(s.ram.usedMb * 1024 * 1024)} used + ${formatBytes(s.ram.totalMb * 1024 * 1024)} total +
    +
    +
    +
    + Used + ${(s.ram.usedMb / 1024).toFixed(1)} GB +
    +
    + Free + ${(s.ram.freeMb / 1024).toFixed(1)} GB +
    +
    +
    + `; + + html += ` +
    +
    +
    +
    + Disk Usage +
    +
    ${s.disk.percent}%
    +
    +
    +
    +
    +
    +
    + ${s.disk.usedGb} GB used + ${s.disk.totalGb} GB total +
    +
    +
    +
    + Used + ${s.disk.usedGb} GB +
    +
    + Free + ${s.disk.freeGb} GB +
    +
    +
    + `; + + html += ` +
    +
    +
    +
    + System Information +
    +
    +
    +
    + Hostname + ${escapeHtml(s.hostname || 'N/A')} +
    +
    + OS + ${escapeHtml(s.os || 'N/A')} +
    +
    + Uptime + ${formatUptime(s.uptime)} +
    +
    + Status + ● Online +
    +
    +
    + `; + + html += ` +
    + Last updated: ${new Date().toLocaleTimeString()} • Auto-refreshing every 5 seconds +
    + `; + + statsModalBody.innerHTML = html; +} + +function formatBytes(bytes) { + if (bytes === 0) return '0 B'; + const k = 1024; + const sizes = ['B', 'KB', 'MB', 'GB', 'TB']; + const i = Math.floor(Math.log(bytes) / Math.log(k)); + return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + ' ' + sizes[i]; +} + +function formatUptime(seconds) { + if (!seconds || seconds <= 0) return 'N/A'; + const days = Math.floor(seconds / 86400); + const hours = Math.floor((seconds % 86400) / 3600); + const mins = Math.floor((seconds % 3600) / 60); + if (days > 0) return `${days}d ${hours}h ${mins}m`; + if (hours > 0) return `${hours}h ${mins}m`; + return `${mins}m`; +} + +if (statsModalClose) statsModalClose.addEventListener('click', closeNodeStatsModal); +if (nodeStatsModalOverlay) { + nodeStatsModalOverlay.addEventListener('click', (e) => { + if (e.target === nodeStatsModalOverlay) closeNodeStatsModal(); + }); +} + +document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && nodeStatsModalOverlay?.classList.contains('show')) { + closeNodeStatsModal(); + } +}); + +document.addEventListener('DOMContentLoaded', () => { + const openAlertModalBtn = document.getElementById('openAlertModalBtn'); + const alertModal = document.getElementById('alertModal'); + const closeAlertModal = document.getElementById('closeAlertModal'); + const closeAlertModalFooter = document.getElementById('closeAlertModalFooter'); + const addAlertBtn = document.getElementById('addAlertBtn'); + const alertContent = document.getElementById('alertContent'); + const alertDate = document.getElementById('alertDate'); + const alertEndDate = document.getElementById('alertEndDate'); + const alertNeverEnds = document.getElementById('alertNeverEnds'); + const alertsList = document.getElementById('alertsList'); + + if (openAlertModalBtn) { + console.log('Setup alert listeners, button:', openAlertModalBtn, 'modal:', alertModal); + + function formatAlertDate(value) { + if (!value) return 'Not set'; + const date = new Date(value); + if (Number.isNaN(date.getTime())) return 'Invalid date'; + return date.toLocaleString([], { + year: 'numeric', + month: 'short', + day: 'numeric', + hour: '2-digit', + minute: '2-digit' + }); + } + + function parseLocalDateTimeInput(value) { + if (!value) return null; + const parts = value.split('T'); + if (parts.length !== 2) return null; + const [y, m, d] = parts[0].split('-').map(Number); + const [h, min] = parts[1].split(':').map(Number); + if ([y, m, d, h, min].some((num) => Number.isNaN(num))) return null; + const localDate = new Date(y, m - 1, d, h, min); + if (Number.isNaN(localDate.getTime())) return null; + return localDate; + } + + function getAlertStatusMeta(alert) { + const now = Date.now(); + const startAt = alert?.date ? new Date(alert.date).getTime() : 0; + const endAt = alert?.neverEnds || !alert?.endDate ? null : new Date(alert.endDate).getTime(); + + if (Number.isFinite(startAt) && startAt > now) { + return { + label: 'Scheduled', + style: 'color:#fbbf24;font-size:10px;margin-left:6px;background:rgba(251,191,36,0.1);padding:2px 6px;border-radius:4px;' + }; + } + + if (endAt !== null && Number.isFinite(endAt) && endAt <= now) { + return { + label: 'Ended', + style: 'color:#f87171;font-size:10px;margin-left:6px;background:rgba(248,113,113,0.1);padding:2px 6px;border-radius:4px;' + }; + } + + return { + label: 'Active', + style: 'color:#4ade80;font-size:10px;margin-left:6px;background:rgba(74,222,128,0.1);padding:2px 6px;border-radius:4px;' + }; + } + + function syncAlertEndDateState() { + if (!alertEndDate || !alertNeverEnds) return; + const keepActive = !!alertNeverEnds.checked; + alertEndDate.disabled = keepActive; + alertEndDate.required = !keepActive; + alertEndDate.style.opacity = keepActive ? '0.55' : '1'; + } + + function toggleAlertModal(show) { + if (show) { + alertModal.setAttribute('aria-hidden', 'false'); + alertModal.classList.add('show'); + const inner = alertModal.querySelector('.enterprise-modal'); + if (inner) setTimeout(() => inner.classList.add('show'), 10); + if (alertNeverEnds) alertNeverEnds.checked = true; + syncAlertEndDateState(); + loadAlerts(); + } else { + alertModal.setAttribute('aria-hidden', 'true'); + const inner = alertModal.querySelector('.enterprise-modal'); + if (inner) inner.classList.remove('show'); + setTimeout(() => alertModal.classList.remove('show'), inner ? 200 : 0); + } + } + + function loadAlerts() { + if (!alertsList) return; + alertsList.innerHTML = '
    Loading...
    '; + fetch('/api/settings/alert') + .then(res => res.json()) + .then(data => { + if (!Array.isArray(data) || data.length === 0) { + alertsList.innerHTML = '
    No alerts found.
    '; + return; + } + alertsList.innerHTML = ''; + data.sort((a, b) => new Date(b.date || 0) - new Date(a.date || 0)); + data.forEach(alert => { + const row = document.createElement('div'); + row.style.background = 'rgba(255,255,255,0.03)'; + row.style.padding = '10px'; + row.style.borderRadius = '8px'; + row.style.display = 'flex'; + row.style.justifyContent = 'space-between'; + row.style.alignItems = 'center'; + + const info = document.createElement('div'); + const startDateStr = formatAlertDate(alert.date); + const endDateStr = alert.neverEnds ? 'Until removed' : formatAlertDate(alert.endDate); + const statusMeta = getAlertStatusMeta(alert); + const status = `${statusMeta.label}`; + + info.innerHTML = `
    ${startDateStr} ${status}
    Ends: ${endDateStr}
    ${alert.message}
    `; + + const delBtn = document.createElement('button'); + delBtn.className = 'btn ghost'; + delBtn.innerHTML = ''; + delBtn.style.padding = '6px 10px'; + delBtn.style.color = '#ff6b6b'; + delBtn.style.borderColor = 'rgba(255,107,107,0.2)'; + delBtn.onclick = () => deleteAlert(alert.id); + + row.appendChild(info); + row.appendChild(delBtn); + alertsList.appendChild(row); + }); + }) + .catch(err => { + console.error(err); + alertsList.innerHTML = '
    Failed to load alerts
    '; + }); + } + + function deleteAlert(id) { + if (!confirm('Delete this alert?')) return; + fetch('/api/settings/alert/' + id, { method: 'DELETE' }) + .then(res => res.json()) + .then(data => { + if (data.ok) loadAlerts(); + else alert('Failed: ' + data.error); + }) + .catch(err => alert('Error: ' + err)); + } + + openAlertModalBtn.addEventListener('click', (e) => { + e.preventDefault(); + toggleAlertModal(true); + }); + + if (closeAlertModal) { + closeAlertModal.addEventListener('click', () => toggleAlertModal(false)); + } + if (closeAlertModalFooter) { + closeAlertModalFooter.addEventListener('click', () => toggleAlertModal(false)); + } + + window.addEventListener('click', (e) => { + if (e.target === alertModal) toggleAlertModal(false); + }); + + if (alertNeverEnds) { + alertNeverEnds.addEventListener('change', syncAlertEndDateState); + syncAlertEndDateState(); + } + + if (alertDate && alertEndDate) { + alertDate.addEventListener('change', () => { + alertEndDate.min = alertDate.value || ''; + if (alertEndDate.value && alertDate.value && alertEndDate.value < alertDate.value) { + alertEndDate.value = ''; + } + }); + } + + if (addAlertBtn) { + addAlertBtn.addEventListener('click', () => { + const message = alertContent.value.trim(); + const dateStr = alertDate.value; + const endDateStr = alertEndDate?.value || ''; + const keepActive = !!alertNeverEnds?.checked; + + if (!message) { + alert('Please enter a message'); + return; + } + + const startDate = parseLocalDateTimeInput(dateStr); + if (!startDate) { + alert('Please select a complete date and time.'); + return; + } + + let isoEndDate = null; + if (!keepActive) { + const endDate = parseLocalDateTimeInput(endDateStr); + if (!endDate) { + alert('Please select an end date.'); + return; + } + if (endDate.getTime() <= startDate.getTime()) { + alert('End date must be after start date.'); + return; + } + isoEndDate = endDate.toISOString(); + } + + fetch('/api/settings/alert', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + message, + date: startDate.toISOString(), + endDate: isoEndDate, + neverEnds: keepActive + }) + }) + .then(res => res.json()) + .then(data => { + if (data.ok) { + alertContent.value = ''; + alertDate.value = ''; + if (alertEndDate) alertEndDate.value = ''; + if (alertNeverEnds) alertNeverEnds.checked = true; + syncAlertEndDateState(); + loadAlerts(); + } else { + alert('Failed: ' + (data.error || 'Unknown')); + } + }) + .catch(err => alert('Error: ' + err)); + }); + } + } + + let webhooksConfig = { mode: 'single', single: null, multiple: {} }; + let webhookCategories = []; + let webhookEditCategory = null; + + const webhookModeSingle = document.getElementById('webhookModeSingle'); + const webhookModeMultiple = document.getElementById('webhookModeMultiple'); + const webhookSingleSection = document.getElementById('webhookSingleSection'); + const webhookMultipleSection = document.getElementById('webhookMultipleSection'); + const webhookSingleList = document.getElementById('webhookSingleList'); + const webhookSingleEmpty = document.getElementById('webhookSingleEmpty'); + const webhookCategoriesGrid = document.getElementById('webhookCategoriesGrid'); + const openAddWebhookBtn = document.getElementById('openAddWebhookBtn'); + const webhookModalOverlay = document.getElementById('webhookModalOverlay'); + const webhookModalClose = document.getElementById('webhookModalClose'); + const webhookModalCancel = document.getElementById('webhookModalCancel'); + const webhookModalSave = document.getElementById('webhookModalSave'); + const webhookModalTitle = document.getElementById('webhookModalTitle'); + const webhookModalSubtitle = document.getElementById('webhookModalSubtitle'); + const webhookUrlInput = document.getElementById('webhookUrlInput'); + const webhookModalError = document.getElementById('webhookModalError'); + const webhookModeIndicator = document.getElementById('webhookModeIndicator'); + const webhookCategoryLabel = document.getElementById('webhookCategoryLabel'); + const webhookDeleteOverlay = document.getElementById('webhookDeleteOverlay'); + const webhookDeleteClose = document.getElementById('webhookDeleteClose'); + const webhookDeleteCancelBtn = document.getElementById('webhookDeleteCancelBtn'); + const webhookDeleteConfirmBtn = document.getElementById('webhookDeleteConfirmBtn'); + const webhookDeleteText = document.getElementById('webhookDeleteText'); + + let pendingDeleteCategory = null; + + function toggleWebhookModal(show, options = {}) { + if (!webhookModalOverlay) return; + const resetInput = options.resetInput !== false; + const innerModal = webhookModalOverlay.querySelector('.enterprise-modal'); + webhookModalOverlay.setAttribute('aria-hidden', show ? 'false' : 'true'); + if (show) { + webhookModalOverlay.classList.add('show'); + if (innerModal) { + innerModal.style.animation = 'none'; + innerModal.offsetHeight; + innerModal.style.animation = ''; + setTimeout(() => innerModal.classList.add('show'), 10); + } + if (webhookModalError) { + webhookModalError.textContent = ''; + webhookModalError.style.display = 'none'; + } + if (webhookUrlInput && resetInput) webhookUrlInput.value = ''; + setTimeout(() => webhookUrlInput && webhookUrlInput.focus(), 100); + } else { + if (innerModal) innerModal.classList.remove('show'); + setTimeout(() => webhookModalOverlay.classList.remove('show'), 200); + } + } + + function toggleWebhookDeleteModal(show) { + if (!webhookDeleteOverlay) return; + const innerModal = webhookDeleteOverlay.querySelector('.enterprise-modal'); + webhookDeleteOverlay.setAttribute('aria-hidden', show ? 'false' : 'true'); + if (show) { + webhookDeleteOverlay.classList.add('show'); + if (innerModal) { + innerModal.style.animation = 'none'; + innerModal.offsetHeight; + innerModal.style.animation = ''; + setTimeout(() => innerModal.classList.add('show'), 10); + } + } else { + if (innerModal) innerModal.classList.remove('show'); + setTimeout(() => webhookDeleteOverlay.classList.remove('show'), 200); + } + } + + async function loadWebhooks() { + try { + const res = await fetch('/api/settings/webhooks'); + const data = await res.json(); + if (data.ok) { + webhooksConfig = data.config || { mode: 'single', single: null, multiple: {} }; + webhookCategories = data.categories || []; + renderWebhooks(); + } + } catch (e) { + console.error('[webhooks] Load error:', e); + } + } + window._loadWebhooks = loadWebhooks; + + function renderWebhooks() { + if (!webhookModeSingle) return; + + if (webhooksConfig.mode === 'single') { + webhookModeSingle.classList.add('active'); + webhookModeMultiple.classList.remove('active'); + if (webhookSingleSection) webhookSingleSection.style.display = ''; + if (webhookMultipleSection) webhookMultipleSection.style.display = 'none'; + } else { + webhookModeSingle.classList.remove('active'); + webhookModeMultiple.classList.add('active'); + if (webhookSingleSection) webhookSingleSection.style.display = 'none'; + if (webhookMultipleSection) webhookMultipleSection.style.display = ''; + } + + const singleConfigured = !!(webhooksConfig.singleConfigured || webhooksConfig.single); + if (singleConfigured) { + if (webhookSingleEmpty) webhookSingleEmpty.style.display = 'none'; + if (webhookSingleList) webhookSingleList.innerHTML = renderWebhookItem('All Events', webhooksConfig.single); + } else { + if (webhookSingleEmpty) webhookSingleEmpty.style.display = 'flex'; + if (webhookSingleList) webhookSingleList.innerHTML = ''; + } + + if (webhookCategoriesGrid) { + webhookCategoriesGrid.innerHTML = webhookCategories.map(cat => { + const maskedUrl = webhooksConfig.multiple && webhooksConfig.multiple[cat.id]; + const isConfigured = !!(webhooksConfig.multipleConfigured && webhooksConfig.multipleConfigured[cat.id]); + const hasUrl = isConfigured || !!maskedUrl; + const safeColor = /^#[0-9a-fA-F]{3,8}$/.test(cat.color) ? cat.color : '#888'; + const safeIcon = /^[a-zA-Z0-9\- ]+$/.test(cat.icon) ? cat.icon : 'fa-solid fa-circle'; + return ` +
    +
    +
    + +
    +
    +
    ${escapeHtml(cat.label)}
    +
    ${hasUrl ? escapeHtml(maskedUrl || 'Configured') : 'Not configured'}
    +
    +
    +
    + ${hasUrl ? 'Active' : 'Inactive'} + ${hasUrl ? ` + + + ` : ''} + +
    +
    `; + }).join(''); + } + } + + function renderWebhookItem(label, maskedUrl) { + return ` +
    +
    +
    +
    +
    ${escapeHtml(label)}
    +
    ${escapeHtml(maskedUrl || 'Configured')}
    +
    +
    +
    + + + +
    +
    `; + } + + if (webhookModeSingle) { + webhookModeSingle.addEventListener('click', async () => { + if (webhooksConfig.mode === 'single') return; + try { + const res = await fetch('/api/settings/webhooks', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mode: 'single' }) + }); + const data = await res.json(); + if (data.ok) { webhooksConfig.mode = 'single'; renderWebhooks(); } + } catch (e) { console.error(e); } + }); + } + + if (webhookModeMultiple) { + webhookModeMultiple.addEventListener('click', async () => { + if (webhooksConfig.mode === 'multiple') return; + try { + const res = await fetch('/api/settings/webhooks', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ mode: 'multiple' }) + }); + const data = await res.json(); + if (data.ok) { webhooksConfig.mode = 'multiple'; renderWebhooks(); } + } catch (e) { console.error(e); } + }); + } + + if (openAddWebhookBtn) { + openAddWebhookBtn.addEventListener('click', () => { + webhookEditCategory = null; + if (webhookModalTitle) webhookModalTitle.textContent = 'Add Single Webhook'; + if (webhookModalSubtitle) webhookModalSubtitle.textContent = 'Enter a Discord webhook URL for all log categories'; + if (webhookModeIndicator) webhookModeIndicator.style.display = 'none'; + toggleWebhookModal(true, { resetInput: true }); + }); + } + + if (webhookSingleList) { + webhookSingleList.addEventListener('click', (e) => { + const btn = e.target.closest('button[data-webhook-action]'); + if (!btn || !webhookSingleList.contains(btn)) return; + const action = btn.getAttribute('data-webhook-action'); + if (action === 'test-single') testWebhookSingle(); + else if (action === 'edit-single') openEditWebhookSingle(); + else if (action === 'delete-single') confirmDeleteWebhookSingle(); + }); + } + + if (webhookCategoriesGrid) { + webhookCategoriesGrid.addEventListener('click', (e) => { + const btn = e.target.closest('button[data-webhook-action]'); + if (!btn || !webhookCategoriesGrid.contains(btn)) return; + const action = btn.getAttribute('data-webhook-action'); + const categoryId = btn.getAttribute('data-webhook-category'); + if (!categoryId) return; + if (action === 'edit-category') openWebhookCategoryModal(categoryId); + else if (action === 'delete-category') deleteWebhookCategory(categoryId); + else if (action === 'test-category') testWebhookCategory(categoryId); + }); + } + + if (webhookModalClose) webhookModalClose.addEventListener('click', () => toggleWebhookModal(false)); + if (webhookModalCancel) webhookModalCancel.addEventListener('click', () => toggleWebhookModal(false)); + if (webhookModalOverlay) webhookModalOverlay.addEventListener('click', (e) => { if (e.target === webhookModalOverlay) toggleWebhookModal(false); }); + + if (webhookModalSave) { + webhookModalSave.addEventListener('click', async () => { + const url = (webhookUrlInput.value || '').trim(); + if (!url) { + webhookModalError.textContent = 'Please enter a webhook URL'; + webhookModalError.style.display = 'block'; + return; + } + if (!/^https:\/\/discord\.com\/api\/webhooks\/\d+\/[\w-]+$/.test(url)) { + webhookModalError.textContent = 'Invalid Discord webhook URL format'; + webhookModalError.style.display = 'block'; + return; + } + webhookModalSave.disabled = true; + webhookModalSave.innerHTML = ' Saving...'; + try { + const body = { url }; + if (webhookEditCategory) body.category = webhookEditCategory; + const res = await fetch('/api/settings/webhooks', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }); + const data = await res.json(); + if (data.ok) { + toggleWebhookModal(false); + loadWebhooks(); + } else { + webhookModalError.textContent = data.error || 'Failed to save'; + webhookModalError.style.display = 'block'; + } + } catch (e) { + webhookModalError.textContent = 'Network error'; + webhookModalError.style.display = 'block'; + } finally { + webhookModalSave.disabled = false; + webhookModalSave.innerHTML = ' Save Webhook'; + } + }); + } + + if (webhookDeleteClose) webhookDeleteClose.addEventListener('click', () => toggleWebhookDeleteModal(false)); + if (webhookDeleteCancelBtn) webhookDeleteCancelBtn.addEventListener('click', () => toggleWebhookDeleteModal(false)); + if (webhookDeleteOverlay) webhookDeleteOverlay.addEventListener('click', (e) => { if (e.target === webhookDeleteOverlay) toggleWebhookDeleteModal(false); }); + + if (webhookDeleteConfirmBtn) { + webhookDeleteConfirmBtn.addEventListener('click', async () => { + webhookDeleteConfirmBtn.disabled = true; + webhookDeleteConfirmBtn.innerHTML = ' Deleting...'; + try { + const body = {}; + if (pendingDeleteCategory) body.category = pendingDeleteCategory; + const res = await fetch('/api/settings/webhooks', { + method: 'DELETE', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body) + }); + const data = await res.json(); + if (data.ok) { toggleWebhookDeleteModal(false); loadWebhooks(); } + } catch (e) { console.error(e); } + finally { + webhookDeleteConfirmBtn.disabled = false; + webhookDeleteConfirmBtn.innerHTML = ' Delete'; + pendingDeleteCategory = null; + } + }); + } + + function openEditWebhookSingle() { + webhookEditCategory = null; + if (webhookModalTitle) webhookModalTitle.textContent = 'Replace Webhook'; + if (webhookModalSubtitle) webhookModalSubtitle.textContent = 'Enter a new Discord webhook URL to replace the current one'; + if (webhookModeIndicator) webhookModeIndicator.style.display = 'none'; + toggleWebhookModal(true, { resetInput: true }); + } + + function confirmDeleteWebhookSingle() { + pendingDeleteCategory = null; + if (webhookDeleteText) webhookDeleteText.textContent = 'Are you sure you want to remove the webhook? It will stop receiving all panel activity logs.'; + toggleWebhookDeleteModal(true); + } + + async function testWebhookSingle() { + try { + const res = await fetch('/api/settings/webhooks/test', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({}) + }); + const data = await res.json(); + showWebhookToast(data.ok ? 'Test message sent!' : (data.error || 'Failed'), data.ok ? 'success' : 'error'); + } catch (e) { showWebhookToast('Network error', 'error'); } + } + + function openWebhookCategoryModal(catId) { + const cat = webhookCategories.find(c => c.id === catId); + if (!cat) return; + webhookEditCategory = catId; + const isConfigured = !!(webhooksConfig.multipleConfigured && webhooksConfig.multipleConfigured[catId]); + if (webhookModalTitle) webhookModalTitle.textContent = isConfigured ? 'Replace Webhook' : 'Set Webhook'; + if (webhookModalSubtitle) webhookModalSubtitle.textContent = 'Webhook for: ' + cat.label; + if (webhookModeIndicator) webhookModeIndicator.style.display = 'block'; + if (webhookCategoryLabel) webhookCategoryLabel.textContent = cat.label; + toggleWebhookModal(true, { resetInput: true }); + } + + function deleteWebhookCategory(catId) { + const cat = webhookCategories.find(c => c.id === catId); + pendingDeleteCategory = catId; + if (webhookDeleteText) webhookDeleteText.textContent = 'Remove the webhook for "' + (cat ? cat.label : catId) + '"?'; + toggleWebhookDeleteModal(true); + } + + async function testWebhookCategory(catId) { + try { + const res = await fetch('/api/settings/webhooks/test', { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ category: catId }) + }); + const data = await res.json(); + showWebhookToast(data.ok ? 'Test message sent!' : (data.error || 'Failed'), data.ok ? 'success' : 'error'); + } catch (e) { showWebhookToast('Network error', 'error'); } + } + + window.openEditWebhookSingle = openEditWebhookSingle; + window.confirmDeleteWebhookSingle = confirmDeleteWebhookSingle; + window.testWebhookSingle = testWebhookSingle; + window.openWebhookCategoryModal = openWebhookCategoryModal; + window.deleteWebhookCategory = deleteWebhookCategory; + window.testWebhookCategory = testWebhookCategory; + + function showWebhookToast(msg, type) { + const existing = document.querySelector('.webhook-toast'); + if (existing) existing.remove(); + const toast = document.createElement('div'); + toast.className = 'webhook-toast'; + toast.style.cssText = 'position:fixed;bottom:24px;right:24px;z-index:10001;padding:12px 20px;border-radius:10px;font-size:14px;font-weight:500;color:white;pointer-events:none;animation:fadeInUp 0.3s ease;' + + (type === 'success' ? 'background:rgba(34,197,94,0.9);' : 'background:rgba(239,68,68,0.9);'); + toast.innerHTML = '' + escapeHtml(msg); + document.body.appendChild(toast); + setTimeout(() => { toast.style.opacity = '0'; toast.style.transition = 'opacity 0.3s'; setTimeout(() => toast.remove(), 300); }, 3000); + } +}); +(function () { + let _panelInfoTokens = {}; + let _latestVersionFound = null; + let _cachedVersion = ''; + let _cachedArchitecture = ''; + let _copyButtonsInitialized = false; + + function initializePanelInfoCopyButtons() { + if (_copyButtonsInitialized) return; + + const copyVersionBtn = document.getElementById('copyVersionBtn'); + const copyArchBtn = document.getElementById('copyArchBtn'); + const versionEl = document.getElementById('panelInfoVersion'); + const archEl = document.getElementById('panelInfoArchitecture'); + + if (copyVersionBtn && versionEl) { + copyVersionBtn.addEventListener('click', () => { + const version = versionEl.textContent.trim(); + copyToClipboard(version).then(() => { + const icon = copyVersionBtn.querySelector('i'); + if (icon) { + icon.className = 'fa-solid fa-check'; + setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500); + } + }).catch(() => {}); + }); + } + + if (copyArchBtn && archEl) { + copyArchBtn.addEventListener('click', () => { + const arch = archEl.textContent.trim(); + copyToClipboard(arch).then(() => { + const icon = copyArchBtn.querySelector('i'); + if (icon) { + icon.className = 'fa-solid fa-check'; + setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500); + } + }).catch(() => {}); + }); + } + + _copyButtonsInitialized = true; + } + + async function loadPanelInfo() { + const versionEl = document.getElementById('panelInfoVersion'); + const archEl = document.getElementById('panelInfoArchitecture'); + if (!versionEl || !archEl) return; + + versionEl.innerHTML = 'Loading...'; + archEl.innerHTML = 'Loading...'; + + initializePanelInfoCopyButtons(); + + try { + const res = await fetch('/api/settings/panel-info', { credentials: 'include' }); + if (!res.ok) { + versionEl.innerHTML = 'Error'; + archEl.innerHTML = 'Error'; + return; + } + const data = await res.json(); + _cachedVersion = data.version || 'unknown'; + _cachedArchitecture = data.architecture || 'unknown'; + versionEl.innerHTML = `${escapeHtml(_cachedVersion)}`; + archEl.innerHTML = `${escapeHtml(_cachedArchitecture)}`; + _panelInfoTokens = data.actionTokens || {}; + renderAutoUpdateButton(!!data.autoUpdateEnabled); + } catch (e) { + console.error('[panel-info] Failed to load:', e); + versionEl.innerHTML = 'Network error'; + archEl.innerHTML = 'Network error'; + } + } + + window.loadPanelInfo = loadPanelInfo; + + function handleCopy(btnId, getValue) { + const btn = document.getElementById(btnId); + if (!btn) return; + btn.addEventListener('click', async () => { + const value = getValue(); + if (!value || value === 'unknown' || value === 'Loading...') return; + + const textarea = document.createElement('textarea'); + textarea.value = value; + textarea.style.position = 'fixed'; + textarea.style.left = '-9999px'; + textarea.style.top = '0'; + document.body.appendChild(textarea); + textarea.focus(); + textarea.select(); + + try { + document.execCommand('copy'); + btn.classList.add('copied'); + const icon = btn.querySelector('i'); + if (icon) { icon.className = 'fa-solid fa-check'; } + setTimeout(() => { + btn.classList.remove('copied'); + if (icon) { icon.className = 'fa-solid fa-copy'; } + }, 1500); + } catch (err) { + console.error('Copy failed', err); + } + document.body.removeChild(textarea); + }); + } + handleCopy('copyVersionBtn', () => _cachedVersion); + handleCopy('copyArchBtn', () => _cachedArchitecture); + + const checkBtn = document.getElementById('checkForUpdatesBtn'); + const autoUpdateBtn = document.getElementById('toggleAutoUpdateBtn'); + + function renderAutoUpdateButton(enabled) { + if (!autoUpdateBtn) return; + autoUpdateBtn.dataset.enabled = enabled ? 'true' : 'false'; + autoUpdateBtn.className = `btn btn-auto-update ${enabled ? 'enabled' : 'disabled'}`; + autoUpdateBtn.innerHTML = enabled + ? ' Auto Update: On' + : ' Auto Update: Off'; + } + + function resetCheckBtn() { + if (!checkBtn) return; + checkBtn.dataset.mode = ''; + checkBtn.className = 'btn btn-update-check'; + checkBtn.innerHTML = ' Check for Updates'; + checkBtn.disabled = false; + } + + if (checkBtn) { + checkBtn.addEventListener('click', async () => { + const statusEl = document.getElementById('panelUpdateStatus'); + + if (checkBtn.dataset.mode === 'install') { + await doInstall(_latestVersionFound, 'auto'); + return; + } + + const icon = checkBtn.querySelector('.fa-arrows-rotate'); + if (icon) { + icon.classList.remove('spinning'); + void icon.offsetWidth; + icon.classList.add('spinning'); + icon.addEventListener('animationend', () => icon.classList.remove('spinning'), { once: true }); + } + + checkBtn.disabled = true; + if (statusEl) { statusEl.textContent = 'Checking for updates...'; statusEl.className = 'panelinfo-update-status info'; } + + try { + const res = await fetch('/api/settings/panel-update/check', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': _panelInfoTokens.checkUpdate || '' }, + credentials: 'include', + body: JSON.stringify({}), + }); + + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + if (statusEl) { statusEl.textContent = data.error || 'Failed to check for updates'; statusEl.className = 'panelinfo-update-status error'; } + checkBtn.disabled = false; + return; + } + + if (data.updateAvailable) { + _latestVersionFound = data.latestVersion; + if (data.actionTokens) _panelInfoTokens = { ..._panelInfoTokens, ...data.actionTokens }; + if (statusEl) { + statusEl.innerHTML = `New version found: ${escapeHtml(data.latestVersion)} (current: ${escapeHtml(data.currentVersion)})`; + statusEl.className = 'panelinfo-update-status success'; + } + checkBtn.dataset.mode = 'install'; + checkBtn.className = 'btn btn-update-install'; + checkBtn.innerHTML = ' Install Update'; + checkBtn.disabled = false; + } else { + if (statusEl) { + statusEl.innerHTML = `You are running the latest version (${escapeHtml(data.currentVersion)})`; + statusEl.className = 'panelinfo-update-status success'; + } + checkBtn.disabled = false; + await loadPanelInfo(); + } + } catch (e) { + console.error('[panel-update] Check failed:', e); + if (statusEl) { statusEl.textContent = 'Network error while checking for updates'; statusEl.className = 'panelinfo-update-status error'; } + checkBtn.disabled = false; + } + }); + } + + if (autoUpdateBtn) { + autoUpdateBtn.addEventListener('click', async () => { + const statusEl = document.getElementById('panelUpdateStatus'); + const currentlyEnabled = autoUpdateBtn.dataset.enabled === 'true'; + const nextEnabled = !currentlyEnabled; + + autoUpdateBtn.disabled = true; + if (statusEl) { + statusEl.textContent = nextEnabled ? 'Enabling auto update...' : 'Disabling auto update...'; + statusEl.className = 'panelinfo-update-status info'; + } + + try { + if (!_panelInfoTokens.setAutoUpdate) { + await loadPanelInfo(); + } + + const res = await fetch('/api/settings/panel-update/auto', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': _panelInfoTokens.setAutoUpdate || '' }, + credentials: 'include', + body: JSON.stringify({ enabled: nextEnabled }), + }); + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + if (statusEl) { + statusEl.textContent = data.error || 'Failed to toggle auto update'; + statusEl.className = 'panelinfo-update-status error'; + } + return; + } + + renderAutoUpdateButton(!!data.autoUpdateEnabled); + if (statusEl) { + statusEl.textContent = data.autoUpdateEnabled + ? 'Auto Update enabled. New updates will appear in your ADPanel.' + : 'Auto update disabled.'; + statusEl.className = 'panelinfo-update-status success'; + } + } catch (e) { + console.error('[panel-auto-update] Toggle failed:', e); + if (statusEl) { + statusEl.textContent = 'Network error while toggling auto update'; + statusEl.className = 'panelinfo-update-status error'; + } + } finally { + autoUpdateBtn.disabled = false; + } + }); + } + + async function doInstall(version, source) { + const statusEl = document.getElementById('panelUpdateStatus'); + if (!version) { + if (statusEl) { statusEl.textContent = 'No version specified.'; statusEl.className = 'panelinfo-update-status error'; } + return; + } + + const cleanVersion = String(version).trim(); + if (!/^v?\d+\.\d+\.\d+/.test(cleanVersion)) { + if (statusEl) { statusEl.textContent = 'Invalid version format. Use format: v1.0.0'; statusEl.className = 'panelinfo-update-status error'; } + return; + } + + if (!confirm(`Install ADPanel ${cleanVersion}? The panel will need to be restarted after installation.`)) { + return; + } + + if (checkBtn) { + checkBtn.className = 'btn btn-update-installing'; + checkBtn.innerHTML = ' Installing...'; + checkBtn.disabled = true; + } + const manualBtn = document.getElementById('manualInstallBtn'); + const manualInput = document.getElementById('manualVersionInput'); + if (manualBtn) manualBtn.disabled = true; + if (manualInput) manualInput.disabled = true; + + if (statusEl) { statusEl.textContent = 'Downloading and installing update...'; statusEl.className = 'panelinfo-update-status info'; } + + try { + if (!_panelInfoTokens.installUpdate) { + await loadPanelInfo(); + } + + const res = await fetch('/api/settings/panel-update/install', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': _panelInfoTokens.installUpdate || '' }, + credentials: 'include', + body: JSON.stringify({ version: cleanVersion }), + }); + + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + if (statusEl) { statusEl.textContent = data.error || 'Failed to install update'; statusEl.className = 'panelinfo-update-status error'; } + resetCheckBtn(); + if (manualBtn) manualBtn.disabled = false; + if (manualInput) manualInput.disabled = false; + return; + } + + if (statusEl) { + statusEl.innerHTML = `Update to ${escapeHtml(data.version)} installed! ${data.filesUpdated} files updated. Panel restart scheduled.`; + statusEl.className = 'panelinfo-update-status success'; + } + + if (checkBtn) { + checkBtn.className = 'btn btn-update-check'; + checkBtn.innerHTML = ' Update Installed'; + checkBtn.disabled = true; + checkBtn.dataset.mode = ''; + } + if (manualBtn) manualBtn.disabled = false; + if (manualInput) { manualInput.disabled = false; manualInput.value = ''; } + + setTimeout(() => { + resetCheckBtn(); + loadPanelInfo(); + }, 3000); + + } catch (e) { + console.error('[panel-update] Install failed:', e); + if (statusEl) { statusEl.textContent = 'Network error while installing update'; statusEl.className = 'panelinfo-update-status error'; } + resetCheckBtn(); + if (manualBtn) manualBtn.disabled = false; + if (manualInput) manualInput.disabled = false; + } + } + + const manualInstallBtn = document.getElementById('manualInstallBtn'); + const manualVersionInput = document.getElementById('manualVersionInput'); + if (manualInstallBtn && manualVersionInput) { + manualInstallBtn.addEventListener('click', async () => { + const version = manualVersionInput.value.trim(); + if (!version) { + const statusEl = document.getElementById('panelUpdateStatus'); + if (statusEl) { statusEl.textContent = 'Please enter a version number.'; statusEl.className = 'panelinfo-update-status error'; } + manualVersionInput.focus(); + return; + } + await doInstall(version, 'manual'); + }); + + manualVersionInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + manualInstallBtn.click(); + } + }); + } + + const urlParams = new URLSearchParams(window.location.search); + if (urlParams.get('panel') === 'panelinfo') { + loadPanelInfo(); + } +})(); + +(function () { + const overlay = document.getElementById('nodeUpdateOverlay'); + const modal = document.getElementById('nodeUpdateModal'); + const openBtns = [ + document.getElementById('openNodeUpdateBtn'), + document.getElementById('openNodeUpdateCardBtn') + ].filter(Boolean); + const closeBtn = document.getElementById('nodeUpdateClose'); + const cancelBtn = document.getElementById('nodeUpdateCancel'); + const nodeSelect = document.getElementById('nodeUpdateSelect'); + const versionEl = document.getElementById('nodeUpdateVersion'); + const archEl = document.getElementById('nodeUpdateArchitecture'); + const checkBtn = document.getElementById('checkNodeUpdatesBtn'); + const autoBtn = document.getElementById('toggleNodeAutoUpdateBtn'); + const manualBtn = document.getElementById('nodeManualInstallBtn'); + const manualInput = document.getElementById('nodeManualVersionInput'); + const statusEl = document.getElementById('nodeUpdateStatus'); + + if (!overlay || !modal) return; + + let _tokens = {}; + let _nodes = []; + let _selectedNodeId = ''; + let _selectedNodeName = ''; + let _latestVersionFound = null; + let _copyInitialized = false; + + function setNodeStatus(message, type) { + if (!statusEl) return; + statusEl.textContent = message || ''; + statusEl.className = `panelinfo-update-status ${type || ''}`.trim(); + } + + function setNodeStatusHtml(html, type) { + if (!statusEl) return; + statusEl.innerHTML = html || ''; + statusEl.className = `panelinfo-update-status ${type || ''}`.trim(); + } + + function renderNodeAutoButton(enabled) { + if (!autoBtn) return; + autoBtn.dataset.enabled = enabled ? 'true' : 'false'; + autoBtn.className = `btn btn-auto-update ${enabled ? 'enabled' : 'disabled'}`; + autoBtn.innerHTML = enabled + ? ' Auto Update: On' + : ' Auto Update: Off'; + } + + function resetNodeCheckButton() { + if (!checkBtn) return; + checkBtn.dataset.mode = ''; + checkBtn.className = 'btn btn-update-check'; + checkBtn.innerHTML = ' Check for Updates'; + checkBtn.disabled = false; + } + + function initializeNodeCopyButtons() { + if (_copyInitialized) return; + const copyVersionBtn = document.getElementById('copyNodeVersionBtn'); + const copyArchBtn = document.getElementById('copyNodeArchBtn'); + + if (copyVersionBtn && versionEl) { + copyVersionBtn.addEventListener('click', () => { + copyToClipboard(versionEl.textContent.trim()).then(() => { + const icon = copyVersionBtn.querySelector('i'); + if (icon) { + icon.className = 'fa-solid fa-check'; + setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500); + } + }).catch(() => {}); + }); + } + + if (copyArchBtn && archEl) { + copyArchBtn.addEventListener('click', () => { + copyToClipboard(archEl.textContent.trim()).then(() => { + const icon = copyArchBtn.querySelector('i'); + if (icon) { + icon.className = 'fa-solid fa-check'; + setTimeout(() => { icon.className = 'fa-solid fa-copy'; }, 1500); + } + }).catch(() => {}); + }); + } + + _copyInitialized = true; + } + + function populateNodeSelect(nodes, selectedNode) { + if (!nodeSelect) return; + _nodes = Array.isArray(nodes) ? nodes : []; + if (!_nodes.length) { + nodeSelect.innerHTML = ''; + nodeSelect.disabled = true; + return; + } + nodeSelect.disabled = false; + const selectedId = selectedNode?.id || _selectedNodeId || _nodes[0].id; + nodeSelect.innerHTML = _nodes.map(node => { + const label = `${node.name || node.id} (${node.address || 'unknown'})`; + return ``; + }).join(''); + _selectedNodeId = String(selectedId || ''); + const found = _nodes.find(node => String(node.id) === _selectedNodeId); + _selectedNodeName = found?.name || selectedNode?.name || _selectedNodeId; + } + + async function loadNodeUpdateInfo(nodeId) { + initializeNodeCopyButtons(); + if (versionEl) versionEl.innerHTML = 'Loading...'; + if (archEl) archEl.innerHTML = 'Loading...'; + resetNodeCheckButton(); + + try { + const params = new URLSearchParams(); + if (nodeId) params.set('nodeId', nodeId); + const res = await fetch('/api/settings/node-update/info' + (params.toString() ? `?${params.toString()}` : ''), { + credentials: 'include', + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) { + if (versionEl) versionEl.innerHTML = 'Error'; + if (archEl) archEl.innerHTML = 'Error'; + setNodeStatus(data.error || 'Failed to load node update information', 'error'); + return; + } + + populateNodeSelect(data.nodes || [], data.selectedNode); + _tokens = data.actionTokens || {}; + if (data.selectedNode?.id) { + _selectedNodeId = String(data.selectedNode.id); + _selectedNodeName = data.selectedNode.name || _selectedNodeId; + } + if (versionEl) versionEl.innerHTML = `${escapeHtml(data.version || 'unknown')}`; + if (archEl) archEl.innerHTML = `${escapeHtml(data.architecture || 'unknown')}`; + renderNodeAutoButton(!!data.autoUpdateEnabled); + if (data.error) { + setNodeStatus(data.error, 'error'); + } else if (data.updateApiAvailable === false) { + setNodeStatus('This node is online but does not expose the new update endpoint yet.', 'info'); + } else { + setNodeStatus('', ''); + } + } catch (e) { + console.error('[node-update] Failed to load:', e); + if (versionEl) versionEl.innerHTML = 'Network error'; + if (archEl) archEl.innerHTML = 'Network error'; + setNodeStatus('Network error while loading node update information', 'error'); + } + } + + function showNodeUpdateModal(show, nodeId) { + if (show) { + overlay.classList.add('show'); + modal.classList.add('show'); + window.setTimeout(() => { + if (typeof syncModalBaseline === 'function') syncModalBaseline(overlay); + }, 0); + loadNodeUpdateInfo(nodeId || _selectedNodeId); + return; + } + overlay.classList.remove('show'); + modal.classList.remove('show'); + if (typeof resetModalUnsavedState === 'function') resetModalUnsavedState(overlay); + } + + window.openNodeUpdateModal = (nodeId) => showNodeUpdateModal(true, nodeId); + + openBtns.forEach(btn => btn.addEventListener('click', () => showNodeUpdateModal(true))); + if (closeBtn) closeBtn.addEventListener('click', () => showNodeUpdateModal(false)); + if (cancelBtn) cancelBtn.addEventListener('click', () => showNodeUpdateModal(false)); + overlay.addEventListener('click', (e) => { + if (e.target === overlay) showNodeUpdateModal(false); + }); + document.addEventListener('keydown', (e) => { + if (e.key === 'Escape' && overlay.classList.contains('show')) showNodeUpdateModal(false); + }); + + if (nodeSelect) { + nodeSelect.addEventListener('change', () => { + _selectedNodeId = nodeSelect.value; + loadNodeUpdateInfo(_selectedNodeId); + }); + } + + async function doNodeInstall(version, source) { + if (!_selectedNodeId) { + setNodeStatus('Select a node first.', 'error'); + return; + } + const cleanVersion = String(version || '').trim(); + if (!/^v?\d+\.\d+\.\d+/.test(cleanVersion)) { + setNodeStatus('Invalid version format. Use format: v1.0.0', 'error'); + return; + } + if (!confirm(`Install ADaemon ${cleanVersion} on ${_selectedNodeName || _selectedNodeId}? The node will run go clean and restart adaemon.`)) { + return; + } + + if (checkBtn) { + checkBtn.className = 'btn btn-update-installing'; + checkBtn.innerHTML = ' Installing...'; + checkBtn.disabled = true; + } + if (manualBtn) manualBtn.disabled = true; + if (manualInput) manualInput.disabled = true; + if (nodeSelect) nodeSelect.disabled = true; + setNodeStatus('Downloading update and sending it securely to the node...', 'info'); + + try { + if (!_tokens.installUpdate) { + await loadNodeUpdateInfo(_selectedNodeId); + } + + const res = await fetch('/api/settings/node-update/install', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': _tokens.installUpdate || '' }, + credentials: 'include', + body: JSON.stringify({ nodeId: _selectedNodeId, version: cleanVersion }), + }); + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + setNodeStatus(data.error || 'Failed to install node update', 'error'); + resetNodeCheckButton(); + await loadNodeUpdateInfo(_selectedNodeId); + return; + } + + setNodeStatusHtml(`Update to ${escapeHtml(data.version)} installed. ${Number(data.filesUpdated || 0)} files updated, go clean completed, and adaemon restart was scheduled.`, 'success'); + if (checkBtn) { + checkBtn.className = 'btn btn-update-check'; + checkBtn.innerHTML = ' Update Installed'; + checkBtn.disabled = true; + checkBtn.dataset.mode = ''; + } + if (manualInput) manualInput.value = ''; + + setTimeout(() => { + resetNodeCheckButton(); + loadNodeUpdateInfo(_selectedNodeId); + }, 3500); + } catch (e) { + console.error('[node-update] Install failed:', e); + setNodeStatus('Network error while installing node update', 'error'); + resetNodeCheckButton(); + } finally { + if (manualBtn) manualBtn.disabled = false; + if (manualInput) manualInput.disabled = false; + if (nodeSelect) nodeSelect.disabled = false; + } + } + + if (checkBtn) { + checkBtn.addEventListener('click', async () => { + if (checkBtn.dataset.mode === 'install') { + await doNodeInstall(_latestVersionFound, 'auto'); + return; + } + if (!_selectedNodeId) { + setNodeStatus('Select a node first.', 'error'); + return; + } + + const icon = checkBtn.querySelector('.fa-arrows-rotate'); + if (icon) { + icon.classList.remove('spinning'); + void icon.offsetWidth; + icon.classList.add('spinning'); + icon.addEventListener('animationend', () => icon.classList.remove('spinning'), { once: true }); + } + + checkBtn.disabled = true; + setNodeStatus('Checking for node updates...', 'info'); + + try { + if (!_tokens.checkUpdate) { + await loadNodeUpdateInfo(_selectedNodeId); + } + const res = await fetch('/api/settings/node-update/check', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': _tokens.checkUpdate || '' }, + credentials: 'include', + body: JSON.stringify({ nodeId: _selectedNodeId }), + }); + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + setNodeStatus(data.error || 'Failed to check node updates', 'error'); + checkBtn.disabled = false; + return; + } + + if (data.updateAvailable) { + _latestVersionFound = data.latestVersion; + if (data.actionTokens) _tokens = { ..._tokens, ...data.actionTokens }; + setNodeStatusHtml(`New node version found: ${escapeHtml(data.latestVersion)} (current: ${escapeHtml(data.currentVersion)})`, 'success'); + checkBtn.dataset.mode = 'install'; + checkBtn.className = 'btn btn-update-install'; + checkBtn.innerHTML = ' Install Update'; + checkBtn.disabled = false; + } else { + setNodeStatusHtml(`This node is running the latest version (${escapeHtml(data.currentVersion)})`, 'success'); + checkBtn.disabled = false; + await loadNodeUpdateInfo(_selectedNodeId); + } + } catch (e) { + console.error('[node-update] Check failed:', e); + setNodeStatus('Network error while checking node updates', 'error'); + checkBtn.disabled = false; + } + }); + } + + if (autoBtn) { + autoBtn.addEventListener('click', async () => { + if (!_selectedNodeId) { + setNodeStatus('Select a node first.', 'error'); + return; + } + const currentlyEnabled = autoBtn.dataset.enabled === 'true'; + const nextEnabled = !currentlyEnabled; + + autoBtn.disabled = true; + setNodeStatus(nextEnabled ? 'Enabling node auto update...' : 'Disabling node auto update...', 'info'); + + try { + if (!_tokens.setAutoUpdate) { + await loadNodeUpdateInfo(_selectedNodeId); + } + const res = await fetch('/api/settings/node-update/auto', { + method: 'POST', + headers: { 'Content-Type': 'application/json', 'x-action-token': _tokens.setAutoUpdate || '' }, + credentials: 'include', + body: JSON.stringify({ nodeId: _selectedNodeId, enabled: nextEnabled }), + }); + const data = await res.json().catch(() => ({})); + + if (!res.ok) { + setNodeStatus(data.error || 'Failed to toggle node auto update', 'error'); + return; + } + + renderNodeAutoButton(!!data.autoUpdateEnabled); + setNodeStatus(data.autoUpdateEnabled + ? 'Auto Update enabled. New ADaemon releases will be installed on this node.' + : 'Node auto update disabled.', 'success'); + } catch (e) { + console.error('[node-auto-update] Toggle failed:', e); + setNodeStatus('Network error while toggling node auto update', 'error'); + } finally { + autoBtn.disabled = false; + } + }); + } + + if (manualBtn && manualInput) { + manualBtn.addEventListener('click', async () => { + const version = manualInput.value.trim(); + if (!version) { + setNodeStatus('Please enter a version number.', 'error'); + manualInput.focus(); + return; + } + await doNodeInstall(version, 'manual'); + }); + + manualInput.addEventListener('keydown', (e) => { + if (e.key === 'Enter') { + e.preventDefault(); + manualBtn.click(); + } + }); + } +})(); diff --git a/public/login.css b/public/login.css new file mode 100644 index 0000000..da948a3 --- /dev/null +++ b/public/login.css @@ -0,0 +1,694 @@ +:root { + --shadow-offset: 0; + --shadow-blur: 15px; + --shadow-spread: -5px; + --shadow-color: rgba(255, 255, 255, 0.7); + + --tint-color: 255, 255, 255; + --tint-opacity: 0.10; + + --frost-blur: 5px; + + --noise-frequency: 0.010; + --distortion-strength: 150; + + --outer-shadow-blur: 24px; + + --menu-top: 100rem; + --menu-left: -5rem; + --watermark-offset-x: 3.5rem; +} + +html, +body { + height: 100%; + margin: 0; + padding: 0; +} + +body { + font-family: sans-serif; + background-repeat: no-repeat; + background-size: cover; + background-position: center; + background-attachment: fixed; + background-color: #06080d; + color: white; + display: flex; + flex-direction: column; + align-items: center; +} + +@media (max-width: 768px) { + body { + background-attachment: scroll; + } +} + +form { + position: absolute; + display: flex; + flex-direction: column; + user-select: none; + gap: 10px; + width: 300px; + margin-top: 300px; + z-index: 100; +} + +@media (max-width: 768px) { + form { + margin-top: 270px; + } +} + +.input-icon { + position: absolute; + top: 50%; + left: 16px; + transform: translateY(-50%); + color: #4f4f4f; + font-size: 16px; + z-index: 10; + transition: color 0.4s cubic-bezier(0.2, 0, 0, 1), opacity 0.4s cubic-bezier(0.2, 0, 0, 1); + pointer-events: none; +} + +.input-holder { + position: relative; + display: flex; + align-items: center; + width: 380px; + margin-left: -40px; +} + +.input-holder:hover .input-icon { + color: #3f3f3f; +} + +.input-holder:focus-within .input-icon { + color: rgba(26, 26, 26, 0.78); +} + +.login-input { + width: 100%; + margin: 0; + padding-left: 40px; + box-sizing: border-box; +} + +input { + padding: 10px; + border: 1px solid transparent; + user-select: none; + border-radius: 10px; + background-color: #dbdbdb; + box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.05); + transition: background-color 0.4s cubic-bezier(0.2, 0, 0, 1), border-color 0.4s cubic-bezier(0.2, 0, 0, 1), box-shadow 0.4s cubic-bezier(0.2, 0, 0, 1); + font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + color: #424242; +} + +input::placeholder { + color: #6a6a6a; + opacity: 1; +} + +input:hover { + background-color: #d4d4d4; +} + +input:focus { + background-color: rgba(255, 255, 255, 0.98); + border-color: #007aff; + box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.05), 0 0 0 3px rgba(0, 122, 255, 0.3); + outline: none; + color: #1a1a1a; + caret-color: #1a1a1a; +} + +input:focus::placeholder { + color: rgba(26, 26, 26, 0.55); +} + +button { + padding: 10px; + background-color: #007bff; + border: none; + border-radius: 5px; + cursor: pointer; + color: white; + font-weight: bold; +} + +.get-started { + position: relative; + border-radius: 12px; + /* Smoother curve */ + height: 48px; + /* Slightly taller for touch target size */ + width: 380px; + user-select: none; + margin-top: 50px; + margin-left: -40px; + 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 */ + 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); + border: none; + cursor: pointer; + display: flex; + 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; +} + +.get-started__logo { + width: 18px; + height: 18px; + object-fit: contain; + flex: 0 0 auto; + display: block; + margin: 0 6px 0 7px; +} + +@media (max-width: 768px) { + .get-started { + margin-top: 30px; + } +} + +.get-started:hover { + background: linear-gradient(to bottom, #404040, #2a2a2a, #111111); + transform: scale(0.995); + /* Extremely subtle press in effect */ + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.6); +} + +.get-started:active { + transform: scale(0.98); + box-shadow: 0 2px 5px rgba(0, 0, 0, 0.5); +} + +.error { + color: red; + margin-bottom: 10px; + text-align: center; +} + +.menu { + position: absolute; + width: 390px; + height: 480px; + border-radius: 30px; + padding: 30px; + margin-top: 60px; + 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; +} + +.menu::before { + content: ""; + position: absolute; + inset: 0; + z-index: 0; + border-radius: 30px; + box-shadow: inset var(--shadow-offset) var(--shadow-offset) var(--shadow-blur) var(--shadow-spread) var(--shadow-color); + background-color: rgba(var(--tint-color), var(--tint-opacity)); +} + +.menu::after { + content: ""; + position: absolute; + inset: 0; + z-index: -1; + border-radius: 30px; + isolation: isolate; +} + +.menu>* { + position: relative; + z-index: 1; +} + +@media (max-width: 768px) { + .menu { + font-size: 24px; + padding: 20px; + margin-top: 20px; + } +} + +.forgot-password { + position: absolute; + cursor: pointer; + color: #f5f5f7; + /* Matching pure white sub-tone */ + user-select: none; + margin-top: 150px; + margin-left: 230px; + font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + font-size: 14px; + font-weight: 500; + white-space: nowrap; + opacity: 0.65; + text-decoration: none !important; + transition: opacity 0.2s ease, text-shadow 0.2s ease; + text-shadow: 0 1px 4px rgba(0, 0, 0, 0.4); +} + +.forgot-password:hover { + opacity: 1; + text-shadow: 0 2px 8px rgba(255, 255, 255, 0.4); + /* Illuminates instead of changing color */ +} + +.video { + position: fixed; + top: 0; + left: 0; + width: 100vw; + height: 100vh; + object-fit: cover; + z-index: -1; +} + +.sign-up { + position: relative; + 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; + z-index: 1; + text-shadow: 0 2px 8px rgba(0, 0, 0, 0.4); +} + +@media (max-width: 768px) { + .sign-up { + top: 100px; + } +} + +.sign-up-desc { + position: relative; + 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; + opacity: 1; + text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); +} + +@media (max-width: 768px) { + .sign-up-desc { + top: 170px; + } +} + +.sign-up-sublines { + position: relative; + 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; + opacity: 1; + text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); +} + +@media (max-width: 758px) { + .sign-up-sublines { + top: 210px; + } +} + + +#watermark { + position: fixed; + pointer-events: none; + + top: 20px; + left: 30px; + + z-index: 999; + display: flex; +} + +@media (max-width: 768px) { + #watermark { + top: 10px; + left: 20px; + } +} + +#watermark img { + width: 160px; + height: auto; + object-fit: contain; + z-index: 1; +} + +.circle-icon { + position: absolute; + background-color: white; + padding: 20px; + border-radius: 15px; + height: 12px; + width: 9px; + box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5); + margin-top: -210px; + margin-left: 120px; + border: 1px solid #c4c4c4; +} + +.circle-icon__glyph { + color: #000; + font-size: 25px; + margin-top: -50px; + margin-left: -10px; +} + +@media (max-width: 768px) { + .circle-icon { + margin-top: -220px; + } +} + +.toast-host { + position: fixed; + top: 18px; + right: 5px; + z-index: 999999; + pointer-events: none; +} + +.toast { + width: 300px; + transform: translateX(120%); + opacity: 0; + pointer-events: none; + will-change: transform, opacity; +} + +.toast-inner { + background: rgba(255, 45, 85, 0.18); + border-radius: 16px; + padding: 14px 14px 12px; + box-shadow: 0 16px 45px rgba(0, 0, 0, 0.45); + font-family: "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + color: #fff; +} + +.toast-msg { + font-weight: 600; + font-size: 16px; + margin-left: 10px; + text-align: center; + white-space: nowrap; + letter-spacing: 0.2px; +} + +.toast-bar { + height: 6px; + margin-top: 10px; + border-radius: 9999px; + background: rgba(255, 255, 255, 0.18); + overflow: hidden; + position: relative; +} + +.toast-bar::after { + content: ""; + position: absolute; + inset: 0; + transform-origin: left; + background: rgba(255, 255, 255, 0.95); + animation: toastProgress 4500ms linear forwards; +} + +.toast.toast-show { + animation: toastIn 320ms cubic-bezier(.2, .9, .2, 1) forwards; +} + +.toast.toast-hide { + animation: toastOut 260ms cubic-bezier(.4, 0, .2, 1) forwards; +} + +@keyframes toastIn { + from { + transform: translateX(120%); + opacity: 0; + } + + to { + transform: translateX(0); + opacity: 1; + } +} + +@keyframes toastOut { + from { + transform: translateX(0); + opacity: 1; + } + + to { + transform: translateX(120%); + opacity: 0; + } +} + +@keyframes toastProgress { + from { + transform: scaleX(1); + } + + to { + transform: scaleX(0); + } +} + +.captcha-modal { + position: fixed; + inset: 0; + display: none; + align-items: center; + justify-content: center; + padding: 20px; + background: rgba(0, 0, 0, 0.6); + z-index: 100000; +} + +.captcha-modal.show { + display: flex !important; + visibility: visible !important; + opacity: 1 !important; + pointer-events: auto !important; + z-index: 100000 !important; +} + +.captcha-modal.show .captcha-modal__card { + visibility: visible !important; + opacity: 1 !important; +} + +.captcha-modal__backdrop { + position: absolute; + inset: 0; + background: radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.06), transparent 45%), + radial-gradient(circle at 80% 80%, rgba(255, 255, 255, 0.05), transparent 40%); + pointer-events: none; +} + +.captcha-modal__card { + position: relative; + z-index: 1; + width: min(420px, 95vw); + background: rgba(18, 18, 18, 0.9); + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 16px; + padding: 22px 20px 18px; + box-shadow: 0 20px 48px rgba(0, 0, 0, 0.45); + font-family: "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; + color: #f2f2f2; +} + +.captcha-modal__title { + font-size: 18px; + font-weight: 700; + margin: 0 0 6px; +} + +.captcha-modal__title-icon { + margin-right: 8px; + color: #4ade80; + font-size: 18px; +} + +.captcha-modal__desc { + margin: 0 0 14px; + font-size: 14px; + opacity: 0.85; + min-height: 18px; +} + +.captcha-modal__widget { + min-height: 90px; + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 12px; +} + +.login-form--blocked { + pointer-events: none; + opacity: 0.3; +} + +.captcha-modal__widget #recaptchaWidget[hidden], +.captcha-modal__widget #cf-turnstile[hidden] { + display: none; +} + + +.local-captcha { + width: 100%; +} + +.local-captcha__prompt { + font-size: 14px; + font-weight: 600; + margin-bottom: 10px; + color: #e0e0e0; +} + +.local-captcha__grid { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 6px; + margin-bottom: 12px; +} + +.local-captcha__cell { + position: relative; + aspect-ratio: 1; + border-radius: 8px; + overflow: hidden; + cursor: pointer; + border: 2px solid transparent; + transition: border-color 0.2s ease, transform 0.15s ease; + background: rgba(255, 255, 255, 0.05); +} + +.local-captcha__cell:hover { + transform: scale(1.03); + border-color: rgba(255, 255, 255, 0.3); +} + +.local-captcha__cell.selected { + border-color: #4ade80; +} + +.local-captcha__cell.selected .local-captcha__check { + opacity: 1; +} + +.local-captcha__cell img { + width: 100%; + height: 100%; + object-fit: cover; + display: block; + pointer-events: none; + -webkit-user-drag: none; + user-drag: none; +} + +.local-captcha__check { + position: absolute; + top: 6px; + right: 6px; + width: 22px; + height: 22px; + background: #4ade80; + border-radius: 50%; + display: flex; + align-items: center; + justify-content: center; + opacity: 0; + transition: opacity 0.2s ease; + color: #000; + font-size: 12px; +} + +.local-captcha__footer { + display: flex; + align-items: center; + justify-content: space-between; + gap: 10px; +} + +.local-captcha__step { + font-size: 12px; + opacity: 0.7; +} + +.local-captcha__submit { + padding: 8px 20px; + font-size: 13px; + font-weight: 600; + border-radius: 8px; + border: none; + background: linear-gradient(135deg, #4ade80, #22c55e); + color: #000; + cursor: pointer; + transition: all 0.2s ease; +} + +.local-captcha__submit:hover { + background: linear-gradient(135deg, #22c55e, #16a34a); +} + +.local-captcha__submit:disabled { + opacity: 0.5; + cursor: not-allowed; +} + +.local-captcha__status { + margin-top: 8px; + font-size: 13px; + text-align: center; + min-height: 18px; +} + +.local-captcha__status[data-state="error"] { + color: #f87171; +} + +.local-captcha__status[data-state="success"] { + color: #4ade80; +} + +.local-captcha__status[data-state="muted"] { + color: #a3a3a3; +} diff --git a/public/settings.css b/public/settings.css new file mode 100644 index 0000000..855380e --- /dev/null +++ b/public/settings.css @@ -0,0 +1,8501 @@ + :root { + --accent: #4f46e5; + --bg: #f3f4f6; + --settings-bg: #e9edf2; + --panel-gray: #282c34; + --glass: rgba(255, 255, 255, 0.6); + --radius: 12px; + --shadow: 0 8px 30px rgba(16, 24, 40, 0.12); + --muted: #6b7280; + --text: #0f172a; + --btn-grad: linear-gradient(90deg, rgba(255, 255, 255, 0.96), rgba(245, 247, 255, 0.96)); + --btn-color: #071232; + --card-contrast-bg: rgba(255, 255, 255, 0.85); + --modal-bg: #d7dee6; + --hover-border: rgba(15, 23, 42, 0.08); + --gap: 24px; + } + + [data-theme="dark"] { + --accent: #7c3aed; + --bg: #282c34; + --settings-bg: rgba(30, 36, 40, 0.92); + --panel-gray: #282c34; + --glass: rgba(255, 255, 255, 0.03); + --shadow: 0 10px 30px rgba(2, 6, 23, 0.6); + --muted: #9ca3af; + --text: #e6eef8; + --btn-grad: linear-gradient(90deg, rgba(40, 44, 50, 0.92), rgba(48, 52, 58, 0.94)); + --btn-color: #e6eef8; + --card-contrast-bg: rgba(0, 0, 0, 0.45); + --modal-bg: rgba(18, 20, 22, 0.96); + --hover-border: rgba(255, 255, 255, 0.07); + } + + body.compact { + --gap: 12px; + } + + body.no-animations * { + transition: none !important; + animation: none !important; + } + + * { + box-sizing: border-box; + -ms-overflow-style: none; + scrollbar-width: none; + } + + *::-webkit-scrollbar { + display: none; + width: 0; + height: 0; + } + + html, + body { + height: 100% + } + + body { + margin: 0; + font-family: 'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, 'Helvetica Neue', Arial; + background: var(--bg); + color: var(--text); + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale; + padding: 20px; + transition: background .45s ease, color .35s ease; + } + + .focus-ring:focus { + border: 1px solid #53a7f7 !important; + box-shadow: 0 0 6px #53a7f777 !important; + } + + .theme-overlay { + position: fixed; + inset: 0; + z-index: 9998; + pointer-events: none; + opacity: 0; + transition: opacity .28s ease; + background: linear-gradient(135deg, rgba(255, 255, 255, 0.03), rgba(0, 0, 0, 0.04)); + } + + .theme-overlay.show { + opacity: 1 + } + + .app { + max-width: 1100px; + margin: 0 auto; + display: grid; + grid-template-columns: 260px 1fr; + gap: var(--gap); + align-items: start + } + + main, + .panel, + .layout-inner, + .content-flex, + .content-area { + min-width: 0; + } + + main { + display: block; + } + + .sidebar { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.6), rgba(255, 255, 255, 0.5)); + border-radius: 12px; + padding: 12px; + box-shadow: var(--shadow); + position: sticky; + top: 18px; + height: auto; + max-height: calc(100vh - 36px); + overflow: auto; + display: flex; + flex-direction: column; + gap: 12px; + } + + [data-theme="dark"] .sidebar { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0.01)); + } + + .brand { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 6px; + flex: 0 0 auto + } + + .brand .logo { + width: 40px; + height: 40px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + background: var(--panel-gray); + color: #fff; + font-weight: 700; + font-size: 18px; + box-shadow: 0 6px 18px rgba(40, 44, 52, 0.12) + } + + .brand h1 { + font-size: 14px; + margin: 0 + } + + .brand p { + margin: 0; + font-size: 12px; + color: var(--muted) + } + + .nav { + margin-top: 6px; + flex: 1 1 auto; + overflow: auto + } + + .nav button { + width: 100%; + display: flex; + align-items: center; + gap: 10px; + padding: 10px; + border-radius: 10px; + border: 0; + background: transparent; + color: var(--muted); + cursor: pointer; + font-weight: 600; + transition: all .18s ease; + white-space: nowrap; + outline: none; + } + + .nav button:focus-visible { + outline: 2px solid var(--accent); + outline-offset: -2px; + } + + .nav button.active { + background: linear-gradient(90deg, rgba(79, 70, 229, 0.08), rgba(79, 70, 229, 0.04)); + color: var(--accent); + box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04); + } + + .nav button i { + width: 18px; + text-align: center + } + + .panel { + background: var(--settings-bg); + border-radius: 12px; + padding: 18px; + box-shadow: var(--shadow); + position: relative; + overflow: hidden; + display: flex; + flex-direction: column; + transition: transform .28s cubic-bezier(.2, .9, .2, 1), box-shadow .2s + } + + .panel:hover { + transform: none + } + + .panel h2 { + margin: 0 0 6px 0; + font-family: 'Space Grotesk', sans-serif + } + + .panel p { + margin: 0 0 14px 0; + color: var(--muted) + } + + .closeEscFixed { + position: fixed; + right: 14px; + top: 14px; + width: 52px; + height: 52px; + border-radius: 999px; + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + background: var(--btn-grad); + cursor: pointer; + border: 1px solid rgba(15, 23, 42, 0.06); + font-weight: 700; + z-index: 9999; + transition: transform .14s ease, box-shadow .14s ease, background .14s ease + } + + .closeEscFixed:hover { + transform: scale(1.03); + box-shadow: 0 12px 30px rgba(2, 6, 23, 0.12) + } + + .closeEscFixed:hover .closeEscFixed-inner { + transform: scale(1); + } + + .closeEscFixed i { + font-size: 15px; + color: var(--btn-color) + } + + .closeEscFixed small { + display: block; + font-size: 10px; + color: var(--muted); + margin-top: 2px + } + + .layout-inner { + display: flex; + gap: 16px; + flex: 1 1 auto; + align-items: stretch; + } + + .left-col { + width: 320px + } + + .theme-btn { + padding: 10px 14px; + border-radius: 10px; + border: 0; + background: var(--btn-grad); + color: var(--btn-color); + font-weight: 700; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 8px; + box-shadow: 0 8px 20px rgba(16, 24, 40, 0.06); + transition: transform .12s ease, box-shadow .12s ease, opacity .12s ease + } + + .theme-btn:hover { + transform: translateY(-2px) + } + + .theme-btn.active { + box-shadow: 0 12px 36px rgba(16, 24, 40, 0.12); + outline: 3px solid rgba(79, 70, 229, 0.06) + } + + .btn { + padding: 10px 14px; + border-radius: 10px; + border: 0; + background: var(--btn-grad); + color: var(--btn-color); + font-weight: 700; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 8px; + box-shadow: 0 8px 20px rgba(16, 24, 40, 0.06); + transition: transform .12s ease, box-shadow .12s ease, opacity .12s ease; + ; + } + + .btn:hover { + box-shadow: 0 14px 36px rgba(16, 24, 40, 0.12); + transform: none; + } + + .btn.ghost { + background: transparent; + border: 1px solid rgba(15, 23, 42, 0.06); + color: var(--text); + box-shadow: none + } + + [data-theme="dark"] .btn.ghost { + border: 1px solid rgba(255, 255, 255, 0.04); + color: var(--text) + } + + .card { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.9), rgba(255, 255, 255, 0.75)); + padding: 12px; + border-radius: 10px; + box-shadow: 0 6px 18px rgba(15, 23, 42, 0.06) + } + + [data-theme="dark"] .card { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0.01)); + } + + .bg-select { + margin-top: 10px + } + + .bg-preview { + height: 120px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + position: relative; + overflow: hidden; + transition: all .18s ease; + border: 5px solid var(--panel-gray) + } + + .bg-preview .label { + position: absolute; + left: 10px; + top: 8px; + background: rgba(0, 0, 0, 0.12); + padding: 6px 10px; + border-radius: 8px; + font-weight: 600; + font-size: 13px + } + + .controls { + display: flex; + gap: 10px; + align-items: center; + margin-top: 10px + } + + .color-dot { + width: 42px; + height: 42px; + border-radius: 8px; + border: 4px solid #fff; + box-shadow: 0 8px 18px rgba(2, 6, 23, 0.08); + display: flex; + align-items: center; + justify-content: center; + font-weight: 700 + } + + input[type=color] { + width: 42px; + height: 42px; + border-radius: 8px; + border: 0; + padding: 0; + margin: 0; + background: transparent; + cursor: pointer + } + + .field { + flex: 1 + } + + .field input[type=text] { + width: 100%; + padding: 8px; + border-radius: 8px; + border: 1px solid rgba(15, 23, 42, 0.06) + } + + .thumbs { + display: grid; + grid-template-columns: repeat(4, 1fr); + gap: 8px; + margin-top: 10px + } + + .thumb { + height: 70px; + border-radius: 8px; + overflow: hidden; + position: relative; + cursor: pointer; + border: 3px solid transparent; + transition: transform .14s, box-shadow .14s + } + + .thumb img { + width: 100%; + height: 100%; + object-fit: cover; + display: block + } + + .thumb:hover { + transform: translateY(-6px); + box-shadow: 0 10px 30px rgba(2, 6, 23, 0.12) + } + + .thumb.selected { + border-color: var(--accent) + } + + .upload { + margin-top: 12px; + display: flex; + gap: 8px; + align-items: center + } + + .upload input[type=file] { + display: none + } + + .upload .upload-btn { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + border-radius: 8px; + border: 1px dashed rgba(15, 23, 42, 0.06); + background: transparent; + cursor: pointer + } + + .note { + font-size: 13px; + color: var(--muted); + margin-top: 12px + } + + .prefs-list { + margin-top: 10px; + display: grid; + gap: 8px + } + + .pref-row { + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px; + border-radius: 10px; + background: var(--card-contrast-bg); + border: 1px solid rgba(15, 23, 42, 0.04) + } + + .pref-row small { + color: var(--muted) + } + + .content-area { + padding: 8px 0; + width: 100%; + min-height: 100%; + } + + .content-area:hover { + transform: none !important; + } + + .panel-section { + display: none + } + + .panel-section.active { + display: block; + animation: fadeIn .18s ease both + } + + .clickable-card { + cursor: pointer; + transition: transform .12s ease, box-shadow .12s ease, border-color .12s ease; + border: 1px solid transparent; + padding: 10px + } + + .clickable-card:hover { + transform: none; + box-shadow: 0 18px 40px rgba(16, 24, 40, 0.12); + border: 1px solid var(--hover-border) + } + + .server-row { + 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 + } + + .server-row .left { + display: flex; + align-items: center; + gap: 12px + } + + .server-row .iconWrap { + width: 44px; + height: 44px; + border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.06) + } + + [data-theme="dark"] .server-row .iconWrap { + background: rgba(255, 255, 255, 0.02) + } + + .server-row .name { + font-weight: 700 + } + + .server-name-wrap { + display: flex; + flex-direction: column; + min-width: 0 + } + + .server-name-display { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 280px + } + + .server-row .actions { + display: flex; + gap: 8px; + align-items: center + } + + .templates-grid { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); + gap: 12px; + align-items: stretch + } + + .template-card { + padding: 0; + border-radius: 16px; + background: linear-gradient(155deg, rgba(255, 255, 255, 0.05), rgba(255, 255, 255, 0.02)); + border: 1px solid rgba(255, 255, 255, 0.1); + box-shadow: 0 16px 30px rgba(0, 0, 0, 0.2); + backdrop-filter: blur(8px); + overflow: hidden; + min-height: 146px; + height: 100%; + display: flex + } + + .template-card__body { + display: grid; + grid-template-columns: 50px minmax(0, 1fr) auto; + gap: 14px; + align-items: start; + padding: 14px 16px; + width: 100%; + height: 100% + } + + .template-card__icon { + width: 50px; + height: 50px; + border-radius: 12px; + display: inline-flex; + align-items: center; + justify-content: center; + background: rgba(255, 255, 255, 0.08); + color: #fff; + font-size: 18px + } + + .template-card__thumb { + width: 100%; + height: 100%; + border-radius: 12px; + background-size: cover; + background-position: center; + display: block + } + + .template-card__content { + display: grid; + gap: 7px; + min-width: 0 + } + + .template-card__title { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap + } + + .template-card__title .name { + font-weight: 800; + font-size: 15px + } + + .template-card__title .inline-badge { + background: rgba(99, 102, 241, 0.12); + color: #cdd1ff; + border: 1px solid rgba(99, 102, 241, 0.25) + } + + .template-card__description { + color: var(--muted); + font-size: 13px; + line-height: 1.45; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden + } + + .template-card__meta { + display: flex; + flex-wrap: wrap; + gap: 8px; + font-size: 12px; + color: var(--muted) + } + + .template-card__meta span { + padding: 6px 10px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.05); + border: 1px solid rgba(255, 255, 255, 0.08); + display: inline-flex; + gap: 6px; + align-items: center + } + + .template-card__actions { + display: flex; + flex-direction: column; + align-items: flex-end; + justify-content: center; + gap: 7px + } + + .template-card__actions .btn.ghost { + width: 36px; + height: 36px; + min-height: 36px; + padding: 0; + display: inline-flex; + align-items: center; + justify-content: center + } + + .template-card__actions .btn.edit-template { + border-color: rgba(96, 165, 250, 0.32); + color: #bfdbfe + } + + .template-card__actions .btn.export-template { + border-color: rgba(148, 163, 184, 0.35); + color: #cbd5e1 + } + + .template-card__actions .btn.delete-template { + border-color: rgba(239, 68, 68, 0.35); + color: #fca5a5 + } + + @media (max-width: 700px) { + .templates-grid { + grid-template-columns: 1fr; + } + + .template-card__body { + grid-template-columns: 44px minmax(0, 1fr); + gap: 12px; + } + + .template-card__icon { + width: 44px; + height: 44px; + font-size: 16px; + } + + .template-card__actions { + grid-column: 1 / -1; + flex-direction: row; + justify-content: flex-end; + align-items: center; + gap: 8px; + padding-top: 2px; + } + } + + .btn.ghost { + transform: scale(1) !important; + } + + .btn.ghost:hover { + background-color: rgba(143, 143, 143, 0.056); + } + + .servers-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + margin-bottom: 8px + } + + .templates-header { + align-items: flex-end; + } + + .templates-header-actions { + margin-left: auto; + display: flex; + align-items: center; + gap: 10px; + } + + .create-inline { + display: none; + gap: 8px; + align-items: center + } + + .create-inline input { + display: none; + padding: 8px; + border-radius: 8px; + border: 1px solid rgba(15, 23, 42, 0.06) + } + + .modal-overlay { + position: fixed; + inset: 0; + background: rgba(2, 6, 23, 0.6); + display: none; + align-items: center; + justify-content: center; + z-index: 10000 + } + + .modal-overlay.show { + display: flex + } + + .modal { + width: 440px; + background: var(--modal-bg); + border-radius: 12px; + padding: 16px; + box-shadow: 0 20px 60px rgba(2, 6, 23, 0.4); + transform: translateY(12px); + opacity: 0; + transition: all .22s ease; + color: var(--text) + } + + .modal.show { + transform: none; + opacity: 1 + } + + .modal h3 { + margin: 0 0 6px 0 + } + + .modal .actions { + display: flex; + gap: 8px; + justify-content: flex-end; + margin-top: 12px + } + + .account-row { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px; + border-radius: 10px; + background: var(--card-contrast-bg); + border: 1px solid rgba(15, 23, 42, 0.04) + } + + .account-left { + display: flex; + align-items: center; + gap: 12px + } + + .account-email { + font-weight: 700 + } + + .access-pill { + padding: 6px 8px; + border-radius: 8px; + background: rgba(0, 0, 0, 0.04); + font-size: 13px + } + + @keyframes fadeIn { + from { + opacity: 0; + transform: translateY(6px) + } + + to { + opacity: 1; + transform: none + } + } + + @media (max-width:760px) { + .app { + grid-template-columns: 1fr; + padding: 12px + } + + .sidebar { + position: relative; + height: auto; + margin-bottom: 12px; + max-height: none; + overflow: visible + } + + .layout-inner { + flex-direction: column + } + + .left-col { + width: 100% + } + + .thumbs { + grid-template-columns: repeat(2, 1fr) + } + + .bg-preview { + height: 100px + } + + .closeEscFixed { + right: 12px; + top: 12px; + width: 48px; + height: 48px + } + } + + @media (max-width:420px) { + .thumbs { + grid-template-columns: repeat(2, 1fr) + } + + .brand .logo { + width: 36px; + height: 36px; + font-size: 16px + } + } + + .nodes-empty { + padding: 16px; + color: var(--muted); + display: flex; + align-items: center; + justify-content: space-between; + background: var(--card-contrast-bg); + border: 1px solid rgba(15, 23, 42, 0.06); + border-radius: 10px; + } + + .nodes-header { + display: flex; + align-items: center; + justify-content: space-between; + } + + .node-update-card { + margin: 16px 0; + padding: 14px 16px; + border-radius: 10px; + background: linear-gradient(135deg, rgba(15, 23, 42, 0.72), rgba(30, 41, 59, 0.58)); + border: 1px solid rgba(148, 163, 184, 0.16); + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + } + + .node-update-card-left { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; + } + + .node-update-card-icon { + width: 42px; + height: 42px; + border-radius: 8px; + display: grid; + place-items: center; + color: #dbeafe; + background: rgba(37, 99, 235, 0.22); + border: 1px solid rgba(96, 165, 250, 0.28); + flex: 0 0 auto; + } + + .node-update-card-title { + font-size: 14px; + font-weight: 700; + color: rgba(255, 255, 255, 0.92); + } + + .node-update-card-subtitle { + margin-top: 3px; + font-size: 12px; + color: rgba(255, 255, 255, 0.54); + } + + .node-update-card-meta { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 12px; + flex-wrap: wrap; + color: rgba(255, 255, 255, 0.56); + font-size: 12px; + } + + .node-update-card-meta span { + display: inline-flex; + align-items: center; + gap: 6px; + white-space: nowrap; + } + + @media (max-width: 760px) { + .nodes-header { + align-items: flex-start; + gap: 12px; + flex-direction: column; + } + + .node-update-card { + align-items: flex-start; + flex-direction: column; + } + + .node-update-card-meta { + width: 100%; + justify-content: space-between; + } + } + + .node-update-enterprise-modal { + width: 620px; + } + + .node-update-info-card { + margin-bottom: 16px; + } + + .node-update-actions-row { + margin-top: 4px; + } + + .node-row { + 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.06); + cursor: pointer; + } + + .node-left { + display: flex; + gap: 10px; + align-items: center; + } + + .status-dot { + width: 10px; + height: 10px; + border-radius: 50%; + display: inline-block; + margin-right: 8px; + background: #a1a1a1; + } + + .status-dot.green { + background: #16a34a; + } + + .status-dot.red { + background: #ef4444; + } + + .status-dot.gray { + background: #9ca3af; + } + + .muted { + color: var(--muted); + } + + .kpi { + font-size: 12px; + color: var(--muted); + } + + .modal.big { + width: 1000vw; + height: 80vh; + max-height: 900px; + display: flex; + flex-direction: column; + } + + .modal .tabs { + display: flex; + gap: 8px; + border-bottom: 1px solid rgba(15, 23, 42, 0.08); + padding-bottom: 8px; + margin-bottom: 12px; + } + + .modal .tabs button { + padding: 8px 12px; + border-radius: 8px; + } + + .modal .tabs button.active { + background: var(--accent, #4f46e5); + color: #fff; + } + + .modal .tab-page { + display: none; + overflow: auto; + } + + .modal .tab-page.active { + display: block; + } + + .grid-2 { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + } + + .field-col { + display: flex; + flex-direction: column; + gap: 6px; + } + + .field-col input, + .field-col textarea, + .field-col select { + padding: 10px; + border-radius: 8px; + border: 1px solid rgba(15, 23, 42, 0.06); + background: var(--panel-bg, #fff); + color: var(--text, #111827); + } + + .codebox { + width: 100%; + min-height: 260px; + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + background: rgba(0, 0, 0, 0.04); + border: 1px solid rgba(15, 23, 42, 0.06); + border-radius: 8px; + padding: 10px; + resize: vertical; + color: var(--text); + } + + .inline-badge { + font-size: 12px; + padding: 2px 8px; + border-radius: 999px; + background: rgba(15, 23, 42, 0.06); + } + + .danger { + background: #fee2e2; + border-color: #fecaca; + } + + .row-actions { + display: flex; + gap: 8px; + align-items: center; + } + + .chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 8px; + border-radius: 9999px; + background: rgba(15, 23, 42, 0.06); + font-size: 12px; + } + + .template-chip { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 2px 10px; + border-radius: 999px; + background: rgba(56, 189, 248, 0.12); + color: var(--text); + border: 1px solid rgba(56, 191, 248, 0.1); + font-size: 12px; + } + + .template-picker-grid-enterprise { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 16px; + } + + .template-option-card { + position: relative; + height: 160px; + border-radius: 16px; + overflow: hidden; + cursor: pointer; + background: linear-gradient(135deg, rgba(30, 41, 59, 0.9), rgba(15, 23, 42, 0.95)); + border: 1px solid rgba(255, 255, 255, 0.08); + transition: all 0.3s cubic-bezier(0.32, 0.72, 0, 1); + } + + .template-option-card::before { + content: ''; + position: absolute; + inset: 0; + background: var(--bg-image, linear-gradient(135deg, rgba(99, 102, 241, 0.15), rgba(139, 92, 246, 0.1))); + background-size: cover; + background-position: center; + background-repeat: no-repeat; + opacity: 0.4; + transition: opacity 0.3s ease, transform 0.4s cubic-bezier(0.32, 0.72, 0, 1); + } + + .template-option-card:hover::before { + opacity: 0.55; + transform: scale(1.05); + } + + .template-option-card:hover { + transform: translateY(-4px); + border-color: rgba(99, 102, 241, 0.4); + } + + .template-option-card.active { + border-color: rgba(99, 102, 241, 0.7); + } + + .template-option-card.active::before { + opacity: 0.6; + } + + .template-option-card.active::after { + content: ''; + position: absolute; + top: 12px; + right: 12px; + width: 24px; + height: 24px; + border-radius: 50%; + background: linear-gradient(135deg, #6366f1, #8b5cf6); + display: flex; + align-items: center; + justify-content: center; + } + + .template-option-card.active .template-card-check { + display: flex; + } + + .template-card-check { + display: none; + position: absolute; + top: 12px; + right: 12px; + width: 24px; + height: 24px; + border-radius: 50%; + background: linear-gradient(135deg, #6366f1, #8b5cf6); + align-items: center; + justify-content: center; + box-shadow: 0 4px 12px rgba(99, 102, 241, 0.4); + z-index: 3; + } + + .template-card-check i { + font-size: 12px; + color: #fff; + } + + .template-option-content { + position: absolute; + bottom: 0; + left: 0; + right: 0; + padding: 16px; + background: linear-gradient(to top, rgba(0, 0, 0, 0.85) 0%, rgba(0, 0, 0, 0.6) 50%, transparent 100%); + z-index: 2; + } + + .template-option-title { + font-weight: 700; + font-size: 15px; + color: rgba(255, 255, 255, 0.95); + display: flex; + align-items: center; + gap: 8px; + margin-bottom: 4px; + } + + .template-option-title i { + font-size: 14px; + color: rgba(99, 102, 241, 0.9); + } + + .template-option-desc { + font-size: 12px; + color: rgba(255, 255, 255, 0.6); + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; + overflow: hidden; + line-height: 1.4; + } + + .template-option-pill { + margin-top: 8px; + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.1); + backdrop-filter: blur(4px); + font-size: 11px; + color: rgba(255, 255, 255, 0.8); + } + + .template-option-pill i { + font-size: 10px; + color: rgba(56, 189, 248, 0.9); + } + + .template-picker-grid { + display: grid; + grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); + gap: 12px; + margin-top: 12px; + } + + .template-option { + border-radius: 12px; + padding: 12px; + background: linear-gradient(135deg, rgba(56, 189, 248, 0.08), rgba(79, 70, 229, 0.12)); + cursor: pointer; + transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.2s ease; + display: flex; + flex-direction: column; + gap: 6px; + position: relative; + } + + .template-option:hover { + transform: translateY(-2px); + box-shadow: 0 5px 20px rgba(15, 23, 42, 0.25); + border-color: rgba(79, 70, 229, 0.5); + } + + .template-option.active { + border-color: var(--accent, #4f46e5); + box-shadow: 0 10px 30px rgba(79, 70, 229, 0.35); + background: linear-gradient(135deg, rgba(79, 70, 229, 0.18), rgba(56, 189, 248, 0.16)); + } + + .template-option .title { + font-weight: 700; + display: flex; + align-items: center; + gap: 8px; + } + + .template-option .desc { + color: var(--muted); + font-size: 13px; + } + + .template-option .pill { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 4px 10px; + border-radius: 999px; + background: rgba(15, 23, 42, 0.08); + font-size: 12px; + } + + @media (max-width: 900px) { + .templates-header { + align-items: flex-start; + } + + .templates-header-actions { + width: 100%; + justify-content: flex-end; + } + + .grid-2 { + grid-template-columns: 1fr; + } + + .modal.big { + width: 92vw; + height: 90vh; + } + } + + #modalCurrent { + color: white; + caret-color: white; + } + + #modalNew { + color: white; + caret-color: white; + } + + #modalConfirm { + color: white; + caret-color: white; + } + + .modalcurrent-placeholder { + position: relative; + width: 420px; + } + + .modalcurrent-placeholder input { + width: 100%; + height: 35px; + padding: 10px 42px 10px 35px; + border-radius: 8px; + border: 1px solid rgba(15, 23, 42, 0.06); + outline: none; + background: rgba(49, 49, 49, 0.697); + color: #fff; + } + + .modalcurrent-placeholder i.fa-lock { + position: absolute; + left: 10px; + top: 50%; + transform: translateY(-50%); + color: gray; + pointer-events: none; + } + + .toggle-pass { + position: absolute; + right: 10px; + top: 50%; + transform: translateY(-50%); + background: none; + border: none; + padding: 0; + cursor: pointer; + } + + .toggle-pass i { + font-size: 18px; + color: gray; + } + + .modalnew-placeholder { + position: relative; + width: 420px; + } + + .modalnew-placeholder input { + width: 100%; + height: 35px; + padding: 10px 42px 10px 35px; + border-radius: 8px; + border: 1px solid rgba(15, 23, 42, 0.06); + outline: none; + background: rgba(49, 49, 49, 0.697); + color: #fff; + } + + .modalnew-placeholder i.fa-lock { + position: absolute; + left: 10px; + top: 50%; + transform: translateY(-50%); + color: gray; + pointer-events: none; + } + + .modalconfirm-placeholder { + position: relative; + width: 420px; + } + + .modalconfirm-placeholder input { + width: 100%; + height: 35px; + padding: 10px 42px 10px 35px; + border-radius: 8px; + border: 1px solid rgba(15, 23, 42, 0.06); + outline: none; + background: rgba(49, 49, 49, 0.697); + color: #fff; + } + + .modalconfirm-placeholder i.fa-lock { + position: absolute; + left: 10px; + top: 50%; + transform: translateY(-50%); + color: gray; + pointer-events: none; + } + + .panel-section:focus, + .panel-section:focus-visible { + outline: none; + } + + #preferences, + #preferences * { + outline: none !important; + border: none !important; + box-shadow: none !important; + } + + #preferences::before, + #preferences::after { + display: none !important; + content: none !important; + } + + .switch { + position: relative; + display: inline-block; + width: 52px; + height: 26px; + } + + .switch input { + opacity: 0; + width: 0; + height: 0; + } + + .switch .slider { + position: absolute; + cursor: pointer; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: rgba(255, 255, 255, 0.1); + transition: 0.3s ease; + border-radius: 26px; + border: 1px solid rgba(255, 255, 255, 0.1); + } + + .switch .slider:before { + position: absolute; + content: ""; + height: 20px; + width: 20px; + left: 2px; + bottom: 2px; + background: #fff; + transition: 0.3s ease; + border-radius: 50%; + box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2); + } + + .switch input:checked+.slider { + background: linear-gradient(135deg, #7c3aed, #6366f1); + border-color: transparent; + } + + .switch input:checked+.slider:before { + transform: translateX(26px); + } + + .switch input:focus+.slider { + box-shadow: 0 0 0 3px rgba(124, 58, 237, 0.2); + } + + .node-ssl-switch { + width: 56px; + height: 32px; + flex-shrink: 0; + } + + .node-ssl-switch .slider { + border-radius: 999px; + background: rgba(255, 255, 255, 0.14); + border: 1px solid rgba(255, 255, 255, 0.18); + box-shadow: none; + } + + .node-ssl-switch .slider:before { + width: 24px; + height: 24px; + left: 3px; + bottom: 3px; + box-shadow: none; + } + + .node-ssl-switch input:checked+.slider { + background: rgba(34, 197, 94, 0.9); + border-color: rgba(34, 197, 94, 0.9); + box-shadow: none; + } + + .node-ssl-switch input:checked+.slider:before { + transform: translateX(24px); + } + + .node-ssl-switch input:focus+.slider { + box-shadow: none; + } + + .node-ssl-switch input:focus-visible+.slider { + outline: 2px solid rgba(34, 197, 94, 0.45); + outline-offset: 2px; + } + + .security-card:hover { + background: rgba(255, 255, 255, 0.05) !important; + border-color: rgba(255, 255, 255, 0.12) !important; + } + + + .closeEscFixed-inner { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + } + + .bg-card-header { + display: flex; + justify-content: space-between; + align-items: center; + } + + .bg-card-title { + font-weight: 700; + } + + .bg-card-subtitle { + font-size: 13px; + color: var(--muted); + } + + .bg-card-icon { + font-size: 18px; + color: var(--muted); + } + + .bg-preview-text { + text-align: center; + opacity: 0.92; + } + + .bg-hex-display { + font-weight: 700; + font-size: 16px; + } + + .bg-preview-label { + font-size: 12px; + color: rgba(255, 255, 255, 0.86); + } + + .image-selection-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-top: 8px; + } + + .image-selection-title { + font-weight: 700; + } + + .image-selection-subtitle { + font-size: 13px; + color: var(--muted); + } + + .url-input-container { + flex: 1; + display: flex; + gap: 8px; + } + + .url-input { + flex: 1; + padding: 10px; + border-radius: 8px; + border: 1px solid rgba(15, 23, 42, 0.06); + } + + .card-mt { + margin-top: 10px; + } + + .card-title { + font-weight: 700; + } + + .pref-label { + font-weight: 700; + } + + .density-select { + padding: 8px; + border-radius: 8px; + } + + .checkbox-label { + display: flex; + align-items: center; + gap: 8px; + } + + .content-flex { + flex: 1 1 auto; + min-height: 100%; + } + + .preferences-title { + font-weight: 700; + margin-bottom: 10px; + outline: none; + border: none; + } + + .preferences-desc { + color: var(--muted); + } + + .preferences-grid { + margin-top: 12px; + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 12px; + } + + .saved-bg-card { + padding: 12px; + border-radius: 10px; + background: var(--card-contrast-bg); + color: var(--text); + } + + .saved-bg-title { + font-weight: 700; + } + + .saved-bg-value { + margin-top: 8px; + color: var(--text); + } + + .account-header { + display: flex; + justify-content: space-between; + align-items: center; + } + + .account-title { + font-weight: 700; + } + + .account-subtitle { + color: var(--muted); + } + + .logout-container { + transform: translateX(-78%); + display: flex; + justify-content: center; + align-items: center; + } + + .account-content { + margin-top: 12px; + display: grid; + gap: 8px; + } + + .change-pass-card { + margin-top: 6px; + padding: 12px; + border-radius: 10px; + background: var(--card-contrast-bg); + transition: background-color 0.2s ease; + } + + .change-pass-card:hover { + transform: none !important; + background-color: rgba(47, 47, 47, 0.044); + } + + .change-pass-header { + display: flex; + justify-content: space-between; + align-items: center; + } + + .change-pass-title { + font-weight: 700; + } + + .change-pass-subtitle { + color: var(--muted); + } + + .change-pass-icon { + font-size: 18px; + color: var(--muted); + } + + .note-box { + margin-top: 10px; + padding: 10px; + border-radius: 8px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(15, 23, 42, 0.04); + font-size: 13px; + color: var(--muted); + } + + .accounts-section { + margin-top: 12px; + } + + .accounts-title { + font-weight: 700; + margin-bottom: 8px; + } + + .accounts-subtitle { + color: var(--muted); + margin-bottom: 8px; + } + + .accounts-search-container { + position: relative; + margin-bottom: 12px; + } + + .accounts-search-icon { + position: absolute; + left: 14px; + top: 50%; + transform: translateY(-50%); + color: var(--muted); + font-size: 14px; + pointer-events: none; + } + + .accounts-search-input { + width: 100%; + padding: 12px 14px 12px 40px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 10px; + color: var(--text); + font-size: 14px; + transition: all 0.2s ease; + } + + .accounts-search-input:focus { + outline: none; + background: rgba(255, 255, 255, 0.06); + } + + .accounts-search-input::placeholder { + color: var(--muted); + } + + .accounts-list { + display: grid; + gap: 8px; + } + + .security-title { + font-weight: 700; + } + + .security-subtitle { + color: var(--muted); + margin-top: 8px; + } + + .security-card { + margin-top: 16px; + background: rgba(255, 255, 255, 0.03); + border-radius: 12px; + padding: 16px; + cursor: pointer; + transition: all 0.2s ease; + } + + .security-card-mt-sm { + margin-top: 12px; + } + + .security-card-inner { + display: flex; + justify-content: space-between; + align-items: center; + } + + .security-card-left { + display: flex; + align-items: center; + gap: 12px; + } + + .security-card-icon { + width: 42px; + height: 42px; + border-radius: 10px; + background-size: cover; + background-position: center; + background-repeat: no-repeat; + } + + .security-card-icon-rate { + background-image: url('/images/rate-limiter.webp'); + } + + .security-card-icon-captcha { + background-image: url('/images/captcha.webp'); + } + + .security-card-title { + font-weight: 600; + font-size: 15px; + } + + .security-card-desc { + color: var(--muted); + font-size: 13px; + } + + .security-details { + display: none; + margin-top: 16px; + padding-top: 16px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + } + + .security-details-grid { + display: grid; + gap: 12px; + } + + .security-details-row { + display: flex; + align-items: center; + gap: 12px; + } + + .security-details-col { + flex: 1; + } + + .security-details-label { + font-size: 13px; + color: var(--muted); + display: block; + margin-bottom: 6px; + } + + .security-details-label i { + margin-right: 4px; + } + + .security-details-input { + width: 100%; + height: 38px; + padding: 0 12px; + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(0, 0, 0, 0.2); + color: white; + outline: none; + font-size: 14px; + } + + .security-details-footer { + display: flex; + justify-content: space-between; + align-items: center; + margin-top: 4px; + } + + .security-summary { + font-size: 12px; + color: var(--muted); + } + + .security-save-btn { + padding: 8px 16px; + font-size: 13px; + } + + .security-feedback { + font-size: 13px; + margin-top: 4px; + } + + .captcha-active-box { + display: flex; + align-items: center; + gap: 8px; + padding: 10px; + background: rgba(34, 197, 94, 0.1); + border-radius: 8px; + } + + .captcha-active-icon { + color: #22c55e; + } + + .captcha-active-text { + font-size: 13px; + color: #22c55e; + } + + .captcha-info { + margin-top: 12px; + font-size: 12px; + color: var(--muted); + } + + .security-card-icon-maintenance { + background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(234, 88, 12, 0.12)); + border-radius: 10px; + } + + .security-card-icon-sessions { + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, rgba(59, 130, 246, 0.16), rgba(14, 165, 233, 0.12)); + border: 1px solid rgba(59, 130, 246, 0.18); + } + + .security-card-icon-sessions i { + font-size: 18px; + color: #7dd3fc; + } + + .sessions-panel-header { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 14px; + flex-wrap: wrap; + } + + .sessions-panel-title { + font-weight: 700; + font-size: 18px; + } + + .sessions-panel-subtitle { + margin-top: 8px; + color: var(--muted); + } + + .security-sessions-card { + cursor: default; + } + + .sessions-standalone-card { + margin-top: 0; + cursor: default; + } + + .security-sessions-header-meta { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + flex-wrap: wrap; + margin-left: 12px; + } + + .security-inline-chip { + display: inline-flex; + align-items: center; + justify-content: center; + min-height: 32px; + padding: 0 12px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.06); + border: 1px solid rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.82); + font-size: 12px; + font-weight: 600; + letter-spacing: 0.01em; + white-space: nowrap; + } + + .security-inline-chip.security-inline-chip-warning { + background: rgba(245, 158, 11, 0.12); + border-color: rgba(245, 158, 11, 0.22); + color: #fbbf24; + } + + .security-inline-chip.security-inline-chip-success { + background: rgba(34, 197, 94, 0.12); + border-color: rgba(34, 197, 94, 0.22); + color: #4ade80; + } + + .sessions-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + flex-wrap: wrap; + margin-bottom: 14px; + } + + .sessions-search-container { + flex: 1 1 320px; + margin-bottom: 0; + } + + .sessions-summary { + font-size: 12px; + color: var(--muted); + white-space: nowrap; + } + + .sessions-feedback { + margin-bottom: 12px; + min-height: 18px; + } + + .sessions-list { + display: grid; + gap: 10px; + } + + .sessions-empty-state { + display: flex; + align-items: center; + justify-content: center; + gap: 10px; + min-height: 110px; + border-radius: 14px; + border: 1px dashed rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + color: var(--muted); + font-size: 14px; + text-align: center; + padding: 18px; + } + + .session-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + padding: 14px 16px; + border-radius: 16px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.06); + transition: border-color 0.2s ease, background 0.2s ease; + } + + .session-row:hover { + border-color: rgba(96, 165, 250, 0.18); + background: rgba(255, 255, 255, 0.05); + } + + .session-row-main { + min-width: 0; + display: flex; + flex-direction: column; + gap: 8px; + } + + .session-row-top { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + } + + .session-row-id { + font-family: 'SF Mono', Monaco, monospace; + font-size: 12px; + color: rgba(255, 255, 255, 0.78); + background: rgba(255, 255, 255, 0.05); + border: 1px solid rgba(255, 255, 255, 0.07); + border-radius: 10px; + padding: 7px 10px; + white-space: nowrap; + } + + .session-row-email { + font-size: 14px; + font-weight: 700; + color: rgba(255, 255, 255, 0.94); + word-break: break-word; + } + + .session-row-meta { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 8px; + } + + .session-meta-pill { + display: inline-flex; + align-items: center; + gap: 6px; + min-height: 30px; + padding: 0 10px; + border-radius: 999px; + background: rgba(255, 255, 255, 0.05); + border: 1px solid rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.68); + font-size: 12px; + max-width: 100%; + } + + .session-meta-pill.session-meta-pill-current { + background: rgba(34, 197, 94, 0.12); + border-color: rgba(34, 197, 94, 0.22); + color: #4ade80; + } + + .session-meta-pill.session-meta-pill-ua { + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .session-row-actions { + flex-shrink: 0; + display: flex; + align-items: center; + gap: 10px; + } + + .session-revoke-btn { + min-width: 124px; + justify-content: center; + background: rgba(239, 68, 68, 0.12); + border: 1px solid rgba(239, 68, 68, 0.22); + color: #fda4af; + box-shadow: none; + } + + .session-revoke-btn:hover { + background: rgba(239, 68, 68, 0.18); + box-shadow: none; + } + + .session-revoke-btn:disabled { + opacity: 0.55; + cursor: not-allowed; + transform: none; + } + + .sessions-pagination { + margin-top: 14px; + display: flex; + align-items: center; + justify-content: flex-end; + gap: 8px; + flex-wrap: wrap; + } + + .sessions-pagination-pages { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; + } + + .sessions-page-btn { + min-width: 40px; + height: 40px; + padding: 0 12px; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.82); + font-weight: 700; + cursor: pointer; + transition: all 0.2s ease; + } + + .sessions-page-btn:hover { + background: rgba(255, 255, 255, 0.08); + } + + .sessions-page-btn.is-active { + background: rgba(59, 130, 246, 0.18); + border-color: rgba(59, 130, 246, 0.28); + color: #bfdbfe; + } + + .sessions-page-btn:disabled { + opacity: 0.35; + cursor: not-allowed; + } + + .session-revoke-modal { + width: 480px; + } + + .session-revoke-form { + padding-bottom: 16px; + } + + .session-revoke-target-card { + padding: 14px 16px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.07); + display: flex; + flex-direction: column; + gap: 6px; + } + + .session-revoke-target-label { + font-size: 12px; + font-weight: 600; + color: rgba(255, 255, 255, 0.5); + text-transform: uppercase; + letter-spacing: 0.08em; + } + + .session-revoke-target-value { + font-family: 'SF Mono', Monaco, monospace; + font-size: 13px; + color: rgba(255, 255, 255, 0.88); + word-break: break-all; + } + + .session-revoke-target-subvalue { + font-size: 13px; + color: rgba(255, 255, 255, 0.68); + word-break: break-word; + } + + @media (max-width: 720px) { + .security-sessions-header-meta { + width: 100%; + justify-content: flex-start; + margin-left: 0; + margin-top: 12px; + } + + .sessions-panel-header { + align-items: stretch; + } + + .sessions-summary { + white-space: normal; + } + + .session-row { + flex-direction: column; + align-items: stretch; + } + + .session-row-actions { + width: 100%; + } + + .session-revoke-btn { + width: 100%; + } + } + + .maintenance-enterprise-modal { + width: 560px; + max-width: 95vw; + } + + .enterprise-modal-icon.maintenance-icon { + background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(234, 88, 12, 0.1)); + } + + .enterprise-modal-icon.maintenance-icon::before { + display: none; + } + + .enterprise-modal-icon.maintenance-icon i { + display: block; + font-size: 28px; + color: #f59e0b; + } + + .maintenance-modal-body { + padding: 20px 28px; + max-height: 55vh; + overflow-y: auto; + } + + .maintenance-timing-chips { + display: flex; + gap: 8px; + } + + .maintenance-alert-toggle-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + } + + .maintenance-alert-toggle-row .switch { + flex-shrink: 0; + } + + .maintenance-modal-body input[type="datetime-local"]::-webkit-calendar-picker-indicator { + filter: invert(0.7); + cursor: pointer; + } + + .maintenance-security-notice { + margin-top: 8px; + padding: 14px; + background: rgba(245, 158, 11, 0.05); + border: 1px solid rgba(245, 158, 11, 0.08); + border-radius: 12px; + } + + .maintenance-security-notice-inner { + display: flex; + align-items: flex-start; + gap: 10px; + } + + .maintenance-security-notice-inner > i { + color: #f59e0b; + margin-top: 2px; + flex-shrink: 0; + font-size: 14px; + } + + .maintenance-security-notice-inner > div { + font-size: 12px; + color: rgba(255, 255, 255, 0.45); + line-height: 1.55; + } + + .maintenance-security-notice-inner strong { + color: #f59e0b; + } + + .maintenance-btn-enable { + background: linear-gradient(135deg, rgba(245, 158, 11, 0.9), rgba(217, 119, 6, 0.85)) !important; + } + + .maintenance-btn-enable:hover { + background: linear-gradient(135deg, rgba(245, 158, 11, 1), rgba(217, 119, 6, 0.95)) !important; + } + + .maintenance-btn-enable:disabled { + opacity: 0.6; + cursor: not-allowed; + } + + .switch-sm { + transform: scale(0.85); + } + + .nodes-title { + font-weight: 700; + } + + .nodes-list { + margin-top: 12px; + display: grid; + gap: 8px; + } + + .nodes-search-wrap { + position: relative; + display: flex; + align-items: center; + } + .nodes-search-wrap i { + position: absolute; + left: 10px; + color: var(--muted); + font-size: 13px; + pointer-events: none; + } + .nodes-search-wrap input { + padding: 8px 12px 8px 32px; + border-radius: 8px; + border: 1px solid rgba(15,23,42,0.12); + background: var(--card-contrast-bg); + color: var(--text); + font-size: 13px; + min-width: 180px; + outline: none; + transition: border-color .15s; + } + .nodes-search-wrap input:focus { + border-color: var(--accent, #6366f1); + } + + .nodes-pagination { + margin-top: 8px; + } + .nodes-pagination-inner { + display: flex; + align-items: center; + justify-content: space-between; + padding: 8px 4px; + font-size: 13px; + color: var(--muted); + } + .nodes-pagination-btns { + display: flex; + align-items: center; + gap: 8px; + } + .nodes-pagination-current { + font-size: 13px; + color: var(--muted); + min-width: 90px; + text-align: center; + } + .nodes-pagination-info { + font-size: 13px; + } + .btn-sm { + padding: 4px 10px !important; + font-size: 13px !important; + min-height: unset !important; + } + + .templates-title { + font-weight: 700; + } + + .templates-subtitle { + color: var(--muted); + } + + .templates-feedback { + margin-top: 8px; + } + + .templates-list { + margin-top: 12px; + } + + .servers-title { + font-weight: 700; + } + + .servers-subtitle { + color: var(--muted); + } + + .servers-list { + margin-top: 12px; + display: grid; + gap: 8px; + } + + .modal-body { + margin-top: 10px; + max-height: 360px; + overflow: auto; + } + + .modal-body-lg { + max-height: 420px; + } + + .modal-actions { + margin-top: 12px; + } + + .modal-actions-end { + display: flex; + justify-content: flex-end; + gap: 8px; + } + + + .server-template-enterprise-modal { + width: 680px; + max-width: 95vw; + } + + .enterprise-modal-icon.server-template-icon { + background: transparent; + } + + .enterprise-modal-icon.server-template-icon::before { + display: none; + } + + .enterprise-modal-icon.server-template-icon i { + display: block; + font-size: 28px; + color: #a78bfa; + } + + .server-template-body { + padding: 20px 28px; + max-height: 50vh; + overflow-y: auto; + } + + .server-template-body::-webkit-scrollbar { + display: none; + } + + .server-template-body { + scrollbar-width: none; + -ms-overflow-style: none; + } + + + .template-enterprise-modal { + width: 540px; + max-width: 95vw; + } + + .enterprise-modal-icon.template-icon { + background: transparent; + } + + .enterprise-modal-icon.template-icon::before { + display: none; + } + + .enterprise-modal-icon.template-icon i { + display: block; + font-size: 28px; + color: #fff; + } + + .template-modal-body { + padding: 20px 28px; + max-height: 55vh; + overflow-y: auto; + } + + .template-modal-body::-webkit-scrollbar { + display: none; + } + + .template-modal-body { + scrollbar-width: none; + -ms-overflow-style: none; + } + + .node-form-textarea { + width: 100%; + min-height: 80px; + padding: 12px 14px; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 10px; + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.95); + font-size: 14px; + font-family: inherit; + resize: vertical; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .node-form-textarea:focus { + outline: none; + border-color: rgba(99, 102, 241, 0.5); + background: rgba(255, 255, 255, 0.06); + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15); + } + + .node-form-textarea::placeholder { + color: rgba(255, 255, 255, 0.3); + } + + .startup-cmd-display { + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 12px; + background: rgba(0, 0, 0, 0.3); + overflow: hidden; + } + + .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); + 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; + } + + .startup-cmd-copy-btn { + background: rgba(255, 255, 255, 0.06); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 6px; + color: rgba(255, 255, 255, 0.45); + padding: 5px 9px; + cursor: pointer; + font-size: 12px; + transition: all 0.2s ease; + } + + .startup-cmd-copy-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.8); + } + + .startup-cmd-code { + margin: 0; + padding: 14px 16px; + 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; + } + + .startup-cmd-code code { + font-family: inherit; + color: inherit; + } + + .startup-cmd-editor-wrap { + display: flex; + border: 1px solid rgba(255, 255, 255, 0.1); + border-radius: 10px; + background: rgba(255, 255, 255, 0.04); + overflow: hidden; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .startup-cmd-editor-wrap:focus-within { + border-color: rgba(99, 102, 241, 0.5); + background: rgba(255, 255, 255, 0.06); + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.15); + } + + .startup-cmd-editor-gutter { + display: flex; + align-items: flex-start; + padding: 13px 0 13px 14px; + user-select: none; + } + + .startup-cmd-prompt { + font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', monospace; + font-size: 14px; + font-weight: 600; + color: rgba(99, 102, 241, 0.6); + } + + .startup-cmd-textarea { + border: none !important; + border-radius: 0 !important; + background: transparent !important; + box-shadow: none !important; + padding-left: 8px !important; + font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', 'Cascadia Code', 'Consolas', monospace; + font-size: 13px; + line-height: 1.6; + min-height: 70px; + resize: vertical; + } + + .startup-cmd-textarea:focus { + box-shadow: none !important; + } + + .startup-cmd-variables { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px; + margin-top: 10px; + } + + .startup-cmd-var-label { + font-size: 11.5px; + font-weight: 500; + color: rgba(255, 255, 255, 0.35); + margin-right: 2px; + } + + .startup-cmd-var { + font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', monospace; + font-size: 11px; + padding: 3px 8px; + border-radius: 5px; + background: rgba(99, 102, 241, 0.1); + border: 1px solid rgba(99, 102, 241, 0.15); + color: rgba(165, 180, 252, 0.85); + } + + .startup-cmd-help { + display: block; + margin-top: 8px; + color: rgba(255, 255, 255, 0.45); + line-height: 1.5; + } + + .startup-cmd-help.is-error { + color: rgba(248, 113, 113, 0.96); + } + + .minecraft-java-field { + margin-top: 16px; + } + + .minecraft-java-select-wrap { + position: relative; + display: flex; + align-items: center; + border: 1px solid rgba(99, 102, 241, 0.22); + border-radius: 10px; + background: rgba(255, 255, 255, 0.04); + transition: border-color 0.2s ease, box-shadow 0.2s ease, background 0.2s ease; + } + + .minecraft-java-select-wrap:focus-within { + border-color: rgba(99, 102, 241, 0.55); + background: rgba(255, 255, 255, 0.06); + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.14); + } + + .minecraft-java-select-wrap > i { + position: absolute; + left: 13px; + color: rgba(248, 113, 113, 0.82); + font-size: 16px; + pointer-events: none; + z-index: 1; + } + + .minecraft-java-select { + width: 100%; + min-height: 44px; + padding-left: 42px !important; + border: none !important; + border-radius: 10px !important; + background-color: transparent !important; + box-shadow: none !important; + color: rgba(255, 255, 255, 0.9); + font-weight: 600; + } + + .minecraft-java-select:focus { + box-shadow: none !important; + } + + .minecraft-java-select option { + color: #0f172a; + background: #ffffff; + } + + + .create-node-header { + display: grid; + gap: 4px; + font-weight: 600; + } + + .template-form-input-wrapper { + position: relative; + width: 100%; + } + + .template-form-input { + width: 100%; + height: 35px; + padding-right: 35px; + outline: none; + background-color: rgba(37, 37, 37, 0.85); + color: white; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 5px; + transition: 0.2s; + } + + .template-form-input-no-border { + border: none; + border-radius: 4px; + background-color: rgba(37, 37, 37, 0.84); + } + + .template-form-textarea { + width: 100%; + min-height: 72px; + padding-right: 35px; + outline: none; + background-color: rgba(37, 37, 37, 0.85); + color: white; + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 5px; + resize: vertical; + transition: 0.2s; + } + + .template-form-icon { + position: absolute; + right: 10px; + top: 50%; + transform: translateY(-50%); + color: #aaa; + pointer-events: none; + transition: 0.2s; + } + + .template-form-icon-top { + top: 10px; + transform: none; + } + + .template-form-actions { + margin-top: 4px; + display: flex; + gap: 8px; + flex-wrap: wrap; + } + + .template-form-feedback { + margin-top: 2px; + } + + + .create-node-header { + display: flex; + align-items: center; + justify-content: space-between; + } + + .create-node-form { + margin-top: 12px; + } + + .create-node-ports { + margin-top: 16px; + } + + .create-node-ports-title { + font-weight: 700; + margin-bottom: 8px; + } + + .create-node-ports-row { + display: flex; + gap: 12px; + flex-wrap: wrap; + align-items: flex-end; + } + + .ports-range-row { + display: flex; + gap: 8px; + align-items: flex-end; + } + + .ports-list-field { + display: none; + flex: 1; + } + + .create-node-actions { + margin-top: 16px; + display: flex; + gap: 8px; + } + + .create-node-feedback { + margin-top: 8px; + } + + .captcha-enterprise-modal { + width: 580px; + max-width: 95vw; + } + + .enterprise-modal-icon.captcha-icon { + background: transparent; + align-items: center; + justify-content: center; + } + + .enterprise-modal-icon.captcha-icon::before { + display: none; + } + + .captcha-modal-icon { + width: 58px; + height: 58px; + object-fit: contain; + display: block; + margin: 0 auto; + } + + .captcha-modal-body { + padding: 20px 28px; + max-height: 55vh; + overflow-y: auto; + } + + .captcha-modal-form { + display: grid; + gap: 16px; + } + + .captcha-input-label { + display: inline-flex; + align-items: center; + gap: 6px; + } + + .captcha-input { + font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace; + } + + .captcha-input-wrapper { + position: relative; + } + + .captcha-input-secret { + padding-right: 44px; + } + + .captcha-toggle-btn { + position: absolute; + right: 10px; + top: 50%; + transform: translateY(-50%); + width: 26px; + height: 26px; + border: none; + border-radius: 8px; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.65); + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .captcha-toggle-btn:hover { + background: rgba(255, 255, 255, 0.12); + color: rgba(255, 255, 255, 0.9); + } + + .captcha-notice { + margin-top: 18px; + padding: 14px; + border-radius: 12px; + border: 1px solid rgba(59, 130, 246, 0.25); + background: rgba(59, 130, 246, 0.12); + } + + .captcha-notice-inner { + display: flex; + align-items: flex-start; + gap: 10px; + } + + .captcha-notice-icon { + color: #60a5fa; + margin-top: 2px; + } + + .captcha-notice-text { + font-size: 12px; + color: rgba(255, 255, 255, 0.78); + line-height: 1.5; + } + + .captcha-notice-strong { + color: #93c5fd; + } + + .captcha-modal-feedback { + font-size: 13px; + margin-top: 14px; + min-height: 18px; + } + + .node-modal-header { + display: flex; + align-items: center; + justify-content: space-between; + } + + .node-modal-tabs { + margin-top: 12px; + } + + .node-modal-ports { + margin-top: 16px; + } + + .node-modal-ports-title { + font-weight: 700; + margin-bottom: 8px; + } + + .node-modal-ports-row { + display: flex; + gap: 12px; + flex-wrap: wrap; + align-items: flex-end; + } + + .node-modal-actions { + margin-top: 16px; + display: flex; + gap: 8px; + } + + .linking-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + flex-wrap: wrap; + } + + .linking-section { + margin-top: 16px; + } + + .cmd-textarea { + display: none; + } + + .cmd-actions { + display: none; + margin-top: 8px; + } + + .danger-zone { + padding: 12px; + border: 1px solid; + border-radius: 8px; + } + + .danger-title { + font-weight: 700; + } + + .danger-desc { + margin-top: 6px; + } + + .danger-actions { + margin-top: 12px; + } + + .danger-feedback { + margin-top: 6px; + } + + + .account-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 16px; + } + + .logout-btn-modern { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 20px; + border-radius: 12px; + border: none; + background: linear-gradient(135deg, rgba(239, 68, 68, 0.15), rgba(220, 38, 38, 0.1)); + color: #f87171; + font-weight: 600; + font-size: 13px; + cursor: pointer; + transition: all 0.25s cubic-bezier(0.25, 0.46, 0.45, 0.94); + backdrop-filter: blur(8px); + -webkit-backdrop-filter: blur(8px); + } + + .logout-btn-modern:hover { + background: linear-gradient(135deg, rgba(239, 68, 68, 0.25), rgba(220, 38, 38, 0.2)); + } + + .logout-btn-modern:active { + transform: scale(0.98); + } + + .logout-btn-modern i { + font-size: 14px; + } + + #logoutBtn.logout-container, + .logout-container { + display: none !important; + } + + .enterprise-modal *::-webkit-scrollbar, + .enterprise-modal-body::-webkit-scrollbar { + display: none; + width: 0; + height: 0; + } + + .enterprise-modal *, + .enterprise-modal-body { + scrollbar-width: none; + -ms-overflow-style: none; + } + + .enterprise-modal-overlay { + background: rgba(0, 0, 0, 0.65); + backdrop-filter: blur(24px) saturate(180%); + -webkit-backdrop-filter: blur(24px) saturate(180%); + } + + .enterprise-modal-overlay.show { + display: flex; + animation: overlayReveal 0.35s cubic-bezier(0.32, 0.72, 0, 1) forwards; + } + + @keyframes overlayReveal { + 0% { + opacity: 0; + backdrop-filter: blur(0) saturate(100%); + } + + 100% { + opacity: 1; + backdrop-filter: blur(24px) saturate(180%); + } + } + + .enterprise-modal { + position: relative; + width: 520px; + max-width: 94vw; + max-height: 85vh; + display: flex; + flex-direction: column; + background: linear-gradient(165deg, + rgba(30, 32, 38, 0.95) 0%, + rgba(22, 24, 28, 0.98) 100%); + backdrop-filter: blur(40px) saturate(180%); + -webkit-backdrop-filter: blur(40px) saturate(180%); + border-radius: 24px; + overflow: hidden; + opacity: 0; + animation: modalReveal 0.5s cubic-bezier(0.32, 0.72, 0, 1) forwards; + box-shadow: + 0 0 0 1px rgba(255, 255, 255, 0.06), + 0 25px 80px -12px rgba(0, 0, 0, 0.5), + 0 0 100px rgba(0, 0, 0, 0.3); + } + + @keyframes modalReveal { + 0% { + opacity: 0; + transform: scale(0.96); + filter: blur(8px); + } + + 100% { + opacity: 1; + transform: scale(1); + filter: blur(0); + } + } + + .enterprise-modal-header { + display: flex; + align-items: center; + gap: 16px; + padding: 24px 28px 20px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.03), transparent); + } + + .enterprise-modal-icon { + width: 84px; + height: 84px; + border-radius: 16px; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + overflow: hidden; + } + + .enterprise-modal-icon::before { + content: ''; + width: 100%; + height: 100%; + background: url('/images/captcha.webp') center/contain no-repeat; + } + + .enterprise-modal-icon[style*="transparent"]::before { + display: none; + } + + .enterprise-modal-icon i { + display: none; + } + + .enterprise-modal-icon.perm-icon { + background: transparent; + } + + .enterprise-modal-icon.perm-icon::before { + display: none; + } + + .enterprise-modal-icon.perm-icon i { + display: block; + font-size: 28px; + color: #fff; + } + + .enterprise-modal-icon.password-icon { + background: transparent; + } + + .enterprise-modal-icon.password-icon::before { + display: none; + } + + .enterprise-modal-icon.password-icon i { + display: block; + font-size: 28px; + color: #fff; + } + + .enterprise-modal-titles { + flex: 1; + min-width: 0; + } + + .enterprise-modal-title { + margin: 0; + font-size: 20px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + letter-spacing: -0.02em; + } + + .enterprise-modal-subtitle { + margin: 6px 0 0; + font-size: 14px; + color: rgba(255, 255, 255, 0.5); + } + + .enterprise-modal-close { + width: 36px; + height: 36px; + border-radius: 10px; + border: none; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 14px; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + flex-shrink: 0; + } + + .enterprise-modal-close:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.8); + } + + .enterprise-modal-body { + flex: 1; + padding: 4px 28px 20px; + overflow-y: auto; + min-height: 0; + } + + .enterprise-modal-footer { + display: flex; + align-items: center; + justify-content: flex-end; + gap: 10px; + padding: 16px 28px 24px; + background: linear-gradient(180deg, transparent, rgba(0, 0, 0, 0.15)); + } + + .enterprise-btn-primary { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + border-radius: 12px; + border: none; + background: linear-gradient(135deg, rgba(99, 102, 241, 0.9), rgba(79, 70, 229, 0.85)); + color: #fff; + font-weight: 600; + font-size: 14px; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .enterprise-btn-primary:hover { + background: linear-gradient(135deg, rgba(99, 102, 241, 1), rgba(79, 70, 229, 0.95)); + filter: brightness(1.1); + } + + .enterprise-btn-primary:active { + transform: scale(0.98); + } + + .enterprise-btn-secondary { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + border-radius: 12px; + border: none; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.7); + font-weight: 600; + font-size: 14px; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .enterprise-btn-secondary:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.9); + } + + .access-modal { + width: 580px; + } + + .access-modal .enterprise-modal-body { + padding: 8px 28px 20px; + max-height: 400px; + } + + .access-server-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 14px; + padding: 14px 16px; + border-radius: 14px; + background: rgba(255, 255, 255, 0.03); + margin-bottom: 8px; + transition: all 0.2s ease; + } + + .access-server-row:hover { + background: rgba(255, 255, 255, 0.06); + } + + .access-server-left { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; + } + + .access-server-icon { + width: 40px; + height: 40px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, rgba(96, 165, 250, 0.15), rgba(59, 130, 246, 0.1)); + color: #93c5fd; + font-size: 16px; + flex-shrink: 0; + } + + .access-server-name { + font-weight: 600; + font-size: 14px; + color: rgba(255, 255, 255, 0.9); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .access-server-actions { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; + } + + .access-btn { + padding: 8px 14px; + border-radius: 10px; + border: none; + font-weight: 600; + font-size: 12px; + cursor: pointer; + transition: all 0.2s ease; + display: inline-flex; + align-items: center; + gap: 6px; + } + + .access-btn-edit { + background: rgba(99, 102, 241, 0.15); + color: #a5b4fc; + } + + .access-btn-edit:hover { + background: rgba(99, 102, 241, 0.25); + } + + .access-btn-revoke { + background: rgba(239, 68, 68, 0.1); + color: #fca5a5; + } + + .access-btn-revoke:hover { + background: rgba(239, 68, 68, 0.2); + } + + .access-btn-add { + background: rgba(16, 185, 129, 0.15); + color: #6ee7b7; + } + + .access-btn-add:hover { + background: rgba(16, 185, 129, 0.25); + } + + .perm-modal { + width: 500px; + } + + .perm-modal-body { + max-height: 380px; + } + + .perm-info { + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + margin-bottom: 14px; + padding: 12px 14px; + background: rgba(255, 255, 255, 0.03); + border-radius: 12px; + } + + .perm-grid { + display: flex; + flex-direction: column; + gap: 6px; + } + + .perm-item { + display: flex; + align-items: center; + gap: 12px; + padding: 12px 14px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.02); + cursor: pointer; + transition: all 0.2s ease; + } + + .perm-item:hover { + background: rgba(255, 255, 255, 0.05); + } + + .perm-item.select-all { + background: rgba(99, 102, 241, 0.08); + margin-bottom: 8px; + } + + .perm-checkbox { + width: 20px; + height: 20px; + border-radius: 6px; + border: 2px solid rgba(255, 255, 255, 0.2); + background: transparent; + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + flex-shrink: 0; + appearance: none; + -webkit-appearance: none; + } + + .perm-checkbox:checked { + background: linear-gradient(135deg, #6366f1, #4f46e5); + border-color: transparent; + } + + .perm-checkbox:checked::after { + content: '✓'; + color: white; + font-size: 12px; + font-weight: 700; + } + + .perm-label { + font-size: 14px; + color: rgba(255, 255, 255, 0.8); + flex: 1; + } + + .perm-item.select-all .perm-label { + font-weight: 600; + color: rgba(255, 255, 255, 0.9); + } + + .perm-success-toast { + position: fixed; + bottom: 32px; + left: 50%; + transform: translateX(-50%) translateY(20px); + background: #22c55e; + color: #fff; + padding: 14px 24px; + border-radius: 8px; + font-size: 14px; + font-weight: 500; + display: flex; + align-items: center; + gap: 10px; + z-index: 100000; + opacity: 0; + pointer-events: none; + transition: opacity 0.3s, transform 0.3s; + box-shadow: 0 4px 20px rgba(34, 197, 94, 0.3); + } + + .perm-success-toast.show { + opacity: 1; + transform: translateX(-50%) translateY(0); + pointer-events: auto; + } + + .perm-success-toast i { + font-size: 18px; + } + + .password-modal { + width: 460px; + } + + .password-form { + padding: 0 28px 8px; + display: flex; + flex-direction: column; + gap: 16px; + } + + .password-field { + display: flex; + flex-direction: column; + gap: 8px; + } + + .password-label { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); + } + + .password-input-wrap { + position: relative; + display: flex; + align-items: center; + } + + .password-input-wrap input { + width: 100%; + height: 48px; + padding: 0 48px 0 16px; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(0, 0, 0, 0.2); + color: rgba(255, 255, 255, 0.95); + font-size: 14px; + outline: none; + transition: all 0.2s ease; + } + + .password-input-wrap input::placeholder { + color: rgba(255, 255, 255, 0.3); + } + + .password-input-wrap input:focus { + border-color: rgba(99, 102, 241, 0.5); + background: rgba(0, 0, 0, 0.3); + } + + .password-toggle { + position: absolute; + right: 12px; + width: 32px; + height: 32px; + border-radius: 8px; + border: none; + background: transparent; + color: rgba(255, 255, 255, 0.4); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + z-index: 10; + } + + .password-toggle:hover { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.7); + } + + .password-strength { + height: 4px; + border-radius: 2px; + background: rgba(255, 255, 255, 0.1); + overflow: hidden; + margin-top: 4px; + } + + .password-strength-bar { + height: 100%; + border-radius: 2px; + transition: all 0.3s ease; + } + + .password-strength-bar.weak { + width: 25%; + background: #ef4444; + } + + .password-strength-bar.fair { + width: 50%; + background: #f59e0b; + } + + .password-strength-bar.good { + width: 75%; + background: #10b981; + } + + .password-strength-bar.strong { + width: 100%; + background: #22c55e; + } + + .enterprise-loading { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 12px; + padding: 40px; + color: rgba(255, 255, 255, 0.5); + font-size: 14px; + } + + .enterprise-loading-spinner { + width: 32px; + height: 32px; + border-radius: 50%; + border: 3px solid rgba(255, 255, 255, 0.1); + border-top-color: rgba(99, 102, 241, 0.8); + animation: enterpriseSpin 0.8s linear infinite; + } + + @keyframes enterpriseSpin { + to { + transform: rotate(360deg); + } + } + + .enterprise-empty { + text-align: center; + padding: 40px 20px; + color: rgba(255, 255, 255, 0.4); + } + + .enterprise-empty i { + font-size: 36px; + margin-bottom: 12px; + display: block; + opacity: 0.5; + } + + + .node-enterprise-modal { + width: 580px; + max-width: 95vw; + } + + .node-configure-modal { + width: 620px; + } + + .enterprise-modal-icon.node-icon { + background: transparent; + } + + .enterprise-modal-icon.node-icon::before { + display: none; + } + + .enterprise-modal-icon.node-icon i { + display: block; + font-size: 28px; + color: #fff; + } + + .node-tabs { + display: flex; + gap: 4px; + padding: 0 28px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + } + + .node-tab { + padding: 12px 16px; + border: none; + background: transparent; + color: rgba(255, 255, 255, 0.5); + font-weight: 600; + font-size: 13px; + cursor: pointer; + display: flex; + align-items: center; + gap: 8px; + border-bottom: 2px solid transparent; + margin-bottom: -1px; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .node-tab:hover { + color: rgba(255, 255, 255, 0.8); + } + + .node-tab.active { + color: rgba(255, 255, 255, 0.95); + border-bottom-color: #6366f1; + } + + .node-tab-danger { + color: rgba(239, 68, 68, 0.6); + } + + .node-tab-danger:hover { + color: rgba(239, 68, 68, 0.9); + } + + .node-tab-danger.active { + color: #f87171; + border-bottom-color: #ef4444; + } + + .node-modal-body { + padding: 20px 28px; + max-height: 55vh; + overflow-y: auto; + } + + .node-modal-body::-webkit-scrollbar { + display: none; + } + + .node-modal-body { + scrollbar-width: none; + -ms-overflow-style: none; + } + + .node-enterprise-modal .tab-page { + display: none; + } + + .node-enterprise-modal .tab-page.active { + display: block; + } + + .node-form-section { + margin-bottom: 20px; + } + + .node-form-section:last-child { + margin-bottom: 0; + } + + .node-form-section-title { + font-size: 13px; + font-weight: 700; + color: rgba(255, 255, 255, 0.7); + margin-bottom: 12px; + display: flex; + align-items: center; + gap: 8px; + } + + .node-form-section-title i { + color: rgba(99, 102, 241, 0.8); + font-size: 14px; + } + + .resources-section { + margin-bottom: 24px; + padding-bottom: 24px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + } + + .resources-section:last-of-type { + border-bottom: none; + margin-bottom: 0; + } + + .resources-section-header { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 16px; + padding-bottom: 10px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + } + + .resources-section-header i { + font-size: 14px; + color: rgba(99, 102, 241, 0.85); + } + + .resources-section-header span:first-of-type { + font-size: 13px; + font-weight: 700; + color: rgba(255, 255, 255, 0.75); + letter-spacing: 0.3px; + text-transform: uppercase; + } + + .resource-usage-row { + margin-top: 16px; + padding-top: 16px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + } + + .resource-usage-row .node-form-label { + margin-bottom: 8px; + } + + .node-form-hint { + font-weight: 400; + color: rgba(255, 255, 255, 0.4); + font-size: 12px; + } + + .node-form-grid { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12px; + } + + .node-form-grid-3 { + grid-template-columns: 1fr 1fr 1fr; + } + + .node-form-field { + display: flex; + flex-direction: column; + gap: 6px; + min-width: 0; + } + + .node-form-label { + font-size: 12px; + font-weight: 600; + color: rgba(255, 255, 255, 0.6); + display: inline-flex; + align-items: center; + gap: 6px; + } + + .node-form-input { + width: 100%; + height: 44px; + min-width: 0; + padding: 0 14px; + border-radius: 10px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(0, 0, 0, 0.25); + color: rgba(255, 255, 255, 0.95); + font-size: 14px; + outline: none; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .node-form-input::placeholder { + color: rgba(255, 255, 255, 0.3); + } + + .node-form-input:focus { + border-color: rgba(99, 102, 241, 0.5); + background: rgba(0, 0, 0, 0.35); + } + + .node-form-input[readonly] { + background: rgba(255, 255, 255, 0.03); + border-color: rgba(255, 255, 255, 0.18); + color: rgba(255, 255, 255, 0.72); + cursor: not-allowed; + } + + .node-ports-mode { + display: flex; + gap: 8px; + margin-bottom: 12px; + } + + .node-port-chip { + cursor: pointer; + } + + .node-port-chip input { + display: none; + } + + .node-port-chip span { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 8px 14px; + border-radius: 8px; + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.5); + font-size: 13px; + font-weight: 600; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .node-port-chip input:checked+span { + background: rgba(99, 102, 241, 0.15); + color: #a5b4fc; + } + + .node-port-chip:hover span { + background: rgba(255, 255, 255, 0.08); + } + + .node-port-chip input:checked:hover+span { + background: rgba(99, 102, 241, 0.2); + } + + .ports-list-field { + display: none; + } + + .node-feedback { + font-size: 13px; + color: rgba(255, 255, 255, 0.6); + margin-top: 12px; + padding: 10px 12px; + border-radius: 8px; + background: rgba(255, 255, 255, 0.03); + } + + .node-feedback:empty { + display: none; + } + + .node-modal-footer { + border-top: 1px solid rgba(255, 255, 255, 0.06); + } + + .node-linking-header { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 12px; + } + + .node-linking-info { + flex: 1; + min-width: 0; + } + + .node-linking-desc { + font-size: 12px; + color: rgba(255, 255, 255, 0.4); + margin: 4px 0 0; + } + + .node-linking-actions { + display: flex; + gap: 6px; + } + + .node-action-btn { + display: inline-flex; + align-items: center; + gap: 6px; + padding: 8px 12px; + border-radius: 8px; + border: none; + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.7); + font-size: 12px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .node-action-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: rgba(255, 255, 255, 0.9); + } + + .node-generate-btn { + padding: 8px 14px; + font-size: 12px; + } + + .node-codebox { + width: 100%; + min-height: 120px; + padding: 14px; + border-radius: 10px; + border: 1px solid rgba(255, 255, 255, 0.06); + background: rgba(0, 0, 0, 0.3); + color: rgba(255, 255, 255, 0.8); + font-family: 'JetBrains Mono', 'Fira Code', 'SF Mono', Monaco, monospace; + font-size: 12px; + line-height: 1.6; + resize: none; + outline: none; + } + + .node-codebox::-webkit-scrollbar { + display: none; + } + + .node-codebox { + scrollbar-width: none; + } + + .node-cmd-box { + min-height: 80px; + display: none; + } + + .node-cmd-actions { + display: none; + margin-top: 8px; + justify-content: flex-end; + } + + .node-danger-zone { + display: flex; + flex-direction: column; + align-items: center; + text-align: center; + padding: 32px 24px; + border-radius: 14px; + background: linear-gradient(180deg, rgba(239, 68, 68, 0.08), rgba(220, 38, 38, 0.04)); + } + + .node-danger-icon { + width: 56px; + height: 56px; + border-radius: 50%; + background: rgba(239, 68, 68, 0.15); + display: flex; + align-items: center; + justify-content: center; + margin-bottom: 16px; + } + + .node-danger-icon i { + font-size: 24px; + color: #f87171; + } + + .node-danger-content { + margin-bottom: 20px; + } + + .node-danger-title { + margin: 0 0 8px; + font-size: 16px; + font-weight: 700; + color: rgba(255, 255, 255, 0.95); + } + + .node-danger-desc { + margin: 0; + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + max-width: 340px; + } + + .node-danger-desc strong { + color: rgba(255, 255, 255, 0.7); + } + + .node-danger-btn { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 12px 20px; + border-radius: 10px; + border: none; + background: linear-gradient(135deg, rgba(239, 68, 68, 0.9), rgba(220, 38, 38, 0.85)); + color: #fff; + font-weight: 600; + font-size: 14px; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .node-danger-btn:hover { + filter: brightness(1.1); + } + + .node-danger-btn:active { + transform: scale(0.98); + } + + .node-danger-feedback { + margin-top: 16px; + width: 100%; + } + + @media (max-width: 600px) { + .enterprise-modal { + width: 95vw; + border-radius: 20px; + } + + .enterprise-modal-header { + padding: 20px 20px 16px; + } + + .enterprise-modal-body { + padding: 4px 20px 16px; + } + + .enterprise-modal-footer { + padding: 14px 20px 20px; + } + + .password-form { + padding: 0 20px 8px; + } + + .access-server-row { + flex-direction: column; + align-items: stretch; + gap: 12px; + } + + .access-server-actions { + justify-content: flex-end; + } + + .node-enterprise-modal { + width: 95vw; + } + + .node-form-grid, + .node-form-grid-3 { + grid-template-columns: 1fr; + } + + .node-tabs { + padding: 0 20px; + overflow-x: auto; + } + + .node-modal-body { + padding: 16px 20px; + } + + .node-linking-header { + flex-direction: column; + align-items: stretch; + } + + .node-linking-actions { + justify-content: flex-end; + } + } + + .resources-enterprise-modal { + width: 580px; + max-width: 95vw; + } + + .enterprise-modal-icon.resources-icon { + background: transparent; + width: auto; + height: auto; + border-radius: 0; + } + + .enterprise-modal-icon.resources-icon::before { + display: none; + } + + .enterprise-modal-icon.resources-icon i { + display: block; + font-size: 28px; + color: #10b981; + } + + .resources-modal-body { + padding: 4px 28px 20px; + } + + .resource-rename-action { + justify-content: flex-end; + } + + .resource-rename-btn { + width: 100%; + min-height: 44px; + justify-content: center; + } + + .resources-warning-banner { + display: flex; + align-items: center; + gap: 12px; + padding: 14px 16px; + margin-bottom: 24px; + background: linear-gradient(135deg, rgba(245, 158, 11, 0.15), rgba(217, 119, 6, 0.1)); + border: 1px solid rgba(245, 158, 11, 0.25); + border-radius: 10px; + } + + .resources-warning-banner i { + font-size: 16px; + color: #f59e0b; + flex-shrink: 0; + } + + .resources-warning-banner span { + font-size: 13px; + color: rgba(255, 255, 255, 0.85); + font-weight: 500; + } + + .resource-input-wrapper { + position: relative; + display: flex; + align-items: center; + } + + .resource-input-wrapper .node-form-input { + padding-right: 60px; + } + + .resource-input-suffix { + position: absolute; + right: 12px; + font-size: 12px; + font-weight: 500; + color: rgba(255, 255, 255, 0.4); + pointer-events: none; + } + + .resource-tooltip { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + cursor: help; + } + + .resource-tooltip i { + font-size: 12px; + color: rgba(255, 255, 255, 0.42); + transition: color 0.2s ease; + } + + .resource-tooltip:hover i { + color: rgba(255, 255, 255, 0.78); + } + + .resource-tooltip-card { + display: none; + position: absolute; + z-index: 30; + bottom: calc(100% + 8px); + left: 50%; + transform: translateX(-50%); + width: max-content; + max-width: 260px; + 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; + text-align: left; + } + + .resource-tooltip:hover .resource-tooltip-card { + display: block; + } + + .resource-select { + appearance: none; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='rgba(255,255,255,0.4)' d='M6 8L2 4h8z'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 12px center; + padding-right: 32px; + cursor: pointer; + } + + .resource-hint { + display: block; + margin-top: 6px; + font-size: 11px; + color: rgba(255, 255, 255, 0.35); + } + + .resource-current-display { + padding: 12px 14px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 10px; + } + + .resource-usage-bar { + height: 8px; + background: rgba(255, 255, 255, 0.1); + border-radius: 4px; + overflow: hidden; + margin-bottom: 8px; + } + + .resource-usage-fill { + height: 100%; + background: linear-gradient(90deg, #10b981, #34d399); + border-radius: 4px; + transition: width 0.5s cubic-bezier(0.32, 0.72, 0, 1); + } + + .resource-usage-fill.warning { + background: linear-gradient(90deg, #f59e0b, #fbbf24); + } + + .transfer-enterprise-modal { + width: 580px; + max-width: 95vw; + } + + .enterprise-modal-icon.transfer-icon { + background: transparent; + } + + .enterprise-modal-icon.transfer-icon::before { + display: none; + } + + .enterprise-modal-icon.transfer-icon i { + display: block; + font-size: 28px; + color: #93c5fd; + } + + .transfer-node-list { + display: grid; + gap: 10px; + margin-top: 10px; + } + + .transfer-node-item { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 12px; + border-radius: 14px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + cursor: pointer; + transition: transform .18s ease, box-shadow .18s ease, border-color .18s ease; + } + + .transfer-node-item:hover { + transform: translateY(-2px); + box-shadow: 0 18px 40px rgba(0, 0, 0, 0.28); + border-color: rgba(255, 255, 255, 0.14); + } + + .transfer-node-meta { + display: flex; + align-items: center; + gap: 10px; + min-width: 0; + } + + .transfer-node-title { + font-weight: 800; + color: rgba(255, 255, 255, 0.92); + } + + .transfer-node-sub { + font-size: 12px; + color: rgba(255, 255, 255, 0.55); + } + + .transfer-node-actions { + display: flex; + align-items: center; + gap: 8px; + } + + .transfer-progress { + margin-top: 14px; + padding-top: 12px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + } + + .transfer-progress-text { + margin-top: 8px; + font-size: 13px; + color: rgba(255, 255, 255, 0.7); + } + + .resource-usage-text { + font-size: 12px; + color: rgba(255, 255, 255, 0.5); + } + + @media (max-width: 600px) { + .resources-enterprise-modal { + width: 95vw; + } + + .resources-warning-banner { + flex-direction: column; + gap: 10px; + } + + .resources-warning-icon { + width: 32px; + height: 32px; + } + } + + .portforward-enterprise-modal { + width: 580px; + max-width: 95vw; + } + + .enterprise-modal-icon.portforward-icon { + background: transparent; + width: auto; + height: auto; + border-radius: 0; + } + + .enterprise-modal-icon.portforward-icon::before { + display: none; + } + + .enterprise-modal-icon.portforward-icon i { + display: block; + font-size: 28px; + color: #a78bfa; + } + + .portforward-modal-body { + padding: 4px 28px 20px; + } + + .pf-rules-list { + display: flex; + flex-direction: column; + gap: 8px; + min-height: 40px; + margin-bottom: 14px; + } + + .pf-empty-state { + display: flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 20px; + color: rgba(255, 255, 255, 0.35); + font-size: 13px; + font-style: italic; + border: 1px dashed rgba(255, 255, 255, 0.1); + border-radius: 10px; + } + + .pf-rule-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px 14px; + background: rgba(167, 139, 250, 0.08); + border: 1px solid rgba(167, 139, 250, 0.18); + border-radius: 10px; + transition: border-color 0.18s ease; + } + + .pf-rule-item:hover { + border-color: rgba(167, 139, 250, 0.35); + } + + .pf-rule-ports { + display: flex; + align-items: center; + gap: 12px; + } + + .pf-rule-port { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + font-weight: 600; + padding: 4px 10px; + border-radius: 6px; + } + + .pf-rule-port.pf-public { + background: rgba(167, 139, 250, 0.15); + color: #c4b5fd; + } + + .pf-rule-port.pf-public i { + font-size: 11px; + color: #a78bfa; + } + + .pf-rule-port.pf-internal { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.7); + } + + .pf-rule-port.pf-internal i { + font-size: 11px; + color: rgba(255, 255, 255, 0.4); + } + + .pf-rule-arrow { + color: rgba(255, 255, 255, 0.3); + font-size: 12px; + } + + .pf-remove { + background: none; + border: none; + color: rgba(255, 255, 255, 0.4); + cursor: pointer; + padding: 4px 6px; + border-radius: 6px; + transition: color 0.18s ease, background 0.18s ease; + } + + .pf-remove:hover { + color: #f87171; + background: rgba(248, 113, 113, 0.1); + } + + .pf-add-row { + display: flex; + flex-direction: column; + gap: 10px; + } + + .pf-add-inputs { + display: flex; + align-items: flex-end; + gap: 10px; + } + + .pf-input-group { + flex: 1; + display: flex; + flex-direction: column; + gap: 4px; + } + + .pf-input-label { + font-size: 11px; + font-weight: 600; + color: rgba(255, 255, 255, 0.5); + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .pf-input { + width: 100%; + } + + select.pf-input { + cursor: pointer; + appearance: none; + -webkit-appearance: none; + background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='12' height='12' viewBox='0 0 12 12'%3E%3Cpath fill='rgba(255,255,255,0.5)' d='M6 8L1 3h10z'/%3E%3C/svg%3E"); + background-repeat: no-repeat; + background-position: right 10px center; + padding-right: 30px; + } + + .pf-arrow-icon { + display: flex; + align-items: center; + justify-content: center; + padding-bottom: 8px; + color: rgba(255, 255, 255, 0.3); + font-size: 14px; + flex-shrink: 0; + } + + .pf-add-btn { + align-self: flex-start; + } + + @media (max-width: 600px) { + .portforward-enterprise-modal { + width: 95vw; + } + + .pf-add-inputs { + flex-direction: column; + gap: 8px; + } + + .pf-arrow-icon { + transform: rotate(90deg); + padding-bottom: 0; + } + + .pf-rule-ports { + flex-direction: column; + gap: 6px; + } + + .pf-rule-arrow { + transform: rotate(90deg); + } + } + + .ports-list-container { + display: flex; + flex-direction: column; + gap: 10px; + } + + .ports-list { + display: flex; + flex-wrap: wrap; + gap: 8px; + min-height: 36px; + } + + .ports-list:empty::before { + content: 'No ports configured'; + color: rgba(255, 255, 255, 0.4); + font-size: 13px; + font-style: italic; + } + + .port-item { + display: inline-flex; + align-items: center; + gap: 8px; + background: rgba(79, 70, 229, 0.15); + border-radius: 8px; + padding: 6px 10px; + font-size: 13px; + font-weight: 500; + color: #a5b4fc; + } + + .port-item i { + font-size: 11px; + } + + .port-item .port-remove { + background: none; + border: none; + color: rgba(255, 255, 255, 0.5); + cursor: pointer; + padding: 2px 4px; + border-radius: 4px; + transition: all 0.15s ease; + display: flex; + align-items: center; + justify-content: center; + } + + .port-item .port-remove:hover { + color: #ef4444; + background: rgba(239, 68, 68, 0.15); + } + + .port-item-primary { + background: rgba(16, 185, 129, 0.15); + color: #6ee7b7; + } + + .port-item-primary i { + color: #34d399; + } + + .port-edit-input { + width: 80px; + background: rgba(255, 255, 255, 0.08); + border: 1px solid rgba(255, 255, 255, 0.15); + border-radius: 5px; + color: inherit; + font-size: 13px; + font-weight: 600; + padding: 3px 6px; + text-align: center; + -moz-appearance: textfield; + } + + .port-edit-input::-webkit-outer-spin-button, + .port-edit-input::-webkit-inner-spin-button { + -webkit-appearance: none; + margin: 0; + } + + .port-edit-input:focus { + outline: none; + border-color: rgba(16, 185, 129, 0.6); + background: rgba(255, 255, 255, 0.12); + } + + .port-badge-primary { + font-size: 10px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.5px; + background: rgba(16, 185, 129, 0.25); + color: #6ee7b7; + padding: 2px 6px; + border-radius: 4px; + } + + .ports-add-row { + display: flex; + gap: 10px; + align-items: center; + } + + .ports-input { + flex: 1; + max-width: 200px; + } + + .ports-add-btn { + padding: 8px 14px; + font-size: 13px; + white-space: nowrap; + } + + .customization-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + margin-bottom: 20px; + } + + .customization-title { + font-size: 20px; + font-weight: 700; + color: #fff; + } + + .customization-subtitle { + font-size: 14px; + color: var(--muted); + margin-top: 4px; + } + + .customization-section { + background: var(--card-contrast-bg); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 12px; + padding: 20px; + margin-bottom: 16px; + } + + .customization-section-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 16px; + margin-bottom: 20px; + padding-bottom: 16px; + border-bottom: 1px solid rgba(255, 255, 255, 0.06); + } + + .customization-section-info { + display: flex; + align-items: center; + gap: 14px; + } + + .customization-section-icon { + width: 44px; + height: 44px; + border-radius: 12px; + background: linear-gradient(135deg, rgba(99, 102, 241, 0.2), rgba(139, 92, 246, 0.15)); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + } + + .customization-section-icon i { + font-size: 18px; + color: #a5b4fc; + } + + .customization-section-title { + font-size: 16px; + font-weight: 600; + color: #fff; + } + + .customization-section-desc { + font-size: 13px; + color: var(--muted); + margin-top: 2px; + } + + .login-watermark-enterprise-modal { + width: 560px; + } + + .login-background-enterprise-modal { + width: 600px; + } + + @media (max-width: 600px) { + .alert-schedule-grid { + grid-template-columns: 1fr; + } + } + + .login-background-modal-badge { + width: 72px; + height: 72px; + border-radius: 18px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, rgba(99, 102, 241, 0.18), rgba(59, 130, 246, 0.12)); + color: #c7d2fe; + box-shadow: inset 0 0 0 1px rgba(99, 102, 241, 0.14); + } + + .login-background-modal-badge i { + font-size: 24px; + } + + .login-watermark-intro { + font-size: 13px; + line-height: 1.65; + color: rgba(255, 255, 255, 0.62); + } + + .login-watermark-source-tabs { + display: flex; + gap: 10px; + margin-top: 10px; + } + + .login-watermark-source-tab { + flex: 1; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 12px 16px; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + color: rgba(255, 255, 255, 0.62); + font-size: 13px; + font-weight: 600; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .login-watermark-source-tab:hover { + border-color: rgba(255, 255, 255, 0.14); + color: rgba(255, 255, 255, 0.86); + } + + .login-watermark-source-tab.active { + border-color: rgba(99, 102, 241, 0.45); + background: rgba(99, 102, 241, 0.15); + color: #c7d2fe; + box-shadow: inset 0 0 0 1px rgba(99, 102, 241, 0.12); + } + + .create-user-enterprise-modal { + width: min(620px, calc(100vw - 28px)); + } + + .create-user-modal-body { + padding: 24px; + } + + .create-user-role-tabs { + margin-top: 8px; + } + + .create-user-role-tabs .login-watermark-source-tab { + min-height: 46px; + } + + .create-user-admin-tab.active { + border-color: rgba(245, 158, 11, 0.46); + background: rgba(245, 158, 11, 0.14); + color: #fde68a; + box-shadow: inset 0 0 0 1px rgba(245, 158, 11, 0.12); + } + + .create-user-admin-stepup { + border: 1px solid rgba(245, 158, 11, 0.16); + background: linear-gradient(160deg, rgba(245, 158, 11, 0.08), rgba(255, 255, 255, 0.025)); + border-radius: 16px; + padding: 16px; + } + + .create-user-password-wrap { + position: relative; + } + + .create-user-password-wrap .node-form-input { + padding-right: 48px; + } + + .create-user-password-toggle { + position: absolute; + right: 12px; + top: 50%; + transform: translateY(-50%); + width: 32px; + height: 32px; + display: inline-flex; + align-items: center; + justify-content: center; + border: 0; + border-radius: 8px; + background: transparent; + color: rgba(255, 255, 255, 0.45); + cursor: pointer; + transition: background 0.18s ease, color 0.18s ease; + } + + .create-user-password-toggle:hover { + background: rgba(255, 255, 255, 0.06); + color: rgba(255, 255, 255, 0.86); + } + + .create-user-2fa-input { + font-family: "SF Mono", Monaco, Consolas, monospace; + letter-spacing: 0.16em; + } + + .create-user-feedback { + display: none; + margin-top: 16px; + padding: 12px 14px; + border-radius: 12px; + border: 1px solid rgba(239, 68, 68, 0.28); + background: rgba(239, 68, 68, 0.12); + color: #fecaca; + font-size: 13px; + line-height: 1.55; + } + + .created-user-role-badge { + display: inline-flex; + align-items: center; + width: fit-content; + margin-top: 8px; + padding: 5px 9px; + 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.72); + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.04em; + } + + .created-user-role-badge.admin { + border-color: rgba(245, 158, 11, 0.32); + background: rgba(245, 158, 11, 0.14); + color: #fde68a; + } + + .login-watermark-upload-input { + display: none; + } + + .login-watermark-dropzone { + width: 100%; + display: flex; + align-items: center; + gap: 16px; + padding: 18px; + border-radius: 18px; + border: 1px dashed rgba(255, 255, 255, 0.14); + background: linear-gradient(160deg, rgba(255, 255, 255, 0.05), rgba(255, 255, 255, 0.02)); + color: #fff; + text-align: left; + cursor: pointer; + transition: all 0.2s cubic-bezier(0.32, 0.72, 0, 1); + } + + .login-watermark-dropzone:hover { + border-color: rgba(99, 102, 241, 0.28); + background: linear-gradient(160deg, rgba(99, 102, 241, 0.09), rgba(255, 255, 255, 0.04)); + } + + .login-watermark-dropzone-icon { + width: 46px; + height: 46px; + border-radius: 14px; + display: inline-flex; + align-items: center; + justify-content: center; + background: rgba(99, 102, 241, 0.14); + color: #c7d2fe; + flex-shrink: 0; + font-size: 18px; + } + + .login-watermark-dropzone-copy { + display: flex; + flex-direction: column; + gap: 4px; + flex: 1; + min-width: 0; + } + + .login-watermark-dropzone-copy strong { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.95); + } + + .login-watermark-dropzone-copy span { + font-size: 12px; + line-height: 1.5; + color: rgba(255, 255, 255, 0.52); + } + + .login-watermark-dropzone-action { + font-size: 12px; + font-weight: 700; + letter-spacing: 0.04em; + text-transform: uppercase; + color: #c7d2fe; + } + + .login-watermark-upload-meta { + min-height: 18px; + margin-top: 10px; + font-size: 12px; + color: rgba(255, 255, 255, 0.54); + } + + .login-watermark-input-hint { + display: block; + margin-top: 8px; + font-size: 12px; + line-height: 1.5; + color: rgba(255, 255, 255, 0.42); + } + + .login-watermark-preview-card { + margin-top: 8px; + padding: 16px; + border-radius: 18px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: linear-gradient(165deg, rgba(255, 255, 255, 0.05), rgba(255, 255, 255, 0.02)); + } + + .login-watermark-preview-top { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 14px; + } + + .login-watermark-preview-title { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.96); + } + + .login-watermark-preview-badge { + padding: 6px 10px; + border-radius: 999px; + background: rgba(99, 102, 241, 0.16); + color: #c7d2fe; + font-size: 12px; + font-weight: 700; + white-space: nowrap; + } + + .login-watermark-preview-frame { + position: relative; + min-height: 158px; + display: flex; + align-items: center; + justify-content: center; + padding: 22px; + border-radius: 16px; + overflow: hidden; + background: linear-gradient(135deg, rgba(18, 20, 25, 0.94), rgba(31, 36, 46, 0.88)); + border: 1px solid rgba(255, 255, 255, 0.05); + } + + .login-watermark-preview-frame::before { + content: ''; + position: absolute; + inset: 0; + background: + radial-gradient(circle at top right, rgba(99, 102, 241, 0.22), transparent 42%), + radial-gradient(circle at bottom left, rgba(59, 130, 246, 0.12), transparent 35%); + pointer-events: none; + } + + .login-watermark-preview-frame img { + position: relative; + max-width: 100%; + max-height: 124px; + object-fit: contain; + filter: drop-shadow(0 10px 28px rgba(0, 0, 0, 0.34)); + } + + .login-background-media-frame { + position: relative; + min-height: 190px; + display: flex; + align-items: center; + justify-content: center; + padding: 12px; + border-radius: 16px; + overflow: hidden; + background: linear-gradient(135deg, rgba(18, 20, 25, 0.94), rgba(31, 36, 46, 0.88)); + border: 1px solid rgba(255, 255, 255, 0.05); + } + + .login-background-media-frame::before { + content: ''; + position: absolute; + inset: 0; + background: + radial-gradient(circle at top right, rgba(99, 102, 241, 0.24), transparent 40%), + radial-gradient(circle at bottom left, rgba(59, 130, 246, 0.14), transparent 38%); + pointer-events: none; + } + + .login-background-media { + position: relative; + width: 100%; + height: 170px; + display: none; + border-radius: 14px; + object-fit: cover; + box-shadow: 0 14px 34px rgba(0, 0, 0, 0.28); + background: rgba(8, 10, 14, 0.82); + } + + .login-background-media.is-visible { + display: block; + } + + .login-watermark-preview-meta { + margin-top: 12px; + font-size: 13px; + line-height: 1.6; + color: rgba(255, 255, 255, 0.56); + } + + .login-watermark-feedback { + display: none; + margin-top: 16px; + padding: 12px 14px; + border-radius: 12px; + font-size: 13px; + line-height: 1.55; + } + + .login-watermark-feedback.error { + display: block; + border: 1px solid rgba(239, 68, 68, 0.28); + background: rgba(239, 68, 68, 0.12); + color: #fecaca; + } + + .login-watermark-feedback.success { + display: block; + border: 1px solid rgba(34, 197, 94, 0.28); + background: rgba(34, 197, 94, 0.12); + color: #bbf7d0; + } + + .quick-actions-config { + min-height: 100px; + } + + .quick-actions-list { + display: grid; + grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); + gap: 12px; + margin-bottom: 16px; + } + + .quick-action-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 10px; + transition: all 0.2s ease; + } + + .quick-action-item:hover { + background: rgba(255, 255, 255, 0.05); + border-color: rgba(255, 255, 255, 0.1); + } + + .quick-action-item-info { + display: flex; + align-items: center; + gap: 12px; + flex: 1; + min-width: 0; + } + + .quick-action-item-icon { + width: 36px; + height: 36px; + border-radius: 8px; + background: linear-gradient(135deg, rgba(99, 102, 241, 0.15), rgba(139, 92, 246, 0.1)); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + } + + .quick-action-item-icon i { + font-size: 14px; + color: #a5b4fc; + } + + .quick-action-item-details { + min-width: 0; + } + + .quick-action-item-title { + font-size: 14px; + font-weight: 600; + color: #fff; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .quick-action-item-link { + font-size: 11px; + color: var(--muted); + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 120px; + } + + .quick-action-item-actions { + display: flex; + align-items: center; + gap: 6px; + opacity: 0; + transition: opacity 0.2s ease; + } + + .quick-action-item:hover .quick-action-item-actions { + opacity: 1; + } + + .quick-action-item-btn { + width: 28px; + height: 28px; + border-radius: 6px; + border: none; + background: rgba(255, 255, 255, 0.06); + color: var(--muted); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + } + + .quick-action-item-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: #fff; + } + + .quick-action-item-btn.delete:hover { + background: rgba(239, 68, 68, 0.2); + color: #fca5a5; + } + + .quick-actions-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 40px 20px; + text-align: center; + color: var(--muted); + } + + .quick-actions-empty i { + font-size: 32px; + opacity: 0.4; + margin-bottom: 12px; + } + + .quick-actions-empty p { + font-size: 14px; + font-weight: 500; + margin-bottom: 4px; + } + + .quick-actions-empty small { + font-size: 12px; + opacity: 0.7; + } + + .quick-actions-limit-note { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 14px; + background: rgb(22, 22, 22); + border-radius: 8px; + font-size: 12px; + color: var(--muted); + } + + .quick-actions-limit-note i { + color: #ffffff9b; + } + + .quick-action-enterprise-modal { + width: 560px; + max-width: 95vw; + } + + .enterprise-modal-icon.quick-action-icon { + background: transparent; + width: auto; + height: auto; + border-radius: 0; + } + + .enterprise-modal-icon.quick-action-icon::before { + display: none; + } + + .enterprise-modal-icon.quick-action-icon i { + display: none; + } + + .enterprise-modal-icon.quick-action-icon img { + display: block; + max-height: 130px; + width: auto; + object-fit: contain; + } + + .quick-action-modal-body { + padding: 4px 28px 20px; + max-height: 60vh; + overflow-y: auto; + } + + .quick-action-preview-section { + margin-bottom: 20px; + } + + .quick-action-preview-label { + font-size: 12px; + color: var(--muted); + margin-bottom: 10px; + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .quick-action-preview-card { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 10px; + padding: 20px; + background: rgba(255, 255, 255, 0.04); + border: 1px solid rgba(255, 255, 255, 0.08); + border-radius: 12px; + max-width: 180px; + margin: 0 auto; + transition: all 0.3s ease; + } + + .quick-action-preview-card i { + font-size: 1.5rem; + color: #a5b4fc; + } + + .quick-action-preview-card p { + font-size: 14px; + font-weight: 600; + color: #fff; + text-align: center; + word-break: break-word; + } + + .quick-action-preview-card.anim-pulse:hover { + animation: qaPulse 0.6s ease-in-out; + } + + .quick-action-preview-card.anim-shake:hover { + animation: qaShake 0.5s ease-in-out; + } + + .quick-action-preview-card.anim-bounce:hover { + animation: qaBounce 0.5s ease; + } + + .quick-action-preview-card.anim-glow:hover { + box-shadow: 0 0 20px rgba(99, 102, 241, 0.4); + } + + .quick-action-preview-card.anim-scale { + position: relative; + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); + transform-origin: center center; + isolation: isolate; + } + + .quick-action-preview-card.anim-scale:hover { + transform: scale(1.08); + } + + /* Children with 3D transform layer */ + .quick-action-preview-card.anim-scale > i, + .quick-action-preview-card.anim-scale > p { + display: inline-block; + transform-style: preserve-3d; + transform: translateZ(100px) scale(1); + transition: transform 0.2s cubic-bezier(0.34, 1.56, 0.64, 1); + } + + /* Counter-scale on hover */ + .quick-action-preview-card.anim-scale:hover > i, + .quick-action-preview-card.anim-scale:hover > p { + transform: translateZ(100px) scale(calc(1 / 1.08)); + } + + .quick-action-preview-card.anim-rotate:hover i { + animation: qaRotate 0.5s ease; + } + + .quick-action-preview-card.anim-default:hover { + transform: translateY(-4px); + border-color: rgba(255, 255, 255, 0.15); + background: rgba(124, 92, 255, 0.16); + } + + @keyframes qaPulse { + + 0%, + 100% { + transform: scale(1); + } + + 50% { + transform: scale(1.05); + } + } + + @keyframes qaShake { + + 0%, + 100% { + transform: translateX(0); + } + + 20% { + transform: translateX(-4px); + } + + 40% { + transform: translateX(4px); + } + + 60% { + transform: translateX(-4px); + } + + 80% { + transform: translateX(4px); + } + } + + @keyframes qaBounce { + + 0%, + 100% { + transform: translateY(0); + } + + 40% { + transform: translateY(-8px); + } + + 60% { + transform: translateY(-4px); + } + } + + @keyframes qaRotate { + from { + transform: rotate(0deg); + } + + to { + transform: rotate(360deg); + } + } + + .icon-input-wrapper { + display: flex; + align-items: center; + gap: 10px; + } + + .icon-input-wrapper .node-form-input { + flex: 1; + } + + .icon-preview { + width: 42px; + height: 42px; + border-radius: 8px; + background: rgba(255, 255, 255, 0.06); + border: 1px solid rgba(255, 255, 255, 0.1); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + } + + .icon-preview i { + font-size: 18px; + color: #a5b4fc; + } + + .icon-suggestions { + margin-top: 12px; + } + + .icon-suggestions-label { + font-size: 12px; + color: var(--muted); + margin-bottom: 8px; + } + + .icon-suggestions-grid { + display: flex; + flex-wrap: wrap; + gap: 6px; + } + + .icon-suggestion { + width: 36px; + height: 36px; + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + color: var(--muted); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + } + + .icon-suggestion:hover { + background: rgba(99, 102, 241, 0.15); + border-color: rgba(99, 102, 241, 0.3); + color: #a5b4fc; + } + + .icon-suggestion.selected { + background: rgba(99, 102, 241, 0.2); + border-color: rgba(99, 102, 241, 0.4); + color: #a5b4fc; + } + + .icon-suggestion i { + font-size: 14px; + } + + .quick-action-switch-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 12px 14px; + border-radius: 14px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + } + + .quick-action-switch-label { + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.92); + cursor: pointer; + } + + .quick-action-switch { + position: relative; + width: 62px; + height: 34px; + display: inline-block; + flex-shrink: 0; + cursor: pointer; + } + + .quick-action-switch input { + opacity: 0; + width: 0; + height: 0; + } + + .quick-action-switch-slider { + position: absolute; + inset: 0; + border-radius: 999px; + background: rgba(255, 255, 255, 0.12); + border: 1px solid rgba(255, 255, 255, 0.12); + transition: all 0.25s cubic-bezier(0.32, 0.72, 0, 1); + } + + .quick-action-switch-slider::before { + content: ""; + position: absolute; + width: 26px; + height: 26px; + left: 3px; + top: 3px; + border-radius: 50%; + background: #fff; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.3); + transition: transform 0.25s cubic-bezier(0.32, 0.72, 0, 1); + } + + .quick-action-switch-slider::after { + content: "OFF"; + position: absolute; + right: 8px; + top: 50%; + transform: translateY(-50%); + font-size: 9px; + font-weight: 700; + letter-spacing: 0.08em; + color: rgba(255, 255, 255, 0.5); + transition: all 0.25s cubic-bezier(0.32, 0.72, 0, 1); + pointer-events: none; + } + + .quick-action-switch:hover .quick-action-switch-slider { + background: rgba(255, 255, 255, 0.18); + border-color: rgba(255, 255, 255, 0.2); + } + + .quick-action-switch input:checked + .quick-action-switch-slider { + background: linear-gradient(135deg, #6366f1, #4f46e5); + border-color: rgba(129, 140, 248, 0.75); + box-shadow: 0 0 0 1px rgba(99, 102, 241, 0.25), 0 10px 20px rgba(79, 70, 229, 0.35); + } + + .quick-action-switch input:checked + .quick-action-switch-slider::before { + transform: translateX(28px); + } + + .quick-action-switch input:checked + .quick-action-switch-slider::after { + content: "ON"; + right: auto; + left: 10px; + color: rgba(255, 255, 255, 0.92); + } + + .quick-action-switch input:focus-visible + .quick-action-switch-slider { + box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.3); + } + + .required { + color: #f87171; + } + + @media (max-width: 600px) { + .quick-action-enterprise-modal { + width: 95vw; + } + + .icon-suggestions-grid { + gap: 4px; + } + + .icon-suggestion { + width: 32px; + height: 32px; + } + + .quick-actions-list { + grid-template-columns: 1fr; + } + + .customization-section-header { + flex-direction: column; + align-items: stretch; + gap: 12px; + } + + .login-watermark-source-tabs, + .create-user-role-tabs, + .login-watermark-dropzone, + .login-watermark-preview-top { + flex-direction: column; + align-items: stretch; + } + + .create-user-modal-body { + padding: 18px; + } + + .login-watermark-dropzone-action { + margin-left: 0; + align-self: flex-start; + } + } + + + .databases-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 16px; + } + + .databases-title { + font-weight: 700; + font-size: 18px; + } + + .databases-subtitle { + color: var(--muted); + font-size: 13px; + margin-top: 4px; + } + + .databases-content { + display: flex; + flex-direction: column; + gap: 16px; + } + + .db-card-icon-phpmyadmin { + width: 42px; + height: 42px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + } + + .db-details { + margin-top: 16px; + padding-top: 16px; + border-top: 1px solid rgba(255, 255, 255, 0.06); + } + + .db-status-box { + padding: 16px; + background: rgba(255, 255, 255, 0.03); + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.06); + } + + .db-status-loading { + display: flex; + align-items: center; + gap: 12px; + color: var(--muted); + } + + .db-status-loading i { + font-size: 18px; + } + + .db-status-success { + display: flex; + align-items: center; + gap: 10px; + color: #22c55e; + } + + .db-status-success i { + font-size: 18px; + } + + .db-status-error { + display: flex; + align-items: center; + gap: 10px; + color: #ef4444; + } + + .db-status-error i { + font-size: 18px; + } + + .db-disable-progress { + --db-brand: #f59e0b; + display: flex; + flex-direction: column; + gap: 14px; + } + + .db-disable-header { + display: flex; + align-items: center; + gap: 12px; + } + + .db-disable-header i { + font-size: 20px; + color: var(--db-brand); + animation: spin 1s linear infinite; + } + + .db-disable-header-text { + display: flex; + flex-direction: column; + gap: 2px; + } + + .db-disable-title { + font-weight: 600; + font-size: 14px; + color: var(--db-brand); + } + + .db-disable-subtitle { + font-size: 12px; + color: var(--muted); + } + + .db-disable-bar-track { + width: 100%; + height: 6px; + background: rgba(255, 255, 255, 0.06); + border-radius: 6px; + overflow: hidden; + } + + .db-disable-bar-fill { + height: 100%; + background: var(--db-brand); + border-radius: 6px; + transition: width 0.5s ease; + width: 0%; + } + + .db-disable-steps { + display: flex; + flex-direction: column; + gap: 6px; + } + + .db-disable-step { + display: flex; + align-items: center; + gap: 8px; + font-size: 12px; + color: var(--muted); + opacity: 0.5; + transition: opacity 0.3s ease, color 0.3s ease; + } + + .db-disable-step.active { + opacity: 1; + color: var(--db-brand); + } + + .db-disable-step.done { + opacity: 1; + color: var(--db-brand); + } + + .db-disable-step i { + width: 14px; + text-align: center; + font-size: 12px; + } + + .db-disable-elapsed { + font-size: 11px; + color: var(--muted); + text-align: right; + } + + .db-disable-done { + display: flex; + align-items: center; + gap: 12px; + } + + .db-disable-done i { + font-size: 20px; + color: var(--db-brand); + } + + .db-disable-done span { + font-weight: 600; + font-size: 14px; + color: var(--db-brand); + } + + @keyframes spin { + from { transform: rotate(0deg); } + to { transform: rotate(360deg); } + } + + .db-users-section { + margin-top: 16px; + padding: 16px; + background: rgba(255, 255, 255, 0.02); + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.06); + } + + .db-users-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 16px; + } + + .db-users-title { + font-weight: 700; + font-size: 15px; + } + + .db-users-subtitle { + color: var(--muted); + font-size: 12px; + margin-top: 2px; + } + + .db-users-list { + display: flex; + flex-direction: column; + gap: 8px; + } + + .db-users-empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 32px; + color: var(--muted); + text-align: center; + } + + .db-users-empty i { + font-size: 32px; + margin-bottom: 12px; + opacity: 0.5; + } + + .db-users-empty p { + font-size: 14px; + } + + .db-user-row { + display: flex; + align-items: center; + justify-content: space-between; + padding: 12px 14px; + background: rgba(255, 255, 255, 0.03); + border-radius: 10px; + transition: all 0.2s ease; + } + + .db-user-row:hover { + background: rgba(255, 255, 255, 0.05); + border-color: rgba(255, 255, 255, 0.1); + } + + .db-user-left { + display: flex; + align-items: center; + gap: 12px; + } + + .db-user-icon { + width: 36px; + height: 36px; + border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, rgba(99, 102, 241, 0.2), rgba(79, 70, 229, 0.15)); + color: #a5b4fc; + } + + .db-user-icon.admin { + background: linear-gradient(135deg, rgba(19, 170, 82, 0.25), rgba(16, 140, 68, 0.15)); + color: #22c55e; + } + + .db-user-badge { + display: inline-block; + padding: 2px 8px; + font-size: 10px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.5px; + background: linear-gradient(135deg, rgba(19, 170, 82, 0.2), rgba(16, 140, 68, 0.12)); + color: #22c55e; + border-radius: 6px; + margin-left: 8px; + } + + .db-user-name { + font-weight: 600; + font-size: 14px; + } + + .db-user-created { + font-size: 12px; + color: var(--muted); + margin-top: 2px; + } + + .db-user-actions { + display: flex; + gap: 8px; + } + + .db-user-btn { + padding: 8px 12px; + border-radius: 8px; + border: none; + font-size: 12px; + font-weight: 600; + cursor: pointer; + display: flex; + align-items: center; + gap: 6px; + transition: all 0.2s ease; + } + + .db-user-btn-edit { + background: rgba(99, 102, 241, 0.15); + color: #a5b4fc; + } + + .db-user-btn-edit:hover { + background: rgba(99, 102, 241, 0.25); + } + + .db-user-btn-delete { + background: rgba(239, 68, 68, 0.1); + color: #fca5a5; + } + + .db-user-btn-delete:hover { + background: rgba(239, 68, 68, 0.2); + } + + .mongodb-delete-modal { + width: 420px; + max-width: 95vw; + background: rgba(20, 20, 28, 0.98); + border: none; + box-shadow: none; + border-radius: 20px; + } + + .mongodb-delete-modal-content { + padding: 40px 32px; + text-align: center; + } + + .mongodb-delete-icon { + width: 80px; + height: 80px; + margin: 0 auto 24px; + border-radius: 50%; + background: linear-gradient(145deg, rgba(239, 68, 68, 0.2), rgba(220, 38, 38, 0.15)); + display: flex; + align-items: center; + justify-content: center; + } + + .mongodb-delete-icon i { + font-size: 36px; + color: #ef4444; + } + + .mongodb-delete-title { + font-size: 22px; + font-weight: 700; + color: #fff; + margin: 0 0 12px; + } + + .mongodb-delete-text { + font-size: 15px; + color: rgba(255, 255, 255, 0.85); + margin: 0 0 8px; + } + + .mongodb-delete-text strong { + color: #fca5a5; + } + + .mongodb-delete-subtext { + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + margin: 0 0 28px; + } + + .mongodb-delete-actions { + display: flex; + gap: 12px; + justify-content: center; + } + + .mongodb-delete-btn { + padding: 12px 24px; + border-radius: 10px; + border: none; + font-size: 14px; + font-weight: 600; + cursor: pointer; + display: flex; + align-items: center; + gap: 8px; + transition: transform 0.2s ease, background 0.2s ease; + } + + .mongodb-delete-btn:hover { + transform: none; + } + + .mongodb-delete-btn-cancel { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.8); + } + + .mongodb-delete-btn-cancel:hover { + background: rgba(255, 255, 255, 0.12); + } + + .mongodb-delete-btn-confirm { + background: linear-gradient(145deg, #ef4444, #dc2626); + color: #fff; + } + + .mongodb-delete-btn-confirm:hover { + background: linear-gradient(145deg, #f87171, #ef4444); + } + + .db-type-section { + margin-top: 16px; + padding: 16px; + background: rgba(255, 255, 255, 0.02); + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.06); + } + + .db-type-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 16px; + } + + .db-type-title { + font-weight: 700; + font-size: 15px; + } + + .db-type-subtitle { + color: var(--muted); + font-size: 12px; + margin-top: 2px; + } + + .db-type-current { + display: flex; + align-items: center; + gap: 14px; + padding: 14px; + background: rgba(255, 255, 255, 0.03); + border-radius: 10px; + } + + .db-type-icon { + width: 48px; + height: 48px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + font-size: 20px; + } + + .db-type-icon.postgresql { + background: linear-gradient(135deg, rgba(51, 103, 145, 0.2), rgba(51, 103, 145, 0.1)); + color: #336791; + } + + .db-type-icon.mongodb { + background: linear-gradient(135deg, rgba(77, 179, 61, 0.2), rgba(77, 179, 61, 0.1)); + color: #4db33d; + } + + .db-type-name { + font-weight: 700; + font-size: 15px; + } + + .db-type-host { + font-size: 13px; + color: var(--muted); + margin-top: 2px; + } + + .db-access-section { + margin-top: 16px; + padding: 16px; + background: linear-gradient(135deg, rgba(34, 197, 94, 0.08), rgba(16, 185, 129, 0.05)); + border-radius: 12px; + } + + .db-access-header { + display: flex; + align-items: center; + gap: 12px; + margin-bottom: 14px; + } + + .db-access-icon { + width: 40px; + height: 40px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 18px; + } + + .db-access-icon.success { + background: rgba(34, 197, 94, 0.15); + color: #22c55e; + } + + .db-access-title { + font-weight: 700; + font-size: 15px; + color: #22c55e; + } + + .db-access-subtitle { + font-size: 12px; + color: rgba(255, 255, 255, 0.6); + margin-top: 2px; + } + + .db-access-url-box { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + padding: 12px 14px; + background: rgba(0, 0, 0, 0.2); + border-radius: 10px; + } + + .db-access-url-wrapper { + font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Mono', monospace; + font-size: 13px; + color: rgba(255, 255, 255, 0.9); + word-break: break-all; + display: flex; + flex-wrap: wrap; + align-items: center; + } + + .db-access-url { + font-family: 'SF Mono', 'Monaco', 'Inconsolata', 'Fira Mono', monospace; + font-size: 13px; + color: rgba(255, 255, 255, 0.9); + word-break: break-all; + } + + .db-conn-prefix, + .db-conn-suffix, + .db-conn-sep { + color: rgba(255, 255, 255, 0.6); + } + + .db-conn-user { + color: #a5f3fc; + } + + .db-conn-host { + color: #86efac; + } + + .db-conn-pass { + color: #fcd34d; + transition: filter 0.2s ease, color 0.2s ease; + cursor: pointer; + } + + .db-conn-pass.blurred { + filter: blur(5px); + user-select: none; + } + + .db-conn-pass.blurred:hover { + filter: blur(3px); + } + + .db-access-actions { + display: flex; + gap: 8px; + flex-shrink: 0; + } + + .db-enterprise-modal { + width: 540px; + max-width: 95vw; + } + + .enterprise-modal-icon.db-setup-icon { + background: none; + width: auto; + height: auto; + } + + .enterprise-modal-icon.db-setup-icon::before { + display: none; + } + + .enterprise-modal-icon.db-setup-icon i { + display: none; + } + + .enterprise-modal-icon.db-setup-icon img { + display: block; + object-fit: contain; + } + + .db-setup-modal-body { + padding: 24px 28px 28px; + max-height: 60vh; + overflow-y: auto; + } + + .db-setup-modal-body .node-form-section { + margin-bottom: 24px; + } + + .db-setup-modal-body .node-form-section:last-child { + margin-bottom: 0; + } + + .db-type-selector { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 10px; + } + + .db-type-option { + cursor: pointer; + } + + .db-type-option input { + display: none; + } + + .db-type-card { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 8px; + padding: 16px 12px; + border-radius: 12px; + background: rgba(255, 255, 255, 0.03); + border: 2px solid rgba(255, 255, 255, 0.08); + transition: all 0.2s ease; + } + + .db-type-card i { + font-size: 24px; + color: var(--muted); + transition: color 0.2s ease; + } + + .db-type-card span { + font-size: 13px; + font-weight: 600; + color: rgba(255, 255, 255, 0.7); + } + + .db-type-option input:checked+.db-type-card { + background: rgba(99, 102, 241, 0.12); + border-color: rgba(99, 102, 241, 0.5); + } + + .db-type-option input:checked+.db-type-card i { + color: #a5b4fc; + } + + .db-type-option input:checked+.db-type-card span { + color: rgba(255, 255, 255, 0.95); + } + + .db-type-card:hover { + background: rgba(255, 255, 255, 0.05); + border-color: rgba(255, 255, 255, 0.15); + } + + .db-security-notice { + margin-top: 16px; + padding: 14px; + background: rgba(59, 130, 246, 0.08); + border-radius: 10px; + border: 1px solid rgba(59, 130, 246, 0.15); + } + + .db-security-notice-inner { + display: flex; + align-items: flex-start; + gap: 12px; + } + + .db-security-notice-inner>i { + font-size: 16px; + color: #3b82f6; + margin-top: 2px; + } + + .db-security-notice strong { + display: block; + font-size: 13px; + color: #60a5fa; + margin-bottom: 4px; + } + + .db-security-notice p { + font-size: 12px; + color: rgba(255, 255, 255, 0.6); + margin: 0; + line-height: 1.5; + } + + .db-user-modal { + width: 420px; + max-width: 95vw; + } + + .enterprise-modal-icon.db-user-icon { + background: none; + } + + .enterprise-modal-icon.db-user-icon::before { + display: none; + } + + .enterprise-modal-icon.db-user-icon i { + display: block; + font-size: 28px; + color: #6ee7b7; + } + + .db-pass-modal { + width: 420px; + max-width: 95vw; + } + + .db-change-type-modal { + width: 540px; + max-width: 95vw; + } + + .db-change-warning { + display: flex; + align-items: flex-start; + gap: 14px; + padding: 16px; + background: rgba(239, 68, 68, 0.1); + border-radius: 12px; + margin-bottom: 20px; + } + + .db-change-warning-icon { + width: 40px; + height: 40px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(239, 68, 68, 0.15); + color: #f87171; + font-size: 18px; + flex-shrink: 0; + } + + .db-change-warning-content strong { + display: block; + color: #f87171; + font-size: 14px; + margin-bottom: 6px; + } + + .db-change-warning-content p { + font-size: 13px; + color: rgba(255, 255, 255, 0.7); + margin: 0; + line-height: 1.5; + } + + .db-btn-danger { + background: linear-gradient(135deg, rgba(239, 68, 68, 0.9), rgba(220, 38, 38, 0.85)) !important; + } + + .db-btn-danger:hover { + background: linear-gradient(135deg, rgba(239, 68, 68, 1), rgba(220, 38, 38, 0.95)) !important; + } + + .db-pass-toggle { + right: 12px; + } + + @media (max-width: 600px) { + .db-type-selector { + grid-template-columns: 1fr; + } + + .db-enterprise-modal, + .db-change-type-modal { + width: 95vw; + } + + .db-access-url-box { + flex-direction: column; + align-items: stretch; + } + + .db-access-actions { + justify-content: flex-end; + } + + .db-users-header { + flex-direction: column; + align-items: stretch; + gap: 12px; + } + + .db-user-row { + flex-direction: column; + align-items: stretch; + gap: 12px; + } + + .db-user-actions { + justify-content: flex-end; + } + } + + .install-progress-container { + margin: 16px 0; + padding: 16px; + background: rgba(139, 92, 246, 0.08); + border-radius: 12px; + border: 1px solid rgba(139, 92, 246, 0.2); + } + + .install-progress-label { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 10px; + font-size: 13px; + } + + .install-progress-label span:first-child { + color: rgba(255, 255, 255, 0.9); + font-weight: 500; + } + + .install-progress-label span:last-child { + color: #a78bfa; + font-weight: 700; + } + + .install-progress-bar { + height: 8px; + background: rgba(255, 255, 255, 0.1); + border-radius: 4px; + overflow: hidden; + } + + .install-progress-fill { + height: 100%; + background: linear-gradient(90deg, #8b5cf6, #a78bfa, #c4b5fd); + border-radius: 4px; + transition: width 0.3s ease; + position: relative; + } + + .install-progress-fill::after { + content: ''; + position: absolute; + top: 0; + left: 0; + right: 0; + bottom: 0; + background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent); + animation: progressShine 1.5s infinite; + } + + @keyframes progressShine { + 0% { + transform: translateX(-100%); + } + + 100% { + transform: translateX(100%); + } + } + + .db-pass-toggle { + position: absolute !important; + right: 12px !important; + top: 50% !important; + transform: translateY(-50%) !important; + width: 32px !important; + height: 32px !important; + border-radius: 8px !important; + border: none !important; + background: transparent !important; + color: rgba(255, 255, 255, 0.4) !important; + cursor: pointer !important; + display: flex !important; + align-items: center !important; + justify-content: center !important; + z-index: 100 !important; + transition: all 0.2s ease !important; + } + + .db-pass-toggle:hover { + background: rgba(255, 255, 255, 0.1) !important; + color: rgba(255, 255, 255, 0.8) !important; + } + + .db-pass-toggle i { + font-size: 14px !important; + pointer-events: none !important; + } + + .qr-option-btn { + display: flex; + align-items: center; + gap: 14px; + width: 100%; + padding: 16px; + border-radius: 14px; + border: 1px solid rgba(255, 255, 255, 0.06); + background: rgba(255, 255, 255, 0.03); + color: rgba(255, 255, 255, 0.9); + cursor: pointer; + transition: all 0.25s ease; + text-align: left; + } + + .qr-option-btn:hover:not(:disabled) { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.1); + transform: none; + } + + .qr-option-btn:active:not(:disabled) { + transform: scale(0.99); + } + + .qr-option-icon { + width: 44px; + height: 44px; + border-radius: 12px; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + font-size: 18px; + color: white; + } + + .qr-option-content { + flex: 1; + min-width: 0; + } + + .qr-option-title { + font-size: 15px; + font-weight: 600; + margin-bottom: 4px; + } + + .qr-option-desc { + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + } + + .qr-options-modal { + width: 440px; + } + + .qr-reset-modal { + width: 460px; + } + + .stats-enterprise-modal { + width: 90vw !important; + height: 90vh !important; + max-width: 1400px !important; + max-height: 900px !important; + } + + .stats-icon { + background: transparent !important; + color: #a78bfa !important; + } + + .stats-icon::before { + display: none !important; + } + + .stats-icon i { + color: #a78bfa; + } + + .stats-modal-body { + flex: 1; + padding: 32px; + overflow-y: auto; + display: grid; + grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); + gap: 24px; + align-content: start; + } + + .stats-loading { + grid-column: 1 / -1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + height: 300px; + color: rgba(255, 255, 255, 0.5); + font-size: 15px; + } + + .stats-spinner { + width: 40px; + height: 40px; + border: 3px solid rgba(255, 255, 255, 0.1); + border-top-color: #a78bfa; + border-radius: 50%; + animation: stats-spin 0.8s linear infinite; + } + + @keyframes stats-spin { + to { + transform: rotate(360deg); + } + } + + .stats-offline { + grid-column: 1 / -1; + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 16px; + height: 300px; + color: rgba(255, 255, 255, 0.5); + } + + .stats-offline-icon { + width: 80px; + height: 80px; + border-radius: 50%; + background: rgba(239, 68, 68, 0.15); + display: flex; + align-items: center; + justify-content: center; + font-size: 32px; + color: #ef4444; + } + + .stats-offline-text { + font-size: 18px; + font-weight: 600; + color: #ef4444; + } + + .stats-offline-desc { + font-size: 14px; + color: rgba(255, 255, 255, 0.4); + } + + .stats-card { + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 16px; + padding: 24px; + display: flex; + flex-direction: column; + gap: 16px; + } + + .stats-card-header { + display: flex; + align-items: center; + justify-content: space-between; + } + + .stats-card-title { + display: flex; + align-items: center; + gap: 12px; + font-size: 15px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); + } + + .stats-card-icon { + width: 36px; + height: 36px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + font-size: 16px; + } + + .stats-card-icon.cpu { + background: rgba(59, 130, 246, 0.15); + color: #60a5fa; + } + + .stats-card-icon.ram { + background: rgba(16, 185, 129, 0.15); + color: #34d399; + } + + .stats-card-icon.disk { + background: rgba(245, 158, 11, 0.15); + color: #fbbf24; + } + + .stats-card-icon.info { + background: rgba(139, 92, 246, 0.15); + color: #a78bfa; + } + + .stats-card-value { + font-size: 28px; + font-weight: 700; + color: #fff; + } + + .stats-card-value.warning { + color: #fbbf24; + } + + .stats-card-value.critical { + color: #ef4444; + } + + .stats-progress-container { + display: flex; + flex-direction: column; + gap: 8px; + } + + .stats-progress-bar { + height: 12px; + background: rgba(255, 255, 255, 0.08); + border-radius: 6px; + overflow: hidden; + position: relative; + } + + .stats-progress-fill { + height: 100%; + border-radius: 6px; + transition: width 0.5s ease, background 0.3s ease; + position: relative; + } + + .stats-progress-fill.cpu { + background: linear-gradient(90deg, #3b82f6, #60a5fa); + } + + .stats-progress-fill.ram { + background: linear-gradient(90deg, #10b981, #34d399); + } + + .stats-progress-fill.disk { + background: linear-gradient(90deg, #f59e0b, #fbbf24); + } + + .stats-progress-fill.warning { + background: linear-gradient(90deg, #f59e0b, #fbbf24) !important; + } + + .stats-progress-fill.critical { + background: linear-gradient(90deg, #ef4444, #f87171) !important; + } + + .stats-progress-labels { + display: flex; + justify-content: space-between; + font-size: 13px; + color: rgba(255, 255, 255, 0.5); + } + + .stats-details { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 12px; + margin-top: 8px; + } + + .stats-detail-item { + display: flex; + flex-direction: column; + gap: 4px; + } + + .stats-detail-label { + font-size: 12px; + color: rgba(255, 255, 255, 0.4); + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .stats-detail-value { + font-size: 15px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); + } + + .stats-warnings { + grid-column: 1 / -1; + display: flex; + flex-direction: column; + gap: 12px; + } + + .stats-warning-item { + display: flex; + align-items: center; + gap: 14px; + padding: 16px 20px; + border-radius: 12px; + font-size: 14px; + font-weight: 500; + } + + .stats-warning-item.warning { + background: rgba(245, 158, 11, 0.12); + border: 1px solid rgba(245, 158, 11, 0.25); + color: #fbbf24; + } + + .stats-warning-item.critical { + background: rgba(239, 68, 68, 0.12); + border: 1px solid rgba(239, 68, 68, 0.25); + color: #f87171; + } + + .stats-warning-icon { + font-size: 18px; + } + + .stats-info-grid { + display: grid; + grid-template-columns: repeat(2, 1fr); + gap: 16px; + } + + .stats-info-item { + display: flex; + flex-direction: column; + gap: 6px; + } + + .stats-info-label { + font-size: 12px; + color: rgba(255, 255, 255, 0.4); + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .stats-info-value { + font-size: 15px; + font-weight: 600; + color: rgba(255, 255, 255, 0.9); + } + + .stats-last-updated { + grid-column: 1 / -1; + text-align: center; + font-size: 13px; + color: rgba(255, 255, 255, 0.35); + padding-top: 16px; + border-top: 1px solid rgba(255, 255, 255, 0.05); + } + + @media (max-width: 768px) { + .stats-enterprise-modal { + width: 95vw !important; + height: 95vh !important; + border-radius: 16px; + } + + .stats-modal-body { + padding: 20px; + grid-template-columns: 1fr; + } + } + + .qa-subgroup { + margin-bottom: 4px; + } + + .qa-subgroup-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 12px; + } + + .qa-subgroup-title { + font-weight: 600; + font-size: 14px; + color: var(--muted); + text-transform: uppercase; + letter-spacing: 0.5px; + } + + .qa-separator { + height: 1px; + background: rgba(15, 23, 42, 0.08); + margin: 24px 0; + } + + [data-theme="dark"] .qa-separator { + background: rgba(255, 255, 255, 0.08); + } + + .btn-sm { + padding: 6px 12px; + font-size: 13px; + border-radius: 8px; + } + + .webhooks-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 20px; + } + + .webhooks-title { + font-size: 20px; + font-weight: 700; + } + + .webhooks-subtitle { + color: var(--muted); + font-size: 14px; + margin-top: 2px; + } + + .webhooks-mode-selector { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 12px; + margin-bottom: 24px; + } + + .webhook-mode-tab { + position: relative; + display: flex; + align-items: center; + gap: 14px; + padding: 16px 18px; + border-radius: 12px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.03); + color: var(--text); + cursor: pointer; + transition: all 0.2s ease; + text-align: left; + font-family: inherit; + font-size: 14px; + overflow: hidden; + } + + .webhook-mode-tab:hover { + background: rgba(255, 255, 255, 0.05); + border-color: transparent; + } + + .webhook-mode-tab::before { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + padding: 1px; + background: + linear-gradient(90deg, #a5b4fc 50%, transparent 50%) top repeat-x, + linear-gradient(90deg, #a5b4fc 50%, transparent 50%) bottom repeat-x, + linear-gradient(0deg, #a5b4fc 50%, transparent 50%) left repeat-y, + linear-gradient(0deg, #a5b4fc 50%, transparent 50%) right repeat-y; + background-size: 20px 1px, 20px 1px, 1px 20px, 1px 20px; + background-position: 0 0, 0 100%, 0 0, 100% 0; + -webkit-mask: + linear-gradient(#fff 0 0) content-box, + linear-gradient(#fff 0 0); + -webkit-mask-composite: xor; + mask-composite: exclude; + animation: borderMoving 4s linear infinite; + opacity: 0; + transition: opacity 0.3s ease; + pointer-events: none; + } + + .webhook-mode-tab:hover::before { + opacity: 1; + } + + @keyframes borderMoving { + 0% { + background-position: 0 0, 0 100%, 0 0, 100% 0; + } + + 100% { + background-position: 20px 0, -20px 100%, 0 -20px, 100% 20px; + } + } + + + .webhook-mode-tab.active { + border-color: rgba(99, 102, 241, 0.5); + background: rgba(99, 102, 241, 0.08); + } + + .webhook-mode-tab>i { + font-size: 20px; + color: var(--muted); + min-width: 24px; + text-align: center; + } + + .webhook-mode-tab.active>i { + color: #a5b4fc; + } + + .webhook-mode-title { + font-weight: 600; + font-size: 14px; + } + + .webhook-mode-desc { + color: var(--muted); + font-size: 12px; + margin-top: 2px; + } + + .webhooks-list { + display: flex; + flex-direction: column; + gap: 10px; + } + + .webhooks-empty { + text-align: center; + padding: 40px 20px; + color: var(--muted); + } + + .webhooks-empty i { + font-size: 36px; + margin-bottom: 12px; + opacity: 0.3; + display: block; + } + + .webhooks-empty p { + font-size: 15px; + font-weight: 600; + margin: 0 0 4px; + } + + .webhooks-empty small { + font-size: 13px; + opacity: 0.7; + } + + .webhook-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 12px; + transition: all 0.2s ease; + } + + .webhook-item:hover { + border-color: rgba(255, 255, 255, 0.12); + background: rgba(255, 255, 255, 0.05); + } + + .webhook-item-left { + display: flex; + align-items: center; + gap: 12px; + min-width: 0; + flex: 1; + } + + .webhook-item-icon { + width: 38px; + height: 38px; + border-radius: 10px; + background: rgba(88, 101, 242, 0.15); + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + } + + .webhook-item-icon i { + color: #5865f2; + font-size: 16px; + } + + .webhook-item-info { + min-width: 0; + } + + .webhook-item-label { + font-weight: 600; + font-size: 14px; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + } + + .webhook-item-url { + color: var(--muted); + font-size: 12px; + font-family: 'SF Mono', Monaco, 'Cascadia Code', monospace; + white-space: nowrap; + overflow: hidden; + text-overflow: ellipsis; + max-width: 320px; + } + + .webhook-item-actions { + display: flex; + align-items: center; + gap: 6px; + flex-shrink: 0; + } + + .webhook-action-btn { + width: 34px; + height: 34px; + border-radius: 8px; + border: none; + background: rgba(255, 255, 255, 0.05); + color: var(--muted); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + transition: all 0.2s ease; + font-size: 13px; + } + + .webhook-action-btn:hover { + background: rgba(255, 255, 255, 0.1); + color: var(--text); + } + + .webhook-action-btn.danger:hover { + background: rgba(239, 68, 68, 0.15); + color: #f87171; + } + + .webhook-action-btn.test:hover { + background: rgba(34, 197, 94, 0.15); + color: #34d399; + } + + .webhook-categories-grid { + display: flex; + flex-direction: column; + gap: 10px; + } + + .webhook-category-card { + display: flex; + align-items: center; + justify-content: space-between; + padding: 14px 16px; + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 12px; + transition: all 0.2s ease; + } + + .webhook-category-card:hover { + border-color: rgba(255, 255, 255, 0.12); + } + + .webhook-category-left { + display: flex; + align-items: center; + gap: 12px; + } + + .webhook-category-icon { + width: 38px; + height: 38px; + border-radius: 10px; + display: flex; + align-items: center; + justify-content: center; + flex-shrink: 0; + font-size: 15px; + } + + .webhook-category-name { + font-weight: 600; + font-size: 14px; + } + + .webhook-category-desc { + color: var(--muted); + font-size: 12px; + margin-top: 2px; + } + + .webhook-category-right { + display: flex; + align-items: center; + gap: 8px; + } + + .webhook-category-status { + font-size: 12px; + color: var(--muted); + padding: 4px 10px; + border-radius: 6px; + background: rgba(255, 255, 255, 0.04); + } + + .webhook-category-status.active { + color: #34d399; + background: rgba(34, 197, 94, 0.1); + } + + .webhook-category-btn { + padding: 7px 14px; + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.04); + color: var(--text); + cursor: pointer; + font-size: 13px; + font-family: inherit; + transition: all 0.2s ease; + } + + .webhook-category-btn:hover { + background: rgba(255, 255, 255, 0.08); + border-color: rgba(255, 255, 255, 0.2); + } + + @media (max-width: 768px) { + .webhooks-mode-selector { + grid-template-columns: 1fr; + } + + .webhook-item-url { + max-width: 180px; + } + } + + .panelinfo-header { + display: flex; + justify-content: space-between; + align-items: center; + margin-bottom: 20px; + } + + .panelinfo-title { + font-size: 20px; + font-weight: 700; + } + + .panelinfo-subtitle { + color: var(--muted); + font-size: 14px; + margin-top: 2px; + } + + .panelinfo-content { + display: flex; + flex-direction: column; + gap: 20px; + } + + .panelinfo-card { + background: rgba(255, 255, 255, 0.03); + border: 1px solid rgba(255, 255, 255, 0.06); + border-radius: 14px; + transition: border-color 0.2s ease; + } + + .panelinfo-card:hover { + border-color: rgba(255, 255, 255, 0.1); + } + + .panelinfo-card-inner { + padding: 20px 24px; + display: flex; + flex-direction: column; + gap: 16px; + } + + .panelinfo-row { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + } + + .panelinfo-label { + display: flex; + align-items: center; + gap: 10px; + font-size: 14px; + font-weight: 600; + color: rgba(255, 255, 255, 0.8); + flex-shrink: 0; + } + + .panelinfo-label i { + font-size: 15px; + color: rgba(255, 255, 255, 0.45); + width: 20px; + text-align: center; + } + + .panelinfo-value-group { + display: flex; + align-items: center; + gap: 8px; + flex-shrink: 0; + } + + .panelinfo-value code { + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Consolas', monospace; + font-size: 14px; + font-weight: 600; + color: #a5b4fc; + background: rgba(99, 102, 241, 0.12); + padding: 4px 12px; + border-radius: 8px; + border: 1px solid rgba(99, 102, 241, 0.15); + letter-spacing: 0.3px; + white-space: nowrap; + } + + .panelinfo-copy-btn { + width: 30px; + height: 30px; + border-radius: 8px; + border: 1px solid rgba(255, 255, 255, 0.08); + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.4); + cursor: pointer; + display: flex; + align-items: center; + justify-content: center; + font-size: 12px; + transition: all 0.2s ease; + flex-shrink: 0; + position: relative; + } + + .panelinfo-copy-btn:hover { + background: rgba(255, 255, 255, 0.08); + color: rgba(255, 255, 255, 0.8); + border-color: rgba(255, 255, 255, 0.15); + } + + .panelinfo-copy-btn.copied { + color: #34d399; + background: rgba(34, 197, 94, 0.1); + border-color: rgba(255, 255, 255, 0.08); + } + + .panelinfo-copy-btn.copied::before { + content: "Copied!"; + position: absolute; + bottom: 100%; + left: 50%; + transform: translateX(-50%) translateY(-8px); + background: #1f2937; + color: #fff; + padding: 4px 8px; + border-radius: 4px; + font-size: 11px; + font-weight: 600; + white-space: nowrap; + pointer-events: none; + opacity: 0; + animation: tooltipFadeIn 0.2s ease forwards; + border: 1px solid rgba(255, 255, 255, 0.1); + box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06); + z-index: 99999; + } + + .panelinfo-copy-btn.copied::after { + content: ""; + position: absolute; + bottom: 100%; + left: 50%; + transform: translateX(-50%) translateY(-4px); + border-width: 4px; + border-style: solid; + border-color: #1f2937 transparent transparent transparent; + opacity: 0; + animation: tooltipFadeIn 0.2s ease forwards; + z-index: 99999; + } + + @keyframes tooltipFadeIn { + from { + opacity: 0; + transform: translateX(-50%) translateY(-4px); + } + + to { + opacity: 1; + transform: translateX(-50%) translateY(-8px); + } + } + + .panelinfo-actions-row { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + flex-wrap: wrap; + } + + .panelinfo-update-section { + display: flex; + flex-direction: column; + gap: 10px; + flex-shrink: 0; + } + + .panelinfo-manual-section { + display: flex; + flex-direction: column; + gap: 10px; + flex-shrink: 0; + } + + .panelinfo-manual-input-group { + display: flex; + align-items: center; + gap: 8px; + } + + .panelinfo-manual-input { + width: 140px; + padding: 9px 14px; + border-radius: 10px; + border: 1px solid rgba(255, 255, 255, 0.1); + background: rgba(255, 255, 255, 0.04); + color: rgba(255, 255, 255, 0.9); + font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Consolas', monospace; + font-size: 13px; + font-weight: 500; + outline: none; + transition: all 0.2s ease; + } + + .panelinfo-manual-input::placeholder { + color: rgba(255, 255, 255, 0.3); + } + + .panelinfo-manual-input:focus { + border-color: rgba(139, 92, 246, 0.5); + background: rgba(255, 255, 255, 0.06); + box-shadow: 0 0 0 2px rgba(139, 92, 246, 0.1); + } + + .btn-manual-install { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 9px 16px; + border-radius: 10px; + border: none; + background: linear-gradient(135deg, #8b5cf6, #7c3aed); + color: #fff; + font-size: 13px; + font-weight: 600; + font-family: inherit; + cursor: pointer; + transition: all 0.25s ease; + box-shadow: 0 1px 4px rgba(124, 58, 237, 0.15); + white-space: nowrap; + } + + .btn-manual-install:hover:not(:disabled) { + transform: none; + box-shadow: 0 2px 6px rgba(124, 58, 237, 0.2); + background: linear-gradient(135deg, #a78bfa, #8b5cf6); + } + + .btn-manual-install:active:not(:disabled) { + transform: scale(0.98); + } + + .btn-manual-install:disabled { + opacity: 0.6; + cursor: not-allowed; + } + + .panelinfo-manual-label { + font-size: 12px; + font-weight: 500; + color: rgba(255, 255, 255, 0.45); + letter-spacing: 0.3px; + } + + .btn-update-check { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 20px; + border-radius: 10px; + border: none; + background: linear-gradient(135deg, #3b82f6, #2563eb); + color: #fff; + font-size: 14px; + font-weight: 600; + font-family: inherit; + cursor: pointer; + transition: all 0.25s ease; + box-shadow: 0 1px 4px rgba(37, 99, 235, 0.15); + white-space: nowrap; + } + + .btn-update-check:hover:not(:disabled) { + transform: none; + box-shadow: 0 2px 6px rgba(37, 99, 235, 0.2); + background: linear-gradient(135deg, #60a5fa, #3b82f6); + } + + .btn-update-check:active:not(:disabled) { + transform: scale(0.98); + } + + .btn-update-check:disabled { + opacity: 0.6; + cursor: not-allowed; + } + + .btn-auto-update { + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + padding: 9px 16px; + border-radius: 10px; + border: none; + color: #fff; + font-size: 13px; + font-weight: 600; + font-family: inherit; + cursor: pointer; + transition: all 0.2s ease; + white-space: nowrap; + box-shadow: 0 1px 4px rgba(15, 23, 42, 0.18); + } + + .btn-auto-update.enabled { + background: linear-gradient(135deg, #10b981, #059669); + } + + .btn-auto-update.enabled:hover:not(:disabled) { + background: linear-gradient(135deg, #34d399, #10b981); + transform: none; + } + + .btn-auto-update.disabled { + background: linear-gradient(135deg, #64748b, #475569); + } + + .btn-auto-update.disabled:hover:not(:disabled) { + background: linear-gradient(135deg, #94a3b8, #64748b); + transform: none; + } + + .btn-auto-update:active:not(:disabled) { + transform: scale(0.98); + } + + .btn-auto-update:disabled { + opacity: 0.7; + cursor: not-allowed; + } + + .btn-update-check .fa-arrows-rotate.spinning { + animation: spin-once 0.8s ease-in-out; + } + + @keyframes spin-once { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } + } + + @keyframes spin-continuous { + 0% { + transform: rotate(0deg); + } + + 100% { + transform: rotate(360deg); + } + } + + .btn-update-install { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 20px; + border-radius: 10px; + border: none; + background: linear-gradient(135deg, #10b981, #059669); + color: #fff; + font-size: 14px; + font-weight: 600; + font-family: inherit; + cursor: pointer; + transition: all 0.25s ease; + box-shadow: 0 1px 4px rgba(5, 150, 105, 0.15); + white-space: nowrap; + } + + .btn-update-install:hover:not(:disabled) { + transform: scale(1.01); + box-shadow: 0 2px 6px rgba(5, 150, 105, 0.2); + background: linear-gradient(135deg, #34d399, #10b981); + } + + .btn-update-install:active:not(:disabled) { + transform: scale(0.98); + } + + .btn-update-install:disabled { + opacity: 0.6; + cursor: not-allowed; + } + + .btn-update-installing { + display: inline-flex; + align-items: center; + gap: 8px; + padding: 10px 20px; + border-radius: 10px; + border: none; + background: linear-gradient(135deg, #f59e0b, #d97706); + color: #fff; + font-size: 14px; + font-weight: 600; + font-family: inherit; + cursor: not-allowed; + opacity: 0.9; + white-space: nowrap; + } + + .btn-update-installing .fa-spinner { + animation: spin-continuous 1s linear infinite; + } + + .panelinfo-update-status { + font-size: 13px; + color: rgba(255, 255, 255, 0.7); + min-height: 20px; + padding: 0 4px; + line-height: 1.5; + } + + .panelinfo-update-status.success { + color: #34d399; + } + + .panelinfo-update-status.error { + color: #f87171; + } + + .panelinfo-update-status.info { + color: #60a5fa; + } + + @media (max-width: 768px) { + .panelinfo-row { + flex-direction: column; + align-items: flex-start; + gap: 8px; + } + + .panelinfo-actions-row { + flex-direction: column; + } + + .panelinfo-manual-input { + width: 120px; + } + } + + + + + .glass-card { + background: rgba(255, 255, 255, 0.08); + border-radius: 24px; + overflow: hidden; + margin-bottom: 24px; + border: 1px solid rgba(255, 255, 255, 0.08); + } + + .glass-card:hover { + background: rgba(255, 255, 255, 0.10); + } + + + .color-picker-row { + display: grid; + grid-template-columns: 48px 1fr auto; + align-items: center; + gap: 16px; + width: 100%; + } + + .upload-row { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + } + + .upload-row .glass-input { + flex: 1; + min-width: 0; + } + + .btn-glass, + .glass-input { + height: 48px; + box-sizing: border-box; + } + + + .glass-card-inner { + padding: 0; + } + + .glass-card-header { + display: grid; + grid-template-columns: 48px 1fr; + grid-template-rows: auto auto; + gap: 2px 16px; + align-items: center; + padding: 24px 32px; + } + + .glass-card-title { + display: contents; + } + + .background-title { + display: flex; + align-items: center; + gap: 16px; + grid-column: 1 / -1; + } + + .background-title i { + color: var(--accent); + font-size: 28px; + width: 48px; + height: 48px; + min-width: 48px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(124, 58, 237, 0.12); + border-radius: 14px; + align-self: center; + } + + .background-title span { + font-size: 20px; + font-weight: 700; + color: #fff; + letter-spacing: -0.02em; + align-self: center; + } + + .glass-card-title i { + grid-row: 1 / -1; + color: var(--accent); + font-size: 28px; + width: 48px; + height: 48px; + min-width: 48px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(124, 58, 237, 0.12); + border-radius: 14px; + align-self: center; + } + + .glass-card-title span { + font-size: 20px; + font-weight: 700; + color: #fff; + letter-spacing: -0.02em; + align-self: center; + } + + .glass-card-header:has(.glass-card-subtitle) .glass-card-title span { + align-self: end; + } + + .glass-card-subtitle { + grid-column: 2; + font-size: 14px; + color: rgba(255, 255, 255, 0.4); + font-weight: 500; + margin: 0; + align-self: start; + } + + .bg-section-grid { + display: grid; + grid-template-columns: 360px 1fr; + gap: 48px; + padding: 0 32px 32px 32px; + } + + .bg-preview-wrapper { + min-width: 0; + } + + #bgPreview { + height: 200px; + width: 100%; + border-radius: 16px; + background: rgba(0, 0, 0, 0.2); + } + + .bg-controls-wrapper { + display: flex; + flex-direction: column; + gap: 32px; + padding-top: 10px; + } + + .control-group label { + display: block; + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.1em; + color: rgba(255, 255, 255, 0.3); + margin-bottom: 14px; + } + + .color-picker-row { + display: grid; + grid-template-columns: 140px 1fr auto; + align-items: center; + gap: 16px; + position: relative; + } + + .upload-row { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + } + + .upload-row input[type="file"] { + display: none; + } + + .glass-input { + background: rgba(0, 0, 0, 0.2); + border: none; + color: #fff; + padding: 14px 20px; + border-radius: 12px; + font-family: inherit; + font-size: 14px; + font-weight: 500; + outline: none; + width: 100%; + box-shadow: none; + } + + .glass-input:focus { + background: rgba(0, 0, 0, 0.35); + } + + .btn-glass { + background: rgba(255, 255, 255, 0.08); + border: none; + color: #fff; + padding: 0 24px; + border-radius: 12px; + font-weight: 600; + font-size: 14px; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 10px; + box-shadow: none; + height: 48px; + box-sizing: border-box; + flex-shrink: 0; + white-space: nowrap; + } + + .btn-glass:hover { + background: var(--accent); + } + + .btn-glass:active { + opacity: 0.8; + } + + .btn-upload { + appearance: none; + -webkit-appearance: none; + background: rgba(255, 255, 255, 0.08); + border: none; + color: #fff; + padding: 0 20px; + border-radius: 12px; + font-family: inherit; + font-weight: 600; + font-size: 14px; + line-height: 48px; + height: 48px; + box-sizing: border-box; + cursor: pointer; + display: inline-flex; + align-items: center; + justify-content: center; + gap: 8px; + flex-shrink: 0; + white-space: nowrap; + box-shadow: none; + outline: none; + vertical-align: middle; + } + + .btn-upload:hover { + background: var(--accent); + } + + .btn-upload:active { + opacity: 0.8; + } + + .color-dot { + width: 48px; + height: 48px; + border-radius: 50%; + cursor: pointer; + justify-self: start; + flex-shrink: 0; + box-shadow: + inset 0 0 0 2px rgba(0, 0, 0, 0.2), + 0 0 0 2px rgba(255, 255, 255, 0.15); + } + + .color-dot:hover { + transform: scale(1.05); + } + + #colorPicker { + width: 48px; + height: 48px; + opacity: 0; + position: absolute; + cursor: pointer; + } + + .color-picker-wrapper { + position: relative; + display: flex; + align-items: center; + width: 48px; + } + + + + .upload-row .glass-input { + flex: 1; + min-width: 0; + } + + .thumbs-section { + padding: 0 32px 32px 32px; + } + + .thumbs-title { + font-size: 11px; + font-weight: 700; + text-transform: uppercase; + letter-spacing: 0.1em; + color: rgba(255, 255, 255, 0.3); + margin-bottom: 20px; + text-align: center; + } + + .thumbs { + display: flex; + flex-wrap: wrap; + justify-content: center; + gap: 20px; + } + + .thumb { + height: 70px; + width: 100px; + border-radius: 12px; + overflow: hidden; + border: none; + cursor: pointer; + transition: all 0.3s ease; + opacity: 0.5; + filter: grayscale(40%); + } + + .thumb:hover { + opacity: 0.8; + transform: scale(1.05); + filter: grayscale(0%); + } + + .thumb.selected { + opacity: 1; + transform: scale(1.1); + filter: grayscale(0%); + box-shadow: none; + outline: none; + position: relative; + } + + .thumb.selected::after { + content: ''; + position: absolute; + inset: 0; + background: rgba(255, 255, 255, 0.1); + pointer-events: none; + } + + .note { + padding: 0 32px 24px 32px; + font-size: 13px; + color: rgba(255, 255, 255, 0.3); + font-style: italic; + margin-top: -10px; + text-align: center; + } + + .saved-bg-value { + padding: 24px 32px; + font-family: monospace; + color: #a5b4fc; + font-size: 14px; + background: rgba(0, 0, 0, 0.2); + margin: 0 32px 32px 32px; + border-radius: 12px; + } + + @media (max-width: 900px) { + .bg-section-grid { + grid-template-columns: 1fr; + gap: 32px; + } + } + + .glass-card { + background: rgba(255, 255, 255, 0.08); + border: 1px solid rgba(255, 255, 255, 0.08); + } + + .glass-card:hover { + background: rgba(255, 255, 255, 0.10); + } + + .glass-card-title { + display: contents; + } + + .glass-card-title i { + grid-row: 1 / -1; + font-size: 28px; + width: 48px; + height: 48px; + min-width: 48px; + display: flex; + align-items: center; + justify-content: center; + background: rgba(124, 58, 237, 0.12); + border-radius: 14px; + align-self: center; + } + + .glass-card-title span { + font-size: 20px; + font-weight: 700; + color: #fff; + letter-spacing: -0.02em; + align-self: center; + } + + .glass-card-header:has(.glass-card-subtitle) .glass-card-title span { + align-self: end; + } + + .bg-controls-wrapper { + width: 100%; + } + + .control-group { + width: 100%; + } + + .color-picker-row { + display: grid; + grid-template-columns: 48px 1fr auto; + align-items: center; + gap: 16px; + width: 100%; + } + + .color-dot { + cursor: pointer; + flex-shrink: 0; + box-shadow: + inset 0 0 0 2px rgba(0, 0, 0, 0.2), + 0 0 0 2px rgba(255, 255, 255, 0.15); + } + + .color-dot:active { + transform: scale(0.95); + } + + .upload-row { + display: flex; + align-items: center; + gap: 12px; + width: 100%; + } + + .upload-row .glass-input { + flex: 1; + min-width: 0; + } + + #hexInput, + #urlInput { + text-align: center; + font-weight: 600; + letter-spacing: 0.5px; + } + + .btn-glass, + .glass-input { + height: 48px; + box-sizing: border-box; + } + .alert-enterprise-modal { + width: 620px; + } + + .alert-schedule-grid input[type="datetime-local"] { + padding-right: 44px; + } diff --git a/public/style.css b/public/style.css new file mode 100644 index 0000000..9a85e06 --- /dev/null +++ b/public/style.css @@ -0,0 +1,579 @@ +body { + background: url("https://cdn.pixabay.com/photo/2024/07/19/08/16/waves-8905720_1280.png") center/cover no-repeat; +} + +:root { + --bg-1: linear-gradient(180deg, #0f1724 0%, #0b1020 100%); + --muted: #9aa4b2; + --accent: #61dafb; + --accent-2: #7c5cff; + --glass: rgba(255, 255, 255, 0.03); + --panel-radius: 14px; + --dock-height: 62px; + --dock-icon-size: 36px; + --ui-scale: 1; + --console-width: min(1100px, 92vw); + --console-height: min(42vh, 540px); + font-family: Inter, ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial; +} + +html, +body { + height: 100%; + margin: 0; + color: #e6eef8; + -webkit-font-smoothing: antialiased; + -moz-osx-font-smoothing: grayscale +} + +.app-wrap { + display: flex; + flex-direction: column; + min-height: 100vh; + gap: 14px; + padding: 12px 16px 120px 16px; + box-sizing: border-box; + align-items: center; +} + +.topbar { + width: 100%; + max-width: calc(var(--console-width) + 120px); + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-bottom: 6px +} + +.brand { + display: flex; + align-items: center; + gap: 6px +} + +.brand .logo { + width: 68px; + height: 68px; + border-radius: 12px; + background: linear-gradient(135deg, var(--accent), var(--accent-2)); + display: flex; + align-items: center; + justify-content: center; + font-weight: 800; + color: #061126; + box-shadow: 0 10px 36px rgba(92, 40, 182, 0.12); + font-size: 28px +} + +.top-actions { + display: flex; + gap: 8px; + align-items: center +} + +.icon-btn { + background: var(--glass); + border: 1px solid rgba(255, 255, 255, 0.03); + padding: 8px; + border-radius: 10px; + cursor: pointer; + display: inline-flex; + align-items: center; + gap: 8px; + color: var(--muted); + font-weight: 600; + font-size: 13px +} + +.icon-btn:hover { + transform: translateY(-3px); + box-shadow: 0 10px 30px rgba(2, 6, 23, 0.5) +} + +.topbar .icon-btn { + position: relative; + background: transparent !important; + border-color: transparent !important; + z-index: 1; +} + +.topbar .icon-btn::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; +} + +.topbar .icon-btn:hover { + transform: none !important; + background: transparent !important; + box-shadow: none; +} + +.topbar .icon-btn:hover::before { + transform: scale(1.04); + background: rgba(255, 255, 255, 0.10); + box-shadow: 0 10px 30px rgba(2, 6, 23, 0.5); +} + +.main-stage { + display: flex; + gap: 20px; + width: 100%; + max-width: calc(var(--console-width) + 120px); + align-items: flex-start; + justify-content: center +} + +.console-panel { + width: var(--console-width); + min-width: 440px; + max-width: calc(var(--console-width)); + transform-origin: top left; + transform: scale(var(--ui-scale)); + transition: transform 160ms ease; + margin-left: -4%; + margin-top: 6px +} + +.console-window { + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0.01)); + border-radius: 12px; + padding: 12px; + box-shadow: 0 10px 30px rgba(2, 6, 23, 0.6); + border: 1px solid rgba(255, 255, 255, 0.03) +} + +.controls { + display: flex; + gap: 8px; + align-items: center; + margin-bottom: 10px +} + +select#scriptSelect { + padding: 9px 32px 9px 12px; + border-radius: 12px; + background: #0e1116; + color: #fff; + border: 1px solid rgba(255, 255, 255, 0.06); + min-width: 200px; + font-size: 13px; + appearance: none; + -webkit-appearance: none; + -moz-appearance: none; + background-image: url("data:image/svg+xml;charset=UTF-8,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='white' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'%3e%3cpolyline points='6 9 12 15 18 9'%3e%3c/polyline%3e%3c/svg%3e"); + background-repeat: no-repeat; + background-position: right 10px center; + background-size: 14px; + cursor: pointer; + transition: all .15s ease +} + +select#scriptSelect:hover { + border-color: rgba(255, 255, 255, 0.15); + background-color: #13171e +} + +.run-button, +.stop-button { + padding: 8px 10px; + border-radius: 10px; + border: none; + display: inline-flex; + align-items: center; + justify-content: center; + cursor: pointer; + font-size: 14px +} + +.run-button { + background: linear-gradient(90deg, #14b8a6, #10b981); + color: white +} + +.stop-button { + background: linear-gradient(90deg, #ef4444, #f97316); + color: white +} + +.window-header { + display: flex; + align-items: center; + justify-content: space-between; + margin-bottom: 8px; + color: var(--muted) +} + +.window-controls { + display: flex; + gap: 8px; + align-items: center +} + +.dot { + width: 11px; + height: 11px; + border-radius: 50%; + display: inline-block +} + +#console { + background: #0f1720; + color: #9ae6b4; + padding: 12px; + border-radius: 10px; + font-family: "Courier New", monospace; + font-size: 13px; + line-height: 1.45; + height: var(--console-height); + overflow: auto; + border: 1px solid rgba(255, 255, 255, 0.02); + box-sizing: border-box; +} + +.cmd-row { + display: flex; + align-items: center; + gap: 8px; + margin-top: 10px +} + +#cmdInput { + flex: 1; + padding: 10px; + border-radius: 10px; + background: #0e1116; + border: 1px solid rgba(255, 255, 255, 0.02); + color: #cbd5e1; + font-size: 13px +} + +.modal-overlay { + position: fixed; + inset: 0; + background: rgba(2, 6, 23, 0.72); + display: none; + align-items: center; + justify-content: center; + z-index: 10000; + backdrop-filter: blur(6px) +} + +.modal-overlay.show { + display: flex +} + +.modal { + width: 1100px; + max-width: 96vw; + background: #071218; + border-radius: 12px; + padding: 14px; + border: 1px solid rgba(255, 255, 255, 0.06); + box-shadow: 0 28px 80px rgba(2, 6, 23, 0.72); + color: var(--muted) +} + +.modal-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + margin-bottom: 12px +} + +.modal-title { + font-weight: 700; + color: #fff +} + +.modal-close { + background: transparent; + border: 0; + color: var(--muted); + font-size: 18px; + cursor: pointer +} + +.modal-body { + display: flex; + gap: 12px +} + +.modal-left { + width: 40%; + min-height: 300px +} + +.modal-right { + width: 60% +} + +.modal.file-open .modal-right { + width: 70% +} + +.editor-modal .modal { + width: 92vw; + max-width: 1360px; + height: 88vh; + display: flex; + flex-direction: column; + padding: 12px +} + +.editor-header { + display: flex; + justify-content: space-between; + align-items: center; + gap: 12px; + margin-bottom: 10px; + color: var(--muted) +} + +.editor-title { + font-weight: 700; + color: #fff +} + +.editor-actions { + display: flex; + gap: 8px +} + +#entries { + list-style: none; + padding: 0; + margin: 0; + display: flex; + flex-direction: column; + gap: 8px; + height: 58vh; + overflow: auto +} + +#entries li { + display: flex; + align-items: center; + justify-content: space-between; + padding: 10px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.02); + cursor: pointer; + transition: all .12s +} + +#entries li:hover { + transform: scale(1.03); + box-shadow: 0 8px 30px rgba(2, 6, 23, 0.4) +} + +.entry-left { + display: flex; + align-items: center; + gap: 12px +} + +.entry-icon { + width: 42px; + height: 42px; + border-radius: 10px; + background: rgba(255, 255, 255, 0.02); + display: flex; + align-items: center; + justify-content: center +} + +.entry-name { + font-weight: 700; + color: #fff +} + +.entry-meta { + color: var(--muted); + font-size: 12px +} + +.entry-actions button { + background: transparent; + border: 1px solid rgba(255, 255, 255, 0.03); + padding: 6px 8px; + border-radius: 8px; + color: var(--muted); + cursor: pointer; + font-size: 13px +} + +.entry-actions button:hover { + color: #fff; + border-color: rgba(255, 255, 255, 0.06) +} + +#bigEditor { + flex: 1; + display: flex; + flex-direction: column; + gap: 8px; + background: #071219; + border-radius: 10px; + padding: 12px; + overflow: auto +} + +#bigEditor .code-area { + flex: 1; + display: block; + border-radius: 8px; + padding: 12px; + background: #021018; + overflow: auto; + color: #dbeafe; + font-family: monospace; + font-size: 14px; + white-space: pre; + outline: none +} + +#bigEditor textarea { + width: 100%; + height: 100%; + background: #021018; + border: none; + color: #dbeafe; + padding: 12px; + border-radius: 6px; + font-family: monospace; + font-size: 14px; + resize: none; + box-sizing: border-box +} + +.kw { + color: #82aaff; + font-weight: 700 +} + +.fn { + color: #ffd580; + font-weight: 700 +} + +.cls { + color: #b6e3ff; + font-weight: 700 +} + +.str { + color: #9ae6b4 +} + +.com { + color: #6b7280; + font-style: italic +} + +.num { + color: #f0a9ff +} + +.task-modal .modal { + width: 520px +} + +.dock-wrap { + position: fixed; + left: 50%; + transform: translateX(-50%); + bottom: 12px; + z-index: 2200; + width: 450px; +} + +.dock { + display: flex; + align-items: center; + gap: 12px; + padding: 8px 12px; + border-radius: 999px; + background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), rgba(255, 255, 255, 0.01)); + backdrop-filter: blur(6px); + box-shadow: 0 18px 40px rgba(2, 6, 23, 0.55); + border: 1px solid rgba(255, 255, 255, 0.03) +} + +.dock .dock-item { + display: flex; + flex-direction: column; + align-items: center; + gap: 6px; + padding: 6px; + border-radius: 10px; + cursor: pointer; + transition: transform .12s, box-shadow .12s +} + +.dock .dock-item:hover { + transform: translateY(-6px); + box-shadow: 0 16px 30px rgba(2, 6, 23, 0.45) +} + +.dock .dock-item .icon { + width: var(--dock-icon-size); + height: var(--dock-icon-size); + border-radius: 8px; + display: flex; + align-items: center; + justify-content: center; + background: linear-gradient(135deg, #0f1724, rgba(255, 255, 255, 0.02)); + color: var(--accent); + font-size: 16px +} + +.dock .dock-item .label { + font-size: 11px; + color: var(--muted); + margin-top: 2px +} + +.dock .sep { + width: 1px; + height: 36px; + background: rgba(255, 255, 255, 0.04); + margin: 0 6px; + border-radius: 2px; +} + +input[type=file] { + display: none +} + +@media (max-width:1100px) { + .main-stage { + flex-direction: column; + align-items: center + } + + .console-panel { + width: 92% + } +} + +@media (max-width:640px) { + .brand .logo { + width: 56px; + height: 56px + } + + .modal { + width: 94vw + } +} \ No newline at end of file diff --git a/quick-actions.json b/quick-actions.json new file mode 100644 index 0000000..21cda01 --- /dev/null +++ b/quick-actions.json @@ -0,0 +1,52 @@ +{ + "admin": [ + { + "id": "default-1", + "title": "Manage account", + "link": "/settings?panel=account", + "icon": "fa-solid fa-user", + "animation": "scale", + "newTab": false, + "scaleValue": 1.05 + }, + { + "id": "default-2", + "title": "Manage servers", + "link": "/settings?panel=servers", + "icon": "fa-solid fa-bars-progress", + "animation": "scale", + "newTab": false, + "scaleValue": 1.05 + }, + { + "id": "default-3", + "title": "ADPanel Github", + "link": "https://github.com/antonndev/ADPanel-Enterprise", + "icon": "fa-duotone fa-regular fa-panel-ews", + "animation": "scale", + "newTab": true, + "scaleValue": 1.05 + } + ], + "user": [ + { + "id": "qa-1769250612756", + "title": "Manage account", + "link": "/#account", + "icon": "fa-solid fa-user", + "animation": "scale", + "newTab": false, + "scaleValue": 1.01 + }, + { + "id": "qa-1769251431563", + "title": "ADPanel Site", + "link": "https://github.com/antonndev/ADPanel-Enterprise", + "icon": "fa-solid fa-globe", + "animation": "scale", + "newTab": true, + "scaleValue": 1.01 + } + ], + "updatedAt": 1773427337191 +} \ No newline at end of file diff --git a/routes/dashboard-assistant.js b/routes/dashboard-assistant.js new file mode 100644 index 0000000..a47f2b2 --- /dev/null +++ b/routes/dashboard-assistant.js @@ -0,0 +1,231 @@ +"use strict"; + +const express = require("express"); +const multer = require("multer"); +const { createDashboardAssistantService } = require("../utils/dashboard-assistant-service"); + +const AUDIO_UPLOAD_LIMIT_BYTES = parseInt(process.env.DASHBOARD_ASSISTANT_AUDIO_LIMIT_BYTES || "", 10) || 15 * 1024 * 1024; + +function inferStatusCode(error) { + const message = String(error?.message || "").toLowerCase(); + if (message.includes("not authenticated")) return 401; + if (message.includes("admin required") || message.includes("permission") || message.includes("access disabled")) return 403; + if (message.includes("not configured")) return 503; + if ( + message.includes("required") || + message.includes("valid") || + message.includes("too large") || + message.includes("could not be transcribed") || + message.includes("no audio") + ) { + return 400; + } + return 500; +} + +module.exports = function createDashboardAssistantRouter(deps) { + if (!deps || typeof deps !== "object") { + throw new Error("Dashboard assistant router dependencies are required."); + } + + const router = express.Router(); + const upload = multer({ + storage: multer.memoryStorage(), + limits: { fileSize: AUDIO_UPLOAD_LIMIT_BYTES, files: 1 }, + }); + const service = createDashboardAssistantService(deps); + + async function requireAuth(req, res) { + if (!(await deps.isAuthenticated(req))) { + res.status(401).json({ error: "not authenticated" }); + return false; + } + return true; + } + + async function requireAssistantAccess(req, res) { + if (!(await requireAuth(req, res))) return false; + if (await deps.isAdmin(req)) return true; + + const allowNormalUsers = typeof deps.isDashboardAssistantEnabledForNormalUsers === "function" + ? !!(await deps.isDashboardAssistantEnabledForNormalUsers()) + : false; + if (!allowNormalUsers) { + res.status(403).json({ error: "assistant access disabled" }); + return false; + } + return true; + } + + async function requireAssistantAdmin(req, res) { + if (!(await requireAssistantAccess(req, res))) return false; + if (!(await deps.isAdmin(req))) { + res.status(403).json({ error: "admin required" }); + return false; + } + return true; + } + + router.get("/bootstrap", async (req, res) => { + try { + if (!(await requireAssistantAccess(req, res))) return; + const state = await service.getBootstrap(req); + return res.json({ ok: true, ...state }); + } catch (error) { + console.error("[dashboard-assistant] bootstrap failed:", error); + return res.status(500).json({ error: "failed to load assistant" }); + } + }); + + router.post("/token", async (req, res) => { + try { + if (!(await requireAssistantAdmin(req, res))) return; + if (typeof deps.requireActionTokenOr403 === "function") { + const ok = deps.requireActionTokenOr403(req, res, "POST /api/dashboard-assistant/token"); + if (!ok) return; + } + + const { provider, token } = req.body || {}; + const saved = await service.saveProviderToken({ provider, token }); + return res.json({ ok: true, provider: saved }); + } catch (error) { + const statusCode = inferStatusCode(error); + return res.status(statusCode).json({ error: error?.message || "failed to save provider token" }); + } + }); + + router.post("/access", async (req, res) => { + try { + if (!(await requireAssistantAdmin(req, res))) return; + if (typeof deps.requireActionTokenOr403 === "function") { + const ok = deps.requireActionTokenOr403(req, res, "POST /api/dashboard-assistant/access"); + if (!ok) return; + } + + const currentUser = await deps.findUserByEmail(String(req.session?.user || "").trim().toLowerCase()); + const currentConfig = typeof deps.getDashboardAssistantConfig === "function" + ? deps.getDashboardAssistantConfig() + : { allowNormalUsers: false }; + const nextConfig = { + ...currentConfig, + allowNormalUsers: !!req.body?.allowNormalUsers, + updatedAt: new Date().toISOString(), + updatedBy: currentUser?.email || String(req.session?.user || "").trim().toLowerCase() || null, + }; + + if (typeof deps.saveDashboardAssistantConfig !== "function" || !deps.saveDashboardAssistantConfig(nextConfig)) { + return res.status(500).json({ error: "failed to save assistant access" }); + } + + return res.json({ ok: true, allowNormalUsers: nextConfig.allowNormalUsers }); + } catch (error) { + const statusCode = inferStatusCode(error); + return res.status(statusCode).json({ error: error?.message || "failed to save assistant access" }); + } + }); + + router.post("/reset", async (req, res) => { + try { + if (!(await requireAssistantAccess(req, res))) return; + const userEmail = String(req.session?.user || "").trim().toLowerCase(); + const chat = await service.createFreshChat(userEmail); + return res.json({ ok: true, chat, messages: [] }); + } catch (error) { + console.error("[dashboard-assistant] reset failed:", error); + return res.status(500).json({ error: "failed to reset assistant chat" }); + } + }); + + router.post("/transcribe", (req, res, next) => { + upload.single("audio")(req, res, (error) => { + if (error) { + const statusCode = error.code === "LIMIT_FILE_SIZE" ? 400 : 500; + return res.status(statusCode).json({ error: error.code === "LIMIT_FILE_SIZE" ? "The recording is too large." : "Audio upload failed." }); + } + next(); + }); + }, async (req, res) => { + try { + if (!(await requireAssistantAccess(req, res))) return; + if (!req.file?.buffer) { + return res.status(400).json({ error: "No audio was uploaded." }); + } + + const transcript = await service.transcribeAudio({ + buffer: req.file.buffer, + mimeType: req.file.mimetype, + filename: req.file.originalname, + language: req.body?.language, + prompt: req.body?.prompt, + }); + + return res.json({ ok: true, ...transcript }); + } catch (error) { + const statusCode = inferStatusCode(error); + return res.status(statusCode).json({ error: error?.message || "Transcription failed." }); + } + }); + + router.post("/chat", async (req, res) => { + try { + if (!(await requireAssistantAccess(req, res))) return; + + const userEmail = String(req.session?.user || "").trim().toLowerCase(); + const result = await service.completeChat({ + userEmail, + chatId: req.body?.chatId, + userMessage: req.body?.message, + userIp: req.ip || req.connection?.remoteAddress || "unknown", + }); + + return res.json({ ok: true, ...result }); + } catch (error) { + const statusCode = inferStatusCode(error); + console.error("[dashboard-assistant] chat failed:", error); + return res.status(statusCode).json({ error: error?.message || "Assistant request failed." }); + } + }); + + router.post("/client-follow-up", async (req, res) => { + try { + if (!(await requireAssistantAccess(req, res))) return; + + const userEmail = String(req.session?.user || "").trim().toLowerCase(); + const result = await service.completeClientFollowUp({ + userEmail, + chatId: req.body?.chatId, + summary: req.body?.summary, + sourceType: req.body?.sourceType, + context: req.body?.context, + skipAi: !!req.body?.skipAi, + }); + + return res.json({ ok: true, ...result }); + } catch (error) { + const statusCode = inferStatusCode(error); + console.error("[dashboard-assistant] client-follow-up failed:", error); + return res.status(statusCode).json({ error: error?.message || "Assistant follow-up failed." }); + } + }); + + router.post("/confirm-delete", async (req, res) => { + try { + if (!(await requireAssistantAccess(req, res))) return; + + const userEmail = String(req.session?.user || "").trim().toLowerCase(); + const result = await service.confirmDeleteServer({ + userEmail, + chatId: req.body?.chatId, + serverName: req.body?.server, + userIp: req.ip || req.connection?.remoteAddress || "unknown", + }); + return res.json({ ok: true, ...result }); + } catch (error) { + const statusCode = inferStatusCode(error); + console.error("[dashboard-assistant] confirm-delete failed:", error); + return res.status(statusCode).json({ error: error?.message || "Server deletion failed." }); + } + }); + + return router; +}; diff --git a/routes/subdomains.js b/routes/subdomains.js new file mode 100644 index 0000000..162d475 --- /dev/null +++ b/routes/subdomains.js @@ -0,0 +1,300 @@ +"use strict"; + +const express = require("express"); +const dns = require("dns").promises; +const db = require("../db"); +const nodes = require("../nodes"); +const { getTechnicalServerName } = require("../utils/server-name"); +const router = express.Router(); + + +async function resolveServer(req, res, next) { + const serverName = req.params.serverName; + if (!serverName) return res.status(400).json({ error: "missing server name" }); + + try { + const lowered = String(serverName).trim().toLowerCase(); + const rows = await db.query( + `SELECT * + FROM servers + WHERE LOWER(name) = ? OR LOWER(bot) = ? + ORDER BY + CASE + WHEN LOWER(name) = ? THEN 0 + WHEN LOWER(bot) = ? THEN 1 + ELSE 2 + END, + id DESC + LIMIT 1`, + [lowered, lowered, lowered, lowered] + ); + if (!rows.length) return res.status(404).json({ error: "server not found" }); + req.server = rows[0]; + next(); + } catch (err) { + console.error(err); + res.status(500).json({ error: "internal error" }); + } +} + + + +async function checkPerms(req, perm) { + if (!req.session.user) return false; + + + const userEmail = req.session.user; + let user = null; + + try { + const userRows = await db.query("SELECT * FROM users WHERE email = ? LIMIT 1", [userEmail]); + if (userRows.length > 0) user = userRows[0]; + } catch (e) { + console.error("Error resolving user:", e); + return false; + } + + if (!user) return false; + if (user.admin) return true; + + + const access = await db.query( + "SELECT * FROM user_access WHERE user_id = ? AND server_name = ?", + [user.id, req.server.name] + ); + if (!access.length) return false; + + let acl = {}; + try { + acl = typeof req.server.acl === 'string' ? JSON.parse(req.server.acl) : (req.server.acl || {}); + } catch (e) { acl = {}; } + + const userPerms = acl[userEmail] || {}; + return !!userPerms[perm]; +} + +router.get("/:serverName", resolveServer, async (req, res) => { + + if (!await checkPerms(req, 'subdomain_show')) { + return res.status(403).json({ error: "permission denied" }); + } + + try { + const subs = await db.query("SELECT * FROM subdomains WHERE server_id = ?", [req.server.id]); + res.json({ subdomains: subs }); + } catch (err) { + console.error(err); + res.status(500).json({ error: "db error" }); + } +}); + + +router.post("/:serverName", resolveServer, async (req, res) => { + + if (!await checkPerms(req, 'subdomain_add')) { + return res.status(403).json({ error: "permission denied" }); + } + + const domain = String(req.body.domain || "").trim().toLowerCase(); + if (!domain || domain.length > 253) return res.status(400).json({ error: "invalid domain" }); + + + const hostnameRegex = /^(?!-)[a-z0-9-]{1,63}(? targetIps.includes(addr)); + + if (!matched) { + return res.status(400).json({ + error: "DNS verification failed", + details: "Domain does not point to the expected server address" + }); + } + } catch (err) { + + return res.status(400).json({ error: "DNS lookup failed: record not found" }); + } + + + let subId; + try { + const result = await db.query("INSERT INTO subdomains (server_id, domain, status) VALUES (?, ?, 'approved')", [req.server.id, domain]); + subId = result.insertId; + } catch (err) { + if (err.code === 'ER_DUP_ENTRY') { + return res.status(400).json({ error: "domain already registered" }); + } + console.error(err); + res.status(500).json({ error: "db error" }); + return; + } + + + try { + const { node } = await nodes.remoteContext(req.server.name); + if (node) { + const base = nodes.nodeUrl(node); + const url = `${base}/v1/servers/${encodeURIComponent(getTechnicalServerName(req.server, req.server.name))}/subdomains`; + await nodes.httpJson(url, { + method: 'POST', + headers: nodes.nodeHeaders(node), + body: JSON.stringify({ domain: domain, action: 'create' }) + }); + } + } catch (err) { + console.error("Agent call failed:", err); + + await db.query("DELETE FROM subdomains WHERE id = ?", [subId]); + return res.status(500).json({ error: "agent communication failed" }); + } + + res.json({ ok: true, id: subId }); +}); + +router.post("/:serverName/:id/verify", resolveServer, async (req, res) => { + + if (!await checkPerms(req, 'subdomain_add')) { + return res.status(403).json({ error: "permission denied" }); + } + + const subId = req.params.id; + + let sub, expectedIp; + try { + const rows = await db.query("SELECT * FROM subdomains WHERE id = ? AND server_id = ?", [subId, req.server.id]); + if (!rows.length) return res.status(404).json({ error: "subdomain not found" }); + sub = rows[0]; + + expectedIp = req.server.ip; + if (!expectedIp && req.server.node_id) { + const nodeRows = await db.query("SELECT address FROM nodes WHERE id = ?", [req.server.node_id]); + if (nodeRows.length) expectedIp = nodeRows[0].address; + } + } catch (err) { + console.error(err); + return res.status(500).json({ error: "internal error" }); + } + + if (!expectedIp) { + return res.status(500).json({ error: "cannot determine node ip" }); + } + + + let targetIps = []; + if (/^(\d{1,3}\.){3}\d{1,3}$/.test(expectedIp)) { + targetIps = [expectedIp]; + } else { + try { + targetIps = await dns.resolve4(expectedIp); + } catch (e) { + console.error("Failed to resolve node address:", expectedIp, e); + return res.status(500).json({ error: "failed to resolve node address" }); + } + } + + + try { + const addresses = await dns.resolve4(sub.domain); + + const matched = addresses.some(addr => targetIps.includes(addr)); + + const newStatus = matched ? 'approved' : 'canceled'; + await db.query("UPDATE subdomains SET status = ? WHERE id = ?", [newStatus, subId]); + + + if (matched) { + const { node } = await nodes.remoteContext(req.server.name); + if (node) { + const base = nodes.nodeUrl(node); + const url = `${base}/v1/servers/${encodeURIComponent(getTechnicalServerName(req.server, req.server.name))}/subdomains`; + await nodes.httpJson(url, { + method: 'POST', + headers: nodes.nodeHeaders(node), + body: JSON.stringify({ domain: sub.domain, action: 'create' }) + }); + } + } + + res.json({ ok: true, status: newStatus, expected: expectedIp, found: addresses }); + } catch (err) { + console.error("DNS error:", err.message); + + await db.query("UPDATE subdomains SET status = 'canceled' WHERE id = ?", [subId]); + res.json({ ok: true, status: 'canceled', error: "dns lookup failed" }); + } +}); + +router.delete("/:serverName/:id", resolveServer, async (req, res) => { + + if (!await checkPerms(req, 'subdomain_add')) { + return res.status(403).json({ error: "permission denied" }); + } + + let domain; + try { + const rows = await db.query("SELECT domain FROM subdomains WHERE id = ? AND server_id = ?", [req.params.id, req.server.id]); + if (!rows.length) return res.status(404).json({ error: "subdomain not found" }); + domain = rows[0].domain; + } catch (err) { + console.error(err); + return res.status(500).json({ error: "internal error" }); + } + + try { + + const { node } = await nodes.remoteContext(req.server.name); + if (node) { + const base = nodes.nodeUrl(node); + const url = `${base}/v1/servers/${encodeURIComponent(getTechnicalServerName(req.server, req.server.name))}/subdomains`; + + await nodes.httpJson(url, { + method: 'POST', + headers: nodes.nodeHeaders(node), + body: JSON.stringify({ domain: domain, action: 'delete' }) + }); + } + + await db.query("DELETE FROM subdomains WHERE id = ? AND server_id = ?", [req.params.id, req.server.id]); + res.json({ ok: true }); + } catch (err) { + console.error(err); + res.status(500).json({ error: "db/agent error" }); + } +}); + +module.exports = router; diff --git a/scripts/adpanel-autoscale-monitor.sh b/scripts/adpanel-autoscale-monitor.sh new file mode 100755 index 0000000..c3f029f --- /dev/null +++ b/scripts/adpanel-autoscale-monitor.sh @@ -0,0 +1,37 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PANEL_DIR_DEFAULT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PANEL_DIR="${PANEL_DIR:-$PANEL_DIR_DEFAULT}" +INTERVAL_SECONDS="${PM2_MONITOR_INTERVAL:-300}" +GENERATOR="${PANEL_DIR}/scripts/generate-ecosystem.sh" +ECOSYSTEM_FILE="${PANEL_DIR}/ecosystem.config.js" +PM2_BIN="${PANEL_DIR}/node_modules/.bin/pm2" + +if [ ! -x "$PM2_BIN" ] && command -v pm2 >/dev/null 2>&1; then + PM2_BIN="$(command -v pm2)" +fi + +if [ ! -x "$GENERATOR" ]; then + echo "Generator script not executable: $GENERATOR" >&2 + exit 1 +fi + +if [ ! -x "$PM2_BIN" ]; then + echo "pm2 binary not found. Expected ${PANEL_DIR}/node_modules/.bin/pm2 or global pm2." >&2 + exit 1 +fi + +while true; do + output="$($GENERATOR --quiet --panel-dir "$PANEL_DIR")" + changed="$(echo "$output" | awk -F= '/^CHANGED=/{print $2}')" + + if [ "$changed" = "1" ]; then + # Apply new worker count and memory limits without requiring full host reboot. + "$PM2_BIN" start "$ECOSYSTEM_FILE" --only adpanel --update-env >/dev/null 2>&1 || true + "$PM2_BIN" reload adpanel --update-env >/dev/null 2>&1 || "$PM2_BIN" restart adpanel --update-env >/dev/null 2>&1 || true + fi + + sleep "$INTERVAL_SECONDS" +done diff --git a/scripts/adpanel-runtime.sh b/scripts/adpanel-runtime.sh new file mode 100755 index 0000000..04330bd --- /dev/null +++ b/scripts/adpanel-runtime.sh @@ -0,0 +1,44 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PANEL_DIR_DEFAULT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PANEL_DIR="${PANEL_DIR:-$PANEL_DIR_DEFAULT}" +GENERATOR="${PANEL_DIR}/scripts/generate-ecosystem.sh" +MONITOR="${PANEL_DIR}/scripts/adpanel-autoscale-monitor.sh" +ECOSYSTEM_FILE="${PANEL_DIR}/ecosystem.config.js" +PM2_RUNTIME_BIN="${PANEL_DIR}/node_modules/.bin/pm2-runtime" + +if [ ! -x "$PM2_RUNTIME_BIN" ] && command -v pm2-runtime >/dev/null 2>&1; then + PM2_RUNTIME_BIN="$(command -v pm2-runtime)" +fi + +if [ ! -x "$GENERATOR" ]; then + echo "Generator script not found: $GENERATOR" >&2 + exit 1 +fi + +if [ ! -x "$MONITOR" ]; then + echo "Monitor script not found: $MONITOR" >&2 + exit 1 +fi + +if [ ! -x "$PM2_RUNTIME_BIN" ]; then + echo "pm2-runtime not found. Run npm install to install dependencies." >&2 + exit 1 +fi + +"$GENERATOR" --panel-dir "$PANEL_DIR" >/dev/null + +"$MONITOR" & +MONITOR_PID=$! + +cleanup() { + if [ -n "${MONITOR_PID:-}" ] && kill -0 "$MONITOR_PID" >/dev/null 2>&1; then + kill "$MONITOR_PID" >/dev/null 2>&1 || true + wait "$MONITOR_PID" >/dev/null 2>&1 || true + fi +} +trap cleanup INT TERM EXIT + +exec "$PM2_RUNTIME_BIN" start "$ECOSYSTEM_FILE" --env production diff --git a/scripts/create-user.js b/scripts/create-user.js new file mode 100644 index 0000000..9165573 --- /dev/null +++ b/scripts/create-user.js @@ -0,0 +1,341 @@ +"use strict"; + +const path = require("path"); + +require("dotenv").config({ + path: path.join(__dirname, "..", ".env"), + override: true, +}); + +const speakeasy = require("speakeasy"); +const db = require("../db"); + +let bcrypt; +try { + bcrypt = require("bcrypt"); +} catch { + bcrypt = require("bcryptjs"); +} + +const ADMIN_AVATAR_URL = "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/admin-avatar.webp"; +const DEFAULT_USER_AVATAR_URLS = [ + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-1.webp", + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-2.webp", + "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/normal-3.webp", +]; +const MANAGED_AVATAR_URLS = new Set([ADMIN_AVATAR_URL, ...DEFAULT_USER_AVATAR_URLS]); + +function pickDefaultAvatar(isAdmin) { + if (isAdmin) return ADMIN_AVATAR_URL; + const idx = Math.floor(Math.random() * DEFAULT_USER_AVATAR_URLS.length); + return DEFAULT_USER_AVATAR_URLS[idx]; +} + +async function ensureUsersColumn(columnName, definition) { + try { + await db.query(`ALTER TABLE users ADD COLUMN IF NOT EXISTS ${columnName} ${definition}`); + } catch (err) { + if (!err.message?.includes("Duplicate column")) { + try { + const cols = await db.query(`SHOW COLUMNS FROM users LIKE '${columnName}'`); + if (!cols || cols.length === 0) { + await db.query(`ALTER TABLE users ADD COLUMN ${columnName} ${definition}`); + } + } catch (_) { + } + } + } +} + +function usage() { + return [ + "Usage:", + " sudo node scripts/create-user.js --email user@example.com --password \"pass\" [--admin] [--secret BASE32] [--avatar-url URL]", + " sudo node scripts/create-user.js --email user@example.com --password-hash \"$2b$...\" [--admin] [--secret BASE32] [--avatar-url URL]", + " sudo node scripts/create-user.js --update-password --email user@example.com --password \"newpass\" [--current-password \"oldpass\"]", + " sudo node scripts/create-user.js --update-password --email user@example.com --password-hash \"$2b$...\" [--current-password \"oldpass\"]", + " sudo node scripts/create-user.js --delete --email user@example.com", + ].join("\n"); +} + +function parseArgs(argv) { + const out = { admin: false, delete: false, updatePassword: false }; + for (let i = 0; i < argv.length; i += 1) { + const arg = argv[i]; + if (arg === "--help" || arg === "-h") { + out.help = true; + continue; + } + if (arg === "--admin") { + out.admin = true; + continue; + } + if (arg === "--delete" || arg === "--remove") { + out.delete = true; + continue; + } + if (arg === "--update-password" || arg === "--set-password") { + out.updatePassword = true; + continue; + } + if (arg === "--email") { + out.email = argv[i + 1]; + i += 1; + continue; + } + if (arg === "--password") { + out.password = argv[i + 1]; + i += 1; + continue; + } + if (arg === "--password-hash") { + out.passwordHash = argv[i + 1]; + i += 1; + continue; + } + if (arg === "--current-password") { + out.currentPassword = argv[i + 1]; + i += 1; + continue; + } + if (arg === "--secret") { + out.secret = argv[i + 1]; + i += 1; + continue; + } + if (arg === "--avatar-url") { + out.avatarUrl = argv[i + 1]; + i += 1; + continue; + } + } + return out; +} + +function requireSudo() { + if (typeof process.getuid === "function" && process.getuid() !== 0) { + console.error("This script must be run with sudo."); + return false; + } + return true; +} + +function normalizeAvatarUrl(raw) { + const value = String(raw || "").trim(); + if (!value) return ""; + if (value.length > 2048) { + throw new Error("Avatar URL is too long."); + } + if (value.startsWith("/")) { + return value; + } + + let parsed; + try { + parsed = new URL(value); + } catch { + throw new Error("Avatar URL must be a valid http/https URL or a root-relative path."); + } + + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + throw new Error("Avatar URL must use http or https."); + } + + return value; +} + +async function main() { + const args = parseArgs(process.argv.slice(2)); + + if (!requireSudo()) { + return 1; + } + + if (args.help || !args.email || (!args.delete && !args.updatePassword && !args.password && !args.passwordHash)) { + console.log(usage()); + return 1; + } + + const email = String(args.email || "").trim().toLowerCase(); + if (!email) { + console.error("Invalid email."); + return 1; + } + + await db.ensureSchema(); + await ensureUsersColumn("recovery_codes", "TEXT NULL"); + await ensureUsersColumn("avatar_url", "VARCHAR(2048) NULL"); + + if (args.delete) { + let existing = null; + if (args.currentPassword) { + const found = await db.query( + "SELECT id, password FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", + [email] + ); + existing = Array.isArray(found) ? found[0] : null; + if (!existing) { + console.error("User not found."); + return 2; + } + if (!bcrypt.compareSync(String(args.currentPassword || ""), String(existing.password || ""))) { + console.error("Current password is incorrect."); + return 3; + } + } + + const result = await db.query("DELETE FROM users WHERE LOWER(email) = LOWER(?)", [email]); + const affected = result && typeof result.affectedRows === "number" ? result.affectedRows : 0; + if (!affected) { + console.error("User not found."); + return 2; + } + console.log(`User deleted: ${email}`); + return 0; + } + + if (args.updatePassword) { + const found = await db.query( + "SELECT id, password FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", + [email] + ); + const existing = Array.isArray(found) ? found[0] : null; + if (!existing) { + console.error("User not found."); + return 2; + } + + if (args.currentPassword) { + if (!bcrypt.compareSync(String(args.currentPassword || ""), String(existing.password || ""))) { + console.error("Current password is incorrect."); + return 3; + } + } + + let newHash = args.passwordHash ? String(args.passwordHash).trim() : ""; + if (newHash) { + if (!/^\$2[aby]\$/.test(newHash)) { + console.error("Password hash must be a bcrypt hash."); + return 1; + } + } else { + const rawPassword = String(args.password || ""); + if (!rawPassword) { + console.error("Password is required."); + return 1; + } + newHash = bcrypt.hashSync(rawPassword, 10); + } + + await db.query("UPDATE users SET password = ? WHERE id = ?", [newHash, existing.id]); + console.log(`Password updated: ${email}`); + return 0; + } + + let passwordHash = args.passwordHash ? String(args.passwordHash).trim() : ""; + if (passwordHash) { + if (!/^\$2[aby]\$/.test(passwordHash)) { + console.error("Password hash must be a bcrypt hash."); + return 1; + } + } else { + const rawPassword = String(args.password || ""); + if (!rawPassword) { + console.error("Password is required."); + return 1; + } + passwordHash = bcrypt.hashSync(rawPassword, 10); + } + + const secret = args.secret + ? String(args.secret).trim() + : speakeasy.generateSecret({ length: 20 }).base32; + + const RECOVERY_CODE_COUNT = 7; + const RECOVERY_CODE_LENGTH = 8; + const RECOVERY_CODE_CHARS = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; + + function generateRecoveryCode() { + let code = ''; + for (let i = 0; i < RECOVERY_CODE_LENGTH; i++) { + code += RECOVERY_CODE_CHARS.charAt(Math.floor(Math.random() * RECOVERY_CODE_CHARS.length)); + } + return code; + } + + const plainRecoveryCodes = []; + const hashedRecoveryCodes = []; + for (let i = 0; i < RECOVERY_CODE_COUNT; i++) { + const code = generateRecoveryCode(); + plainRecoveryCodes.push(code); + hashedRecoveryCodes.push(bcrypt.hashSync(code, 10)); + } + + const recoveryCodesJson = JSON.stringify(hashedRecoveryCodes); + const explicitAvatarUrl = normalizeAvatarUrl(args.avatarUrl); + const desiredAvatarUrl = explicitAvatarUrl || pickDefaultAvatar(args.admin); + const existingRows = await db.query( + "SELECT id, avatar_url, admin FROM users WHERE LOWER(email) = LOWER(?) LIMIT 1", + [email] + ); + const existingUser = Array.isArray(existingRows) ? existingRows[0] : null; + + let avatarUrlToStore = desiredAvatarUrl; + if (!explicitAvatarUrl && existingUser?.avatar_url) { + const currentAvatar = String(existingUser.avatar_url).trim(); + if (currentAvatar && !MANAGED_AVATAR_URLS.has(currentAvatar)) { + avatarUrlToStore = currentAvatar; + } else if (args.admin) { + avatarUrlToStore = ADMIN_AVATAR_URL; + } else if (currentAvatar === ADMIN_AVATAR_URL) { + avatarUrlToStore = desiredAvatarUrl; + } else { + avatarUrlToStore = currentAvatar || desiredAvatarUrl; + } + } + + try { + await db.query( + `INSERT INTO users (email, password, secret, admin, recovery_codes, avatar_url) VALUES (?, ?, ?, ?, ?, ?) + ON DUPLICATE KEY UPDATE password = VALUES(password), secret = VALUES(secret), admin = VALUES(admin), recovery_codes = VALUES(recovery_codes), avatar_url = VALUES(avatar_url)`, + [email, passwordHash, secret, args.admin ? 1 : 0, recoveryCodesJson, avatarUrlToStore] + ); + } catch (err) { + throw err; + } + + console.log(`User created/updated: ${email}`); + console.log(`2FA secret: ${secret}`); + console.log(`Avatar URL: ${avatarUrlToStore}`); + console.log(''); + console.log('\x1b[1m\x1b[33m==================== RECOVERY CODES ====================\x1b[0m'); + console.log('\x1b[1m\x1b[31mSAVE THESE CODES! They can only be shown ONCE!\x1b[0m'); + console.log('\x1b[1m\x1b[31mEach code can only be used ONE TIME.\x1b[0m'); + console.log(''); + plainRecoveryCodes.forEach((code, idx) => { + console.log(` \x1b[1m\x1b[36m${idx + 1}. ${code}\x1b[0m`); + }); + console.log(''); + console.log('\x1b[1m\x1b[33m=========================================================\x1b[0m'); + return 0; +} + +async function run() { + let exitCode = 0; + try { + exitCode = await main(); + } catch (err) { + console.error("[create-user] failed:", err?.message || err); + exitCode = 1; + } finally { + try { + await db.close(); + } catch (err) { + console.error("[create-user] close failed:", err?.message || err); + exitCode = exitCode || 1; + } + } + process.exitCode = exitCode; +} + +run(); diff --git a/scripts/generate-ecosystem.sh b/scripts/generate-ecosystem.sh new file mode 100755 index 0000000..2aae282 --- /dev/null +++ b/scripts/generate-ecosystem.sh @@ -0,0 +1,145 @@ +#!/usr/bin/env bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PANEL_DIR_DEFAULT="$(cd "${SCRIPT_DIR}/.." && pwd)" +PANEL_DIR="${PANEL_DIR:-$PANEL_DIR_DEFAULT}" +TEMPLATE_FILE="${PANEL_DIR}/ecosystem.config.template.js" +OUTPUT_FILE="${PANEL_DIR}/ecosystem.config.js" +STATE_FILE="${PANEL_DIR}/data/runtime-scaling.env" +QUIET=0 + +while [ "$#" -gt 0 ]; do + case "$1" in + --panel-dir) + PANEL_DIR="$2" + TEMPLATE_FILE="${PANEL_DIR}/ecosystem.config.template.js" + OUTPUT_FILE="${PANEL_DIR}/ecosystem.config.js" + STATE_FILE="${PANEL_DIR}/data/runtime-scaling.env" + shift 2 + ;; + --quiet) + QUIET=1 + shift + ;; + *) + echo "Unknown option: $1" >&2 + exit 1 + ;; + esac +done + +if [ ! -f "$TEMPLATE_FILE" ]; then + echo "Template file not found: $TEMPLATE_FILE" >&2 + exit 1 +fi + +cpu_cores() { + if command -v nproc >/dev/null 2>&1; then + nproc + return + fi + + if command -v getconf >/dev/null 2>&1; then + getconf _NPROCESSORS_ONLN + return + fi + + echo 1 +} + +total_ram_mb() { + local mem_kb + mem_kb="$(awk '/^MemTotal:/ {print $2}' /proc/meminfo 2>/dev/null || true)" + if [ -z "$mem_kb" ]; then + echo 1024 + return + fi + + echo $((mem_kb / 1024)) +} + +TOTAL_CORES="$(cpu_cores)" +TOTAL_RAM_MB="$(total_ram_mb)" +SAFE_RAM_MB=$((TOTAL_RAM_MB * 80 / 100)) + +if [ "$TOTAL_CORES" -le 2 ]; then + INSTANCES=1 +else + INSTANCES=$((TOTAL_CORES - 2)) +fi + +# Keep at least 192 MB target per worker by reducing workers on low-RAM hosts. +MIN_WORKER_TARGET_MB=192 +if [ "$INSTANCES" -gt 1 ] && [ "$SAFE_RAM_MB" -gt 0 ]; then + POSSIBLE_INSTANCES=$((SAFE_RAM_MB / MIN_WORKER_TARGET_MB)) + if [ "$POSSIBLE_INSTANCES" -lt 1 ]; then + POSSIBLE_INSTANCES=1 + fi + if [ "$POSSIBLE_INSTANCES" -lt "$INSTANCES" ]; then + INSTANCES="$POSSIBLE_INSTANCES" + fi +fi + +if [ "$INSTANCES" -lt 1 ]; then + INSTANCES=1 +fi + +WORKER_RAM_MB=$((SAFE_RAM_MB / INSTANCES)) +if [ "$WORKER_RAM_MB" -lt 128 ]; then + WORKER_RAM_MB=128 +fi + +MAX_OLD_SPACE_MB=$((WORKER_RAM_MB * 85 / 100)) +if [ "$MAX_OLD_SPACE_MB" -lt 96 ]; then + MAX_OLD_SPACE_MB=96 +fi + +APP_SCRIPT_PATH="${PANEL_DIR}/index.js" + +tmp_ecosystem="$(mktemp)" +sed \ + -e "s|__SCRIPT_PATH__|${APP_SCRIPT_PATH}|g" \ + -e "s|__PANEL_DIR__|${PANEL_DIR}|g" \ + -e "s|__INSTANCES__|${INSTANCES}|g" \ + -e "s|__MAX_OLD_SPACE_MB__|${MAX_OLD_SPACE_MB}|g" \ + -e "s|__WORKER_RAM_MB__|${WORKER_RAM_MB}|g" \ + "$TEMPLATE_FILE" > "$tmp_ecosystem" + +mkdir -p "$(dirname "$STATE_FILE")" +tmp_state="$(mktemp)" +cat > "$tmp_state" <&2 +fi + +printf 'TOTAL_CORES=%s\n' "$TOTAL_CORES" +printf 'TOTAL_RAM_MB=%s\n' "$TOTAL_RAM_MB" +printf 'SAFE_RAM_MB=%s\n' "$SAFE_RAM_MB" +printf 'INSTANCES=%s\n' "$INSTANCES" +printf 'WORKER_RAM_MB=%s\n' "$WORKER_RAM_MB" +printf 'MAX_OLD_SPACE_MB=%s\n' "$MAX_OLD_SPACE_MB" +printf 'CHANGED=%s\n' "$CHANGED" diff --git a/scripts/patch_main_go.py b/scripts/patch_main_go.py new file mode 100644 index 0000000..22bb67f --- /dev/null +++ b/scripts/patch_main_go.py @@ -0,0 +1,301 @@ +#!/usr/bin/env python3 +"""Patch main.go: add /v1/fs/uploadUrl route + handleFSUploadURL handler.""" +import sys, io, os + +PATH = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "main.go") + +with io.open(PATH, "r", encoding="utf-8") as f: + src = f.read() + +# --- Edit 1: add the route case right after handleFSUploadStream registration --- +ROUTE_OLD = ( + '\tcase method == "POST" && path == "/v1/fs/upload":\n' + '\t\ta.handleFSUploadStream(w, r)\n' + '\t\treturn\n' +) +ROUTE_NEW = ( + '\tcase method == "POST" && path == "/v1/fs/upload":\n' + '\t\ta.handleFSUploadStream(w, r)\n' + '\t\treturn\n' + '\tcase method == "POST" && path == "/v1/fs/uploadUrl":\n' + '\t\ta.handleFSUploadURL(w, r)\n' + '\t\treturn\n' +) + +if '"/v1/fs/uploadUrl"' in src: + print("[skip] route already registered") +else: + if ROUTE_OLD not in src: + print("ERROR: could not find route registration anchor", file=sys.stderr) + sys.exit(2) + src = src.replace(ROUTE_OLD, ROUTE_NEW, 1) + print("[ok] route registered") + +# --- Edit 2: append the handler right before `func main()` --- +HANDLER = r''' +func sanitizeUploadFilenameForUrl(name string) string { + s := strings.TrimSpace(name) + if s == "" { + return "" + } + s = strings.NewReplacer("\x00", "_", "\r", "_", "\n", "_").Replace(s) + s = filepath.Base(s) + s = filepath.Base(filepath.ToSlash(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.WriteRune('_') + } + } + out := strings.TrimLeft(b.String(), ".") + if out == "" || out == "." || out == ".." { + return "" + } + if len(out) > 200 { + out = out[len(out)-200:] + } + return out +} + +func extractFilenameFromContentDisposition(cd string) string { + if cd == "" { + return "" + } + lower := strings.ToLower(cd) + if i := strings.Index(lower, "filename*="); i >= 0 { + rest := cd[i+len("filename*="):] + if j := strings.Index(rest, ";"); j >= 0 { + rest = rest[:j] + } + rest = strings.Trim(rest, " \t\"") + parts := strings.SplitN(rest, "''", 2) + var v string + if len(parts) == 2 { + v = parts[1] + } else { + v = rest + } + if dec, err := url.QueryUnescape(v); err == nil { + return dec + } + return v + } + if i := strings.Index(lower, "filename="); i >= 0 { + rest := cd[i+len("filename="):] + if j := strings.Index(rest, ";"); j >= 0 { + rest = rest[:j] + } + rest = strings.Trim(rest, " \t\"") + return rest + } + return "" +} + +func (a *Agent) handleFSUploadURL(w http.ResponseWriter, r *http.Request) { + var body struct { + Dir string `json:"dir"` + 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 + } + + absDir, ok := a.safeUnderVolumes(body.Dir) + if !ok { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "invalid dir"}) + return + } + if err := ensureDir(absDir); err != nil { + jsonWrite(w, 500, map[string]any{"ok": false, "error": "cannot create dir"}) + return + } + if err := ensureResolvedUnder(a.volumesDir, absDir); err != nil { + jsonWrite(w, 400, map[string]any{"ok": false, "error": "symlink escape blocked"}) + return + } + + maxBytes := a.uploadLimit + if maxBytes <= 0 { + maxBytes = 1024 * 1024 * 1024 + } + + if diskErr := a.checkDiskLimitForPath(absDir, 0); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + + ctx, cancel := context.WithTimeout(r.Context(), 30*time.Minute) + defer cancel() + + req, _ := http.NewRequestWithContext(ctx, "GET", parsedURL.String(), nil) + req.Header.Set("User-Agent", "ADPanel-Node/1.0") + req.Header.Set("Accept", "*/*") + + resp, err := a.dl.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 > 0 { + if resp.ContentLength > maxBytes { + jsonWrite(w, 413, map[string]any{ + "ok": false, + "error": "file too large", + "limit_mb": maxBytes / (1024 * 1024), + }) + return + } + if diskErr := a.checkDiskLimitForPath(absDir, resp.ContentLength); diskErr != nil { + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + } + + var filename string + if cd := resp.Header.Get("Content-Disposition"); cd != "" { + if f := extractFilenameFromContentDisposition(cd); f != "" { + filename = sanitizeUploadFilenameForUrl(f) + } + } + if filename == "" { + if parsedURL.Path != "" { + base := path.Base(parsedURL.Path) + if base != "" && base != "/" && base != "." { + filename = sanitizeUploadFilenameForUrl(base) + } + } + } + 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 + } + + 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 + } + } + + tmpPath := destPath + ".urlupload.tmp" + _ = os.Remove(tmpPath) + out, err := os.OpenFile(tmpPath, os.O_CREATE|os.O_TRUNC|os.O_WRONLY|syscall.O_NOFOLLOW, 0o644) + 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 + } + + written, copyErr := io.Copy(out, io.LimitReader(resp.Body, maxBytes+1)) + closeErr := out.Close() + + if copyErr != nil { + _ = os.Remove(tmpPath) + 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 { + _ = os.Remove(tmpPath) + jsonWrite(w, 500, map[string]any{"ok": false, "error": "close failed"}) + return + } + if written > maxBytes { + _ = os.Remove(tmpPath) + jsonWrite(w, 413, map[string]any{ + "ok": false, + "error": "file too large", + "limit_mb": maxBytes / (1024 * 1024), + }) + return + } + + if diskErr := a.checkDiskLimitForPath(absDir, written); diskErr != nil { + _ = os.Remove(tmpPath) + diskErr["ok"] = false + jsonWrite(w, 507, diskErr) + return + } + + if err := os.Rename(tmpPath, destPath); err != nil { + _ = os.Remove(tmpPath) + if a.debug { + fmt.Printf("[fs] uploadUrl rename error: %v\n", err) + } + jsonWrite(w, 500, map[string]any{"ok": false, "error": "rename failed"}) + return + } + + jsonWrite(w, 200, map[string]any{ + "ok": true, + "path": destPath, + "filename": filename, + "bytes": written, + "msg": fmt.Sprintf("Downloaded %s (%d bytes)", filename, written), + }) +} + +''' + +MARKER = "func main() {" +if "func (a *Agent) handleFSUploadURL(" in src: + print("[skip] handler already present") +else: + if MARKER not in src: + print("ERROR: cannot find func main() anchor", file=sys.stderr) + sys.exit(3) + src = src.replace(MARKER, HANDLER + MARKER, 1) + print("[ok] handler appended") + +with io.open(PATH, "w", encoding="utf-8") as f: + f.write(src) + +print("[done] main.go patched") diff --git a/security.json b/security.json new file mode 100644 index 0000000..872bdbe --- /dev/null +++ b/security.json @@ -0,0 +1,6 @@ +{ + "rate_limiting": false, + "limit": 25, + "window_seconds": 120, + "trusted_subnets": [] +} \ No newline at end of file diff --git a/start.sh b/start.sh new file mode 100644 index 0000000..d322797 --- /dev/null +++ b/start.sh @@ -0,0 +1,70 @@ +#!/usr/bin/env bash +set -euo pipefail + +echo "Preparing ADPanel runtime..." + +if ! id -u adpanel &>/dev/null; then + echo "[setup] Creating system user 'adpanel'..." + nologin_shell="/usr/sbin/nologin" + if [ ! -x "$nologin_shell" ]; then + nologin_shell="/sbin/nologin" + fi + if [ ! -x "$nologin_shell" ]; then + nologin_shell="/bin/false" + fi + if command -v useradd >/dev/null 2>&1; then + useradd --system --no-create-home --shell "$nologin_shell" adpanel 2>/dev/null || true + elif command -v adduser >/dev/null 2>&1; then + adduser -S -D -H -s "$nologin_shell" adpanel 2>/dev/null || \ + adduser --system --no-create-home --shell "$nologin_shell" adpanel 2>/dev/null || true + fi +fi + +if [ -d /etc/nginx/snippets ]; then + chgrp adpanel /etc/nginx/snippets 2>/dev/null || true + chmod g+w /etc/nginx/snippets 2>/dev/null || true +fi + +SUDOERS_SRC="$(dirname "$0")/adpanel-sudoers" +SUDOERS_DST="/etc/sudoers.d/adpanel-panel" +if [ -f "$SUDOERS_SRC" ]; then + if [ "$(id -u)" -ne 0 ]; then + echo "[WARN] Not running as root; skipping sudoers sync." + else + echo "[setup] Syncing sudoers rules for adpanel user..." + mkdir -p /etc/sudoers.d + tmp_sudoers="$(mktemp /etc/sudoers.d/adpanel-panel.tmp.XXXXXX)" + cp "$SUDOERS_SRC" "$tmp_sudoers" + chmod 0440 "$tmp_sudoers" + + validate_ok=0 + if command -v visudo >/dev/null 2>&1; then + if visudo -cf "$tmp_sudoers" >/dev/null 2>&1; then + validate_ok=1 + else + echo "[WARN] Sudoers validation failed; keeping existing policy." + fi + else + echo "[WARN] visudo not found; applying sudoers without validation." + validate_ok=1 + fi + + if [ "$validate_ok" -eq 1 ]; then + if [ ! -f "$SUDOERS_DST" ] || ! cmp -s "$tmp_sudoers" "$SUDOERS_DST"; then + mv "$tmp_sudoers" "$SUDOERS_DST" + chmod 0440 "$SUDOERS_DST" + echo "[setup] Sudoers rules installed/updated." + else + rm -f "$tmp_sudoers" + echo "[setup] Sudoers rules already up to date." + fi + else + rm -f "$tmp_sudoers" + fi + fi +fi + +PANEL_DIR="$(cd "$(dirname "$0")" && pwd)" +chown -R adpanel:adpanel "$PANEL_DIR" 2>/dev/null || true + +echo "ADPanel runtime preparation complete." diff --git a/store-templates.json b/store-templates.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/store-templates.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/templates.json b/templates.json new file mode 100644 index 0000000..adeafc2 --- /dev/null +++ b/templates.json @@ -0,0 +1,167 @@ +[ + { + "id": "minecraft", + "name": "Minecraft", + "description": "Minecraft Java Edition server", + "defaultPort": 25565, + "templateImage": "/images/minecraft.webp", + "docker": { + "image": "eclipse-temurin", + "tag": "21-jre", + "ports": [ + 25565 + ], + "volumes": [ + "{BOT_DIR}:/data" + ], + "workdir": "/data", + "env": {}, + "command": "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui", + "restart": "unless-stopped", + "console": { + "type": "stdin" + } + } + }, + { + "id": "nodejs", + "name": "Node.js", + "description": "Run Node.js applications easy.", + "defaultPort": 3000, + "templateImage": "/images/nodejs.webp", + "docker": { + "image": "node", + "tag": "20-alpine", + "ports": [ + 3000 + ], + "volumes": [ + "{BOT_DIR}:/app" + ], + "workdir": "/app", + "env": { + "NODE_ENV": "production" + }, + "command": "node /app/index.js", + "restart": "unless-stopped", + "console": { + "type": "stdin" + } + } + }, + { + "id": "csgo", + "name": "Counter-Strike 2", + "description": "Counter-Strike 2 dedicated server installed with an ADPanel SteamCMD installer", + "defaultPort": 27015, + "templateImage": "https://cdn.cloudflare.steamstatic.com/steam/apps/730/header.jpg", + "docker": { + "image": "ghcr.io/ptero-eggs/steamcmd", + "tag": "sniper", + "ports": [ + 27015, + 27020, + 27005 + ], + "volumes": [ + "{BOT_DIR}:/home/container" + ], + "workdir": "/home/container", + "env": { + "SRCDS_APPID": "730", + "SRCDS_MAP": "de_dust2", + "MAX_PLAYERS": "12", + "AUTO_UPDATE": "1", + "TV_PORT": "27020", + "STEAM_GSLT": "", + "VAC_ENABLED": "1", + "RCON_ENABLED": "0", + "SERVER_NAME": "ADPanel CS2 Server", + "SERVER_PASSWORD": "", + "RCON_PASSWORD": "changeme", + "GAME_MODE": "1", + "GAME_TYPE": "0", + "STEAM_USER": "anonymous", + "STEAM_PASS": "", + "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}}", + "install": { + "image": "ghcr.io/pterodactyl/installers:debian", + "entrypoint": "bash", + "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.\"" + }, + "restart": "unless-stopped", + "console": { + "type": "stdin" + } + } + }, + { + "id": "fivem", + "name": "FiveM", + "description": "Run your FiveM servers with this template", + "defaultPort": 30120, + "templateImage": "https://logos-world.net/wp-content/uploads/2021/03/FiveM-Symbol.png", + "docker": { + "image": "ich777/fivemserver", + "tag": "latest", + "ports": [ + 30120, + 30110, + 8080 + ], + "volumes": [ + "{BOT_DIR}:/serverdata/serverfiles" + ], + "workdir": "/serverdata/serverfiles", + "env": { + "DATA_DIR": "/serverdata", + "SERVER_DIR": "/serverdata/serverfiles", + "GAME_CONFIG": "server.cfg", + "SERVER_KEY": "change-me", + "SRV_ADR": "https://runtime.fivem.net/artifacts/fivem/build_proot_linux/master/", + "MANUAL_UPDATES": "", + "ENABLE_WEBCONSOLE": "true", + "UID": "99", + "GID": "100", + "START_VARS": "" + }, + "restart": "unless-stopped", + "console": { + "type": "stdin" + } + } + }, + { + "id": "python", + "name": "Python", + "description": "Run Python applications and frameworks", + "defaultPort": 8000, + "templateImage": "https://stalwart-pegasus-2c2ca4.netlify.app/img/python-logo.webp", + "docker": { + "image": "python", + "tag": "3.12-slim", + "ports": [ + 8000 + ], + "volumes": [ + "{BOT_DIR}:/app" + ], + "workdir": "/app", + "env": { + "PYTHONUNBUFFERED": "1" + }, + "command": "python /app/main.py", + "restart": "unless-stopped", + "console": { + "type": "stdin" + } + } + } +] diff --git a/utils/background.js b/utils/background.js new file mode 100644 index 0000000..210b7cb --- /dev/null +++ b/utils/background.js @@ -0,0 +1,19 @@ +module.exports = { makeCssBackground }; + +function makeCssBackground(type, value) { + if (typeof value !== "string") return null; + const v = value.trim(); + + if (type === "color") { + return /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.test(v) ? v : null; + } + + if (type === "url" || type === "upload" || type === "image") { + if (/^https?:\/\//i.test(v)) return `url("${v.replace(/["\\\n\r\f()<>]/g, encodeURIComponent)}")`; + if (/^data:image\/(png|jpe?g|webp|gif);base64,[A-Za-z0-9+/=]+$/i.test(v)) return `url("${v}")`; + if (/^\/[a-z0-9/_\-.]+$/i.test(v) && !v.includes('..')) return `url("${v}?v=${Date.now()}")`; + return null; + } + + return null; +} \ No newline at end of file diff --git a/utils/bot-ai-tools.js b/utils/bot-ai-tools.js new file mode 100644 index 0000000..36258f7 --- /dev/null +++ b/utils/bot-ai-tools.js @@ -0,0 +1,580 @@ +"use strict"; + +const MAX_BOT_TOOL_LOOPS = 8; +const MAX_PROMPT_SERVER_NAMES = 80; + +const BOT_TOOL_PARAMETER_SCHEMAS = Object.freeze({ + list_accessible_servers: { + type: "object", + properties: {}, + required: [], + }, + inspect_server: { + type: "object", + properties: { + server: { + type: "string", + description: "The accessible server name, display name, alias, or the user's raw server wording.", + }, + }, + required: ["server"], + }, + power_server: { + type: "object", + properties: { + server: { + type: "string", + description: "The accessible server name, display name, alias, or the user's raw server wording.", + }, + action: { + type: "string", + enum: ["start", "stop", "restart", "kill"], + description: "The power action to run.", + }, + }, + required: ["server", "action"], + }, + query_console: { + type: "object", + properties: { + server: { + type: "string", + description: "The accessible server name, display name, alias, or the user's raw server wording.", + }, + question: { + type: "string", + description: "Optional focus question about the console output.", + }, + limit: { + type: "number", + description: "Optional number of recent console lines to inspect, capped at 100.", + }, + }, + required: ["server"], + }, + send_console_command: { + type: "object", + properties: { + server: { + type: "string", + description: "The accessible server name, display name, alias, or the user's raw server wording.", + }, + command: { + type: "string", + description: "One real console command to send.", + }, + }, + required: ["server", "command"], + }, + list_backups: { + type: "object", + properties: { + server: { + type: "string", + description: "The accessible server name, display name, alias, or the user's raw server wording.", + }, + }, + required: ["server"], + }, + create_backup: { + type: "object", + properties: { + server: { + type: "string", + description: "The accessible server name, display name, alias, or the user's raw server wording.", + }, + name: { + type: "string", + description: "Optional backup name.", + }, + description: { + type: "string", + description: "Optional backup description.", + }, + }, + required: ["server"], + }, + restore_backup: { + type: "object", + properties: { + server: { + type: "string", + description: "The accessible server name, display name, alias, or the user's raw server wording.", + }, + backup: { + type: "string", + description: "A backup id, name, archive name, or the user's raw backup wording.", + }, + deleteOldFiles: { + type: "boolean", + description: "Whether old files should be removed before restoring.", + }, + }, + required: ["server", "backup"], + }, + delete_backup: { + type: "object", + properties: { + server: { + type: "string", + description: "The accessible server name, display name, alias, or the user's raw server wording.", + }, + backup: { + type: "string", + description: "A backup id, name, archive name, or the user's raw backup wording.", + }, + }, + required: ["server", "backup"], + }, +}); + +const BOT_TOOL_DEFINITIONS = Object.freeze([ + { + name: "list_accessible_servers", + description: "List the servers the current user can access.", + args: {}, + }, + { + name: "inspect_server", + description: "Inspect one accessible server, including its status and the current user's permissions.", + args: { + server: "string", + }, + }, + { + name: "power_server", + description: "Start, stop, restart, or kill one accessible server when the user has permission.", + args: { + server: "string", + action: "start|stop|restart|kill", + }, + }, + { + name: "query_console", + description: "Read up to 100 recent console lines from one accessible server and return them for analysis.", + args: { + server: "string", + question: "string?", + limit: "number?", + }, + }, + { + name: "send_console_command", + description: "Send one real console command to one accessible server when the user explicitly asked for it and has console_write permission.", + args: { + server: "string", + command: "string", + }, + }, + { + name: "list_backups", + description: "List backups for one accessible server when the user has backups_view permission.", + args: { + server: "string", + }, + }, + { + name: "create_backup", + description: "Create one backup for an accessible server when the user has backups_create permission.", + args: { + server: "string", + name: "string?", + description: "string?", + }, + }, + { + name: "restore_backup", + description: "Restore one backup on an accessible server when the user has backups_create permission.", + args: { + server: "string", + backup: "string", + deleteOldFiles: "boolean?", + }, + }, + { + name: "delete_backup", + description: "Delete one backup on an accessible server when the user has backups_delete permission.", + args: { + server: "string", + backup: "string", + }, + }, +]); + +const BOT_OPENAI_TOOL_DEFINITIONS = Object.freeze( + BOT_TOOL_DEFINITIONS.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: BOT_TOOL_PARAMETER_SCHEMAS[tool.name] || { type: "object", properties: {}, required: [] }, + }, + })) +); + +const BOT_GOOGLE_FUNCTION_DECLARATIONS = Object.freeze( + BOT_TOOL_DEFINITIONS.map((tool) => ({ + name: tool.name, + description: tool.description, + parameters: BOT_TOOL_PARAMETER_SCHEMAS[tool.name] || { type: "object", properties: {}, required: [] }, + })) +); + +function stripDiacritics(value) { + return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, ""); +} + +function normalizeLookupText(value) { + return stripDiacritics(value) + .toLowerCase() + .replace(/[`"'“”‘’()[\]{}<>]/g, " ") + .replace(/[_./-]+/g, " ") + .replace(/[^a-z0-9 ]+/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function compactLookupText(value) { + return normalizeLookupText(value).replace(/\s+/g, ""); +} + +function getServerAliases(entry) { + const aliases = new Set(); + for (const value of [ + entry?.name, + entry?.displayName, + entry?.bot, + entry?.legacy_id, + entry?.legacyId, + entry?.id, + ]) { + const clean = String(value || "").trim(); + if (!clean) continue; + aliases.add(clean); + aliases.add(clean.replace(/[_./-]+/g, " ").replace(/\s+/g, " ").trim()); + } + return Array.from(aliases).filter(Boolean); +} + +function getCurrentServerReference(currentServerName, accessibleServers) { + const currentName = String(currentServerName || "").trim(); + if (!currentName) return null; + const target = compactLookupText(currentName); + return (Array.isArray(accessibleServers) ? accessibleServers : []).find((entry) => { + return getServerAliases(entry).some((alias) => compactLookupText(alias) === target); + }) || null; +} + +function isCurrentServerReference(value) { + const normalized = normalizeLookupText(value); + if (!normalized) return true; + return [ + "current", + "current server", + "this", + "this server", + "server", + "serverul", + "serverul curent", + "serverul asta", + "asta", + "curent", + "it", + ].includes(normalized); +} + +function resolveServerFromAccessibleList(accessibleServers, requestedServer, currentServerName = "") { + const entries = Array.isArray(accessibleServers) ? accessibleServers.filter((entry) => entry?.name) : []; + if (!entries.length) { + return { entry: null, error: "You do not have access to any servers." }; + } + + const raw = String(requestedServer || "").trim(); + if (!raw || isCurrentServerReference(raw)) { + const currentEntry = getCurrentServerReference(currentServerName, entries); + if (currentEntry) return { entry: currentEntry }; + if (entries.length === 1) return { entry: entries[0] }; + return { + entry: null, + error: "The target server is not clear.", + candidates: entries.slice(0, 5).map((entry) => entry.displayName || entry.name), + }; + } + + const normalizedRequested = normalizeLookupText(raw); + const compactRequested = compactLookupText(raw); + const scored = entries.map((entry) => { + let best = 0; + for (const alias of getServerAliases(entry)) { + const normalizedAlias = normalizeLookupText(alias); + const compactAlias = compactLookupText(alias); + if (!normalizedAlias && !compactAlias) continue; + + if (normalizedRequested && normalizedAlias === normalizedRequested) { + best = Math.max(best, 1600 + normalizedAlias.length); + } + if (compactRequested && compactAlias === compactRequested) { + best = Math.max(best, 1550 + compactAlias.length); + } + if (normalizedRequested && normalizedAlias && normalizedRequested.includes(normalizedAlias)) { + best = Math.max(best, 900 + normalizedAlias.length); + } + if (normalizedRequested && normalizedAlias && normalizedAlias.includes(normalizedRequested)) { + best = Math.max(best, 880 + normalizedRequested.length); + } + if (compactRequested && compactAlias && compactRequested.includes(compactAlias)) { + best = Math.max(best, 760 + compactAlias.length); + } + + const aliasTokens = normalizedAlias.split(" ").filter(Boolean); + const requestedTokens = normalizedRequested.split(" ").filter(Boolean); + if (aliasTokens.length && requestedTokens.length) { + const overlap = aliasTokens.filter((token) => requestedTokens.includes(token)).length; + if (overlap === aliasTokens.length) { + best = Math.max(best, 680 + aliasTokens.length * 30); + } else if (overlap > 0) { + best = Math.max(best, 280 + overlap * 45); + } + } + } + return { entry, score: best }; + }).filter((item) => item.score > 0).sort((left, right) => right.score - left.score); + + if (!scored.length) { + return { + entry: null, + error: "I could not match that server to one you can access.", + candidates: entries.slice(0, 5).map((entry) => entry.displayName || entry.name), + }; + } + + const [best, second] = scored; + if (second && best.score < second.score + 140) { + return { + entry: null, + error: "That server name is ambiguous.", + candidates: scored.slice(0, 5).map((item) => item.entry.displayName || item.entry.name), + }; + } + + return { entry: best.entry }; +} + +function resolveBackupFromList(backups, requestedBackup) { + const items = Array.isArray(backups) ? backups : []; + const raw = String(requestedBackup || "").trim(); + if (!raw) { + return { backup: null, error: "A backup identifier is required." }; + } + + const normalizedRequested = normalizeLookupText(raw); + const compactRequested = compactLookupText(raw); + const scored = items.map((backup) => { + const aliases = [ + backup?.id, + backup?.name, + backup?.archive_name, + backup?.archiveName, + backup?.uuid, + ].map((value) => String(value || "").trim()).filter(Boolean); + + let best = 0; + for (const alias of aliases) { + const normalizedAlias = normalizeLookupText(alias); + const compactAlias = compactLookupText(alias); + if (!normalizedAlias && !compactAlias) continue; + + if (normalizedAlias === normalizedRequested) best = Math.max(best, 1600 + normalizedAlias.length); + if (compactAlias === compactRequested) best = Math.max(best, 1550 + compactAlias.length); + if (normalizedRequested && normalizedAlias.includes(normalizedRequested)) best = Math.max(best, 900 + normalizedRequested.length); + if (normalizedRequested && normalizedRequested.includes(normalizedAlias)) best = Math.max(best, 880 + normalizedAlias.length); + if (compactRequested && compactRequested.includes(compactAlias)) best = Math.max(best, 760 + compactAlias.length); + } + + return { backup, score: best }; + }).filter((item) => item.score > 0).sort((left, right) => right.score - left.score); + + if (!scored.length) { + return { backup: null, error: "I could not match that backup." }; + } + + const [best, second] = scored; + if (second && best.score < second.score + 120) { + return { + backup: null, + error: "That backup reference is ambiguous.", + candidates: scored.slice(0, 5).map((item) => item.backup?.name || item.backup?.id).filter(Boolean), + }; + } + + return { backup: best.backup }; +} + +function extractJsonObjectFromText(value) { + const text = String(value || "").trim(); + if (!text) return ""; + + const taggedMatch = text.match(/\s*([\s\S]*?)\s*<\/adpanel_tool_plan>/i); + if (taggedMatch && taggedMatch[1]) { + return String(taggedMatch[1]).trim(); + } + + const fencedMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i); + if (fencedMatch && fencedMatch[1]) { + return String(fencedMatch[1]).trim(); + } + + const firstBrace = text.indexOf("{"); + const lastBrace = text.lastIndexOf("}"); + if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) { + return text.slice(firstBrace, lastBrace + 1).trim(); + } + + return ""; +} + +function parseBotAssistantToolPlan(rawContent) { + const extracted = extractJsonObjectFromText(rawContent); + if (!extracted) return null; + + try { + const parsed = JSON.parse(extracted); + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null; + const toolCalls = Array.isArray(parsed.tool_calls) ? parsed.tool_calls : []; + return { + reply: String(parsed.reply || "").trim(), + tool_calls: toolCalls + .filter((item) => item && typeof item === "object") + .map((item) => ({ + name: String(item.name || "").trim(), + args: item.args && typeof item.args === "object" && !Array.isArray(item.args) ? item.args : {}, + })) + .filter((item) => item.name), + }; + } catch { + return null; + } +} + +function formatPermissionSummary(perms) { + const entries = []; + if (perms?.server_start) entries.push("start"); + if (perms?.server_stop) entries.push("stop"); + if (perms?.console_read) entries.push("read console"); + if (perms?.console_write) entries.push("send console commands"); + if (perms?.backups_view) entries.push("view backups"); + if (perms?.backups_create) entries.push("create or restore backups"); + if (perms?.backups_delete) entries.push("delete backups"); + return entries.length ? entries.join(", ") : "no elevated server actions"; +} + +function buildBotAssistantSystemPrompt({ currentServerName = "", accessibleServers = [], currentServerPerms = null }) { + const currentServer = String(currentServerName || "").trim(); + const visibleServerNames = (Array.isArray(accessibleServers) ? accessibleServers : []) + .slice(0, MAX_PROMPT_SERVER_NAMES) + .map((entry) => entry?.displayName || entry?.name) + .filter(Boolean); + const currentPermSummary = formatPermissionSummary(currentServerPerms); + + return [ + "You are ADPanel Agent inside a server page.", + "Always reply in English.", + "Keep replies short, natural, and precise.", + "Use one short sentence by default.", + "Never narrate internal planning, tool selection, or hidden reasoning.", + "Never say phrases like 'The user wants', 'I need to', 'I should use', 'Plan', or 'Current page server'.", + "You may still use the existing file command format from other system instructions for file tasks.", + "For sensitive server actions, use only the native tool plan format below.", + "Never use SERVER_START, SERVER_STOP, SERVER_RESTART, or SERVER_KILL text lines.", + "When you need a native server action, your entire reply must be one JSON block with no extra text.", + 'Schema: {"reply":"short queued reply","tool_calls":[{"name":"tool_name","args":{}}]}', + "Set tool_calls to an empty array when no native tool is needed.", + 'Example for current server start: {"reply":"Starting it now.","tool_calls":[{"name":"power_server","args":{"server":"current server","action":"start"}}]}', + 'Example for status check: {"reply":"Checking it now.","tool_calls":[{"name":"inspect_server","args":{"server":"current server"}}]}', + 'Example for status plus console check: {"reply":"Checking that now.","tool_calls":[{"name":"inspect_server","args":{"server":"current server"}},{"name":"query_console","args":{"server":"current server","limit":60}}]}', + 'Example for an explicit console command: {"reply":"Sending it now.","tool_calls":[{"name":"send_console_command","args":{"server":"current server","command":"say hello"}}]}', + "Only claim a sensitive action succeeded after the tool result confirms it.", + "If you need more than one tool, call multiple tools in the same tool plan or ask for another tool plan after tool results.", + "For console analysis, use query_console.", + "For real console execution, use send_console_command only when the user explicitly asked to run a command; the backend will deny it unless the user has console_write.", + "For backup restore or delete, list backups first when the backup identifier is unclear.", + "If the user says this server or current server, use the current page server.", + "If the user names a server unclearly, you may pass the raw wording in args.server and the backend will resolve it safely.", + `Current page server: ${currentServer || "unknown"}.`, + `Current page server permissions: ${currentPermSummary}.`, + visibleServerNames.length + ? `Accessible servers visible to this user: ${visibleServerNames.join(", ")}.` + : "No accessible servers were preloaded.", + "Allowed native tools:", + BOT_TOOL_DEFINITIONS.map((tool) => `${tool.name}: ${tool.description}`).join(" "), + ].join(" "); +} + +function buildBotReplyFromToolResult(toolName, toolResult) { + const name = String(toolName || "").trim(); + const result = toolResult && typeof toolResult === "object" ? toolResult : {}; + if (result.ok === false) { + return String(result.error || result.detail || "That action could not be completed.").trim(); + } + + switch (name) { + case "list_accessible_servers": { + const servers = Array.isArray(result.servers) ? result.servers : []; + if (!servers.length) return "You do not have access to any servers."; + const labels = servers.slice(0, 6).map((entry) => entry.displayName || entry.name).filter(Boolean); + return `You can access ${servers.length} server${servers.length === 1 ? "" : "s"}: ${labels.join(", ")}.`; + } + case "inspect_server": + return result.server?.name + ? `${result.server.displayName || result.server.name} is ${result.server.status || "unknown"}.` + : "I checked that server."; + case "power_server": + if (!(result.server && result.action)) return "Power action sent."; + return `Sent the ${result.action} request for ${result.server.displayName || result.server.name}.`; + case "query_console": + return result.server ? `I checked the recent console output for ${result.server.displayName || result.server.name}.` : "I checked the recent console output."; + case "send_console_command": + return result.server ? `Sent that command to ${result.server.displayName || result.server.name}.` : "Sent that command."; + case "list_backups": + return result.server + ? `I found ${Number(result.total || 0)} backup${Number(result.total || 0) === 1 ? "" : "s"} for ${result.server.displayName || result.server.name}.` + : "I checked the backups."; + case "create_backup": + return result.server ? `Created a backup for ${result.server.displayName || result.server.name}.` : "Created the backup."; + case "restore_backup": + return result.server ? `Started restoring that backup on ${result.server.displayName || result.server.name}.` : "Started restoring that backup."; + case "delete_backup": + return result.server ? `Deleted that backup from ${result.server.displayName || result.server.name}.` : "Deleted that backup."; + default: + return ""; + } +} + +function capitalize(value) { + const text = String(value || "").trim(); + return text ? `${text[0].toUpperCase()}${text.slice(1)}` : ""; +} + +function formatPowerProgressLabel(action) { + const normalized = String(action || "").trim().toLowerCase(); + const labels = { + start: "Starting", + stop: "Stopping", + restart: "Restarting", + kill: "Killing", + }; + return labels[normalized] || `${capitalize(normalized)}ing`; +} + +module.exports = { + BOT_GOOGLE_FUNCTION_DECLARATIONS, + BOT_TOOL_DEFINITIONS, + BOT_OPENAI_TOOL_DEFINITIONS, + MAX_BOT_TOOL_LOOPS, + buildBotAssistantSystemPrompt, + buildBotReplyFromToolResult, + extractJsonObjectFromText, + parseBotAssistantToolPlan, + resolveBackupFromList, + resolveServerFromAccessibleList, +}; diff --git a/utils/branding.js b/utils/branding.js new file mode 100644 index 0000000..019fb1f --- /dev/null +++ b/utils/branding.js @@ -0,0 +1,550 @@ + + + + + +const fs = require("fs"); +const path = require("path"); +const crypto = require("crypto"); + +const BRANDING_CONFIG_PATH = path.join(__dirname, "..", "data", "branding.json"); + + +let brandingCache = null; +let brandingCacheTime = 0; +const CACHE_TTL = 60000; + + +const DEFAULT_BRANDING = { + appName: "ADPanel", + logoUrl: null, + localLogoPath: null, + loginWatermarkUrl: "https://stalwart-pegasus-2c2ca4.netlify.app/watermark.webp", + localLoginWatermarkPath: null, + loginBackgroundType: "video", + loginBackgroundExternalUrl: null, + localLoginBackgroundPath: null, + loginBackgroundMimeType: "video/webm" +}; + + +const ALLOWED_EXTENSIONS = ["png", "jpg", "jpeg", "webp", "ico", "svg"]; +const ALLOWED_VIDEO_EXTENSIONS = ["webm", "mp4", "ogg", "ogv"]; +const DEFAULT_LOGIN_BACKGROUND_URL = "/images/bgvid.webm"; +const PUBLIC_IMAGES_DIR = path.join(__dirname, "..", "public", "images"); + + +const IMAGE_MAGIC_BYTES = { + png: [0x89, 0x50, 0x4E, 0x47], + jpg: [0xFF, 0xD8, 0xFF], + jpeg: [0xFF, 0xD8, 0xFF], + webp: [0x52, 0x49, 0x46, 0x46], + ico: [0x00, 0x00, 0x01, 0x00], + svg: null +}; + +const VIDEO_MIME_TYPES = { + webm: "video/webm", + mp4: "video/mp4", + ogg: "video/ogg", + ogv: "video/ogg" +}; + +// Prevent path traversal in local asset filenames +function safeBasename(p) { + if (!p || typeof p !== 'string') return null; + const b = path.basename(p); + return (b && b !== '.' && b !== '..') ? b : null; +} + +function getBrandingAssetVersionSuffix(branding) { + const updatedAt = typeof branding?.updatedAt === "string" ? branding.updatedAt.trim() : ""; + return updatedAt ? `?v=${encodeURIComponent(updatedAt)}` : ""; +} + +function resolveLocalBrandingAssetUrl(filename, branding) { + const safe = safeBasename(filename); + if (!safe) return null; + + const assetPath = path.join(PUBLIC_IMAGES_DIR, safe); + if (!fs.existsSync(assetPath)) return null; + + return `/images/${safe}${getBrandingAssetVersionSuffix(branding)}`; +} + +function resolveLoginWatermarkAssetUrl(branding) { + const config = branding && typeof branding === "object" ? branding : loadBrandingConfig(); + const localUrl = resolveLocalBrandingAssetUrl(config.localLoginWatermarkPath, config); + if (localUrl) return localUrl; + if (config.loginWatermarkUrl) { + return `/branding-media/login-watermark${getBrandingAssetVersionSuffix(config)}`; + } + return DEFAULT_BRANDING.loginWatermarkUrl; +} + +function resolveLoginBackgroundAssetUrl(branding) { + const config = branding && typeof branding === "object" ? branding : loadBrandingConfig(); + const localUrl = resolveLocalBrandingAssetUrl(config.localLoginBackgroundPath, config); + if (localUrl) return localUrl; + if (config.loginBackgroundExternalUrl) { + return `/branding-media/login-background${getBrandingAssetVersionSuffix(config)}`; + } + return DEFAULT_LOGIN_BACKGROUND_URL; +} + +function resolveFaviconAssetUrl(branding) { + const config = branding && typeof branding === "object" ? branding : loadBrandingConfig(); + return `/auth-assets/favicon${getBrandingAssetVersionSuffix(config)}`; +} + + + + + +function loadBrandingConfig() { + const now = Date.now(); + + + if (brandingCache && (now - brandingCacheTime) < CACHE_TTL) { + return brandingCache; + } + + try { + if (fs.existsSync(BRANDING_CONFIG_PATH)) { + const data = fs.readFileSync(BRANDING_CONFIG_PATH, "utf8"); + const config = JSON.parse(data); + + + brandingCache = { + ...DEFAULT_BRANDING, + ...config + }; + brandingCacheTime = now; + return brandingCache; + } + } catch (err) { + console.error("[branding] Error loading config:", err.message); + } + + + brandingCache = { ...DEFAULT_BRANDING }; + brandingCacheTime = now; + return brandingCache; +} + + + + + + +function saveBrandingConfig(config) { + try { + + const dataDir = path.dirname(BRANDING_CONFIG_PATH); + if (!fs.existsSync(dataDir)) { + fs.mkdirSync(dataDir, { recursive: true }); + } + + + const existing = loadBrandingConfig(); + const newConfig = { + ...existing, + ...config, + updatedAt: new Date().toISOString() + }; + + + const tempPath = BRANDING_CONFIG_PATH + ".tmp"; + fs.writeFileSync(tempPath, JSON.stringify(newConfig, null, 2), { mode: 0o600 }); + fs.renameSync(tempPath, BRANDING_CONFIG_PATH); + + + brandingCache = null; + brandingCacheTime = 0; + + return true; + } catch (err) { + console.error("[branding] Error saving config:", err.message); + return false; + } +} + + + + + + +function generateSafeLogoFilename(extension) { + const randomId = crypto.randomBytes(8).toString("hex"); + return `logo-${randomId}.${extension}`; +} + + + + + + +function validateBase64Image(base64Data) { + try { + + let cleanBase64 = base64Data; + if (base64Data.includes(",")) { + cleanBase64 = base64Data.split(",")[1]; + } + + + const buffer = Buffer.from(cleanBase64, "base64"); + + + if (buffer.length < 8) { + return { valid: false, error: "Image data too small" }; + } + + + if (buffer.length > 5 * 1024 * 1024) { + return { valid: false, error: "Image too large (max 5MB)" }; + } + + + let validType = false; + for (const [type, magic] of Object.entries(IMAGE_MAGIC_BYTES)) { + if (magic === null) continue; + + let matches = true; + for (let i = 0; i < magic.length; i++) { + if (buffer[i] !== magic[i]) { + matches = false; + break; + } + } + if (matches) { + validType = true; + break; + } + } + + + if (!validType) { + const text = buffer.toString("utf8", 0, Math.min(100, buffer.length)).toLowerCase(); + if (text.includes(" 40 * 1024 * 1024) { + return { valid: false, error: "Video too large (max 40MB)" }; + } + + const ext = String(expectedExt || "").toLowerCase(); + let valid = false; + + if (ext === "webm") { + valid = buffer[0] === 0x1a && buffer[1] === 0x45 && buffer[2] === 0xdf && buffer[3] === 0xa3; + } else if (ext === "mp4") { + valid = buffer.slice(4, 8).toString("ascii") === "ftyp"; + } else if (ext === "ogg" || ext === "ogv") { + valid = buffer.slice(0, 4).toString("ascii") === "OggS"; + } + + if (!valid) { + return { valid: false, error: "Unrecognized video format" }; + } + + if (declaredMime && !declaredMime.startsWith("video/")) { + return { valid: false, error: "Invalid video MIME type" }; + } + + return { valid: true, data: buffer }; + } catch (err) { + return { valid: false, error: "Failed to decode video data" }; + } +} + + + + +function invalidateBrandingCache() { + brandingCache = null; + brandingCacheTime = 0; +} + + + + + + +function sanitizeAppName(appName) { + if (!appName || typeof appName !== "string") { + return null; + } + + + const trimmed = appName.trim().slice(0, 50); + + + + const sanitized = trimmed.replace(/[^a-zA-Z0-9\s\-_.!]/g, ""); + + if (sanitized.length < 1) { + return null; + } + + return sanitized; +} + + + + + + +function isPrivateOrReservedHost(hostname) { + if (!hostname) return true; + const h = hostname.toLowerCase(); + + if (h === "localhost" || h.endsWith(".localhost")) return true; + + const ipv4 = h.match(/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/); + if (ipv4) { + const [a, b] = [parseInt(ipv4[1], 10), parseInt(ipv4[2], 10)]; + if (a === 0) return true; // 0.0.0.0/8 + if (a === 10) return true; // 10.0.0.0/8 + if (a === 127) return true; // 127.0.0.0/8 + if (a === 169 && b === 254) return true; // 169.254.0.0/16 (link-local / cloud metadata) + if (a === 172 && b >= 16 && b <= 31) return true; // 172.16.0.0/12 + if (a === 192 && b === 168) return true; // 192.168.0.0/16 + return false; + } + + // IPv6 (Node.js URL parser may keep brackets) + const ipv6 = h.startsWith("[") && h.endsWith("]") ? h.slice(1, -1) : h; + if (ipv6 === "::1" || ipv6 === "::" || ipv6.startsWith("fe80:") || ipv6.startsWith("fc") || ipv6.startsWith("fd")) return true; + if (ipv6.startsWith("::ffff:")) { + const mapped = ipv6.slice(7); + // Dotted-decimal form (::ffff:127.0.0.1) + if (mapped.includes(".")) return isPrivateOrReservedHost(mapped); + // Hex form (::ffff:7f00:1) — convert to IPv4 + const hex = mapped.replace(":", "").padStart(8, "0"); + const a = parseInt(hex.slice(0, 2), 16), b = parseInt(hex.slice(2, 4), 16); + const c = parseInt(hex.slice(4, 6), 16), d = parseInt(hex.slice(6, 8), 16); + return isPrivateOrReservedHost(`${a}.${b}.${c}.${d}`); + } + + return false; +} + +function sanitizeLogoUrl(url) { + if (!url || typeof url !== "string") { + return null; + } + + const trimmed = url.trim(); + + + if (!trimmed.startsWith("http://") && !trimmed.startsWith("https://")) { + return null; + } + + + try { + const parsed = new URL(trimmed); + + if (parsed.protocol !== "http:" && parsed.protocol !== "https:") { + return null; + } + + // Block requests to internal/private network addresses (SSRF protection) + if (isPrivateOrReservedHost(parsed.hostname)) { + return null; + } + + return parsed.href; + } catch (e) { + return null; + } +} + + + + + + + +function brandingMiddleware(req, res, next) { + const branding = loadBrandingConfig(); + const safeLogo = safeBasename(branding.localLogoPath); + const safeWatermark = safeBasename(branding.localLoginWatermarkPath); + + + res.locals.branding = { + appName: branding.appName || DEFAULT_BRANDING.appName, + faviconUrl: resolveFaviconAssetUrl(branding), + logoUrl: safeLogo + ? `/images/${safeLogo}` + : (branding.logoUrl || null), + loginWatermarkUrl: safeWatermark + ? `/images/${safeWatermark}` + : resolveLoginWatermarkAssetUrl(branding), + loginBackgroundType: branding.loginBackgroundType || DEFAULT_BRANDING.loginBackgroundType, + loginBackgroundUrl: resolveLoginBackgroundAssetUrl(branding), + loginBackgroundMimeType: branding.loginBackgroundMimeType || DEFAULT_BRANDING.loginBackgroundMimeType + }; + + next(); +} + +module.exports = { + brandingMiddleware, + loadBrandingConfig, + saveBrandingConfig, + sanitizeAppName, + sanitizeLogoUrl, + generateSafeLogoFilename, + validateBase64Image, + validateBase64Video, + getValidatedExtension, + getValidatedVideoExtension, + getMimeTypeForExtension, + getMediaTypeFromFilename, + getMediaTypeFromUrl, + getExtensionFromUrl, + getBrandingAssetVersionSuffix, + resolveFaviconAssetUrl, + resolveLoginWatermarkAssetUrl, + resolveLoginBackgroundAssetUrl, + invalidateBrandingCache, + DEFAULT_BRANDING, + DEFAULT_LOGIN_BACKGROUND_URL +}; diff --git a/utils/dashboard-assistant-service.js b/utils/dashboard-assistant-service.js new file mode 100644 index 0000000..ba515d2 --- /dev/null +++ b/utils/dashboard-assistant-service.js @@ -0,0 +1,4560 @@ +"use strict"; + +const https = require("https"); +const crypto = require("crypto"); +const FormData = require("form-data"); +const { + TOOL_DEFINITIONS, + POWER_TOOL_DEFINITIONS, + buildSystemPrompt, + createDashboardAssistantToolRunner, +} = require("./dashboard-assistant-tools"); + +const DEFAULT_CHAT_TITLE = "ADPanel Assistant"; +const DEFAULT_GROQ_MODEL = process.env.DASHBOARD_ASSISTANT_GROQ_MODEL || "llama-3.1-8b-instant"; +const DEFAULT_GROQ_TRANSCRIPTION_MODEL = process.env.DASHBOARD_ASSISTANT_GROQ_STT_MODEL || "whisper-large-v3"; +const DEFAULT_GOOGLE_MODEL = process.env.DASHBOARD_ASSISTANT_GOOGLE_MODEL || "gemini-2.5-flash-lite"; +const DEFAULT_GOOGLE_TRANSCRIPTION_MODEL = process.env.DASHBOARD_ASSISTANT_GOOGLE_STT_MODEL || "gemini-2.5-flash"; +const VISIBLE_CHAT_HISTORY_LIMIT = 80; +const CHAT_HISTORY_LIMIT = VISIBLE_CHAT_HISTORY_LIMIT; +const MAX_CHAT_MESSAGES = VISIBLE_CHAT_HISTORY_LIMIT; +const MODEL_CONTEXT_RECENT_MESSAGE_LIMIT = 16; +const MODEL_CONTEXT_RECENT_MESSAGE_CHAR_LIMIT = 520; +const MODEL_CONTEXT_NEAR_MESSAGE_CHAR_LIMIT = 760; +const MODEL_CONTEXT_LATEST_MESSAGE_CHAR_LIMIT = 1400; +const MODEL_CONTEXT_OLDER_TRANSCRIPT_COUNT = 10; +const MODEL_CONTEXT_OLDER_TRANSCRIPT_TOTAL_LIMIT = 1400; +const ACCESSIBLE_SERVERS_CACHE_TTL_MS = 15_000; +const ASSISTANT_MAX_LOOPS = 6; +const AUDIO_UPLOAD_LIMIT_BYTES = parseInt(process.env.DASHBOARD_ASSISTANT_AUDIO_LIMIT_BYTES || "", 10) || 15 * 1024 * 1024; +const GOOGLE_OPENAI_CHAT_URL = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions"; +const GOOGLE_INTERACTIONS_URL = "https://generativelanguage.googleapis.com/v1beta/interactions"; +const POWER_ONLY_ASSISTANT = true; +const PROVIDER_LABELS = Object.freeze({ + groq: "Groq", + google: "Google AI Studio", +}); +const SUPPORTED_PROVIDERS = new Set(Object.keys(PROVIDER_LABELS)); +const ASSISTANT_PROVIDER_SECRET_ENV_KEYS = Object.freeze({ + groq: { + encrypted: "DASHBOARD_ASSISTANT_GROQ_API_KEY_ENCRYPTED", + legacy: ["GROQ_API_KEY"], + }, + google: { + encrypted: "DASHBOARD_ASSISTANT_GOOGLE_AI_API_KEY_ENCRYPTED", + legacy: ["GOOGLE_AI_STUDIO_API_KEY", "GOOGLE_AI_KEY"], + }, +}); +const ASSISTANT_PROVIDER_SECRET_VERSION = "enc-v1"; +const ASSISTANT_PROVIDER_SECRET_CONTEXT = "adpanel:dashboard-assistant:provider-key:v1"; +const ASSISTANT_SERVER_PAGE_SECTION_LABELS = Object.freeze({ + console: "console", + info: "info", + files: "files", + activity: "activity", + backups: "backups", + scheduler: "scheduler", + store: "store", + resource_stats: "resource stats", + subdomains: "subdomains", + reinstall: "reinstall", + ai_help: "AI help", +}); +const ASSISTANT_SETTINGS_PANEL_LABELS = Object.freeze({ + preferences: "Preferences", + customization: "Customization", + account: "Account", + security: "Security", + databases: "Databases", + nodes: "Nodes", + templates: "Templates", + servers: "Servers", + webhooks: "Webhooks", + panelinfo: "Panel Info", +}); +const ASSISTANT_SETTINGS_ACTION_LABELS = Object.freeze({ + create_user: "Create User", + branding: "Branding", + login_watermark: "Login Watermark", + login_background: "Login Background", + alert: "Alerts", + quick_action_admin: "Admin Quick Actions", + quick_action_user: "User Quick Actions", + database_setup: "Database Setup", + pgadmin_setup: "pgAdmin Setup", + mongodb_setup: "MongoDB Setup", + captcha: "Captcha", + maintenance: "Maintenance", + create_node: "Create Node", + create_template: "Create Template", + add_webhook: "Add Webhook", +}); +const accessibleServersForAssistantCache = new Map(); +const ASSISTANT_PROVIDER_HTTPS_AGENTS = Object.freeze({ + groq: new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10_000, + maxSockets: 24, + maxFreeSockets: 12, + timeout: 90_000, + }), + google: new https.Agent({ + keepAlive: true, + keepAliveMsecs: 10_000, + maxSockets: 24, + maxFreeSockets: 12, + timeout: 90_000, + }), +}); + +function buildStoredKeyFieldValue(value) { + const clean = String(value || "").trim(); + if (!clean) return ""; + return "\u2022".repeat(clean.length); +} + +function normalizeMessageContent(content) { + if (Array.isArray(content)) { + return content + .map((part) => { + if (typeof part === "string") return part; + if (part && typeof part.text === "string") return part.text; + if (part && part.type === "text" && typeof part.text === "string") return part.text; + return ""; + }) + .join("") + .trim(); + } + return String(content || "").trim(); +} + +function stripAssistantLookupDiacritics(value) { + return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, ""); +} + +function normalizeAssistantLookupText(value) { + return stripAssistantLookupDiacritics(value) + .toLowerCase() + .replace(/[`"'“”‘’()[\]{}<>]/g, " ") + .replace(/[_./-]+/g, " ") + .replace(/[^a-z0-9 ]+/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function compactAssistantLookupText(value) { + return normalizeAssistantLookupText(value).replace(/\s+/g, ""); +} + +function getAssistantServerMentionAliases(entry) { + const aliases = new Set(); + for (const value of [entry?.name, entry?.displayName, entry?.id, entry?.bot, entry?.legacyId]) { + const clean = String(value || "").trim(); + if (!clean) continue; + aliases.add(clean); + const spaced = clean.replace(/[_./-]+/g, " ").replace(/\s+/g, " ").trim(); + if (spaced) aliases.add(spaced); + } + return Array.from(aliases); +} + +function inferAssistantServerMention(message, accessibleServers) { + const raw = String(message || "").trim(); + if (!raw) return null; + + const normalizedMessage = normalizeAssistantLookupText(raw); + const compactMessage = compactAssistantLookupText(raw); + if (!normalizedMessage && !compactMessage) return null; + + const wrappedMentions = Array.from(raw.matchAll(/["'`“”(\[]([^"'`“”()[\]]{1,120})["'`”)\]]/g)) + .map((match) => String(match?.[1] || "").trim()) + .filter(Boolean); + const normalizedWrapped = wrappedMentions.map((value) => normalizeAssistantLookupText(value)).filter(Boolean); + const compactWrapped = wrappedMentions.map((value) => compactAssistantLookupText(value)).filter(Boolean); + + const scored = (Array.isArray(accessibleServers) ? accessibleServers : []) + .filter((entry) => entry?.name) + .map((entry) => { + let best = 0; + for (const alias of getAssistantServerMentionAliases(entry)) { + const normalizedAlias = normalizeAssistantLookupText(alias); + const compactAlias = compactAssistantLookupText(alias); + if (!normalizedAlias && !compactAlias) continue; + + if (normalizedAlias && normalizedWrapped.includes(normalizedAlias)) { + best = Math.max(best, 1600 + normalizedAlias.length); + } + if (compactAlias && compactWrapped.includes(compactAlias)) { + best = Math.max(best, 1550 + compactAlias.length); + } + + if (normalizedAlias && normalizedMessage && ` ${normalizedMessage} `.includes(` ${normalizedAlias} `)) { + best = Math.max(best, 1200 + normalizedAlias.length); + } + if (compactAlias && compactAlias.length >= 4 && compactMessage.includes(compactAlias)) { + best = Math.max(best, 900 + compactAlias.length); + } + + const aliasTokens = normalizedAlias.split(" ").filter(Boolean); + if (aliasTokens.length >= 2) { + const overlap = aliasTokens.filter((token) => ` ${normalizedMessage} `.includes(` ${token} `)).length; + if (overlap === aliasTokens.length) { + best = Math.max(best, 650 + aliasTokens.length * 40); + } else if (overlap > 0) { + best = Math.max(best, 240 + overlap * 35); + } + } else if (aliasTokens.length === 1 && aliasTokens[0].length >= 4 && ` ${normalizedMessage} `.includes(` ${aliasTokens[0]} `)) { + best = Math.max(best, 520 + aliasTokens[0].length); + } + } + return { entry, score: best }; + }) + .filter((item) => item.score > 0) + .sort((left, right) => right.score - left.score); + + if (!scored.length) return null; + + const [best, second] = scored; + if (second && best.score < second.score + 140) { + return null; + } + if (best.score < 520) { + return null; + } + + return { + name: best.entry.name, + displayName: best.entry.displayName || best.entry.name, + score: best.score, + }; +} + +function sanitizeToken(rawToken) { + return String(rawToken || "").replace(/\0/g, "").replace(/[\r\n]+/g, "").trim(); +} + +function sanitizeTranscriptionLanguage(value) { + const primary = String(value || "").trim().toLowerCase().split(/[-_]/)[0]; + return /^[a-z]{2,3}$/.test(primary) ? primary : ""; +} + +function sanitizeTranscriptionPrompt(value) { + const clean = String(value || "").replace(/\s+/g, " ").trim(); + return clean.slice(0, 500); +} + +function sanitizeProvider(value) { + const provider = String(value || "").trim().toLowerCase(); + return SUPPORTED_PROVIDERS.has(provider) ? provider : ""; +} + +function getProviderLabel(provider) { + return PROVIDER_LABELS[sanitizeProvider(provider)] || "AI provider"; +} + +function getAssistantProviderSecretConfig(provider) { + return ASSISTANT_PROVIDER_SECRET_ENV_KEYS[sanitizeProvider(provider)] || null; +} + +function getAssistantProviderSecretMaterial() { + return sanitizeToken( + process.env.DASHBOARD_ASSISTANT_ENCRYPTION_SECRET || + process.env.SESSION_SECRET || + process.env.SECRET_KEY || + "" + ); +} + +function getAssistantProviderCipherKey() { + const secretMaterial = getAssistantProviderSecretMaterial(); + if (!secretMaterial) { + throw new Error("Assistant encryption secret is unavailable."); + } + + return crypto + .createHash("sha256") + .update(ASSISTANT_PROVIDER_SECRET_CONTEXT) + .update("\0") + .update(secretMaterial) + .digest(); +} + +function encryptAssistantProviderToken(rawToken) { + const token = sanitizeToken(rawToken); + if (!token) return ""; + + // Provider API keys must stay reversible so the assistant can call Groq/Google later. + const iv = crypto.randomBytes(12); + const cipher = crypto.createCipheriv("aes-256-gcm", getAssistantProviderCipherKey(), iv); + const ciphertext = Buffer.concat([cipher.update(token, "utf8"), cipher.final()]); + const authTag = cipher.getAuthTag(); + + return [ + ASSISTANT_PROVIDER_SECRET_VERSION, + iv.toString("base64"), + authTag.toString("base64"), + ciphertext.toString("base64"), + ].join(":"); +} + +function decryptAssistantProviderToken(payload) { + const value = sanitizeToken(payload); + if (!value) return ""; + + const [version, ivBase64, authTagBase64, ciphertextBase64] = value.split(":"); + if ( + version !== ASSISTANT_PROVIDER_SECRET_VERSION || + !ivBase64 || + !authTagBase64 || + !ciphertextBase64 + ) { + throw new Error("Invalid assistant provider token format."); + } + + const decipher = crypto.createDecipheriv( + "aes-256-gcm", + getAssistantProviderCipherKey(), + Buffer.from(ivBase64, "base64") + ); + decipher.setAuthTag(Buffer.from(authTagBase64, "base64")); + + const plaintext = Buffer.concat([ + decipher.update(Buffer.from(ciphertextBase64, "base64")), + decipher.final(), + ]).toString("utf8"); + + return sanitizeToken(plaintext); +} + +function detectDirectAccountFlowIntent(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return null; + + const wantsRecovery = + /\b(recover|recovery|forgot|lost|reset)\b/.test(text) && + /\b(code|codes|access|password|email|2fa|two[- ]factor)\b/.test(text); + const wantsChange = + /\b(change|update|open|show|edit|manage|configure|setup|set up|turn on|turn off|disable|enable)\b/.test(text); + + if (/\bpassword\b/.test(text)) { + if (wantsRecovery || /\brecovery code|forgot password|lost password\b/.test(text)) { + return { + flow: "recover_password", + reply: "Opening password recovery.", + }; + } + if (wantsChange || /\bchange my password\b/.test(text)) { + return { + flow: "change_password", + reply: "Opening password change.", + }; + } + } + + if (/\bemail\b/.test(text)) { + if (wantsRecovery || /\brecovery code|lost email access|recover email\b/.test(text)) { + return { + flow: "recover_email", + reply: "Opening email recovery.", + }; + } + if (wantsChange || /\bchange my email\b/.test(text)) { + return { + flow: "change_email", + reply: "Opening email change.", + }; + } + } + + if (/\b2fa\b|\btwo[- ]factor\b|\bauthenticator\b/.test(text)) { + if (wantsRecovery || /\brecovery code|lost authenticator|recover 2fa|recover two[- ]factor\b/.test(text)) { + return { + flow: "recover_2fa", + reply: "Opening 2FA recovery.", + }; + } + if (wantsChange || /\bchange my 2fa\b|\bchange my two[- ]factor\b/.test(text)) { + return { + flow: "change_2fa", + reply: "Opening 2FA settings.", + }; + } + } + + return null; +} + +function detectDirectCreateServerFlowIntent(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return null; + + if (/\b(how|what|which|why|explain|guide|tutorial|cum|ce|care|de ce)\b/.test(text)) { + return null; + } + + const wantsCreateServer = + ( + /\b(create|make|spin\s*up|deploy|provision|start)\b/.test(text) || + /\b(can you create|could you create|help me create|let'?s create|i want to create|want to create|wanna create|would like to create)\b/.test(text) || + /\b(vreau|vrea|vreau sa|hai sa|te rog)\b/.test(text) || + /\b(creez|creeaza|creezi|creare|deschide|arata)\b/.test(text) + ) && + /\b(server|minecraft|nodejs|python|discord)\b/.test(text); + + if (!wantsCreateServer) { + return null; + } + + return { + reply: "Opening the Create Server window.", + }; +} + +function detectDirectBulkPowerIntent(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return null; + + if (/\b(how|what|which|why|explain|guide|tutorial|cum|ce|care|de ce)\b/.test(text)) { + return null; + } + + const mentionsServerWords = /\b(server|servers|servere|serverele)\b/.test(text); + const mentionsBulkQualifier = /\b(?:all|every|all accessible|all my|all the|toate|toți|toate serverele|toate serverele mele|toate serverele la care am acces)\b/.test(text); + const mentionsBulkPronoun = /\b(?:them all|all of them|pe toate)\b/.test(text); + const mentionsNonServerTargets = /\b(plugin|plugins|file|files|folder|folders|directory|directories|node|nodes|template|templates)\b/.test(text); + const mentionsAllServers = + (mentionsServerWords && mentionsBulkQualifier) || + (mentionsBulkPronoun && !mentionsNonServerTargets); + + if (!mentionsAllServers) { + return null; + } + + if (/\b(restart|reboot|cycle|bounce|reload|reporneste|repornește)\b/.test(text)) { + return { action: "restart" }; + } + if (/\b(kill|force stop|hard stop|omoara|omoară|ucide)\b/.test(text)) { + return { action: "kill" }; + } + if (/\b(stop|shutdown|shut down|turn off|power off|take down|opreste|oprește|inchide|închide)\b/.test(text)) { + return { action: "stop" }; + } + if (/\b(start|run|boot|turn on|power on|bring up|spin up|porneste|pornește|deschide)\b/.test(text)) { + return { action: "start" }; + } + + return null; +} + +function detectAssistantPowerAction(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return ""; + if (/\b(restart|reboot|cycle|bounce|reload|reporneste|repornește|da restart)\b/.test(text)) return "restart"; + if (/\b(kill|force stop|hard stop|omoara|omoară|ucide|terminate)\b/.test(text)) return "kill"; + if (/\b(stop|shutdown|shut down|turn off|power off|take down|opreste|oprește|inchide|închide|da stop)\b/.test(text)) return "stop"; + if (/\b(start|run|boot|turn on|power on|bring up|spin up|porneste|pornește|da start)\b/.test(text)) return "start"; + return ""; +} + +function detectDirectSinglePowerIntent(message, serverHint = "") { + const text = String(message || "").trim(); + if (!text) return null; + + const lower = text.toLowerCase(); + if (/\b(how|what|which|why|explain|guide|tutorial|cum|ce|care|de ce)\b/.test(lower)) { + return null; + } + + if (detectDirectBulkPowerIntent(text)) { + return null; + } + + const hasNonPowerIntent = /\b(file|files|config|folder|directory|log|logs|console|error|backup|plugin|plugins|mod|mods|edit|change|write|read|show|list|inspect|analy[sz]e|fix|debug|server\.properties)\b/i.test(text); + if (hasNonPowerIntent) { + return null; + } + + const action = detectAssistantPowerAction(text); + if (!action) return null; + + const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); + if (!server) return null; + + return { + toolName: "power_server", + args: { server: text, action }, + model: "adpanel-power-router", + }; +} + +function messageLooksLikeBusiestLookup(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + + const mentionsTarget = /\b(node|nodes|nod|noduri|server|servers|servere|serverele)\b/.test(text); + if (!mentionsTarget) return false; + + const mentionsLoadWords = /\b(busiest|busy|most loaded|highest load|load|usage|heaviest|incarcat|încărcat|solicitat|ocupat)\b/.test(text); + const mentionsSuperlativeMetric = + /\b(?:uses?|using|consumes?|consuming|has|with)\s+the\s+most\s+(?:cpu|ram|memory|mem|disk|storage|space)\b/.test(text) || + /\b(?:most|highest)\s+(?:cpu|ram|memory|mem|disk|storage|space)\b/.test(text) || + /\b(?:cel mai mult|cea mai multa|cea mai multă)\s+(?:cpu|ram|memorie|memory|disk|storage|spatiu|spațiu)\b/.test(text); + + return mentionsLoadWords || mentionsSuperlativeMetric; +} + +function messageLooksLikeDiagnosisRequest(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + + return ( + /\b(server|servers|servere|serverele)\b/.test(text) && + /\b(diagnose|diagnostic|crash|crashed|crashing|lag|lagging|slow|startup|start up|won'?t start|problem|issue|error|failing|failure|why is|why did|de ce|problema|eroare|a cazut|a căzut)\b/.test(text) + ); +} + +function messageLooksLikeConsoleCheckRequest(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + + if (messageLooksLikeDiagnosisRequest(text)) return true; + + const mentionsConsole = + /\b(console|logs?|log output|output|latest log|latest logs|startup log|crash log|stderr|stdout|stack trace|traceback)\b/.test(text); + const mentionsInspection = + /\b(check|check on|show|read|look|inspect|review|scan|analy[sz]e|what|why|tell me|see|look into|figure out)\b/.test(text); + const mentionsFailure = + /\b(error|errors|crash|crashed|crashing|startup|start up|won'?t start|issue|problem|failing|failure|panic|exception)\b/.test(text); + const mentionsStartupTimingOrHealth = + /\b(how many seconds|how long(?: did it take)?|startup time|start time|boot time|time to start|took(?: .*?)? to start|startup seconds|started (?:correctly|good|well|fine|okay|ok)|did it start (?:correctly|well|fine|okay|ok)|running well|run(?:ning)? good|run(?:ning)? fine|running okay|came online|is it healthy|is it ok|is it okay|started healthy|fully started|all good|booted|launched)\b/.test(text); + + return (mentionsConsole && (mentionsInspection || mentionsFailure)) || mentionsStartupTimingOrHealth; +} + +function messageLooksLikeMinecraftBatchPropertyUpdate(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + + return ( + ( + /\bminecraft\b/.test(text) || + /\bserver\.properties\b/.test(text) || + /\b(online[- ]mode|max[- ]players|motd|pvp|white[- ]list|whitelist|difficulty|view[- ]distance|simulation[- ]distance|spawn[- ]protection|allow[- ]flight|hardcore)\b/.test(text) + ) && + /\b(all|every|all accessible|all my|them all|all of them|toate|pe toate)\b/.test(text) && + /\b(set|change|update|edit|replace|switch|make|put|pune|seteaza|setează|schimba|schimbă|modifica|modifică)\b/.test(text) && + ( + /\b(server\.properties|properties|config)\b/.test(text) || + /[a-z0-9_.-]+\s*(?:=|to|pe)\s*[^\s]+/.test(text) + ) + ); +} + +function messageLooksLikeStructuredMinecraftPropertyMutation(message) { + const text = String(message || "").trim(); + if (!text) return false; + + const lower = text.toLowerCase(); + const mentionsMinecraftContext = + /\bminecraft\b/.test(lower) || + /\bserver\.properties\b/.test(lower) || + MINECRAFT_PROPERTY_ALIASES.some((entry) => entry.pattern.test(text)); + if (!mentionsMinecraftContext) return false; + + return /\b(set|change|update|edit|replace|switch|make|put|pune|seteaza|setează|schimba|schimbă|modifica|modifică)\b/i.test(text); +} + +const MINECRAFT_PROPERTY_ALIASES = Object.freeze([ + { pattern: /\bonline[- ]mode\b/i, key: "online-mode" }, + { pattern: /\bmax[- ]players\b/i, key: "max-players" }, + { pattern: /\bview[- ]distance\b/i, key: "view-distance" }, + { pattern: /\bsimulation[- ]distance\b/i, key: "simulation-distance" }, + { pattern: /\bspawn[- ]protection\b/i, key: "spawn-protection" }, + { pattern: /\ballow[- ]flight\b/i, key: "allow-flight" }, + { pattern: /\bwhite[- ]list\b/i, key: "white-list" }, + { pattern: /\bwhitelist\b/i, key: "white-list" }, + { pattern: /\bmotd\b/i, key: "motd" }, + { pattern: /\bdifficulty\b/i, key: "difficulty" }, + { pattern: /\bpvp\b/i, key: "pvp" }, + { pattern: /\bhardcore\b/i, key: "hardcore" }, +]); + +function inferAssistantMetric(message) { + const text = String(message || "").trim().toLowerCase(); + if (/\bcpu\b/.test(text)) return "cpu"; + if (/\b(memory|ram)\b/.test(text)) return "memory"; + if (/\b(disk|storage|space)\b/.test(text)) return "disk"; + return "balanced"; +} + +function inferAssistantMetricDetails(message) { + const text = String(message || "").trim().toLowerCase(); + const includeMetrics = []; + + if (/\bcpu\b/.test(text)) includeMetrics.push("cpu"); + if (/\b(memory|ram)\b/.test(text)) includeMetrics.push("memory"); + if (/\b(disk|storage|space)\b/.test(text)) includeMetrics.push("disk"); + + return { + metric: includeMetrics.length === 1 ? includeMetrics[0] : "balanced", + includeMetrics, + }; +} + +function detectDirectLoadLookupIntent(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text || !messageLooksLikeBusiestLookup(text)) return null; + + const metricDetails = inferAssistantMetricDetails(text); + const mentionsNode = /\b(node|nodes|nod|noduri)\b/.test(text); + const mentionsServer = /\b(server|servers|servere|serverele)\b/.test(text); + + if (mentionsNode) { + return { + toolName: "get_busiest_node", + args: { metric: metricDetails.metric, includeMetrics: metricDetails.includeMetrics }, + model: "adpanel-load-router", + }; + } + if (mentionsServer) { + return { + toolName: "get_busiest_server", + args: { metric: metricDetails.metric, includeMetrics: metricDetails.includeMetrics }, + model: "adpanel-load-router", + }; + } + return null; +} + +function detectDirectConsoleCheckIntent(message, serverHint = "") { + const text = String(message || "").trim(); + if (!text) return null; + + const looksLikeConsoleCheck = messageLooksLikeConsoleCheckRequest(text) + || (!!serverHint && /\b(console|logs?|log output|startup|crash|error|errors|why|diagnose|issue|problem|failing|failure|started|seconds?|healthy|running well|running fine|running okay|took to start|time to start|boot time|startup time|start time|started good|started well|started fine|started okay|started ok|all good|booted|launched)\b/i.test(text)); + if (!looksLikeConsoleCheck) return null; + + return { + toolName: "check_server_console", + args: { server: text, question: text }, + model: "adpanel-console-router", + }; +} + +function messageLooksLikeServerLimitsCheckRequest(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + if (messageLooksLikeBusiestLookup(text)) return false; + if (messageLooksLikeAssistantOpenRequest(text)) return false; + if (messageLooksLikeConsoleCheckRequest(text)) return false; + + const mentionsMetric = /\b(cpu|ram|memory|disk|storage|space|resource(?:s| stats?)?|quota|quotas|limit|limits|headroom|free|remaining|left|available|usage|used)\b/.test(text); + const mentionsInspection = /\b(check|show|see|tell me|what|how much|how many|look|inspect|review|analy[sz]e|is|are|close|near|almost|running out|enough)\b/.test(text); + const mentionsPressure = /\b(close to|near(?:ly)? full|almost full|very high|too high|running out|low on|full|running hot|saturated|overloaded|healthy|okay|ok|fine)\b/.test(text); + return mentionsMetric && (mentionsInspection || mentionsPressure); +} + +function detectDirectServerLimitsIntent(message, serverHint = "") { + const text = String(message || "").trim(); + if (!text) return null; + + const looksLikeLimitsCheck = messageLooksLikeServerLimitsCheckRequest(text) + || (!!serverHint && /\b(cpu|ram|memory|disk|storage|space|quota|quotas|limit|limits|headroom|free|remaining|left|available|close to|near full|almost full|too high)\b/i.test(text)); + if (!looksLikeLimitsCheck) return null; + + const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); + if (!server) return null; + + const metricDetails = inferAssistantMetricDetails(text); + return { + toolName: "check_server_limits", + args: { + server: text, + question: text, + includeMetrics: metricDetails.includeMetrics, + }, + model: "adpanel-limits-router", + }; +} + +function messageLooksLikeAssistantOpenRequest(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + return /\b(open|show|take me|go to|goto|navigate|bring me|launch|pop ?up|new tab|tab|manage|configure|config|edit|access)\b/.test(text); +} + +function normalizeAssistantServerPageSection(value) { + const text = normalizeAssistantLookupText(value); + if (!text) return "console"; + if (/\b(backups?|snapshots?)\b/.test(text)) return "backups"; + if (/\b(files?|file manager|explorer|folders?|directory|directories)\b/.test(text)) return "files"; + if (/\b(activity|history|events?)\b/.test(text)) return "activity"; + if (/\b(scheduler|schedule|schedules|tasks?)\b/.test(text)) return "scheduler"; + if (/\b(store|plugins?|versions?|marketplace)\b/.test(text)) return "store"; + if (/\b(resource(?:s| stats?)?|cpu|ram|memory|disk|storage)\b/.test(text)) return "resource_stats"; + if (/\b(subdomains?|domains?)\b/.test(text)) return "subdomains"; + if (/\b(reinstall|rebuild|reimage|re-image)\b/.test(text)) return "reinstall"; + if (/\b(ai help|assistant help)\b/.test(text)) return "ai_help"; + if (/\b(info|overview|details?)\b/.test(text)) return "info"; + return "console"; +} + +function formatAssistantServerPageSectionLabel(section) { + const key = String(section || "").trim(); + return ASSISTANT_SERVER_PAGE_SECTION_LABELS[key] || "server page"; +} + +function normalizeAssistantSettingsAction(value) { + const text = normalizeAssistantLookupText(value); + if (!text) return ""; + if (/\b(pgadmin|postgres setup|postgresql setup)\b/.test(text)) return "pgadmin_setup"; + if (/\b(mongodb|mongo setup)\b/.test(text)) return "mongodb_setup"; + if (/\b(create|new|add)\b.*\buser\b/.test(text)) return "create_user"; + if (/\bbranding\b/.test(text)) return "branding"; + if (/\blogin watermark\b|\bwatermark\b/.test(text)) return "login_watermark"; + if (/\blogin background\b/.test(text)) return "login_background"; + if (/\b(alert|announcement|banner|global alert)\b/.test(text)) return "alert"; + if (/\b(admin quick action|quick action admin|admin action)\b/.test(text)) return "quick_action_admin"; + if (/\b(user quick action|quick action user|user action)\b/.test(text)) return "quick_action_user"; + if (/\b(database setup|setup database|set up database|phpmyadmin|mysql setup)\b/.test(text)) return "database_setup"; + if (/\bcaptcha\b/.test(text)) return "captcha"; + if (/\bmaintenance\b/.test(text)) return "maintenance"; + if (/\b(create|new|add)\b.*\bnode\b/.test(text)) return "create_node"; + if (/\b(create|new|add)\b.*\btemplate\b/.test(text)) return "create_template"; + if ((/\b(add|create|new)\b/.test(text) || /\bpopup\b|\bmodal\b/.test(text)) && /\bwebhook\b/.test(text)) return "add_webhook"; + return ""; +} + +function inferAssistantSettingsPanelFromAction(action) { + const normalized = String(action || "").trim(); + if (!normalized) return ""; + if (["branding", "login_watermark", "login_background"].includes(normalized)) return "customization"; + if (["create_user"].includes(normalized)) return "account"; + if (["captcha", "maintenance"].includes(normalized)) return "security"; + if (["database_setup", "pgadmin_setup", "mongodb_setup"].includes(normalized)) return "databases"; + if (["create_node"].includes(normalized)) return "nodes"; + if (["create_template"].includes(normalized)) return "templates"; + if (["add_webhook"].includes(normalized)) return "webhooks"; + if (["alert", "quick_action_admin", "quick_action_user"].includes(normalized)) return "customization"; + return ""; +} + +function normalizeAssistantSettingsPanel(value) { + const text = normalizeAssistantLookupText(value); + if (!text) return ""; + if (/\b(panel info|panelinfo)\b/.test(text)) return "panelinfo"; + if (/\b(customization|customisation|appearance|look|theme|style|branding)\b/.test(text)) return "customization"; + if (/\b(account|accounts?|users?|user management)\b/.test(text)) return "account"; + if (/\b(security|captcha|maintenance)\b/.test(text)) return "security"; + if (/\b(databases?|database|db|mysql|postgres|postgresql|pgadmin|mongo|mongodb)\b/.test(text)) return "databases"; + if (/\b(nodes?|infrastructure)\b/.test(text)) return "nodes"; + if (/\b(templates?|docker templates?)\b/.test(text)) return "templates"; + if (/\b(servers?|instances?)\b/.test(text)) return "servers"; + if (/\b(webhooks?|discord)\b/.test(text)) return "webhooks"; + if (/\b(preferences?|general settings?|settings home)\b/.test(text)) return "preferences"; + return ""; +} + +function formatAssistantSettingsPanelLabel(panel) { + const key = String(panel || "").trim(); + return ASSISTANT_SETTINGS_PANEL_LABELS[key] || "Settings"; +} + +function formatAssistantSettingsActionLabel(action) { + const key = String(action || "").trim(); + return ASSISTANT_SETTINGS_ACTION_LABELS[key] || "that settings tool"; +} + +function extractAssistantUrlsFromText(value) { + return Array.from(String(value || "").matchAll(/https?:\/\/[^\s<>"')]+/gi)) + .map((match) => String(match?.[0] || "").replace(/[.,!?;:]+$/g, "").trim()) + .filter(Boolean); +} + +function parseAssistantServerSectionFromUrlAction(value) { + const action = String(value || "").trim().toLowerCase(); + const map = { + "open-info": "info", + "open-files": "files", + "open-activity": "activity", + "open-backups": "backups", + "open-scheduler": "scheduler", + "open-store": "store", + "open-resource-stats": "resource_stats", + "open-subdomains": "subdomains", + "open-reinstall": "reinstall", + "open-ai-help": "ai_help", + }; + return map[action] || "console"; +} + +function parseAssistantNavigationContextFromUrl(rawUrl) { + const urlText = String(rawUrl || "").trim(); + if (!urlText) return null; + + try { + const parsed = new URL(urlText); + if (parsed.pathname === "/settings") { + const action = normalizeAssistantSettingsAction(parsed.searchParams.get("assistantAction") || ""); + const panel = normalizeAssistantSettingsPanel(parsed.searchParams.get("panel") || "") + || (action ? inferAssistantSettingsPanelFromAction(action) : ""); + if (panel || action) { + return { + kind: "settings", + panel, + action, + }; + } + } + + const serverMatch = parsed.pathname.match(/^\/server\/([^/?#]+)/i); + if (serverMatch?.[1]) { + return { + kind: "server", + server: sanitizeToken(decodeURIComponent(serverMatch[1] || "")), + section: parseAssistantServerSectionFromUrlAction(parsed.searchParams.get("assistantAction") || ""), + }; + } + } catch { + } + + return null; +} + +function getRecentAssistantNavigationContext(conversationHistory = []) { + const recentHistory = Array.isArray(conversationHistory) ? conversationHistory.slice(-12) : []; + + for (let index = recentHistory.length - 1; index >= 0; index -= 1) { + const content = normalizeMessageContent(recentHistory[index]?.content); + const urls = extractAssistantUrlsFromText(content); + for (let urlIndex = urls.length - 1; urlIndex >= 0; urlIndex -= 1) { + const parsed = parseAssistantNavigationContextFromUrl(urls[urlIndex]); + if (parsed) return parsed; + } + } + + return null; +} + +function isShortAssistantNavigationShortcut(message) { + const text = normalizeAssistantLookupText(message); + if (!text || text.length > 48) return false; + if (text.split(" ").filter(Boolean).length > 4) return false; + return !/[?]/.test(String(message || "")); +} + +function messageExplicitlyNamesAssistantServerSection(message) { + return /\b(console|terminal|logs?|backups?|files?|activity|scheduler|tasks?|store|plugins?|versions?|resource(?:s| stats?)?|overview|info|details?|subdomains?|domains?|reinstall|ai help|assistant help)\b/i.test(String(message || "")); +} + +function messageExplicitlyNamesAssistantSettingsDestination(message) { + return /\b(settings?|preferences?|appearance|customization|account|security|databases?|db|nodes?|templates?|servers?|webhooks?|panel info|branding|watermark|background|captcha|maintenance|quick action|create user|create node|create template|pgadmin|mongodb|webhook)\b/i.test(String(message || "")); +} + +function detectDirectOpenServerPageIntent(message, serverHint = "", conversationHistory = []) { + const text = String(message || "").trim(); + if (!text) return null; + const recentNavigationContext = getRecentAssistantNavigationContext(conversationHistory); + const shortNavigationShortcut = isShortAssistantNavigationShortcut(text); + if (!messageLooksLikeAssistantOpenRequest(text) && !(shortNavigationShortcut && recentNavigationContext?.kind === "server")) return null; + if (/\bsettings?\b/i.test(text)) return null; + + const mentionsServerArea = + messageExplicitlyNamesAssistantServerSection(text) + || /\b(server|page)\b/i.test(text); + if (!mentionsServerArea) return null; + + const extractedServer = extractAssistantServerCandidate(text); + const recentServer = recentNavigationContext?.kind === "server" + ? String(recentNavigationContext.server || "").trim() + : ""; + const server = !isWeakAssistantServerReference(extractedServer) + ? extractedServer + : (String(serverHint || "").trim() || recentServer); + if (!server) return null; + + return { + toolName: "open_server_page", + args: { + server, + section: normalizeAssistantServerPageSection(text), + }, + model: "adpanel-navigation-router", + }; +} + +function detectDirectOpenSettingsIntent(message, conversationHistory = []) { + const text = String(message || "").trim(); + if (!text) return null; + + const recentNavigationContext = getRecentAssistantNavigationContext(conversationHistory); + const normalizedPanel = normalizeAssistantSettingsPanel(text); + const normalizedAction = normalizeAssistantSettingsAction(text); + if (!normalizedPanel && !normalizedAction) return null; + if ( + normalizedPanel === "servers" + && !/\bsettings?\b/i.test(text) + && ( + messageExplicitlyNamesAssistantServerSection(text) + || /\bfor\s+(?:a|an|the|that|this)?\s*server\b/i.test(text) + ) + ) { + return null; + } + + const shortNavigationShortcut = isShortAssistantNavigationShortcut(text); + if ( + !messageLooksLikeAssistantOpenRequest(text) + && !/\bsettings?\b/i.test(text) + && !shortNavigationShortcut + && recentNavigationContext?.kind !== "settings" + ) { + return null; + } + + return { + toolName: "open_settings_destination", + args: { + panel: normalizedPanel || inferAssistantSettingsPanelFromAction(normalizedAction), + action: normalizedAction, + }, + model: "adpanel-settings-router", + }; +} + +function cleanAssistantServerCandidate(value) { + let candidate = String(value || "") + .replace(/^[`"'“”‘’([{<\s]+/g, "") + .replace(/[`"'“”‘’)\]}>]+$/g, "") + .replace(/[.,!?;:]+$/g, "") + .trim(); + if (!candidate) return ""; + + candidate = candidate + .replace(/\b(?:if|when|daca|dacă|and|then|si|și|restart|reboot|reporn(?:e|i)ste|repornește|restarteaza|restartează)\b.*$/i, " ") + .replace(/\b(?:a|an|the|my|our|please|pls|now|right|server|servers|servere|serverele|named|called|target|crash|crashed|crashing|lag|lagging|issue|issues|problem|problema|startup|start up|error|errors|failing|failure|why|did|de|ce|căzut|cazut)\b/gi, " ") + .replace(/\s+/g, " ") + .trim(); + + if (!candidate) return ""; + if (/^(?:a|an|it|them|that|this|one|all)$/i.test(candidate)) return ""; + return candidate; +} + +function extractAssistantServerCandidate(message) { + const raw = String(message || "").trim(); + if (!raw) return ""; + + const quoted = raw.match(/["'`“”]([^"'`“”]{1,80})["'`“”]/); + if (quoted) { + const candidate = cleanAssistantServerCandidate(quoted[1]); + if (candidate) return candidate; + } + + const wrappedMatches = Array.from(raw.matchAll(/[\(\[]([^()\[\]]{1,80})[\)\]]/g)); + for (const match of wrappedMatches) { + const candidate = cleanAssistantServerCandidate(match[1]); + if (candidate) return candidate; + } + + const patterns = [ + /\bserver(?:ul)?\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, + /\b(?:srv|bot)\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, + /\b(?:for|on|la|pe)\s+server(?:ul)?\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, + /\b(?:for|on|about|check|diagnose|inspect|why did|why is|problema la|de ce a cazut|de ce a căzut)\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, + /\b(?:start|run|boot|turn on|power on|bring up|spin up|restart|reboot|cycle|bounce|reload|stop|shutdown|shut down|turn off|power off|take down|kill|terminate|porneste|pornește|opreste|oprește|inchide|închide|reporneste|repornește|omoara|omoară|ucide)\s+([a-z0-9][a-z0-9._-]*(?:\s+[a-z0-9][a-z0-9._-]*){0,2})/i, + ]; + + for (const pattern of patterns) { + const match = raw.match(pattern); + if (!match) continue; + const candidate = cleanAssistantServerCandidate(match[1]); + if (candidate) return candidate; + } + + return ""; +} + +function detectDirectDiagnosisIntent(message, serverHint = "") { + const text = String(message || "").trim(); + if (!text) return null; + + const looksLikeDiagnosis = messageLooksLikeDiagnosisRequest(text) + || (!!serverHint && /\b(diagnose|diagnostic|crash|crashed|crashing|lag|lagging|slow|startup|start up|won'?t start|problem|issue|error|failing|failure|why is|why did|de ce|problema|eroare|a cazut|a căzut)\b/i.test(text)); + if (!looksLikeDiagnosis) return null; + + const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); + if (!server) return null; + + return { + toolName: "diagnose_server", + args: { server }, + model: "adpanel-diagnosis-router", + }; +} + +function normalizeMinecraftPropertyKey(value) { + const clean = String(value || "").trim(); + if (/^[A-Za-z0-9._-]+$/.test(clean)) return clean; + + for (const entry of MINECRAFT_PROPERTY_ALIASES) { + if (entry.pattern.test(clean)) { + return entry.key; + } + } + + return ""; +} + +function trimMinecraftPropertyValueSegment(value) { + let clean = String(value || "").trim(); + if (!clean) return ""; + + clean = clean + .split(/\s+\b(?:for|on|pe|la)\b\s+(?:all|every|all accessible|all my|them all|all of them|toate|pe toate|server(?:ul)?|servers|servere|serverele|minecraft)\b/i)[0] + .replace(/\s+\b(?:only if|doar daca|doar dacă)\b[\s\S]*$/i, "") + .replace(/\s+\b(?:if|when|daca|dacă)\b[\s\S]*$/i, "") + .replace(/\s+\b(?:and|then|si|și)\b\s+(?:restart|reboot|reporn(?:e|i)ste|repornește|restarteaza|restartează)\b[\s\S]*$/i, "") + .replace(/\s+\b(?:after(?:wards)?|after that|după|dupa)\b[\s\S]*$/i, "") + .trim(); + + return clean; +} + +function normalizeMinecraftPropertyValue(value) { + let clean = trimMinecraftPropertyValueSegment(value); + if (!clean) return ""; + + clean = clean + .replace(/^[`"'“”‘’]+|[`"'“”‘’]+$/g, "") + .replace(/^[:=]\s*/g, "") + .replace(/[.,!?;:]+$/g, "") + .replace(/^(?:is|este|e)\s+/i, "") + .trim(); + + if (/^(true|on|enabled?|yes|da)$/i.test(clean)) return "true"; + if (/^(false|off|disabled?|no|nu)$/i.test(clean)) return "false"; + return clean.slice(0, 160); +} + +function extractMinecraftConditionalCurrentValue(message) { + const text = String(message || "").trim(); + if (!text) return ""; + + const patterns = [ + /\b(?:if|when)\s+(?:it(?:'s| is)?|the current value is|current value is)?\s*(true|false|on|off|enabled?|disabled?|yes|no)\b/i, + /\b(?:only if)\s+(?:it(?:'s| is)?|the current value is|current value is)?\s*(true|false|on|off|enabled?|disabled?|yes|no)\b/i, + /\b(?:daca|dacă)\s+(?:e|este)?\s*(true|false|on|off|enabled?|disabled?|yes|no|da|nu)\b/i, + /\b(?:doar daca|doar dacă)\s+(?:e|este)?\s*(true|false|on|off|enabled?|disabled?|yes|no|da|nu)\b/i, + ]; + + for (const pattern of patterns) { + const match = text.match(pattern); + if (!match) continue; + const normalized = normalizeMinecraftPropertyValue(match[1]); + if (normalized) return normalized; + } + + return ""; +} + +function messageRequestsRestartAfterPropertyUpdate(message) { + const text = String(message || "").trim(); + if (!text) return false; + return /\b(restart|reboot|reporn(?:e|i)ste|repornește|restarteaza|restartează)\b/i.test(text); +} + +function stripTrailingServerHintFromValue(value, serverHint) { + const cleanValue = String(value || "").trim(); + const cleanServer = String(serverHint || "").trim(); + if (!cleanValue || !cleanServer) return cleanValue; + + const normalizedTokens = normalizeAssistantLookupText(cleanServer).split(" ").filter(Boolean); + if (!normalizedTokens.length) return cleanValue; + const flexibleServerPattern = normalizedTokens.map((token) => escapeRegex(token)).join("[\\s._-]+"); + return cleanValue + .replace(new RegExp(`\\s+(?:on|for|pe|la)\\s+${flexibleServerPattern}\\s*$`, "i"), "") + .trim(); +} + +function extractChainedPowerAction(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return ""; + + if (!/\b(and|then|after|afterwards|after that|si|și|apoi|după|dupa|la final|cand termini|când termini|when done)\b/.test(text)) { + return ""; + } + + return detectAssistantPowerAction(text); +} + +function extractMinecraftPropertyValue(message, propertyKey) { + const raw = String(message || "").trim(); + if (!raw || !propertyKey) return ""; + + const exactPattern = new RegExp(`\\b${escapeRegex(propertyKey)}\\b\\s*(?::|=|to|pe|as|la)?\\s*([^\\n]+)`, "i"); + const exactMatch = raw.match(exactPattern); + if (exactMatch) { + const exactValue = normalizeMinecraftPropertyValue(exactMatch[1]); + if (exactValue) return exactValue; + } + + const aliasEntry = MINECRAFT_PROPERTY_ALIASES.find((entry) => entry.key === propertyKey); + if (!aliasEntry) return ""; + const aliasMatch = raw.match(aliasEntry.pattern); + if (!aliasMatch || typeof aliasMatch.index !== "number") return ""; + + const remainder = raw.slice(aliasMatch.index + aliasMatch[0].length) + .replace(/^\s*(?:to|=|pe|as|la)\s*/i, "") + .trim(); + if (!remainder) return ""; + + if (/^["'`“”]/.test(remainder)) { + const quoted = remainder.match(/^[`"'“”]([^`"'“”]{1,160})[`"'“”]/); + if (quoted) return normalizeMinecraftPropertyValue(quoted[1]); + } + + return normalizeMinecraftPropertyValue( + remainder + ); +} + +function detectDirectMinecraftPropertyIntent(message, serverHint = "") { + const text = String(message || "").trim(); + if (!text) return null; + + if (!messageLooksLikeStructuredMinecraftPropertyMutation(text)) return null; + + const wantsAll = /\b(all|every|all accessible|all my|them all|all of them|toate|pe toate)\b/i.test(text); + const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); + const scope = wantsAll ? "all_accessible_minecraft" : (server ? "single_server" : ""); + if (!scope) return null; + + const propertyFromAssignment = text.match(/\b([a-z0-9._-]+)\b\s*(?:=|:)\s*([^\n]+)/i); + const property = normalizeMinecraftPropertyKey(propertyFromAssignment?.[1] || text); + const rawValue = propertyFromAssignment?.[2] || extractMinecraftPropertyValue(text, property); + const value = normalizeMinecraftPropertyValue(stripTrailingServerHintFromValue(rawValue, server)); + const onlyIfCurrent = extractMinecraftConditionalCurrentValue(text); + const restartAfter = messageRequestsRestartAfterPropertyUpdate(text); + + if (!property || !value) return null; + + return { + toolName: "update_minecraft_server_property", + args: scope === "single_server" + ? { property, value, scope, server, ...(onlyIfCurrent ? { onlyIfCurrent } : {}), ...(restartAfter ? { restartAfter: true } : {}) } + : { property, value, scope, ...(onlyIfCurrent ? { onlyIfCurrent } : {}), ...(restartAfter ? { restartAfter: true } : {}) }, + model: "adpanel-minecraft-router", + }; +} + +function cleanAssistantPathCandidate(value) { + let candidate = String(value || "") + .replace(/^[`"'“”‘’]+|[`"'“”‘’]+$/g, "") + .replace(/[),.!?;:]+$/g, "") + .trim(); + + candidate = candidate + .replace(/^(?:file|path|folder|directory|config)\s+/i, "") + .replace(/\\/g, "/") + .replace(/^\.\/+/, "") + .replace(/^\/+/, "") + .trim(); + + if (!candidate || candidate === "." || candidate === "..") return ""; + return candidate.slice(0, 220); +} + +function extractAssistantFilePath(message) { + const raw = String(message || "").trim(); + if (!raw) return ""; + + const quotedMatches = Array.from(raw.matchAll(/[`"'“”]([^`"'“”]{1,220})[`"'“”]/g)); + for (const match of quotedMatches) { + const candidate = cleanAssistantPathCandidate(match[1]); + if (/[/.]/.test(candidate) || /\.[A-Za-z0-9]{1,12}$/.test(candidate)) { + return candidate; + } + } + + const knownFileMatch = raw.match(/\b(server\.properties|eula\.txt|package\.json|docker-compose\.ya?ml|requirements\.txt|pyproject\.toml|cargo\.toml|dockerfile|makefile|(?:index|main|app)\.(?:js|ts|mjs|cjs|py)|config\.(?:ya?ml|json|toml|ini|cfg)|latest\.log|\.env|plugins|mods|config|logs|crash-reports)\b/i); + if (knownFileMatch) { + return cleanAssistantPathCandidate(knownFileMatch[1]); + } + + const pathMatch = raw.match(/(?:^|[\s(])([A-Za-z0-9._-]+(?:\/[A-Za-z0-9._ -]+)+\/?)(?=$|[\s),.!?])/); + if (pathMatch) { + return cleanAssistantPathCandidate(pathMatch[1]); + } + + const flatFileMatch = raw.match(/(?:^|[\s(])([A-Za-z0-9._-]+\.[A-Za-z0-9]{1,12})(?=$|[\s),.!?])/); + if (flatFileMatch) { + return cleanAssistantPathCandidate(flatFileMatch[1]); + } + + return ""; +} + +function looksLikeAssistantDirectoryPath(filePath) { + const clean = cleanAssistantPathCandidate(filePath); + if (!clean) return false; + if (clean.endsWith("/")) return true; + const base = clean.split("/").filter(Boolean).pop() || ""; + return !/\.[A-Za-z0-9]{1,12}$/i.test(base); +} + +function detectDirectFileInspectIntent(message, serverHint = "") { + const text = String(message || "").trim(); + if (!text) return null; + + const server = extractAssistantServerCandidate(text) || String(serverHint || "").trim(); + const path = extractAssistantFilePath(text); + if (!server || !path) return null; + + const lower = text.toLowerCase(); + const wantsFileContext = + /[/.]/.test(path) || + /\b(file|files|folder|directory|config|log|logs|path|server\.properties|eula|package\.json)\b/.test(lower); + if (!wantsFileContext) return null; + + const wantsInspection = + /\b(read|show|open|view|check|inspect|look at|see|vezi|arata|arată|deschide|what'?s in|what is in|analy[sz]e|review|ce sa vad|ce să văd)\b/i.test(text); + const wantsAdvice = /\b(what should i change|what to change|ce sa schimb|ce să schimb)\b/i.test(text); + if (!wantsInspection && !wantsAdvice) return null; + + const toolName = looksLikeAssistantDirectoryPath(path) && /\b(list|show|see|inside|contents?|explore|browse)\b/i.test(text) + ? "list_files" + : "read_file"; + + return { + toolName, + args: { server, path }, + model: "adpanel-file-router", + }; +} + +function messageNeedsRealActionExecution(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + + const createServerIntent = + /\b(create|make|spin\s*up|deploy|provision)\b/.test(text) && + /\b(server|minecraft|nodejs|python|discord|template|templates|node|nodes)\b/.test(text); + if (createServerIntent) return true; + + const pluginInstallIntent = + /\b(install|add|download|setup|set up)\b/.test(text) && + /\b(plugin|plugins|modrinth|viaversion|geyser|luckperms|vault)\b/.test(text); + if (pluginInstallIntent) return true; + + const deleteServerIntent = + /\b(delete|remove|destroy|wipe)\b/.test(text) && + /\b(server|servers)\b/.test(text); + if (deleteServerIntent) return true; + + const serverPowerIntent = + /\b(start|stop|restart|kill|power|porneste|pornește|opreste|oprește|inchide|închide|omoara|omoară|ucide|reporneste|repornește)\b/.test(text) && + /\b(server|servers|servere|serverele)\b/.test(text); + if (serverPowerIntent) return true; + + if (detectAssistantPowerAction(text) && extractAssistantServerCandidate(text)) return true; + + if (messageLooksLikeBusiestLookup(text)) return true; + + if (messageLooksLikeDiagnosisRequest(text)) return true; + + if (messageLooksLikeStructuredMinecraftPropertyMutation(text)) return true; + + const fileMutationIntent = + /\b(edit|write|replace|overwrite|append|create|delete|remove|rename|move|mkdir|make)\b/.test(text) && + /\b(file|files|folder|directory|config|properties|server\.properties|eula|plugin|plugins|world|mods?)\b/.test(text); + if (fileMutationIntent) return true; + + if (messageLooksLikeMinecraftBatchPropertyUpdate(text)) return true; + + const explicitPathMutation = + /\b(edit|write|replace|overwrite|append|create|delete|remove|rename|move|mkdir|make)\b/.test(text) && + /[./\\][\w./\\-]+/.test(text); + if (explicitPathMutation) return true; + + return false; +} + +function replyClaimsActionSucceeded(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + if (/[?]/.test(text)) return false; + if (/\b(i need|need one more detail|which|what|tell me|choose|pick|do you want|would you like|please provide|cannot|can't|do not have permission|don't have permission|failed|error)\b/.test(text)) { + return false; + } + return /\b(done|completed|created|started|stopped|restarted|killed|updated|deleted|removed|renamed|moved|written|saved|applied|opened|opening)\b/.test(text); +} + +function shouldAllowToolUseForMessage(message, conversationHistory = []) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + + const recentHistory = Array.isArray(conversationHistory) ? conversationHistory.slice(-8) : []; + const lastAssistantMessage = recentHistory + .slice() + .reverse() + .find((entry) => String(entry?.role || "").toLowerCase() === "assistant"); + const lastAssistantText = normalizeMessageContent(lastAssistantMessage?.content).toLowerCase(); + const assistantAskedStructuredFollowUp = + /\b(which|what|how much|how many|choose|pick|tell me|do you want|would you like)\b/.test(lastAssistantText) && + /\b(template|templates|node|nodes|server name|name|ram|cpu|storage|port|password|email|2fa|two[- ]factor|recovery|file|path|plugin|plugins|loader|platform|minecraft version|version)\b/.test(lastAssistantText); + const assistantAskedActionConfirmation = + /\b(ready|want me to|should i|go ahead|create it|create the server|apply it|use that|use this)\b/.test(lastAssistantText) && + /\b(server|template|node|port|ram|cpu|storage|create|provision)\b/.test(lastAssistantText); + const shortStructuredReply = + text.length <= 80 && + ( + isAffirmativeShortReply(text) || + /^(that one|this one)$/i.test(String(text || "").trim()) || + /^\d{2,5}$/.test(text) || + /\b\d+(?:\.\d+)?\s*(?:mb|gb|tb|cores?)\b/.test(text) || + /\b(?:port|ram|cpu|storage|node|template|plugin|loader|platform|paper|purpur|spigot|bukkit|velocity|fabric|forge|neoforge)\b/.test(text) + ); + const infrastructureShortcut = /^(nodes?|templates?|servers?)$/.test(text); + if (infrastructureShortcut) return true; + + const accountIntent = + /\b(change|reset|recover|update|open|show)\b/.test(text) && + /\b(password|email|2fa|two[- ]factor|recovery|recovery code|recovery codes)\b/.test(text); + if (accountIntent) return true; + + const explicitServerListing = + /\b(list|show|which|what)\b/.test(text) && + /\b(server|servers|node|nodes)\b/.test(text); + if (explicitServerListing) return true; + + const explicitTemplateOrNodeListing = + /\b(list|show|which|what)\b/.test(text) && + /\b(template|templates|node|nodes)\b/.test(text); + if (explicitTemplateOrNodeListing) return true; + + const serverQuestion = + /\b(status|port|template|permission|permissions|ip|uptime|online|offline|running|stopped|console)\b/.test(text) && + /\b(?:server|servers|node|nodes)\b/.test(text); + if (serverQuestion) return true; + + if (messageLooksLikeBusiestLookup(text)) return true; + + if (messageLooksLikeDiagnosisRequest(text)) return true; + + const createServerIntent = + /\b(create|make|spin\s*up|deploy|provision)\b/.test(text) && + /\b(server|minecraft|nodejs|python|discord|template|templates|node|nodes)\b/.test(text); + if (createServerIntent) return true; + + const pluginInstallIntent = + /\b(install|add|download|setup|set up)\b/.test(text) && + /\b(plugin|plugins|modrinth|viaversion|geyser|luckperms|vault)\b/.test(text); + if (pluginInstallIntent) return true; + + const deleteServerIntent = + /\b(delete|remove|destroy|wipe)\b/.test(text) && + /\b(server|servers)\b/.test(text); + if (deleteServerIntent) return true; + + const fileOrServerAction = + /\b(start|stop|restart|kill|power|edit|read|write|create|delete|remove|rename|move|open|inspect|list|show|porneste|pornește|opreste|oprește|inchide|închide|omoara|omoară|ucide|reporneste|repornește|citeste|citește|scrie|editeaza|editează|sterge|șterge|arata|arată)\b/.test(text) && + /\b(server|servers|servere|serverele|file|files|folder|directory|config|properties|server\.properties|eula|plugin|plugins|world|mods?)\b/.test(text); + if (fileOrServerAction) return true; + + if (messageLooksLikeMinecraftBatchPropertyUpdate(text)) return true; + + const explicitPathAction = + /\b(read|write|edit|create|delete|rename|move|list|show)\b/.test(text) && + /[./\\][\w./\\-]+/.test(text); + if (explicitPathAction) return true; + + if (assistantAskedStructuredFollowUp) { + return true; + } + + if (assistantAskedActionConfirmation && shortStructuredReply) { + return true; + } + + return false; +} + +function getLastAssistantText(conversationHistory = []) { + const recentHistory = Array.isArray(conversationHistory) ? conversationHistory.slice(-10) : []; + const lastAssistantMessage = recentHistory + .slice() + .reverse() + .find((entry) => String(entry?.role || "").toLowerCase() === "assistant"); + return normalizeMessageContent(lastAssistantMessage?.content).trim(); +} + +function buildCarryForwardVisibleTranscript(messages, options = {}) { + const recentMessages = (Array.isArray(messages) ? messages : []) + .filter((entry) => entry && (entry.role === "user" || entry.role === "assistant")) + .slice(-Math.max(1, Number(options.count) || 18)); + if (!recentMessages.length) return ""; + + const perMessageLimit = Math.max(60, Number(options.perMessageLimit) || 220); + const totalLimit = Math.max(400, Number(options.totalLimit) || 2600); + const lines = []; + + for (const entry of recentMessages) { + const role = String(entry.role || "").toLowerCase() === "user" ? "User" : "Assistant"; + const content = normalizeMessageContent(entry.content) + .replace(/\s+/g, " ") + .trim() + .slice(0, perMessageLimit); + if (!content) continue; + lines.push(`${role}: ${content}`); + } + + return lines.join("\n").slice(0, totalLimit); +} + +function compactAssistantModelMessageContent(content, maxLength = MODEL_CONTEXT_RECENT_MESSAGE_CHAR_LIMIT) { + const text = normalizeMessageContent(content).replace(/\s+/g, " ").trim(); + if (!text) return ""; + if (text.length <= maxLength) return text; + return `${text.slice(0, Math.max(120, maxLength - 3)).trim()}...`; +} + +function buildAssistantModelConversationWindow(messages, options = {}) { + const sourceMessages = (Array.isArray(messages) ? messages : []) + .filter((entry) => entry && (entry.role === "user" || entry.role === "assistant")); + + if (!sourceMessages.length) { + return { + olderContextMessage: "", + recentMessages: [], + }; + } + + const recentCount = Math.max(4, Number(options.recentCount) || MODEL_CONTEXT_RECENT_MESSAGE_LIMIT); + const olderTranscriptCount = Math.max(4, Number(options.olderTranscriptCount) || MODEL_CONTEXT_OLDER_TRANSCRIPT_COUNT); + const olderTranscriptTotalLimit = Math.max(400, Number(options.olderTranscriptTotalLimit) || MODEL_CONTEXT_OLDER_TRANSCRIPT_TOTAL_LIMIT); + const recentMessagesSource = sourceMessages.slice(-recentCount); + const olderMessagesSource = sourceMessages.slice(0, Math.max(0, sourceMessages.length - recentCount)); + const olderTranscript = olderMessagesSource.length + ? buildCarryForwardVisibleTranscript(olderMessagesSource, { + count: Math.min(olderMessagesSource.length, olderTranscriptCount), + perMessageLimit: 150, + totalLimit: olderTranscriptTotalLimit, + }) + : ""; + + const recentMessages = recentMessagesSource + .map((entry, index) => { + const isLatest = index === recentMessagesSource.length - 1; + const isNearLatest = index >= recentMessagesSource.length - 4; + const maxLength = isLatest + ? MODEL_CONTEXT_LATEST_MESSAGE_CHAR_LIMIT + : (isNearLatest ? MODEL_CONTEXT_NEAR_MESSAGE_CHAR_LIMIT : MODEL_CONTEXT_RECENT_MESSAGE_CHAR_LIMIT); + const content = compactAssistantModelMessageContent(entry.content, maxLength); + if (!content) return null; + return { + role: entry.role, + content, + }; + }) + .filter(Boolean); + + return { + olderContextMessage: olderTranscript + ? `Earlier visible chat summary:\n${olderTranscript}\nUse it only when the latest messages omit a reference.` + : "", + recentMessages, + }; +} + +function looksLikeRestrictedAssistantFollowUp(message, conversationHistory = []) { + const text = String(message || "").trim(); + if (!text || text.length > 180) return false; + + const lower = text.toLowerCase(); + if ( + detectAssistantPowerAction(lower) + || messageLooksLikeBusiestLookup(lower) + || messageLooksLikeConsoleCheckRequest(lower) + || !!detectDirectAccountFlowIntent(lower) + ) { + return false; + } + + const lastAssistantText = getLastAssistantText(conversationHistory).toLowerCase(); + if (!lastAssistantText) return false; + + const recentRestrictedResult = + /\b(console|log|started|stopped|restarted|killed|busiest|highest|cpu|ram|memory|disk|storage|node|server|2fa|password|email|healthy|running|seconds?|uptime)\b/.test(lastAssistantText); + if (!recentRestrictedResult) return false; + + const asksFollowUp = + /[?]/.test(text) + || /\b(so|and|what|why|how|how many|how much|which|did|does|is|was|are|were|okay|ok|then|mean|seconds?|sec|deci|bun|acum)\b/.test(lower); + const refersToPreviousAnswer = + /\b(it|that|those|them|this|seconds?|sec|started|crashed|running|healthy|console|logs?|cpu|ram|memory|disk|storage|node|server)\b/.test(lower); + + return asksFollowUp || refersToPreviousAnswer; +} + +function messageLikelyNeedsAccessibleServerContext(message, conversationHistory = []) { + const text = String(message || "").trim(); + const lower = text.toLowerCase(); + if (!lower) return false; + + if (extractAssistantServerCandidate(text)) return true; + if (detectAssistantPowerAction(lower)) return true; + if (messageLooksLikeBusiestLookup(lower)) return true; + if (messageLooksLikeConsoleCheckRequest(lower)) return true; + if (messageLooksLikeServerLimitsCheckRequest(lower)) return true; + if (messageLooksLikeDiagnosisRequest(lower)) return true; + const wantsNavigation = /\b(open|show|take me|go to|goto|navigate|bring me|launch|new tab|tab|pop ?up|manage|configure|config|edit|access)\b/.test(lower) + && /\b(server|console|terminal|backups?|files?|activity|scheduler|tasks?|store|plugins?|versions?|resource(?:s| stats?)?|overview|info|details?|subdomains?|domains?|reinstall|settings?|preferences?|appearance|customization|account|security|databases?|nodes?|templates?|webhooks?|panel info|branding|watermark|background|captcha|maintenance|quick action|create user|create node|create template|pgadmin|mongodb|webhook)\b/.test(lower); + if (wantsNavigation) return true; + if (looksLikeRestrictedAssistantFollowUp(text, conversationHistory)) return true; + + return /\b(server|servers|node|nodes|console|logs?|backups?|scheduler|activity|files?|resource(?:s| stats?)?|cpu|ram|memory|disk|storage|quota|limits?)\b/i.test(text); +} + +function normalizeShortReply(message) { + return String(message || "") + .toLowerCase() + .replace(/[^a-z0-9]+/g, " ") + .trim(); +} + +function isAffirmativeShortReply(message) { + const text = normalizeShortReply(message); + return [ + "yes", + "yeah", + "yep", + "correct", + "go ahead", + "do it", + "that works", + "sounds good", + "sure", + "ok", + "okay", + "ok create it", + "okay create it", + "yes create it", + "create it", + "confirm", + "confirmed", + "use that", + "use this", + "use default", + "use defaults", + "default", + "recommended", + ].includes(text); +} + +function assistantAskedProvisioningQuestion(conversationHistory = []) { + const text = getLastAssistantText(conversationHistory).toLowerCase(); + if (!text) return false; + return ( + /\b(which|what|how much|how many|choose|pick|tell me|do you want|would you like)\b/.test(text) && + /\b(template|templates|node|nodes|server name|name|host port|port|ram|cpu|storage|defaults?)\b/.test(text) + ); +} + +function assistantAskedProvisioningConfirmation(conversationHistory = []) { + const text = getLastAssistantText(conversationHistory).toLowerCase(); + if (!text) return false; + if (/\bi can create it now\b|\bi can create the server now\b|\bi can provision it now\b/.test(text)) { + return true; + } + return ( + /\b(ready|want me to|should i|go ahead|create it|create the server|apply it|use that|use this|confirm)\b/.test(text) && + /\b(server|template|node|port|ram|cpu|storage|create|provision)\b/.test(text) + ); +} + +function assistantAskedDefaultsQuestion(conversationHistory = []) { + const text = getLastAssistantText(conversationHistory).toLowerCase(); + if (!text) return false; + return /\bdefaults?\b/.test(text) && /\b(port|ram|cpu|storage)\b/.test(text); +} + +function isCreateServerConversation(message, conversationHistory = []) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + + const explicitCreateIntent = + /\b(create|make|spin\s*up|deploy|provision)\b/.test(text) && + /\b(server|minecraft|nodejs|python|discord|template|templates|node|nodes)\b/.test(text); + if (explicitCreateIntent) return true; + + const shortProvisioningReply = + text.length <= 120 && + ( + isAffirmativeShortReply(text) || + /^\d{2,5}$/.test(text) || + /\b\d+(?:\.\d+)?\s*(?:mb|gb|tb|cores?)\b/.test(text) || + /\b(?:node|template|port|ram|cpu|storage|minecraft|paper|purpur|spigot|bukkit|fabric|forge|neoforge|python|nodejs)\b/.test(text) + ); + + return (assistantAskedProvisioningQuestion(conversationHistory) || assistantAskedProvisioningConfirmation(conversationHistory)) && shortProvisioningReply; +} + +function inferTranscriptionFilename(filename, mimeType) { + const cleanName = String(filename || "").trim(); + if (cleanName) return cleanName; + const mime = String(mimeType || "").toLowerCase(); + if (mime.includes("wav")) return "dashboard-assistant.wav"; + if (mime.includes("mp4") || mime.includes("m4a")) return "dashboard-assistant.m4a"; + if (mime.includes("ogg")) return "dashboard-assistant.ogg"; + if (mime.includes("mpeg") || mime.includes("mp3")) return "dashboard-assistant.mp3"; + return "dashboard-assistant.webm"; +} + +function isGenericAssistantReply(value) { + const text = String(value || "").trim().toLowerCase(); + return text === "" || text === "done." || text === "done" || text === "completed." || text === "completed"; +} + +function buildReplyFromToolResult(toolName, toolResult) { + const result = toolResult && typeof toolResult === "object" ? toolResult : null; + if (!result) return ""; + if (result.ok === false) { + const error = String(result.error || "").trim(); + const detail = String(result.detail || "").trim(); + const candidates = Array.isArray(result.candidates) + ? result.candidates.map((item) => String(item || "").trim()).filter(Boolean).slice(0, 5) + : []; + if (candidates.length && /server name is ambiguous|multiple servers matched|no accessible server matched/i.test(error)) { + return `${error} Try ${candidates.join(", ")}.`; + } + if (detail && (!error || /^failed to create that server\.?$/i.test(error) || /^that action failed\.?$/i.test(error))) { + return detail; + } + return error || detail || "That action failed."; + } + + switch (String(toolName || "").trim()) { + case "create_server": { + const server = result.server && typeof result.server === "object" ? result.server : {}; + const name = server.displayName || server.name || "the server"; + const node = server.nodeName || server.nodeId || ""; + return node ? `Created ${name} on ${node}.` : `Created ${name}.`; + } + case "install_plugin": { + const pluginName = result.plugin?.name || result.plugin?.slug || "the plugin"; + const serverName = result.server || "the server"; + return `Installed ${pluginName} on ${serverName}.`; + } + case "request_delete_server": + return result.server ? `Please confirm deletion for ${result.server}.` : "Please confirm that deletion first."; + case "power_server": { + if (result.resolutionRequired) { + const action = result.action || "update"; + if (action === "start") return "Finding the matching server to start."; + if (action === "stop") return "Finding the matching server to stop."; + if (action === "restart") return "Finding the matching server to restart."; + if (action === "kill") return "Finding the matching server to kill."; + return "Finding the matching server."; + } + const server = result.displayName || result.server || result.targets?.[0]?.displayName || result.targets?.[0]?.server || "the server"; + const action = result.action || "updated"; + if (action === "start") return `Requesting start for ${server}.`; + if (action === "stop") return `Requesting stop for ${server}.`; + if (action === "restart") return `Requesting restart for ${server}.`; + if (action === "kill") return `Requesting kill for ${server}.`; + return `Updated ${server}.`; + } + case "power_accessible_servers": { + const count = Number(result.count) || (Array.isArray(result.servers) ? result.servers.length : 0) || (Array.isArray(result.targets) ? result.targets.length : 0); + if (result.action === "start") return `Requesting start for ${count || "your"} accessible server${count === 1 ? "" : "s"}.`; + if (result.action === "stop") return `Requesting stop for ${count || "your"} accessible server${count === 1 ? "" : "s"}.`; + if (result.action === "restart") return `Requesting restart for ${count || "your"} accessible server${count === 1 ? "" : "s"}.`; + if (result.action === "kill") return `Requesting kill for ${count || "your"} accessible server${count === 1 ? "" : "s"}.`; + return "Running that power action now."; + } + case "open_server_page": { + const section = formatAssistantServerPageSectionLabel(result.section); + if (result.resolutionRequired) { + return `Preparing a link to ${section}.`; + } + const server = result.displayName || result.server || "that server"; + return section === "console" + ? `Preparing a link to ${server}.` + : `Preparing a link to ${section} for ${server}.`; + } + case "open_settings_destination": { + const actionLabel = formatAssistantSettingsActionLabel(result.action); + const panelLabel = formatAssistantSettingsPanelLabel(result.panel || inferAssistantSettingsPanelFromAction(result.action)); + if (result.action) { + return `Preparing a link to ${actionLabel}.`; + } + return `Preparing a link to ${panelLabel}.`; + } + case "get_busiest_node": + if (result.metric === "cpu") return "Checking the busiest node by CPU now."; + if (result.metric === "memory") return "Checking the busiest node by memory now."; + if (result.metric === "disk") return "Checking the busiest node by disk now."; + return "Checking the busiest node now."; + case "get_busiest_server": + if (result.metric === "cpu") return "Checking your busiest server by CPU now."; + if (result.metric === "memory") return "Checking your busiest server by memory now."; + if (result.metric === "disk") return "Checking your busiest server by disk now."; + return "Checking your busiest server now."; + case "check_server_console": + return "Checking that server console now."; + case "check_server_limits": + return "Checking that server's limits now."; + case "diagnose_server": { + const server = result.displayName || result.server || "that server"; + return `Collecting diagnostics for ${server}.`; + } + case "update_minecraft_server_property": { + const property = result.property || "that setting"; + const count = Number(result.count) || (Array.isArray(result.targets) ? result.targets.length : 0); + const restartText = result.restartAfter ? " with restart requested" : ""; + return `Applying ${property} on ${count || "your"} Minecraft server${count === 1 ? "" : "s"}${restartText}.`; + } + case "list_files": { + const server = result.server || "that server"; + const path = result.path || "/"; + const count = Array.isArray(result.entries) ? result.entries.length : 0; + return `Found ${count} item${count === 1 ? "" : "s"} in ${path} on ${server}.`; + } + case "read_file": { + const server = result.server || "that server"; + const path = result.path || "that file"; + return `Read ${path} on ${server}.`; + } + case "write_file": + return result.path ? `Updated ${result.path} on ${result.server || "the server"}.` : "File updated."; + case "create_directory": + return result.path ? `Created ${result.path}.` : "Folder created."; + case "rename_path": + return result.destination ? `Moved to ${result.destination}.` : "Path renamed."; + case "delete_path": + return result.path ? `Deleted ${result.path}.` : "Path deleted."; + case "open_account_flow": + if (result.flow === "change_password") return "Opening password change."; + if (result.flow === "change_email") return "Opening email change."; + if (result.flow === "change_2fa") return "Opening 2FA settings."; + if (result.flow === "recover_password") return "Opening password recovery."; + if (result.flow === "recover_email") return "Opening email recovery."; + if (result.flow === "recover_2fa") return "Opening 2FA recovery."; + return "Opening that account flow."; + default: + return ""; + } +} + +function escapeRegex(value) { + return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function shouldForceQueuedReply(toolName, toolResult) { + if (!(toolResult && typeof toolResult === "object" && toolResult.browserActionQueued)) { + return false; + } + + return [ + "get_busiest_node", + "get_busiest_server", + "check_server_console", + "check_server_limits", + "diagnose_server", + "update_minecraft_server_property", + ].includes(String(toolName || "").trim()); +} + +function normalizeLooseText(value) { + return String(value || "").toLowerCase().replace(/\s+/g, " ").trim(); +} + +function parseAssistantToolArgs(value) { + if (!value) return null; + if (typeof value === "object") return value; + if (typeof value !== "string") return null; + try { + return JSON.parse(value); + } catch { + return null; + } +} + +function isGenericServerPropertiesWriteToolCall(toolName, rawArgs) { + if (String(toolName || "").trim() !== "write_file") return false; + const parsedArgs = parseAssistantToolArgs(rawArgs); + const path = String(parsedArgs?.path || "").trim().toLowerCase(); + return path === "server.properties" || path.endsWith("/server.properties"); +} + +function isWeakAssistantServerReference(value) { + const clean = normalizeAssistantLookupText(value); + if (!clean) return true; + return /^(?:a|an|server|servers|a server|the server|that server|this server|serverul|serverele|srv|bot|instance|current|this|it|that|them|one)$/i.test(clean); +} + +function applyServerHintToToolArgs(toolName, rawArgs, serverHint = "") { + const hint = String(serverHint || "").trim(); + if (!hint) return rawArgs; + + const parsedArgs = parseAssistantToolArgs(rawArgs); + if (!parsedArgs || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) { + return rawArgs; + } + + const name = String(toolName || "").trim(); + const nextArgs = { ...parsedArgs }; + let changed = false; + + const needsServerFallback = [ + "power_server", + "open_server_page", + "check_server_console", + "check_server_limits", + "diagnose_server", + "inspect_server", + "list_files", + "read_file", + "write_file", + "create_directory", + "rename_path", + "delete_path", + "install_plugin", + ].includes(name); + + if (needsServerFallback && isWeakAssistantServerReference(nextArgs.server)) { + nextArgs.server = hint; + changed = true; + } + + if (name === "update_minecraft_server_property" && String(nextArgs.scope || "").trim().toLowerCase() !== "all_accessible_minecraft") { + if (isWeakAssistantServerReference(nextArgs.server)) { + nextArgs.server = hint; + changed = true; + } + if (!String(nextArgs.scope || "").trim()) { + nextArgs.scope = "single_server"; + changed = true; + } + } + + if (!changed) return rawArgs; + return typeof rawArgs === "string" ? JSON.stringify(nextArgs) : nextArgs; +} + +function buildWriteThenPowerReply(writeResult, powerResult) { + const writeReply = buildReplyFromToolResult("write_file", writeResult) || "File updated."; + const powerReply = buildReplyFromToolResult("power_server", powerResult) + || String(powerResult?.error || powerResult?.detail || "Power action failed.").trim(); + return `${writeReply} ${powerReply}`.trim(); +} + +function buildPowerOnlyCapabilityReply() { + return "I can currently control servers, share direct links to server pages and admin settings tools, open account security popups, check live load, inspect a server console, and check a server's RAM, CPU, and storage headroom."; +} + +function buildInstantSmallTalkReply(message) { + const text = String(message || "").trim(); + const lower = text.toLowerCase(); + if (!lower) return ""; + + if (/^(?:hey|hi|hello|yo|sup|what'?s up|good morning|good afternoon|good evening)(?:\s+(?:there|adpanel))?[!?.]*$/i.test(text)) { + return "Hey."; + } + + if (/^(?:thanks|thank you|ty|thx|nice|perfect|great|awesome)[!?.]*$/i.test(text)) { + return "You're welcome."; + } + + if (/^(?:how are you|are you there|you there|still there)[!?.]*$/i.test(text)) { + return "I'm here."; + } + + if (/^(?:what can you do|what do you do|help|help me|capabilities|what are your capabilities)[!?.]*$/i.test(text)) { + return buildPowerOnlyCapabilityReply(); + } + + return ""; +} + +function buildRestrictedIntentSystemHint(intents = {}) { + const hints = [ + "Older chat may help resolve omitted references, but the latest explicit user request always wins.", + ]; + + if (intents.directAccountFlow?.flow) { + hints.push(`The latest user message is a clear account security request. Prefer calling open_account_flow with flow "${intents.directAccountFlow.flow}".`); + } + if (intents.directBulkPowerFlow?.action) { + hints.push(`The latest user message is a clear bulk power request. Prefer calling power_accessible_servers with action "${intents.directBulkPowerFlow.action}".`); + } + if (intents.directSinglePowerFlow?.args?.action) { + hints.push(`The latest user message is a clear single-server power request. Prefer calling power_server with action "${intents.directSinglePowerFlow.args.action}" and the user's raw server wording.`); + } + if (intents.directLoadLookup?.toolName) { + hints.push(`The latest user message is a clear live load lookup. Prefer calling ${intents.directLoadLookup.toolName}.`); + } + if (intents.directConsoleCheck?.args?.server) { + hints.push("The latest user message is a clear live console request. Prefer calling check_server_console with the user's raw server wording."); + } + if (intents.directServerLimits?.args?.server) { + hints.push("The latest user message is a clear per-server quota or limits request. Prefer calling check_server_limits with the user's raw server wording."); + } + if (intents.directOpenServerPage?.args?.server) { + hints.push(`The latest user message is a clear server navigation request. Prefer calling open_server_page with section "${normalizeAssistantServerPageSection(intents.directOpenServerPage.args.section)}".`); + } + if (intents.directOpenSettings?.args?.panel || intents.directOpenSettings?.args?.action) { + hints.push("The latest user message is a clear settings navigation request. Prefer calling open_settings_destination."); + } + + return hints.join(" ").trim(); +} + +function extractJsonObjectFromText(value) { + const text = String(value || "").trim(); + if (!text) return ""; + + const fencedMatch = text.match(/```(?:json)?\s*([\s\S]*?)```/i); + if (fencedMatch && fencedMatch[1]) { + return String(fencedMatch[1]).trim(); + } + + const firstBrace = text.indexOf("{"); + const lastBrace = text.lastIndexOf("}"); + if (firstBrace !== -1 && lastBrace !== -1 && lastBrace > firstBrace) { + return text.slice(firstBrace, lastBrace + 1).trim(); + } + + return text; +} + +function parseRestrictedAssistantPlan(rawContent) { + const extracted = extractJsonObjectFromText(rawContent); + if (!extracted) return null; + + try { + const parsed = JSON.parse(extracted); + return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null; + } catch { + return null; + } +} + +function normalizeRestrictedToolName(value) { + const name = String(value || "").trim(); + return [ + "power_server", + "power_accessible_servers", + "open_server_page", + "open_settings_destination", + "open_account_flow", + "get_busiest_node", + "get_busiest_server", + "check_server_console", + "check_server_limits", + ].includes(name) ? name : ""; +} + +function sanitizeRestrictedToolArgs(toolName, rawArgs) { + const parsed = rawArgs && typeof rawArgs === "object" && !Array.isArray(rawArgs) ? rawArgs : {}; + + if (toolName === "power_server") { + const action = detectAssistantPowerAction(parsed.action); + return { + server: String(parsed.server || parsed.query || "").trim(), + action: action || "", + }; + } + + if (toolName === "power_accessible_servers") { + const action = detectAssistantPowerAction(parsed.action); + return { + action: action || "", + }; + } + + if (toolName === "open_server_page") { + const server = String(parsed.server || parsed.query || "").trim(); + const rawSection = [ + parsed.section, + parsed.destination, + parsed.area, + parsed.page, + parsed.tab, + ].find((value) => String(value || "").trim()); + const nextArgs = {}; + if (server) { + nextArgs.server = server; + } + if (rawSection) { + nextArgs.section = normalizeAssistantServerPageSection(rawSection); + } + return nextArgs; + } + + if (toolName === "open_settings_destination") { + const rawAction = [ + parsed.action, + parsed.modal, + parsed.destination, + parsed.popup, + ].find((value) => String(value || "").trim()); + const rawPanel = [ + parsed.panel, + parsed.section, + parsed.category, + parsed.destination, + parsed.page, + parsed.tab, + ].find((value) => String(value || "").trim()); + const action = normalizeAssistantSettingsAction(rawAction || ""); + const panel = normalizeAssistantSettingsPanel(rawPanel || "") + || (action ? inferAssistantSettingsPanelFromAction(action) : ""); + const nextArgs = {}; + if (panel) { + nextArgs.panel = panel; + } + if (action) { + nextArgs.action = action; + } + return nextArgs; + } + + if (toolName === "open_account_flow") { + const flow = String(parsed.flow || "").trim(); + return { + flow: [ + "change_password", + "change_email", + "change_2fa", + "recover_password", + "recover_email", + "recover_2fa", + ].includes(flow) ? flow : "", + }; + } + + if (toolName === "get_busiest_node" || toolName === "get_busiest_server") { + const metricDetails = inferAssistantMetricDetails([ + parsed.metric, + Array.isArray(parsed.includeMetrics) ? parsed.includeMetrics.join(" ") : parsed.includeMetrics, + ].filter(Boolean).join(" ")); + return { + metric: metricDetails.metric, + includeMetrics: metricDetails.includeMetrics, + }; + } + + if (toolName === "check_server_console") { + return { + server: String(parsed.server || parsed.query || "").trim(), + question: String(parsed.question || "").trim(), + }; + } + + if (toolName === "check_server_limits") { + const metricDetails = inferAssistantMetricDetails([ + parsed.question, + Array.isArray(parsed.includeMetrics) ? parsed.includeMetrics.join(" ") : parsed.includeMetrics, + ].filter(Boolean).join(" ")); + return { + server: String(parsed.server || parsed.query || "").trim(), + question: String(parsed.question || "").trim(), + includeMetrics: metricDetails.includeMetrics, + }; + } + + return {}; +} + +function hasMeaningfulRestrictedArgValue(value) { + if (Array.isArray(value)) { + return value.some((entry) => hasMeaningfulRestrictedArgValue(entry)); + } + if (value == null) { + return false; + } + if (typeof value === "string") { + return value.trim().length > 0; + } + if (typeof value === "object") { + return Object.values(value).some((entry) => hasMeaningfulRestrictedArgValue(entry)); + } + return true; +} + +function mergeRestrictedToolArgs(fallbackArgs, selectedArgs) { + const fallback = fallbackArgs && typeof fallbackArgs === "object" && !Array.isArray(fallbackArgs) + ? { ...fallbackArgs } + : {}; + const selected = selectedArgs && typeof selectedArgs === "object" && !Array.isArray(selectedArgs) + ? selectedArgs + : {}; + + for (const [key, value] of Object.entries(selected)) { + if (!hasMeaningfulRestrictedArgValue(value)) { + continue; + } + fallback[key] = value; + } + + return fallback; +} + +function buildRestrictedFallbackPlan({ + trimmedMessage, + directAccountFlow, + directBulkPowerFlow, + directSinglePowerFlow, + directLoadLookup, + directConsoleCheck, + directServerLimits, + directOpenServerPage, + directOpenSettings, +}) { + if (directAccountFlow) { + return { + reply: directAccountFlow.reply, + toolName: "open_account_flow", + toolArgs: { flow: directAccountFlow.flow }, + }; + } + + if (directBulkPowerFlow) { + return { + reply: "", + toolName: "power_accessible_servers", + toolArgs: { action: directBulkPowerFlow.action }, + }; + } + + if (directSinglePowerFlow) { + return { + reply: "", + toolName: "power_server", + toolArgs: directSinglePowerFlow.args, + }; + } + + if (directLoadLookup) { + return { + reply: "", + toolName: directLoadLookup.toolName, + toolArgs: directLoadLookup.args, + }; + } + + if (directConsoleCheck) { + return { + reply: "", + toolName: "check_server_console", + toolArgs: directConsoleCheck.args, + }; + } + + if (directServerLimits) { + return { + reply: "", + toolName: "check_server_limits", + toolArgs: directServerLimits.args, + }; + } + + if (directOpenServerPage) { + return { + reply: "", + toolName: "open_server_page", + toolArgs: directOpenServerPage.args, + }; + } + + if (directOpenSettings) { + return { + reply: "", + toolName: "open_settings_destination", + toolArgs: directOpenSettings.args, + }; + } + + return { + reply: "", + toolName: "", + toolArgs: {}, + }; +} + +async function buildRestrictedSingleShotPlan({ + provider, + apiKey, + modelName, + systemPrompt, + latestUserMessage, + inferredServerContextMessage, + restrictedIntentSystemHint, + conversationContextMessage, + persistedMessages, + requestChatCompletion, +}) { + const { olderContextMessage, recentMessages } = buildAssistantModelConversationWindow(persistedMessages, { + recentCount: 16, + olderTranscriptCount: 10, + olderTranscriptTotalLimit: 1400, + }); + + const response = await requestChatCompletion(provider, apiKey, { + model: modelName, + temperature: 0.1, + max_tokens: 180, + messages: [ + { role: "system", content: systemPrompt }, + { + role: "system", + content: [ + "Return exactly one JSON object and nothing else.", + 'Schema: {"reply":"short natural reply for the user","toolName":"power_server|power_accessible_servers|open_server_page|open_settings_destination|open_account_flow|get_busiest_node|get_busiest_server|check_server_console|check_server_limits|","toolArgs":{}}', + "Use an empty toolName when no tool is needed and answer directly in reply.", + "If a tool is needed, keep reply short and queued-style, such as checking now or preparing a link now.", + "Treat the latest user message as the main instruction. Older messages may only help resolve omitted references like it, that server, or short follow-up questions.", + "If the latest message explicitly names a server, action, section, destination, popup, or panel, do not let older context override it.", + "Do not claim the action is finished before the browser runs it.", + "For navigation tools, never say the page was opened automatically. The dashboard will provide a clickable link the user can choose to open.", + "For messy natural requests about startup time, crash cause, logs, whether a server started correctly, or whether it is running well, prefer check_server_console.", + "For one named server questions about RAM, CPU, disk, storage, quotas, remaining space, or whether it is close to its limits, prefer check_server_limits.", + "For all accessible servers power requests, prefer power_accessible_servers.", + "For one named server power requests, prefer power_server and pass the user's raw server wording in toolArgs.server.", + "For requests to open, manage, configure, edit, or access a server page, console, backups, files, scheduler, activity, store, resource stats, or similar server areas, prefer open_server_page.", + "For admin requests to open, manage, configure, edit, or access settings pages or settings modals such as nodes, appearance, branding, maintenance, captcha, databases, quick actions, or webhooks, prefer open_settings_destination.", + "For load questions, choose get_busiest_node or get_busiest_server and include any asked metrics.", + "Use recent conversation context when the user refers to earlier answers.", + "The latest explicit user request always overrides older context.", + "Use older context only to resolve omitted references such as it, that, there, or the server we just discussed.", + "If the latest user message explicitly names a server, destination, section, action, popup, or settings area, do not let older context replace it.", + ].join(" "), + }, + ...(latestUserMessage ? [{ + role: "system", + content: `Primary task: answer the latest user message exactly as requested: ${JSON.stringify(String(latestUserMessage || "").trim())}.`, + }] : []), + ...(inferredServerContextMessage ? [{ role: "system", content: inferredServerContextMessage }] : []), + ...(restrictedIntentSystemHint ? [{ role: "system", content: restrictedIntentSystemHint }] : []), + ...(conversationContextMessage ? [{ role: "system", content: conversationContextMessage }] : []), + ...(olderContextMessage ? [{ role: "system", content: olderContextMessage }] : []), + ...recentMessages, + ], + }); + + return response; +} + +function coerceFiniteNumber(value) { + const num = Number(value); + return Number.isFinite(num) ? num : null; +} + +function convertAmountToMb(amount, unit) { + const numeric = coerceFiniteNumber(amount); + const normalizedUnit = String(unit || "").trim().toLowerCase(); + if (numeric == null) return null; + if (normalizedUnit === "gb") return Math.round(numeric * 1024); + if (normalizedUnit === "tb") return Math.round(numeric * 1024 * 1024); + return Math.round(numeric); +} + +function getRecentMessagesByRole(messages, role, limit = 14) { + return (Array.isArray(messages) ? messages : []) + .filter((entry) => String(entry?.role || "").toLowerCase() === String(role || "").toLowerCase()) + .slice(-limit) + .map((entry) => normalizeMessageContent(entry.content)) + .filter(Boolean); +} + +function findLatestRegexValue(texts, patterns, transform) { + const list = Array.isArray(texts) ? texts : []; + for (let index = list.length - 1; index >= 0; index -= 1) { + const text = String(list[index] || ""); + for (const pattern of patterns) { + const match = pattern.exec(text); + if (!match) continue; + const result = typeof transform === "function" ? transform(match, text) : match[1]; + if (result != null && result !== "") { + return result; + } + } + } + return null; +} + +function detectProvisioningDefaults(messages) { + const recentMessages = Array.isArray(messages) ? messages : []; + const userTexts = getRecentMessagesByRole(recentMessages, "user", 10); + if (userTexts.some((text) => /\b(use|with|pick|choose|go with|take)\s+(the\s+)?defaults?\b/i.test(text))) { + return true; + } + if (userTexts.some((text) => /\b(use|with|pick|choose|go with|take)\s+(the\s+)?recommended\b/i.test(text))) { + return true; + } + if (userTexts.some((text) => /\bwhatever you recommend\b/i.test(text))) { + return true; + } + + const lastUserText = String(userTexts[userTexts.length - 1] || "").trim(); + if (lastUserText && isAffirmativeShortReply(lastUserText) && assistantAskedDefaultsQuestion(recentMessages)) { + return true; + } + + return false; +} + +function detectProvisioningNeedsResourcePrompt(messages) { + const userTexts = getRecentMessagesByRole(messages, "user", 10); + if (!userTexts.length) return false; + const mentionedResources = userTexts.some((text) => /\b(limit(?:ed)?|resources?|ram|memory|cpu|storage|disk)\b/i.test(text)); + const mentionedValues = userTexts.some((text) => /\b\d+(?:\.\d+)?\s*(?:mb|gb|tb|cores?)\b/i.test(text)); + return mentionedResources && !mentionedValues; +} + +function messageMentionsPluginInstall(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return false; + return /\b(install|add|download|setup|set up)\b/.test(text) && /\b(plugin|plugins|modrinth|viaversion|geyser|luckperms|vault)\b/.test(text); +} + +function resolveEntryByAliases(entries, requestedValue, aliasGetter) { + const requested = String(requestedValue || "").trim().toLowerCase(); + if (!requested) return null; + const sourceEntries = Array.isArray(entries) ? entries : []; + + const exactMatch = sourceEntries.find((entry) => + (typeof aliasGetter === "function" ? aliasGetter(entry) : []) + .map((alias) => String(alias || "").trim().toLowerCase()) + .includes(requested) + ); + if (exactMatch) return exactMatch; + + return sourceEntries.find((entry) => + (typeof aliasGetter === "function" ? aliasGetter(entry) : []) + .map((alias) => String(alias || "").trim().toLowerCase()) + .some((alias) => alias.includes(requested) || requested.includes(alias)) + ) || null; +} + +function findAssistantSuggestedEntry(lastAssistantText, entries, aliasGetter) { + const text = normalizeLooseText(lastAssistantText); + if (!text) return null; + + const matches = []; + for (const entry of Array.isArray(entries) ? entries : []) { + const aliases = (typeof aliasGetter === "function" ? aliasGetter(entry) : []) + .map((alias) => normalizeLooseText(alias)) + .filter(Boolean) + .sort((left, right) => right.length - left.length); + + if (!aliases.length) continue; + const matched = aliases.some((alias) => { + const pattern = new RegExp(`(^|[^a-z0-9])${escapeRegex(alias)}(?=$|[^a-z0-9])`, "i"); + return pattern.test(text); + }); + if (matched) matches.push(entry); + } + + return matches.length === 1 ? matches[0] : null; +} + +function formatChoiceList(values, limit = 3) { + const items = Array.from(new Set((Array.isArray(values) ? values : []).map((value) => String(value || "").trim()).filter(Boolean))).slice(0, limit); + if (!items.length) return ""; + if (items.length === 1) return items[0]; + if (items.length === 2) return `${items[0]} or ${items[1]}`; + return `${items.slice(0, -1).join(", ")}, or ${items[items.length - 1]}`; +} + +function isVagueProvisioningReply(message) { + const text = String(message || "").trim().toLowerCase(); + if (!text) return true; + if (/\b(which|what|how much|how many|choose|pick|tell me)\b/.test(text) && /\b(template|node|name|host port|port|ram|cpu|storage|defaults?)\b/.test(text)) { + return false; + } + if (text.split(/\s+/).filter(Boolean).length <= 4 && !/\b(template|node|name|host port|port|ram|cpu|storage|created|defaults?)\b/.test(text)) { + return true; + } + return /\b(i need|need one more detail|need more detail|need more information|need to know more|tell me more)\b/.test(text); +} + + function findLatestAliasEntry(texts, entries, aliasGetter) { + const sourceTexts = Array.isArray(texts) ? texts : []; + const sourceEntries = Array.isArray(entries) ? entries : []; + const preparedEntries = sourceEntries + .map((entry) => { + const aliases = (typeof aliasGetter === "function" ? aliasGetter(entry) : []) + .map((alias) => String(alias || "").trim()) + .filter(Boolean) + .sort((left, right) => right.length - left.length); + return { entry, aliases }; + }) + .filter((item) => item.aliases.length > 0); + + for (let textIndex = sourceTexts.length - 1; textIndex >= 0; textIndex -= 1) { + const text = normalizeLooseText(sourceTexts[textIndex]); + for (const item of preparedEntries) { + for (const alias of item.aliases) { + const aliasText = normalizeLooseText(alias); + if (!aliasText) continue; + const pattern = new RegExp(`(^|[^a-z0-9])${escapeRegex(aliasText)}(?=$|[^a-z0-9])`, "i"); + if (pattern.test(text)) { + return item.entry; + } + } + } + } + + return null; +} + +function parseCarryForwardProvisioningContext(texts) { + const sourceTexts = Array.isArray(texts) ? texts : []; + const carryText = sourceTexts + .slice() + .reverse() + .find((text) => /\bcarry-forward provisioning context:\b/i.test(String(text || ""))); + if (!carryText) { + return {}; + } + + const readField = (name) => { + const match = new RegExp(`\\b${escapeRegex(name)}=([^;]+)`, "i").exec(String(carryText || "")); + return match ? String(match[1] || "").trim() : ""; + }; + const readIntField = (name) => { + const raw = readField(name); + const parsed = parseInt(raw, 10); + return Number.isInteger(parsed) ? parsed : null; + }; + const readFloatField = (name) => { + const raw = readField(name); + const parsed = parseFloat(raw); + return Number.isFinite(parsed) ? parsed : null; + }; + + const nodeValue = readField("node"); + return { + templateId: readField("template") || null, + templateName: readField("template") || null, + nodeId: nodeValue || null, + nodeName: nodeValue || null, + serverName: readField("serverName") || null, + mcFork: readField("mcFork") || null, + mcVersion: readField("mcVersion") || null, + hostPort: readIntField("hostPort"), + ramMb: readIntField("ramMb"), + cpuCores: readFloatField("cpuCores"), + storageMb: readIntField("storageMb"), + useDefaults: /^true$/i.test(readField("useDefaults")), + wantsResourcePrompt: /^true$/i.test(readField("wantsResourcePrompt")), + }; +} + +function jsonApiRequest(fullUrl, { method = "POST", headers = {}, body = null, timeoutMs = 60_000, timeoutMessage = "Request timeout", agent = null } = {}) { + return new Promise((resolve, reject) => { + const payload = body == null ? null : (typeof body === "string" ? body : JSON.stringify(body || {})); + const url = new URL(fullUrl); + const req = https.request( + { + hostname: url.hostname, + port: Number(url.port) || 443, + path: `${url.pathname}${url.search}`, + method, + headers: Object.assign({}, headers, payload == null ? {} : { + "Content-Length": Buffer.byteLength(payload), + }), + agent: agent || undefined, + servername: url.hostname || undefined, + timeout: timeoutMs, + }, + (res) => { + let data = ""; + res.setEncoding("utf8"); + res.on("data", (chunk) => { data += chunk; }); + res.on("end", () => { + try { + resolve({ + status: res.statusCode || 0, + data: data ? JSON.parse(data) : {}, + }); + } catch { + resolve({ + status: res.statusCode || 0, + data: { raw: data }, + }); + } + }); + } + ); + + req.on("error", reject); + req.on("timeout", () => req.destroy(new Error(timeoutMessage))); + if (payload != null) { + req.write(payload); + } + req.end(); + }); +} + +function groqMultipartRequest(pathname, apiKey, formData, timeoutMs = 60_000) { + return new Promise((resolve, reject) => { + const headers = formData.getHeaders({ + "Authorization": `Bearer ${apiKey}`, + }); + + const req = https.request( + { + hostname: "api.groq.com", + port: 443, + path: pathname, + method: "POST", + headers, + agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.groq, + servername: "api.groq.com", + timeout: timeoutMs, + }, + (res) => { + let data = ""; + res.setEncoding("utf8"); + res.on("data", (chunk) => { data += chunk; }); + res.on("end", () => { + try { + resolve({ + status: res.statusCode || 0, + data: data ? JSON.parse(data) : {}, + }); + } catch { + resolve({ + status: res.statusCode || 0, + data: { raw: data }, + }); + } + }); + } + ); + + req.on("error", reject); + req.on("timeout", () => req.destroy(new Error("Groq request timeout"))); + formData.pipe(req); + }); +} + +function createDashboardAssistantService(deps) { + if (!deps || typeof deps !== "object") { + throw new Error("Dashboard assistant dependencies are required."); + } + + const runTool = createDashboardAssistantToolRunner(deps); + let initPromise = null; + // Keep decrypted provider keys in memory so chat requests avoid repeated .env reads and crypto work. + const providerSecretCache = { + loaded: false, + providerPreference: "", + keys: { + groq: "", + google: "", + }, + encrypted: { + groq: "", + google: "", + }, + }; + + function loadProviderSecretCache() { + const env = typeof deps.readEnvFile === "function" ? deps.readEnvFile() : {}; + const nextKeys = { groq: "", google: "" }; + const nextEncrypted = { groq: "", google: "" }; + + for (const providerId of Object.keys(PROVIDER_LABELS)) { + const secretConfig = getAssistantProviderSecretConfig(providerId); + if (!secretConfig) continue; + + const encryptedValue = sanitizeToken( + env[secretConfig.encrypted] || + process.env[secretConfig.encrypted] || + "" + ); + + let resolvedKey = ""; + if (encryptedValue) { + try { + resolvedKey = decryptAssistantProviderToken(encryptedValue); + } catch (error) { + console.error(`[dashboard-assistant] Failed to decrypt ${providerId} API key:`, error); + } + } + + if (!resolvedKey) { + for (const legacyEnvKey of secretConfig.legacy) { + resolvedKey = sanitizeToken(env[legacyEnvKey] || process.env[legacyEnvKey] || ""); + if (resolvedKey) break; + } + } + + nextKeys[providerId] = resolvedKey; + nextEncrypted[providerId] = encryptedValue; + } + + providerSecretCache.providerPreference = sanitizeProvider( + env.DASHBOARD_ASSISTANT_PROVIDER || + process.env.DASHBOARD_ASSISTANT_PROVIDER || + "" + ); + providerSecretCache.keys = nextKeys; + providerSecretCache.encrypted = nextEncrypted; + providerSecretCache.loaded = true; + return providerSecretCache; + } + + function ensureProviderSecretCache() { + if (providerSecretCache.loaded) return providerSecretCache; + return loadProviderSecretCache(); + } + + function getGoogleKey() { + return sanitizeToken(ensureProviderSecretCache().keys.google || ""); + } + + function getGroqKey() { + return sanitizeToken(ensureProviderSecretCache().keys.groq || ""); + } + + function getStoredProviderPreference() { + return sanitizeProvider(ensureProviderSecretCache().providerPreference || ""); + } + + function getProviderKey(provider) { + if (provider === "google") return getGoogleKey(); + if (provider === "groq") return getGroqKey(); + return ""; + } + + function getResolvedProvider() { + const preferred = getStoredProviderPreference(); + if (preferred && getProviderKey(preferred)) { + return preferred; + } + if (getGroqKey()) return "groq"; + if (getGoogleKey()) return "google"; + return preferred || "groq"; + } + + function getChatModelForProvider(provider) { + return provider === "google" ? DEFAULT_GOOGLE_MODEL : DEFAULT_GROQ_MODEL; + } + + function getTranscriptionModelForProvider(provider) { + return provider === "google" ? DEFAULT_GOOGLE_TRANSCRIPTION_MODEL : DEFAULT_GROQ_TRANSCRIPTION_MODEL; + } + + async function loadAccessibleServersForAssistant(userEmail) { + const normalizedEmail = String(userEmail || "").trim().toLowerCase(); + const cachedEntry = accessibleServersForAssistantCache.get(normalizedEmail); + if (cachedEntry && Date.now() - cachedEntry.updatedAt < ACCESSIBLE_SERVERS_CACHE_TTL_MS) { + return cachedEntry.list; + } + + const list = ((typeof deps.loadServersIndex === "function" ? await deps.loadServersIndex() : []) || []).filter(Boolean); + const user = typeof deps.findUserByEmail === "function" ? await deps.findUserByEmail(normalizedEmail) : null; + let resolvedList = list; + + if (!user?.admin) { + const accessList = ((typeof deps.getAccessListForEmail === "function" ? await deps.getAccessListForEmail(normalizedEmail) : []) || []) + .map((item) => String(item || "").trim().toLowerCase()) + .filter(Boolean); + const loweredAccess = new Set(accessList); + resolvedList = loweredAccess.has("all") + ? list + : list.filter((entry) => entry?.name && loweredAccess.has(String(entry.name).trim().toLowerCase())); + } + + accessibleServersForAssistantCache.set(normalizedEmail, { + updatedAt: Date.now(), + list: resolvedList, + }); + return resolvedList; + } + + async function ensureTables() { + if (initPromise) return initPromise; + + initPromise = (async () => { + await deps.db.query(` + CREATE TABLE IF NOT EXISTS dashboard_assistant_chats ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + user_email VARCHAR(255) NOT NULL, + title VARCHAR(255) NOT NULL DEFAULT '${DEFAULT_CHAT_TITLE}', + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY idx_dashboard_assistant_chats_user (user_email), + KEY idx_dashboard_assistant_chats_updated (updated_at) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + + await deps.db.query(` + CREATE TABLE IF NOT EXISTS dashboard_assistant_messages ( + id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, + chat_id BIGINT UNSIGNED NOT NULL, + role ENUM('user', 'assistant', 'system') NOT NULL, + content LONGTEXT NOT NULL, + model VARCHAR(255) NULL, + thinking_time_ms INT UNSIGNED NULL, + created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, + PRIMARY KEY (id), + KEY idx_dashboard_assistant_messages_chat (chat_id), + KEY idx_dashboard_assistant_messages_created (created_at), + CONSTRAINT fk_dashboard_assistant_messages_chat + FOREIGN KEY (chat_id) REFERENCES dashboard_assistant_chats(id) ON DELETE CASCADE + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci + `); + })().catch((error) => { + initPromise = null; + throw error; + }); + + return initPromise; + } + + async function getPrimaryChat(userEmail) { + await ensureTables(); + const normalizedEmail = String(userEmail || "").trim().toLowerCase(); + const existingRows = await deps.db.query( + `SELECT id, title, created_at, updated_at + FROM dashboard_assistant_chats + WHERE user_email = ? + ORDER BY updated_at DESC + LIMIT 1`, + [normalizedEmail] + ); + + if (existingRows[0]) { + return existingRows[0]; + } + + const result = await deps.db.query( + "INSERT INTO dashboard_assistant_chats (user_email, title) VALUES (?, ?)", + [normalizedEmail, DEFAULT_CHAT_TITLE] + ); + + const createdRows = await deps.db.query( + "SELECT id, title, created_at, updated_at FROM dashboard_assistant_chats WHERE id = ? LIMIT 1", + [result.insertId] + ); + return createdRows[0]; + } + + async function createFreshChat(userEmail) { + await ensureTables(); + const normalizedEmail = String(userEmail || "").trim().toLowerCase(); + const result = await deps.db.query( + "INSERT INTO dashboard_assistant_chats (user_email, title) VALUES (?, ?)", + [normalizedEmail, DEFAULT_CHAT_TITLE] + ); + const rows = await deps.db.query( + "SELECT id, title, created_at, updated_at FROM dashboard_assistant_chats WHERE id = ? LIMIT 1", + [result.insertId] + ); + return rows[0]; + } + + async function getChatById(userEmail, chatId) { + await ensureTables(); + const normalizedEmail = String(userEmail || "").trim().toLowerCase(); + const numericChatId = Number(chatId); + if (!Number.isFinite(numericChatId) || numericChatId <= 0) { + return null; + } + const rows = await deps.db.query( + `SELECT id, title, created_at, updated_at + FROM dashboard_assistant_chats + WHERE id = ? AND user_email = ? + LIMIT 1`, + [numericChatId, normalizedEmail] + ); + return rows[0] || null; + } + + async function getChatMessages(chatId, limit = 60) { + await ensureTables(); + const safeLimit = Math.max(1, Math.min(200, parseInt(limit, 10) || 60)); + const rows = await deps.db.query( + `SELECT id, role, content, model, thinking_time_ms, created_at + FROM dashboard_assistant_messages + WHERE chat_id = ? + ORDER BY created_at ASC, id ASC + LIMIT ${safeLimit}`, + [chatId] + ); + return Array.isArray(rows) ? rows : []; + } + + async function getChatMessageCount(chatId) { + await ensureTables(); + const rows = await deps.db.query( + "SELECT COUNT(*) AS total FROM dashboard_assistant_messages WHERE chat_id = ? AND role IN ('user', 'assistant') LIMIT 1", + [chatId] + ); + return Number(rows?.[0]?.total || 0); + } + + async function addMessage(chatId, { role, content, model = null, thinkingTimeMs = null }) { + await ensureTables(); + await deps.db.query( + `INSERT INTO dashboard_assistant_messages (chat_id, role, content, model, thinking_time_ms) + VALUES (?, ?, ?, ?, ?)`, + [chatId, role, String(content || ""), model || null, thinkingTimeMs || null] + ); + await deps.db.query("UPDATE dashboard_assistant_chats SET updated_at = NOW() WHERE id = ?", [chatId]); + } + + async function deleteChat(userEmail, chatId) { + await ensureTables(); + const normalizedEmail = String(userEmail || "").trim().toLowerCase(); + const numericChatId = Number(chatId); + if (!Number.isFinite(numericChatId) || numericChatId <= 0) return; + await deps.db.query( + "DELETE FROM dashboard_assistant_chats WHERE id = ? AND user_email = ? LIMIT 1", + [numericChatId, normalizedEmail] + ); + } + + async function getActiveChat(userEmail, requestedChatId = null) { + const requestedChat = requestedChatId ? await getChatById(userEmail, requestedChatId) : null; + const chat = requestedChat || await getPrimaryChat(userEmail); + if (!chat) return null; + + const messageCount = await getChatMessageCount(chat.id); + if (messageCount < MAX_CHAT_MESSAGES) { + return chat; + } + + const previousMessages = await getChatMessages(chat.id, CHAT_HISTORY_LIMIT); + const freshChat = await createFreshChat(userEmail); + const carryForwardSummary = await buildCarryForwardSystemSummary(previousMessages); + if (carryForwardSummary) { + await addMessage(freshChat.id, { + role: "system", + content: carryForwardSummary, + model: "adpanel-chat-handoff", + }); + } + if (chat.id !== freshChat.id) { + await deleteChat(userEmail, chat.id).catch(() => {}); + } + return freshChat; + } + + async function inferProvisioningContext(messages) { + const userTexts = getRecentMessagesByRole(messages, "user", 16); + const assistantTexts = getRecentMessagesByRole(messages, "assistant", 12); + const systemTexts = getRecentMessagesByRole(messages, "system", 6); + const carryForwardContext = parseCarryForwardProvisioningContext(systemTexts); + if (!userTexts.length && !assistantTexts.length && !Object.keys(carryForwardContext).length) return null; + + const provisioningThreadLikely = + userTexts.some((text) => /\b(create|make|spin up|deploy|provision|new server|server)\b/i.test(text)) || + assistantTexts.some((text) => /\b(template|node|server name|host port|port|ram|cpu|storage|create)\b/i.test(text)) || + Object.keys(carryForwardContext).length > 0; + if (!provisioningThreadLikely) return null; + + let templates = []; + let nodes = []; + try { + templates = typeof deps.loadTemplatesFile === "function" ? (deps.loadTemplatesFile() || []) : []; + } catch { + templates = []; + } + try { + nodes = typeof deps.loadNodes === "function" ? await deps.loadNodes() || [] : []; + } catch { + nodes = []; + } + + const lastUserText = String(userTexts[userTexts.length - 1] || "").trim(); + const lastAssistantText = String(assistantTexts[assistantTexts.length - 1] || "").trim().toLowerCase(); + const acceptedAssistantSuggestion = isAffirmativeShortReply(lastUserText); + const impliedMinecraft = userTexts.some((text) => /\b(minecraft|paper|purpur|spigot|bukkit|vanilla)\b/i.test(text)); + const impliedNodeJs = userTexts.some((text) => /\b(node\.?js|nodejs|discord bot|discord-bot)\b/i.test(text)); + const impliedPython = userTexts.some((text) => /\bpython\b/i.test(text)); + const template = findLatestAliasEntry(userTexts, templates, (entry) => [entry?.id, entry?.name]); + const node = findLatestAliasEntry(userTexts, nodes, (entry) => [entry?.name, entry?.id, entry?.uuid]); + const assistantSuggestedTemplate = acceptedAssistantSuggestion + ? findAssistantSuggestedEntry(lastAssistantText, templates, (entry) => [entry?.id, entry?.name]) + : null; + const assistantSuggestedNode = acceptedAssistantSuggestion + ? findAssistantSuggestedEntry(lastAssistantText, nodes, (entry) => [entry?.name, entry?.id, entry?.uuid]) + : null; + const hostPort = findLatestRegexValue( + userTexts, + [ + /\b(?:host\s+port|hostport|port)\s*(?:is\s+|to\s+|=)?(\d{1,5})\b/i, + /\b(?:on|using)\s+port\s+(\d{1,5})\b/i, + /\buse\s+(\d{1,5})\b/i, + /^(\d{2,5})$/i, + ], + (match) => { + const port = parseInt(match[1], 10); + return Number.isInteger(port) && port >= 1 && port <= 65535 ? port : null; + } + ); + const ramMb = findLatestRegexValue( + userTexts, + [ + /\b(?:ram|memory)\s*(?:is\s+|to\s+|=)?(\d+(?:\.\d+)?)\s*(mb|gb|tb)\b/i, + /\b(\d+(?:\.\d+)?)\s*(mb|gb|tb)\s*(?:of\s+)?(?:ram|memory)\b/i, + ], + (match) => convertAmountToMb(match[1], match[2]) + ); + const cpuCores = findLatestRegexValue( + userTexts, + [ + /\b(?:cpu|cores?)\s*(?:is\s+|to\s+|=)?(\d+(?:\.\d+)?)\b/i, + /\b(\d+(?:\.\d+)?)\s*(?:cpu\s*cores?|cores?)\b/i, + ], + (match) => coerceFiniteNumber(match[1]) + ); + const storageMb = findLatestRegexValue( + userTexts, + [ + /\b(?:storage|disk)\s*(?:is\s+|to\s+|=)?(\d+(?:\.\d+)?)\s*(mb|gb|tb)\b/i, + /\b(\d+(?:\.\d+)?)\s*(mb|gb|tb)\s*(?:of\s+)?(?:storage|disk)\b/i, + ], + (match) => convertAmountToMb(match[1], match[2]) + ); + const serverName = findLatestRegexValue( + userTexts, + [ + /\b(?:name(?:\s+it|\s+is)?|call\s+it|server\s+name(?:\s+is)?|create\s+(?:it\s+)?as)\s+["']?([a-z0-9._-]{2,48})["']?\b/i, + /\b(?:named|called)\s+["']?([a-z0-9._-]{2,48})["']?\b/i, + ], + (match) => match[1] + ); + const mcFork = findLatestRegexValue( + userTexts, + [ + /\b(paper|purpur|spigot|bukkit|vanilla)\b/i, + ], + (match) => String(match[1] || "").trim().toLowerCase() + ); + const mcVersion = findLatestRegexValue( + userTexts, + [ + /\b(?:minecraft\s+)?(1\.\d{1,2}(?:\.\d{1,2})?)\b/i, + ], + (match) => String(match[1] || "").trim() + ); + + const context = { + templateId: template?.id || assistantSuggestedTemplate?.id || carryForwardContext.templateId || (impliedMinecraft ? "minecraft" : (impliedNodeJs ? "nodejs" : (impliedPython ? "python" : null))), + templateName: template?.name || template?.id || assistantSuggestedTemplate?.name || assistantSuggestedTemplate?.id || carryForwardContext.templateName || null, + nodeId: node?.id || node?.uuid || node?.name || assistantSuggestedNode?.id || assistantSuggestedNode?.uuid || assistantSuggestedNode?.name || carryForwardContext.nodeId || null, + nodeName: node?.name || node?.id || node?.uuid || assistantSuggestedNode?.name || assistantSuggestedNode?.id || assistantSuggestedNode?.uuid || carryForwardContext.nodeName || null, + hostPort: hostPort ?? carryForwardContext.hostPort, + ramMb: ramMb ?? carryForwardContext.ramMb, + cpuCores: cpuCores ?? carryForwardContext.cpuCores, + storageMb: storageMb ?? carryForwardContext.storageMb, + serverName: serverName || carryForwardContext.serverName || null, + mcFork: mcFork === "vanilla" ? "paper" : (mcFork || carryForwardContext.mcFork || null), + mcVersion: mcVersion || carryForwardContext.mcVersion || null, + useDefaults: detectProvisioningDefaults(messages) || !!carryForwardContext.useDefaults, + wantsResourcePrompt: detectProvisioningNeedsResourcePrompt(messages) || !!carryForwardContext.wantsResourcePrompt, + }; + + if (!context.templateId && /\btemplate\b/.test(lastAssistantText) && lastUserText) { + context.templateId = lastUserText; + } + if (!context.nodeId && /\bnode\b/.test(lastAssistantText) && lastUserText && !isAffirmativeShortReply(lastUserText)) { + context.nodeId = lastUserText; + } + if (!context.serverName && /\bserver name\b|\bname the server\b|\bname should i use\b/.test(lastAssistantText) && lastUserText && !isAffirmativeShortReply(lastUserText)) { + context.serverName = lastUserText; + } + if (context.hostPort == null && /\bport\b/.test(lastAssistantText) && /^\d{2,5}$/.test(lastUserText)) { + const parsedPort = parseInt(lastUserText, 10); + if (Number.isInteger(parsedPort) && parsedPort >= 1 && parsedPort <= 65535) { + context.hostPort = parsedPort; + } + } + if (context.hostPort == null && acceptedAssistantSuggestion && /\bport\b/.test(lastAssistantText)) { + const defaultPortMatch = /\bdefault(?: is|:)?\s*(\d{2,5})\b/i.exec(lastAssistantText); + if (defaultPortMatch) { + const parsedPort = parseInt(defaultPortMatch[1], 10); + if (Number.isInteger(parsedPort) && parsedPort >= 1 && parsedPort <= 65535) { + context.hostPort = parsedPort; + } + } + } + if (context.ramMb == null && /\bram|memory\b/.test(lastAssistantText)) { + const ramMatch = /\b(\d+(?:\.\d+)?)\s*(mb|gb|tb)\b/i.exec(lastUserText); + if (ramMatch) context.ramMb = convertAmountToMb(ramMatch[1], ramMatch[2]); + } + if (context.cpuCores == null && /\bcpu|cores?\b/.test(lastAssistantText)) { + const cpuMatch = /\b(\d+(?:\.\d+)?)\s*(?:cpu\s*cores?|cores?)\b/i.exec(lastUserText) || /^(\d+(?:\.\d+)?)$/i.exec(lastUserText); + if (cpuMatch) context.cpuCores = coerceFiniteNumber(cpuMatch[1]); + } + if (context.storageMb == null && /\bstorage|disk\b/.test(lastAssistantText)) { + const storageMatch = /\b(\d+(?:\.\d+)?)\s*(mb|gb|tb)\b/i.exec(lastUserText); + if (storageMatch) context.storageMb = convertAmountToMb(storageMatch[1], storageMatch[2]); + } + + return Object.values(context).some((value) => value != null && value !== "") ? context : null; + } + + async function buildCarryForwardSystemSummary(messages) { + const recentMessages = (Array.isArray(messages) ? messages : []) + .filter((entry) => entry && (entry.role === "user" || entry.role === "assistant")) + .slice(-24); + if (!recentMessages.length) { + return ""; + } + + const parts = []; + const provisioningContext = await inferProvisioningContext(recentMessages); + const provisioningSummary = buildConversationContextMessage(provisioningContext); + if (provisioningSummary) { + parts.push(provisioningSummary.replace(/^Recent inferred provisioning context:/, "Carry-forward provisioning context:")); + } + + const lastAssistantText = getLastAssistantText(recentMessages); + if (lastAssistantText && (assistantAskedProvisioningQuestion(recentMessages) || assistantAskedProvisioningConfirmation(recentMessages))) { + parts.push(`Carry-forward last assistant prompt: ${lastAssistantText}`); + } + + const recentUserTexts = getRecentMessagesByRole(recentMessages, "user", 5); + if (recentUserTexts.length) { + parts.push(`Carry-forward recent user intent: ${recentUserTexts.join(" | ").slice(0, 700)}`); + } + + const visibleTranscript = buildCarryForwardVisibleTranscript(recentMessages, { + count: 18, + perMessageLimit: 180, + totalLimit: 2600, + }); + if (visibleTranscript) { + parts.push(`Carry-forward visible chat transcript:\n${visibleTranscript}`); + } + + return parts.join("\n\n").trim().slice(0, 4200); + } + + function buildConversationContextMessage(context) { + if (!context) return ""; + + const parts = []; + if (context.templateId || context.templateName) { + parts.push(`template=${context.templateId || context.templateName}`); + } + if (context.nodeName || context.nodeId) { + parts.push(`node=${context.nodeName || context.nodeId}`); + } + if (context.serverName) { + parts.push(`serverName=${context.serverName}`); + } + if (context.mcFork) { + parts.push(`mcFork=${context.mcFork}`); + } + if (context.mcVersion) { + parts.push(`mcVersion=${context.mcVersion}`); + } + if (context.hostPort != null) { + parts.push(`hostPort=${context.hostPort}`); + } + if (context.ramMb != null) { + parts.push(`ramMb=${context.ramMb}`); + } + if (context.cpuCores != null) { + parts.push(`cpuCores=${context.cpuCores}`); + } + if (context.storageMb != null) { + parts.push(`storageMb=${context.storageMb}`); + } + if (context.useDefaults) { + parts.push("useDefaults=true"); + } + if (context.wantsResourcePrompt) { + parts.push("wantsResourcePrompt=true"); + } + + if (!parts.length) return ""; + + return `Recent inferred provisioning context: ${parts.join("; ")}. Reuse these values unless the user changes them. Ask only for missing or ambiguous fields.`; + } + + async function buildProvisioningPlan(messages) { + const context = await inferProvisioningContext(messages); + if (!context) return null; + + let templates = []; + let nodes = []; + try { + templates = typeof deps.loadTemplatesFile === "function" ? (deps.loadTemplatesFile() || []) : []; + } catch { + templates = []; + } + try { + nodes = typeof deps.loadNodes === "function" ? await deps.loadNodes() || [] : []; + } catch { + nodes = []; + } + + const template = resolveEntryByAliases(templates, context.templateId || context.templateName, (entry) => [entry?.id, entry?.name]); + const node = resolveEntryByAliases(nodes, context.nodeId || context.nodeName, (entry) => [entry?.id, entry?.uuid, entry?.name]); + const useDefaults = !!context.useDefaults; + const templateDefaultPort = template?.defaultPort != null ? parseInt(template.defaultPort, 10) || null : null; + + const missingFields = []; + if (!template) missingFields.push("template"); + if (!node) missingFields.push("node"); + if (!context.serverName) missingFields.push("name"); + if (context.hostPort == null && !(useDefaults && templateDefaultPort != null)) { + missingFields.push("port"); + } + const createArgs = { + name: context.serverName || "", + displayName: context.serverName || "", + templateId: template?.id || context.templateId || "", + nodeId: node?.id || node?.uuid || node?.name || context.nodeId || "", + hostPort: context.hostPort != null ? context.hostPort : templateDefaultPort, + mcFork: context.mcFork || undefined, + mcVersion: context.mcVersion || undefined, + resources: Object.assign( + {}, + context.ramMb != null ? { ramMb: context.ramMb } : {}, + context.cpuCores != null ? { cpuCores: context.cpuCores } : {}, + context.storageMb != null ? { storageMb: context.storageMb } : {} + ), + }; + + if (!Object.keys(createArgs.resources).length) { + delete createArgs.resources; + } + + return { + context, + template, + node, + useDefaults, + wantsResourcePrompt: !!context.wantsResourcePrompt, + templateDefaultPort, + missingFields, + createArgs, + templateChoices: templates.slice(0, 3).map((entry) => entry?.name || entry?.id).filter(Boolean), + nodeChoices: nodes.filter((entry) => entry?.online !== false).slice(0, 3).map((entry) => entry?.name || entry?.id || entry?.uuid).filter(Boolean), + }; + } + + function buildProvisioningFollowUp(plan) { + if (!plan) { + return "Which detail should I use to create the server?"; + } + + const missing = Array.isArray(plan.missingFields) ? plan.missingFields : []; + if (!missing.length) { + return "I can create it now."; + } + + const initialProvisioningPrompt = + missing.includes("template") && + missing.includes("node") && + missing.includes("name") && + missing.includes("port"); + if (initialProvisioningPrompt) { + return "Tell me the template, node, server name, and port. If you want limits, add RAM, CPU, and storage too."; + } + + const missingCore = missing.filter((field) => ["template", "node", "name", "port"].includes(field)); + if (missingCore.length > 1) { + const labels = missingCore.map((field) => { + if (field === "template") return "template"; + if (field === "node") return "node"; + if (field === "name") return "server name"; + return "port"; + }); + return `Tell me the ${formatChoiceList(labels, 4)}.`; + } + + if (missing.includes("template")) { + const choices = formatChoiceList(plan.templateChoices); + return choices ? `Which template should I use: ${choices}?` : "Which template should I use?"; + } + if (missing.includes("node")) { + const choices = formatChoiceList(plan.nodeChoices); + return choices ? `Which node should I use: ${choices}?` : "Which node should I use?"; + } + if (missing.includes("name")) { + return "What should I name the server?"; + } + + if (missing.includes("port")) { + return plan.templateDefaultPort != null + ? `Which port should I use? The default is ${plan.templateDefaultPort}.` + : "Which port should I use?"; + } + + if (plan.wantsResourcePrompt) { + return "If you want limits, tell me the RAM, CPU, or storage."; + } + + return "Which detail should I use to create the server?"; + } + + async function maybeRunProvisioningFallback({ userEmail, userIp, trimmedMessage, persistedMessages, clientActions }) { + if (!isCreateServerConversation(trimmedMessage, persistedMessages)) { + return null; + } + + const plan = await buildProvisioningPlan(persistedMessages); + if (!plan) { + return null; + } + + if (plan.missingFields.length > 0) { + return { + reply: buildProvisioningFollowUp(plan), + model: "adpanel-provisioning-router", + toolName: "", + toolResult: null, + }; + } + + if (plan.wantsResourcePrompt && !plan.createArgs.resources) { + return { + reply: "If you want limits, tell me the RAM, CPU, or storage.", + model: "adpanel-provisioning-router", + toolName: "", + toolResult: null, + }; + } + + const toolResult = await runTool({ + name: "create_server", + args: plan.createArgs, + userEmail, + userIp, + clientActions, + }); + + return { + reply: buildReplyFromToolResult("create_server", toolResult) || String(toolResult?.error || toolResult?.detail || "That server could not be created.").trim(), + model: "adpanel-provisioning-router", + toolName: "create_server", + toolResult, + }; + } + + async function maybeUpdateChatTitle(chatId, userMessage) { + const rows = await deps.db.query("SELECT title FROM dashboard_assistant_chats WHERE id = ? LIMIT 1", [chatId]); + const currentTitle = String(rows[0]?.title || DEFAULT_CHAT_TITLE); + if (currentTitle && currentTitle !== DEFAULT_CHAT_TITLE) { + return; + } + + const nextTitle = String(userMessage || "").trim().slice(0, 80) || DEFAULT_CHAT_TITLE; + await deps.db.query("UPDATE dashboard_assistant_chats SET title = ? WHERE id = ?", [nextTitle, chatId]); + } + + async function saveProviderToken({ provider, token }) { + const resolvedProvider = sanitizeProvider(provider) || "groq"; + const providerLabel = getProviderLabel(resolvedProvider); + const providerSecretConfig = getAssistantProviderSecretConfig(resolvedProvider); + if (!providerSecretConfig) { + throw new Error(`Unsupported provider: ${resolvedProvider}`); + } + + const cachedSecrets = ensureProviderSecretCache(); + const existingKey = getProviderKey(resolvedProvider); + const sanitized = sanitizeToken(token); + const existingEncryptedValue = sanitizeToken(cachedSecrets.encrypted[resolvedProvider] || ""); + + if (!sanitized && !existingKey) { + throw new Error(`Please enter a valid ${providerLabel} API key.`); + } + + const updates = { DASHBOARD_ASSISTANT_PROVIDER: resolvedProvider }; + const tokenToPersist = sanitized || (!existingEncryptedValue ? existingKey : ""); + const encryptedToken = tokenToPersist ? encryptAssistantProviderToken(tokenToPersist) : ""; + if (encryptedToken) { + updates[providerSecretConfig.encrypted] = encryptedToken; + } + + const saved = deps.writeEnvFileBatch(updates); + if (!saved) { + throw new Error(`Failed to save the ${providerLabel} API key.`); + } + + process.env.DASHBOARD_ASSISTANT_PROVIDER = resolvedProvider; + if (encryptedToken) { + process.env[providerSecretConfig.encrypted] = encryptedToken; + } + + const effectiveKey = sanitized || existingKey; + cachedSecrets.providerPreference = resolvedProvider; + cachedSecrets.keys[resolvedProvider] = effectiveKey; + if (encryptedToken) { + cachedSecrets.encrypted[resolvedProvider] = encryptedToken; + } + cachedSecrets.loaded = true; + + return { + provider: resolvedProvider, + label: providerLabel, + configured: !!effectiveKey, + obscuredValue: buildStoredKeyFieldValue(effectiveKey), + }; + } + + async function transcribeWithGroq(apiKey, { buffer, mimeType, filename, language, prompt }) { + const formData = new FormData(); + formData.append("file", buffer, { + filename: inferTranscriptionFilename(filename, mimeType), + contentType: mimeType || "audio/webm", + }); + formData.append("model", DEFAULT_GROQ_TRANSCRIPTION_MODEL); + formData.append("response_format", "json"); + formData.append("temperature", "0"); + + const safeLanguage = sanitizeTranscriptionLanguage(language); + if (safeLanguage) { + formData.append("language", safeLanguage); + } + const safePrompt = sanitizeTranscriptionPrompt(prompt); + if (safePrompt) { + formData.append("prompt", safePrompt); + } + + const response = await groqMultipartRequest("/openai/v1/audio/transcriptions", apiKey, formData, 90_000); + if (response.status !== 200) { + const detail = response.data?.error?.message || response.data?.error || response.data?.raw || `status ${response.status}`; + throw new Error(detail); + } + + const transcript = String(response.data?.text || "").trim(); + if (!transcript) { + throw new Error("The recording could not be transcribed."); + } + + return { + transcript, + model: DEFAULT_GROQ_TRANSCRIPTION_MODEL, + }; + } + + async function transcribeWithGoogle(apiKey, { buffer, mimeType, prompt }) { + const safePrompt = sanitizeTranscriptionPrompt(prompt) || "Transcribe this audio literally and accurately. Keep technical product words intact and prefer numeric digits."; + const requestBody = { + model: DEFAULT_GOOGLE_TRANSCRIPTION_MODEL, + input: [ + { type: "text", text: safePrompt }, + { + type: "audio", + data: buffer.toString("base64"), + mime_type: mimeType || "audio/webm", + }, + ], + }; + + const response = await jsonApiRequest(GOOGLE_INTERACTIONS_URL, { + method: "POST", + headers: { + "Content-Type": "application/json", + "x-goog-api-key": apiKey, + }, + body: requestBody, + agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.google, + timeoutMs: 90_000, + timeoutMessage: "Google AI Studio request timeout", + }); + + if (response.status !== 200) { + const detail = response.data?.error?.message || response.data?.error || response.data?.raw || `status ${response.status}`; + throw new Error(detail); + } + + const outputs = Array.isArray(response.data?.outputs) ? response.data.outputs : []; + const transcript = String(outputs[outputs.length - 1]?.text || response.data?.output?.text || "").trim(); + if (!transcript) { + throw new Error("The recording could not be transcribed."); + } + + return { + transcript, + model: DEFAULT_GOOGLE_TRANSCRIPTION_MODEL, + }; + } + + async function transcribeAudio({ buffer, mimeType, filename, language, prompt }) { + const provider = getResolvedProvider(); + const apiKey = getProviderKey(provider); + if (!apiKey) { + throw new Error(`${getProviderLabel(provider)} is not configured.`); + } + + if (!Buffer.isBuffer(buffer) || buffer.length === 0) { + throw new Error("No audio data was received."); + } + + if (buffer.length > AUDIO_UPLOAD_LIMIT_BYTES) { + throw new Error("The audio recording is too large."); + } + + if (provider === "google") { + return transcribeWithGoogle(apiKey, { buffer, mimeType, filename, language, prompt }); + } + return transcribeWithGroq(apiKey, { buffer, mimeType, filename, language, prompt }); + } + + async function requestChatCompletion(provider, apiKey, payload) { + if (provider === "google") { + return jsonApiRequest(GOOGLE_OPENAI_CHAT_URL, { + method: "POST", + headers: { + "Authorization": `Bearer ${apiKey}`, + "Content-Type": "application/json", + }, + body: Object.assign({ reasoning_effort: "low" }, payload), + agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.google, + timeoutMs: 90_000, + timeoutMessage: "Google AI Studio request timeout", + }); + } + + return jsonApiRequest("https://api.groq.com/openai/v1/chat/completions", { + method: "POST", + headers: { + "Authorization": `Bearer ${apiKey}`, + "Content-Type": "application/json", + }, + body: payload, + agent: ASSISTANT_PROVIDER_HTTPS_AGENTS.groq, + timeoutMs: 90_000, + timeoutMessage: "Groq request timeout", + }); + } + + function mergeContinuationText(base, continuation) { + const first = String(base || "").trim(); + const second = String(continuation || "").trim(); + if (!first) return second; + if (!second) return first; + if (first === second) return first; + if (second.toLowerCase().startsWith(first.toLowerCase())) return second; + if (first.toLowerCase().endsWith(second.toLowerCase())) return first; + const needsSpace = /[a-z0-9)]$/i.test(first) && /^[a-z0-9(]/i.test(second); + return `${first}${needsSpace ? " " : ""}${second}`.trim(); + } + + async function continueTruncatedReply({ provider, apiKey, modelName, modelMessages, partialContent }) { + const response = await requestChatCompletion(provider, apiKey, { + model: modelName, + temperature: 0.1, + max_tokens: 160, + messages: [ + ...modelMessages, + { role: "assistant", content: partialContent }, + { + role: "user", + content: "Continue from exactly where you stopped. Do not restart or repeat. Finish the answer in one short complete reply.", + }, + ], + }); + + if (response.status !== 200) { + return partialContent; + } + + const continuation = normalizeMessageContent(response.data?.choices?.[0]?.message?.content); + return mergeContinuationText(partialContent, continuation); + } + + async function summarizeDirectAssistantToolResult({ provider, apiKey, userMessage, toolName, toolResult }) { + const modelName = getChatModelForProvider(provider); + const compactResult = toolName === "read_file" + ? { + server: toolResult?.server || null, + path: toolResult?.path || null, + truncated: !!toolResult?.truncated, + originalLength: toolResult?.originalLength ?? null, + content: String(toolResult?.content || "").slice(0, 5000), + } + : { + server: toolResult?.server || null, + path: toolResult?.path || null, + entries: Array.isArray(toolResult?.entries) ? toolResult.entries.slice(0, 80) : [], + }; + + const response = await requestChatCompletion(provider, apiKey, { + model: modelName, + temperature: 0.1, + max_tokens: 260, + messages: [ + { + role: "system", + content: [ + "You are ADPanel Assistant.", + "Always reply in English.", + "Keep replies short and useful for speech.", + "Use only the tool result you were given.", + "If the user asked what to change, point to the most relevant setting or issue briefly.", + "If the user asked to see a file, summarize the important parts instead of dumping the whole file.", + "If the tool listed a directory, mention the most relevant entries only.", + ].join(" "), + }, + { + role: "user", + content: `User request: ${userMessage}\n\nTool used: ${toolName}\nTool result JSON:\n${JSON.stringify(compactResult)}`, + }, + ], + }); + + if (response.status !== 200) { + return buildReplyFromToolResult(toolName, toolResult) || "I checked it."; + } + + const summary = normalizeMessageContent(response.data?.choices?.[0]?.message?.content); + return summary || buildReplyFromToolResult(toolName, toolResult) || "I checked it."; + } + + async function completeLightweightAssistantChat({ + provider, + apiKey, + userEmail, + chat, + trimmedMessage, + persistedMessages, + }) { + const modelName = getChatModelForProvider(provider); + const { olderContextMessage, recentMessages } = buildAssistantModelConversationWindow(persistedMessages, { + recentCount: 10, + olderTranscriptCount: 6, + olderTranscriptTotalLimit: 900, + }); + + const startedAt = Date.now(); + const response = await requestChatCompletion(provider, apiKey, { + model: modelName, + temperature: 0.2, + max_tokens: 140, + messages: [ + { + role: "system", + content: buildSystemPrompt({ appName: "ADPanel", userEmail, powerOnly: true }), + }, + ...(olderContextMessage ? [{ role: "system", content: olderContextMessage }] : []), + ...recentMessages, + ], + }); + const thinkingTimeMs = Date.now() - startedAt; + + if (response.status !== 200) { + const detail = response.data?.error?.message || response.data?.error || response.data?.raw || `status ${response.status}`; + throw new Error(detail); + } + + const reply = normalizeMessageContent(response.data?.choices?.[0]?.message?.content) || "How can I help?"; + + await addMessage(chat.id, { + role: "assistant", + content: reply, + model: modelName, + thinkingTimeMs, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply, + model: modelName, + thinkingTimeMs, + clientActions: [], + }; + } + + async function runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName, + toolArgs, + model = "adpanel-restricted-router", + suppressQueuedReply = false, + }) { + const clientActions = []; + const startedAt = Date.now(); + const toolResult = await runTool({ + name: toolName, + args: toolArgs, + userEmail, + userIp, + clientActions, + }); + const thinkingTimeMs = Date.now() - startedAt; + const browserActionQueued = !!toolResult?.browserActionQueued; + const reply = suppressQueuedReply && browserActionQueued + ? "" + : ( + buildReplyFromToolResult(toolName, toolResult) + || String(toolResult?.error || toolResult?.detail || "That request failed.").trim() + ); + + if (reply) { + await addMessage(chat.id, { + role: "assistant", + content: reply, + model, + thinkingTimeMs, + }); + } + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply, + model, + thinkingTimeMs, + clientActions, + }; + } + + async function executeAssistantConversation({ userEmail, chat, trimmedMessage, userIp, persistedMessages }) { + const provider = getResolvedProvider(); + const apiKey = getProviderKey(provider); + if (!apiKey) { + throw new Error(`${getProviderLabel(provider)} is not configured.`); + } + + const directAccountFlow = detectDirectAccountFlowIntent(trimmedMessage); + const directBulkPowerFlow = detectDirectBulkPowerIntent(trimmedMessage); + const directSinglePowerFlow = detectDirectSinglePowerIntent(trimmedMessage); + const directLoadLookup = detectDirectLoadLookupIntent(trimmedMessage); + const directOpenSettings = detectDirectOpenSettingsIntent(trimmedMessage, persistedMessages); + const restrictedFollowUp = looksLikeRestrictedAssistantFollowUp(trimmedMessage, persistedMessages); + const likelyNeedsServerContext = messageLikelyNeedsAccessibleServerContext(trimmedMessage, persistedMessages); + const accessibleServers = likelyNeedsServerContext ? await loadAccessibleServersForAssistant(userEmail) : []; + const inferredServerHint = likelyNeedsServerContext ? inferAssistantServerMention(trimmedMessage, accessibleServers) : null; + const inferredServerName = String(inferredServerHint?.name || "").trim(); + const inferredServerContextMessage = inferredServerName + ? `Latest user message most likely refers to accessible server "${inferredServerHint.displayName || inferredServerName}" (internal name: ${inferredServerName}). Use that server unless the user clearly names a different one.` + : ""; + + const directCreateFlow = !POWER_ONLY_ASSISTANT ? detectDirectCreateServerFlowIntent(trimmedMessage) : null; + if (directCreateFlow && !messageMentionsPluginInstall(trimmedMessage)) { + const clientActions = [{ type: "open_create_server_modal" }]; + await addMessage(chat.id, { + role: "assistant", + content: directCreateFlow.reply, + model: "adpanel-create-server-router", + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply: directCreateFlow.reply, + model: "adpanel-create-server-router", + thinkingTimeMs: 0, + clientActions, + }; + } + + const directConsoleCheck = detectDirectConsoleCheckIntent(trimmedMessage, inferredServerName); + const directServerLimits = detectDirectServerLimitsIntent(trimmedMessage, inferredServerName); + const directOpenServerPage = detectDirectOpenServerPageIntent(trimmedMessage, inferredServerName, persistedMessages); + const explicitNavigationRequest = + messageLooksLikeAssistantOpenRequest(trimmedMessage) || + isShortAssistantNavigationShortcut(trimmedMessage); + const unresolvedNavigationReply = !directOpenServerPage && !directOpenSettings && explicitNavigationRequest + ? ( + messageExplicitlyNamesAssistantServerSection(trimmedMessage) || /\b(?:server|servers?|page)\b/i.test(trimmedMessage) + ? "I can't help with that server link right now." + : (messageExplicitlyNamesAssistantSettingsDestination(trimmedMessage) + ? "I can't help with that settings link right now." + : "") + ) + : ""; + const restrictedCapabilityRequested = + !!directAccountFlow + || !!directLoadLookup + || !!directConsoleCheck + || !!directServerLimits + || !!directOpenServerPage + || !!directOpenSettings + || !!unresolvedNavigationReply + || !!restrictedFollowUp + || !!detectAssistantPowerAction(trimmedMessage) + || messageLooksLikeConsoleCheckRequest(trimmedMessage) + || messageLooksLikeServerLimitsCheckRequest(trimmedMessage); + + const restrictedIntentSystemHint = buildRestrictedIntentSystemHint({ + directAccountFlow, + directBulkPowerFlow, + directSinglePowerFlow, + directLoadLookup, + directConsoleCheck, + directServerLimits, + directOpenServerPage, + directOpenSettings, + }); + + if (POWER_ONLY_ASSISTANT) { + if (directBulkPowerFlow) { + return runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName: "power_accessible_servers", + toolArgs: { action: directBulkPowerFlow.action }, + model: directBulkPowerFlow.model || "adpanel-power-router", + }); + } + + if (directSinglePowerFlow) { + return runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName: "power_server", + toolArgs: directSinglePowerFlow.args, + model: directSinglePowerFlow.model || "adpanel-power-router", + }); + } + + if (directLoadLookup) { + return runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName: directLoadLookup.toolName, + toolArgs: directLoadLookup.args, + model: directLoadLookup.model || "adpanel-load-router", + }); + } + + if (directOpenServerPage) { + return runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName: "open_server_page", + toolArgs: directOpenServerPage.args, + model: directOpenServerPage.model || "adpanel-navigation-router", + }); + } + + if (directOpenSettings) { + return runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName: "open_settings_destination", + toolArgs: directOpenSettings.args, + model: directOpenSettings.model || "adpanel-settings-router", + }); + } + + if (directAccountFlow) { + return runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName: "open_account_flow", + toolArgs: { flow: directAccountFlow.flow }, + model: directAccountFlow.model || "adpanel-account-router", + }); + } + + if (unresolvedNavigationReply) { + await addMessage(chat.id, { + role: "assistant", + content: unresolvedNavigationReply, + model: "adpanel-navigation-guard", + thinkingTimeMs: 0, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply: unresolvedNavigationReply, + model: "adpanel-navigation-guard", + thinkingTimeMs: 0, + clientActions: [], + }; + } + + if (!restrictedCapabilityRequested && !directBulkPowerFlow && !directSinglePowerFlow) { + const instantSmallTalkReply = buildInstantSmallTalkReply(trimmedMessage); + if (instantSmallTalkReply) { + await addMessage(chat.id, { + role: "assistant", + content: instantSmallTalkReply, + model: "adpanel-smalltalk-router", + thinkingTimeMs: 0, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply: instantSmallTalkReply, + model: "adpanel-smalltalk-router", + thinkingTimeMs: 0, + clientActions: [], + }; + } + + return completeLightweightAssistantChat({ + provider, + apiKey, + userEmail, + chat, + trimmedMessage, + persistedMessages, + }); + } + + if (directConsoleCheck) { + return runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName: directConsoleCheck.toolName, + toolArgs: directConsoleCheck.args, + model: directConsoleCheck.model || "adpanel-console-router", + suppressQueuedReply: true, + }); + } + + if (directServerLimits) { + return runRestrictedDirectToolFlow({ + userEmail, + chat, + userIp, + toolName: directServerLimits.toolName, + toolArgs: directServerLimits.args, + model: directServerLimits.model || "adpanel-limits-router", + suppressQueuedReply: true, + }); + } + + const modelName = getChatModelForProvider(provider); + const conversationContextMessage = ""; + const startedAt = Date.now(); + const response = await buildRestrictedSingleShotPlan({ + provider, + apiKey, + modelName, + systemPrompt: buildSystemPrompt({ appName: "ADPanel", userEmail, powerOnly: true }), + latestUserMessage: trimmedMessage, + inferredServerContextMessage, + restrictedIntentSystemHint, + conversationContextMessage, + persistedMessages, + requestChatCompletion, + }); + const thinkingTimeMs = Date.now() - startedAt; + + if (response.status !== 200) { + const detail = response.data?.error?.message || response.data?.error || response.data?.raw || `status ${response.status}`; + throw new Error(detail); + } + + const rawContent = normalizeMessageContent(response.data?.choices?.[0]?.message?.content); + const parsedPlan = parseRestrictedAssistantPlan(rawContent); + const fallbackPlan = buildRestrictedFallbackPlan({ + trimmedMessage, + directAccountFlow, + directBulkPowerFlow, + directSinglePowerFlow, + directLoadLookup, + directConsoleCheck, + directServerLimits, + directOpenServerPage, + directOpenSettings, + }); + const plannedToolName = normalizeRestrictedToolName(parsedPlan?.toolName); + const fallbackToolName = normalizeRestrictedToolName(fallbackPlan.toolName); + const hasExplicitLatestIntent = !!fallbackToolName; + const selectedToolName = hasExplicitLatestIntent + ? fallbackToolName + : (plannedToolName || fallbackToolName); + const fallbackToolArgs = selectedToolName === fallbackToolName && selectedToolName + ? sanitizeRestrictedToolArgs(selectedToolName, fallbackPlan.toolArgs) + : {}; + const selectedToolArgs = selectedToolName && plannedToolName === selectedToolName + ? sanitizeRestrictedToolArgs(selectedToolName, parsedPlan?.toolArgs) + : {}; + const mergedToolArgs = hasExplicitLatestIntent + ? mergeRestrictedToolArgs(selectedToolArgs, fallbackToolArgs) + : mergeRestrictedToolArgs(fallbackToolArgs, selectedToolArgs); + const forcedLatestIntentOverride = !!(hasExplicitLatestIntent && plannedToolName && plannedToolName !== fallbackToolName); + const clientActions = []; + let finalContent = String(parsedPlan?.reply || "").trim(); + + if (selectedToolName) { + const baseToolArgs = Object.keys(mergedToolArgs).length ? mergedToolArgs : fallbackPlan.toolArgs; + const toolArgs = applyServerHintToToolArgs(selectedToolName, baseToolArgs, inferredServerName); + const toolResult = await runTool({ + name: selectedToolName, + args: toolArgs, + userEmail, + userIp, + clientActions, + }); + const toolReply = buildReplyFromToolResult(selectedToolName, toolResult) + || String(toolResult?.error || toolResult?.detail || "").trim(); + + if (forcedLatestIntentOverride && toolReply) { + finalContent = toolReply; + } else if (!finalContent || toolResult?.ok === false || (toolResult?.browserActionQueued && replyClaimsActionSucceeded(finalContent))) { + finalContent = toolReply || finalContent; + } + } else if (!finalContent) { + finalContent = rawContent; + } + + if (!finalContent) { + finalContent = buildPowerOnlyCapabilityReply(); + } + + await addMessage(chat.id, { + role: "assistant", + content: finalContent, + model: modelName, + thinkingTimeMs, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply: finalContent, + model: modelName, + thinkingTimeMs, + clientActions, + }; + } + + const directDiagnosisFlow = !POWER_ONLY_ASSISTANT ? detectDirectDiagnosisIntent(trimmedMessage, inferredServerName) : null; + if (directDiagnosisFlow) { + const clientActions = []; + const toolResult = await runTool({ + name: directDiagnosisFlow.toolName, + args: directDiagnosisFlow.args, + userEmail, + userIp, + clientActions, + }); + const reply = buildReplyFromToolResult(directDiagnosisFlow.toolName, toolResult) + || String(toolResult?.error || toolResult?.detail || "That diagnosis request failed.").trim(); + + await addMessage(chat.id, { + role: "assistant", + content: reply, + model: directDiagnosisFlow.model, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply, + model: directDiagnosisFlow.model, + thinkingTimeMs: 0, + clientActions, + }; + } + + const directMinecraftPropertyFlow = !POWER_ONLY_ASSISTANT ? detectDirectMinecraftPropertyIntent(trimmedMessage, inferredServerName) : null; + if (directMinecraftPropertyFlow) { + const clientActions = []; + const toolResult = await runTool({ + name: directMinecraftPropertyFlow.toolName, + args: directMinecraftPropertyFlow.args, + userEmail, + userIp, + clientActions, + }); + const reply = buildReplyFromToolResult(directMinecraftPropertyFlow.toolName, toolResult) + || String(toolResult?.error || toolResult?.detail || "That Minecraft update failed.").trim(); + + await addMessage(chat.id, { + role: "assistant", + content: reply, + model: directMinecraftPropertyFlow.model, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply, + model: directMinecraftPropertyFlow.model, + thinkingTimeMs: 0, + clientActions, + }; + } + + const directFileInspectFlow = !POWER_ONLY_ASSISTANT ? detectDirectFileInspectIntent(trimmedMessage, inferredServerName) : null; + if (directFileInspectFlow) { + const clientActions = []; + const toolResult = await runTool({ + name: directFileInspectFlow.toolName, + args: directFileInspectFlow.args, + userEmail, + userIp, + clientActions, + }); + + const reply = toolResult?.ok + ? await summarizeDirectAssistantToolResult({ + provider, + apiKey, + userMessage: trimmedMessage, + toolName: directFileInspectFlow.toolName, + toolResult, + }) + : (buildReplyFromToolResult(directFileInspectFlow.toolName, toolResult) + || String(toolResult?.error || toolResult?.detail || "That file request failed.").trim()); + + await addMessage(chat.id, { + role: "assistant", + content: reply, + model: directFileInspectFlow.model, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply, + model: directFileInspectFlow.model, + thinkingTimeMs: 0, + clientActions, + }; + } + + const createConversationLikely = isCreateServerConversation(trimmedMessage, persistedMessages); + if (createConversationLikely && !messageMentionsPluginInstall(trimmedMessage)) { + const clientActions = []; + const provisioningResult = await maybeRunProvisioningFallback({ + userEmail, + userIp, + trimmedMessage, + persistedMessages, + clientActions, + }); + + if (provisioningResult) { + await addMessage(chat.id, { + role: "assistant", + content: provisioningResult.reply, + model: provisioningResult.model || "adpanel-provisioning-router", + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply: provisioningResult.reply, + model: provisioningResult.model || "adpanel-provisioning-router", + thinkingTimeMs: 0, + clientActions, + }; + } + } + + const provisioningContext = await inferProvisioningContext(persistedMessages); + const conversationContextMessage = buildConversationContextMessage(provisioningContext); + const { olderContextMessage, recentMessages } = buildAssistantModelConversationWindow(persistedMessages, { + recentCount: 18, + olderTranscriptCount: 10, + olderTranscriptTotalLimit: 1400, + }); + const modelMessages = [ + { + role: "system", + content: buildSystemPrompt({ appName: "ADPanel", userEmail, powerOnly: POWER_ONLY_ASSISTANT }), + }, + ...(inferredServerContextMessage ? [{ role: "system", content: inferredServerContextMessage }] : []), + ...(restrictedIntentSystemHint ? [{ role: "system", content: restrictedIntentSystemHint }] : []), + ...(conversationContextMessage ? [{ role: "system", content: conversationContextMessage }] : []), + ...(olderContextMessage ? [{ role: "system", content: olderContextMessage }] : []), + ...recentMessages, + ]; + + const clientActions = []; + const modelName = getChatModelForProvider(provider); + let responseModel = modelName; + const allowToolUse = + shouldAllowToolUseForMessage(trimmedMessage, persistedMessages) + || !!directAccountFlow + || !!directBulkPowerFlow + || !!directSinglePowerFlow + || !!directLoadLookup + || !!directConsoleCheck + || !!restrictedCapabilityRequested; + const needsRealActionExecution = messageNeedsRealActionExecution(trimmedMessage); + let thinkingTimeMs = 0; + let finalContent = ""; + let lastToolName = ""; + let lastToolResult = null; + let forcedToolReply = ""; + + for (let attempt = 0; attempt < ASSISTANT_MAX_LOOPS; attempt += 1) { + const startedAt = Date.now(); + const completionPayload = { + model: modelName, + temperature: 0.2, + max_tokens: needsRealActionExecution ? 420 : 280, + messages: modelMessages, + }; + + if (allowToolUse) { + completionPayload.tool_choice = "auto"; + completionPayload.tools = POWER_ONLY_ASSISTANT ? POWER_TOOL_DEFINITIONS : TOOL_DEFINITIONS; + } + + const response = await requestChatCompletion(provider, apiKey, completionPayload); + thinkingTimeMs += Date.now() - startedAt; + + if (response.status !== 200) { + const detail = response.data?.error?.message || response.data?.error || response.data?.raw || `status ${response.status}`; + throw new Error(detail); + } + + const choice = response.data?.choices?.[0] || {}; + const message = choice.message; + const finishReason = String(choice.finish_reason || "").trim().toLowerCase(); + if (!message) { + throw new Error(`${getProviderLabel(provider)} returned an empty response.`); + } + + if (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) { + modelMessages.push({ + role: "assistant", + content: normalizeMessageContent(message.content), + tool_calls: message.tool_calls, + }); + + let powerToolUsedThisTurn = false; + let lastWriteToolResultThisTurn = null; + + for (const call of message.tool_calls) { + if ( + isGenericServerPropertiesWriteToolCall(call?.function?.name, call?.function?.arguments) + && messageLooksLikeStructuredMinecraftPropertyMutation(trimmedMessage) + ) { + const toolResult = { + ok: false, + error: "Use the Minecraft property updater for server.properties key changes.", + }; + lastToolName = String(call?.function?.name || "").trim(); + lastToolResult = toolResult; + modelMessages.push({ + role: "tool", + tool_call_id: call.id, + content: JSON.stringify(toolResult), + }); + continue; + } + + const toolResult = await runTool({ + name: call?.function?.name, + args: applyServerHintToToolArgs(call?.function?.name, call?.function?.arguments, inferredServerName), + userEmail, + userIp, + clientActions, + }); + lastToolName = String(call?.function?.name || "").trim(); + lastToolResult = toolResult; + if (lastToolName === "power_server" || lastToolName === "power_accessible_servers") { + powerToolUsedThisTurn = true; + } + if (lastToolName === "write_file" && toolResult?.ok !== false) { + lastWriteToolResultThisTurn = toolResult; + } + + modelMessages.push({ + role: "tool", + tool_call_id: call.id, + content: JSON.stringify(toolResult), + }); + } + + if (!powerToolUsedThisTurn && lastWriteToolResultThisTurn?.server) { + const chainedPowerAction = extractChainedPowerAction(trimmedMessage); + if (chainedPowerAction) { + const powerToolResult = await runTool({ + name: "power_server", + args: { + server: lastWriteToolResultThisTurn.server, + action: chainedPowerAction, + }, + userEmail, + userIp, + clientActions, + }); + lastToolName = "power_server"; + lastToolResult = powerToolResult; + forcedToolReply = buildWriteThenPowerReply(lastWriteToolResultThisTurn, powerToolResult); + break; + } + } + + if (forcedToolReply) { + finalContent = forcedToolReply; + break; + } + continue; + } + + finalContent = normalizeMessageContent(message.content); + if (forcedToolReply) { + finalContent = forcedToolReply; + } + if (shouldForceQueuedReply(lastToolName, lastToolResult)) { + finalContent = buildReplyFromToolResult(lastToolName, lastToolResult) || finalContent; + } + if (lastToolResult?.browserActionQueued && replyClaimsActionSucceeded(finalContent)) { + finalContent = buildReplyFromToolResult(lastToolName, lastToolResult) || finalContent; + } + if (isGenericAssistantReply(finalContent) && lastToolResult) { + finalContent = buildReplyFromToolResult(lastToolName, lastToolResult) || finalContent; + } + if (isGenericAssistantReply(finalContent) && allowToolUse && !lastToolResult) { + finalContent = "I need one more detail before I can do that."; + } + if (needsRealActionExecution && !lastToolResult && replyClaimsActionSucceeded(finalContent)) { + finalContent = "I need one more detail before I can do that."; + } + if (!lastToolResult && messageLooksLikeBusiestLookup(trimmedMessage) && !/[?]/.test(finalContent)) { + finalContent = /\b(node|nodes|nod|noduri)\b/i.test(trimmedMessage) + ? "I can check that live. Say which node metric you want, or just say busiest node." + : "I can check that live. Say busiest server, or name a metric like CPU or RAM."; + } + if (!lastToolResult && messageLooksLikeDiagnosisRequest(trimmedMessage) && !/[?]/.test(finalContent)) { + finalContent = "Tell me which server to diagnose."; + } + if (!lastToolResult && messageLooksLikeConsoleCheckRequest(trimmedMessage) && !/[?]/.test(finalContent)) { + finalContent = extractAssistantServerCandidate(trimmedMessage) + ? "I can check that console now." + : "Tell me which server console to check."; + } + if (!lastToolResult && detectAssistantPowerAction(trimmedMessage) && !detectDirectBulkPowerIntent(trimmedMessage) && !/[?]/.test(finalContent)) { + finalContent = extractAssistantServerCandidate(trimmedMessage) + ? "I can run that power action now." + : "Tell me which server to start, stop, restart, or kill."; + } + if (!lastToolResult && messageLooksLikeMinecraftBatchPropertyUpdate(trimmedMessage) && !/[?]/.test(finalContent)) { + finalContent = "Tell me the exact server.properties key and value to apply."; + } + if (!lastToolResult && messageLooksLikeStructuredMinecraftPropertyMutation(trimmedMessage) && !/[?]/.test(finalContent)) { + finalContent = "Tell me which server to change, or say all accessible Minecraft servers."; + } + if (!finalContent) { + finalContent = buildReplyFromToolResult(lastToolName, lastToolResult) || "Done."; + } + if (finishReason === "length" && finalContent) { + finalContent = await continueTruncatedReply({ + provider, + apiKey, + modelName, + modelMessages, + partialContent: finalContent, + }); + } + break; + } + + const exploratoryProvisioningTool = ["list_nodes", "list_templates"].includes(lastToolName); + if (createConversationLikely && isVagueProvisioningReply(finalContent) && (!lastToolResult || exploratoryProvisioningTool)) { + const fallbackResult = await maybeRunProvisioningFallback({ + userEmail, + userIp, + trimmedMessage, + persistedMessages, + clientActions, + }); + if (fallbackResult) { + finalContent = fallbackResult.reply; + lastToolName = fallbackResult.toolName; + lastToolResult = fallbackResult.toolResult; + responseModel = fallbackResult.model || responseModel; + } + } + + if (!finalContent) { + throw new Error("The assistant reached its tool limit before finishing."); + } + + await addMessage(chat.id, { + role: "assistant", + content: finalContent, + model: responseModel, + thinkingTimeMs, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + + return { + chat: freshChat, + messages: freshMessages, + reply: finalContent, + model: responseModel, + thinkingTimeMs, + clientActions, + }; + } + + async function completeChat({ userEmail, chatId, userMessage, userIp }) { + const trimmedMessage = String(userMessage || "").trim(); + if (!trimmedMessage) { + throw new Error("A message is required."); + } + + const chat = await getActiveChat(userEmail, chatId); + if (!chat) { + throw new Error("The assistant chat could not be found."); + } + + await addMessage(chat.id, { role: "user", content: trimmedMessage }); + await maybeUpdateChatTitle(chat.id, trimmedMessage); + const persistedMessages = await getChatMessages(chat.id, CHAT_HISTORY_LIMIT); + + return executeAssistantConversation({ + userEmail, + chat, + trimmedMessage, + userIp, + persistedMessages, + }); + } + + async function confirmDeleteServer({ userEmail, chatId, serverName, userIp }) { + const normalizedName = String(serverName || "").trim(); + if (!normalizedName) { + throw new Error("A server name is required."); + } + + const currentUser = await deps.findUserByEmail(userEmail); + if (!(currentUser && currentUser.admin)) { + throw new Error("Admin required."); + } + + if (typeof deps.deleteServerByName !== "function") { + throw new Error("Server deletion is not available here."); + } + + const result = await deps.deleteServerByName(normalizedName); + if (!result?.ok) { + throw new Error(result?.error || "Server deletion failed."); + } + + const chat = await getActiveChat(userEmail, chatId); + if (!chat) { + throw new Error("The assistant chat could not be found."); + } + + const reply = `Deleted ${normalizedName}.`; + await addMessage(chat.id, { + role: "assistant", + content: reply, + model: "adpanel-delete-confirm", + }); + + if (typeof deps.recordActivity === "function") { + try { + deps.recordActivity(normalizedName, "server_delete", null, userEmail, userIp); + } catch { + } + } + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply, + model: "adpanel-delete-confirm", + thinkingTimeMs: 0, + clientActions: [], + }; + } + + async function completeClientFollowUp({ userEmail, chatId, summary, sourceType, context, skipAi = false }) { + const verifiedSummary = String(summary || "").trim(); + if (!verifiedSummary) { + throw new Error("A follow-up summary is required."); + } + + const chat = await getActiveChat(userEmail, chatId); + if (!chat) { + throw new Error("The assistant chat could not be found."); + } + + const provider = getResolvedProvider(); + const apiKey = getProviderKey(provider); + const recentMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + const lastUserText = getRecentMessagesByRole(recentMessages, "user", 1)[0] || ""; + const recentVisibleTranscript = buildCarryForwardVisibleTranscript(recentMessages, { + count: 8, + perMessageLimit: 160, + totalLimit: 1200, + }); + const modelName = getChatModelForProvider(provider); + const compactContext = context && typeof context === "object" + ? JSON.stringify(context).slice(0, 4000) + : ""; + + let reply = verifiedSummary; + let thinkingTimeMs = 0; + let responseModel = skipAi ? "adpanel-client-local" : "adpanel-client-follow-up"; + + if (!skipAi && apiKey) { + const startedAt = Date.now(); + const response = await requestChatCompletion(provider, apiKey, { + model: modelName, + temperature: 0.1, + max_tokens: 220, + messages: [ + { + role: "system", + content: [ + "You are ADPanel Assistant inside the ADPanel dashboard.", + "Always reply in English.", + "Keep replies very short, natural, and good for speech.", + "The browser already executed the action and produced verified result data.", + "Answer using only that verified result and the visible conversation context.", + "Do not mention the browser, tools, routing, JSON, or internal mechanics.", + "If the verified result already answers the user, say it directly.", + "If the action type is console_check, interpret the logs and status directly for the user.", + "If the action type is server_limits_check, explain the live RAM, CPU, and storage headroom directly for the user.", + "When RAM, CPU, or storage looks dangerously high, say that clearly and suggest checking the console next.", + "Prefer the raw log lines and verified status over any prewritten summary when they are available.", + "If startup timing is visible in the verified result, state the seconds clearly.", + "If the user asks whether the server started correctly or is healthy, answer that directly from the logs and status.", + "Do not just repeat the verified summary if the log lines let you answer more precisely.", + ].join(" "), + }, + { + role: "user", + content: [ + recentVisibleTranscript ? `Recent visible chat:\n${recentVisibleTranscript}` : "", + lastUserText ? `Last user request: ${lastUserText}` : "", + sourceType ? `Action type: ${String(sourceType).trim()}` : "", + `Verified result summary: ${verifiedSummary}`, + compactContext ? `Extra verified context JSON: ${compactContext}` : "", + ].filter(Boolean).join("\n\n"), + }, + ], + }); + thinkingTimeMs = Date.now() - startedAt; + responseModel = modelName; + + if (response.status === 200) { + const aiReply = normalizeMessageContent(response.data?.choices?.[0]?.message?.content); + if (aiReply) { + reply = aiReply; + } + } + } + + await addMessage(chat.id, { + role: "assistant", + content: reply, + model: responseModel, + thinkingTimeMs, + }); + + const freshChat = await getChatById(userEmail, chat.id); + const freshMessages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + return { + chat: freshChat, + messages: freshMessages, + reply, + model: responseModel, + thinkingTimeMs, + clientActions: [], + }; + } + + async function getBootstrap(req) { + const userEmail = String(req.session?.user || "").trim().toLowerCase(); + const currentUser = await deps.findUserByEmail(userEmail); + const chat = await getActiveChat(userEmail); + const messages = await getChatMessages(chat.id, VISIBLE_CHAT_HISTORY_LIMIT); + const activeProvider = getResolvedProvider(); + const activeKey = getProviderKey(activeProvider); + const canConfigure = !!(currentUser && currentUser.admin); + const assistantConfig = typeof deps.getDashboardAssistantConfig === "function" + ? deps.getDashboardAssistantConfig() + : { allowNormalUsers: false }; + + const actionTokens = {}; + if (canConfigure && typeof deps.issueActionToken === "function") { + actionTokens.saveToken = deps.issueActionToken(req, "POST /api/dashboard-assistant/token", {}, { ttlSeconds: 300 }); + actionTokens.updateAccess = deps.issueActionToken(req, "POST /api/dashboard-assistant/access", {}, { ttlSeconds: 300 }); + } + + const providers = Object.keys(PROVIDER_LABELS).map((providerId) => { + const key = getProviderKey(providerId); + return { + id: providerId, + label: getProviderLabel(providerId), + configured: !!key, + obscuredValue: canConfigure ? buildStoredKeyFieldValue(key) : "", + }; + }); + + return { + configured: !!activeKey, + provider: activeProvider, + providerLabel: getProviderLabel(activeProvider), + providers, + canConfigure, + allowNormalUsers: !!assistantConfig.allowNormalUsers, + chat, + messages, + actionTokens, + user: currentUser ? { + email: currentUser.email, + admin: !!currentUser.admin, + } : null, + }; + } + + return { + ensureTables, + getBootstrap, + createFreshChat, + getPrimaryChat, + saveProviderToken, + transcribeAudio, + completeChat, + completeClientFollowUp, + confirmDeleteServer, + }; +} + +module.exports = { + createDashboardAssistantService, + DEFAULT_CHAT_TITLE, +}; diff --git a/utils/dashboard-assistant-tools.js b/utils/dashboard-assistant-tools.js new file mode 100644 index 0000000..f2bc446 --- /dev/null +++ b/utils/dashboard-assistant-tools.js @@ -0,0 +1,2529 @@ +"use strict"; + +const path = require("path"); +const { + extractTechnicalServerNameFromNodeCreateResult, +} = require("./server-startup-command"); +const { sanitizeDockerTemplatePayload } = require("./server-template-payload"); + +const FILE_PREVIEW_LIMIT = 16000; +const MODRINTH_API_BASE = "https://api.modrinth.com/v2"; +const MODRINTH_PLUGIN_LOADERS = Object.freeze([ + "paper", + "purpur", + "spigot", + "bukkit", + "velocity", + "waterfall", + "bungeecord", + "fabric", + "quilt", + "forge", + "neoforge", +]); + +const TOOL_DEFINITIONS = [ + { + type: "function", + function: { + name: "list_templates", + description: "List the available ADPanel server templates that can be used for new servers.", + parameters: { + type: "object", + properties: {}, + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "list_nodes", + description: "List the available nodes where new servers can be created.", + parameters: { + type: "object", + properties: {}, + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "create_server", + description: "Create a new server from a chosen template on a chosen node. Use this only after you know the template, node, server name, host port, and the desired RAM/CPU/storage limits, unless the user explicitly asked to use defaults.", + parameters: { + type: "object", + properties: { + name: { + type: "string", + description: "The server name/ID to create.", + }, + displayName: { + type: "string", + description: "Optional display name to show in the dashboard.", + }, + templateId: { + type: "string", + description: "The ADPanel template id or name, such as 'minecraft' or 'nodejs'.", + }, + nodeId: { + type: "string", + description: "The target node id, uuid, or name.", + }, + hostPort: { + type: "number", + description: "The public port for the new server. If omitted, the template default port will be used when available.", + }, + mcFork: { + type: "string", + description: "Optional Minecraft fork, for example 'paper'.", + }, + mcVersion: { + type: "string", + description: "Optional Minecraft version.", + }, + importUrl: { + type: "string", + description: "Optional archive URL to import after creation.", + }, + resources: { + type: "object", + properties: { + ramMb: { type: "number" }, + cpuCores: { type: "number" }, + storageMb: { type: "number" }, + storageGb: { type: "number" }, + swapMb: { type: "number" }, + backupsMax: { type: "number" }, + maxSchedules: { type: "number" }, + }, + additionalProperties: false, + }, + }, + required: ["name", "templateId", "nodeId"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "list_servers", + description: "List the servers the current user can access.", + parameters: { + type: "object", + properties: {}, + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "install_plugin", + description: "Install a Minecraft plugin from Modrinth onto a server by downloading the correct file into the plugins folder. Use this for plugin requests such as ViaVersion, LuckPerms, Vault, Geyser, or similar.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The target server name as used inside ADPanel.", + }, + pluginName: { + type: "string", + description: "The plugin name or slug to install from Modrinth.", + }, + platform: { + type: "string", + description: "Optional loader/platform such as paper, purpur, spigot, bukkit, velocity, fabric, forge, or neoforge.", + }, + gameVersion: { + type: "string", + description: "Optional Minecraft version such as 1.21.8.", + }, + }, + required: ["server", "pluginName"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "inspect_server", + description: "Inspect one server, including status, template, and the current user's permissions.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + }, + required: ["server"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "get_busiest_node", + description: "Ask the browser to find the busiest node right now from live node stats. Admin only. Use this when the user asks which node is most loaded, busiest, hottest, or under the most pressure.", + parameters: { + type: "object", + properties: { + metric: { + type: "string", + enum: ["balanced", "cpu", "memory", "disk"], + description: "Optional load metric. Use balanced unless the user explicitly asks for CPU, memory, or disk.", + }, + includeMetrics: { + type: "array", + items: { + type: "string", + enum: ["cpu", "memory", "disk"], + }, + description: "Optional resource details to include in the spoken result when the user asks for CPU, RAM, or disk values.", + }, + }, + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "get_busiest_server", + description: "Ask the browser to find the busiest accessible server right now from live status data. Use this when the user asks which server is most loaded, busiest, or using the most resources.", + parameters: { + type: "object", + properties: { + metric: { + type: "string", + enum: ["balanced", "cpu", "memory", "disk"], + description: "Optional load metric. Use balanced unless the user explicitly asks for CPU, memory, or disk.", + }, + includeMetrics: { + type: "array", + items: { + type: "string", + enum: ["cpu", "memory", "disk"], + }, + description: "Optional resource details to include in the spoken result when the user asks for CPU, RAM, or disk values.", + }, + }, + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "check_server_console", + description: "Ask the browser to inspect the live console output for one accessible server and answer briefly from the console. Use this for console checks, recent errors, startup failures, crashes, or log-based diagnosis without reading files.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name or raw server reference from the user's request.", + }, + question: { + type: "string", + description: "Optional short focus question, such as why it crashed or what the console shows.", + }, + }, + required: ["server"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "check_server_limits", + description: "Ask the browser to inspect one accessible server's live RAM, CPU, and storage usage against its current limits. Use this for questions about quotas, remaining RAM or disk, resource headroom, whether usage is too high, or whether a server is close to its limits.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name or raw server reference from the user's request.", + }, + question: { + type: "string", + description: "Optional short focus question, such as how much RAM is left or whether the limits look healthy.", + }, + includeMetrics: { + type: "array", + items: { + type: "string", + enum: ["cpu", "memory", "disk"], + }, + description: "Optional resource details to emphasize when the user specifically asks about CPU, RAM, or disk.", + }, + }, + required: ["server"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "diagnose_server", + description: "Ask the browser to inspect one accessible server with live status, recent activity, and short log context, then return a short diagnosis. Use this for requests about crashes, startup problems, lag, instability, or why a server is failing.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + }, + required: ["server"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "update_minecraft_server_property", + description: "Ask the browser to update one key inside server.properties on one named Minecraft server or across all accessible Minecraft servers the current user can edit. Use this for safe key/value changes like online-mode=false, motd, max-players, difficulty, pvp, whitelist, or view-distance.", + parameters: { + type: "object", + properties: { + property: { + type: "string", + description: "The exact server.properties key, such as online-mode, motd, max-players, pvp, whitelist, difficulty, spawn-protection, or view-distance.", + }, + value: { + type: "string", + description: "The value to write, as plain text, such as false, true, 20, easy, or a motd string.", + }, + scope: { + type: "string", + enum: ["single_server", "all_accessible_minecraft"], + description: "Use single_server for one named server or all_accessible_minecraft for every accessible Minecraft server.", + }, + server: { + type: "string", + description: "Required when scope is single_server. The ADPanel server name to update.", + }, + onlyIfCurrent: { + type: "string", + description: "Optional current-value guard. Use true or false when the user says to change it only if the current value matches.", + }, + restartAfter: { + type: "boolean", + description: "Set true when the user also asked to restart after the write succeeds.", + }, + }, + required: ["property", "value", "scope"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "request_delete_server", + description: "Ask the browser to show a confirmation modal before deleting a server. Use this instead of deleting immediately.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name to delete.", + }, + }, + required: ["server"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "list_files", + description: "List files inside a server directory. Use this before reading or editing when you are unsure about the path.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + path: { + type: "string", + description: "A relative directory path inside the server, for example '' or 'plugins'.", + }, + }, + required: ["server"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "read_file", + description: "Read a text file from a server. Use this before changing an existing file unless the user already gave you the full replacement content.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + path: { + type: "string", + description: "The relative file path inside the server.", + }, + }, + required: ["server", "path"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "write_file", + description: "Create or replace a text file on a server.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + path: { + type: "string", + description: "The relative file path inside the server.", + }, + content: { + type: "string", + description: "The complete file content that should be written.", + }, + }, + required: ["server", "path", "content"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "create_directory", + description: "Create a new directory on a server.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + path: { + type: "string", + description: "The relative directory path to create.", + }, + }, + required: ["server", "path"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "rename_path", + description: "Rename or move a file or directory on a server.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + source: { + type: "string", + description: "The current relative path.", + }, + destination: { + type: "string", + description: "The new relative path.", + }, + }, + required: ["server", "source", "destination"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "delete_path", + description: "Delete a file or directory on a server.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + path: { + type: "string", + description: "The relative path to delete.", + }, + isDirectory: { + type: "boolean", + description: "Set to true when the target is a directory.", + }, + }, + required: ["server", "path"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "power_server", + description: "Ask the browser to start, stop, restart, or kill one server when the current user has permission. For every accessible server at once, use power_accessible_servers instead.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The server name as used inside ADPanel.", + }, + action: { + type: "string", + enum: ["start", "stop", "restart", "kill"], + description: "The power action to execute.", + }, + }, + required: ["server", "action"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "power_accessible_servers", + description: "Ask the browser to start, stop, restart, or kill every server the current user can access and control. Use this when the user says all servers, every server, or all accessible servers. Do not call power_server repeatedly for that.", + parameters: { + type: "object", + properties: { + action: { + type: "string", + enum: ["start", "stop", "restart", "kill"], + description: "The power action to execute for all eligible accessible servers.", + }, + }, + required: ["action"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "open_server_page", + description: "Open one accessible server in a new browser tab, optionally jumping straight to its console, backups, files, scheduler, activity, store, resource stats, subdomains, reinstall, or info area.", + parameters: { + type: "object", + properties: { + server: { + type: "string", + description: "The target server name or the user's raw server wording.", + }, + section: { + type: "string", + enum: [ + "console", + "info", + "files", + "activity", + "backups", + "scheduler", + "store", + "resource_stats", + "subdomains", + "reinstall", + "ai_help", + ], + description: "Which part of the server page to open. Use console when the user just wants the server page.", + }, + }, + required: ["server"], + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "open_settings_destination", + description: "Open an admin-only ADPanel settings area or settings modal in a new browser tab. Use this for requests like nodes, appearance, branding, maintenance, captcha, databases, webhooks, quick actions, or create user.", + parameters: { + type: "object", + properties: { + panel: { + type: "string", + enum: [ + "preferences", + "customization", + "account", + "security", + "databases", + "nodes", + "templates", + "servers", + "webhooks", + "panelinfo", + ], + description: "The settings category to open.", + }, + action: { + type: "string", + enum: [ + "create_user", + "branding", + "login_watermark", + "login_background", + "alert", + "quick_action_admin", + "quick_action_user", + "database_setup", + "pgadmin_setup", + "mongodb_setup", + "captcha", + "maintenance", + "create_node", + "create_template", + "add_webhook", + ], + description: "Optional modal or special settings action to open after the panel loads.", + }, + }, + additionalProperties: false, + }, + }, + }, + { + type: "function", + function: { + name: "open_account_flow", + description: "Open an existing ADPanel account flow in the browser for sensitive actions like password, email, or 2FA changes.", + parameters: { + type: "object", + properties: { + flow: { + type: "string", + enum: [ + "change_password", + "change_email", + "change_2fa", + "recover_password", + "recover_email", + "recover_2fa", + ], + description: "The account flow that should be opened.", + }, + }, + required: ["flow"], + additionalProperties: false, + }, + }, + }, +]; + +const POWER_TOOL_NAMES = new Set([ + "power_server", + "power_accessible_servers", + "open_server_page", + "open_settings_destination", + "open_account_flow", + "get_busiest_node", + "get_busiest_server", + "check_server_console", + "check_server_limits", +]); +const POWER_TOOL_DEFINITIONS = TOOL_DEFINITIONS.filter((definition) => + POWER_TOOL_NAMES.has(String(definition?.function?.name || "").trim()) +); + +function buildSystemPrompt({ appName = "ADPanel", userEmail, powerOnly = false }) { + if (powerOnly) { + return [ + `You are ${appName} Assistant inside the ${appName} dashboard.`, + "Always reply in English.", + "Keep replies extremely short, natural, and easy to understand when spoken aloud.", + "Sound like a voice assistant, not a chatbot.", + "Default to one short sentence.", + "Use recent chat context for short follow-up questions about the last result.", + "You receive the visible chat history shown in the dashboard. Use it when the user refers to earlier messages.", + "Always prioritize the latest explicit user request over older context.", + "Use older context only to resolve omitted references like it, that server, there, or the last result.", + "If the latest user message explicitly names a server, page section, popup, settings area, or action, do not let older context override it.", + "If the answer is already in the recent conversation, answer it directly instead of listing capabilities.", + "You currently support only these capability groups: power actions for accessible servers, sharing direct links to accessible server pages, sharing direct links to admin-only settings navigation, account security popups, live busiest node/server checks, live server console checks, and live per-server quota and limits checks.", + "Use power_server for one named server and power_accessible_servers for all accessible servers.", + "Use open_server_page when the user wants to open, manage, configure, edit, or access a server page, console, backups, files, scheduler, activity, info, store, reinstall, subdomains, or resource stats through a direct link.", + "Use open_settings_destination for admin-only settings categories and settings modals such as nodes, appearance, branding, maintenance, captcha, databases, quick actions, webhooks, or create user, and let the dashboard share a direct link.", + "Never claim a page or tab opened automatically. The dashboard will give the user a clickable link.", + "Use open_account_flow for password, email, and 2FA change or recovery requests.", + "Use get_busiest_node for admin requests about the busiest node right now, and get_busiest_server for the busiest accessible server.", + "Use check_server_console for console, crash, startup, error, and log questions about one accessible server.", + "Use check_server_limits for questions about one accessible server's RAM, CPU, disk, storage, free space, remaining headroom, quotas, or whether it is close to its limits.", + "If the user asks how many seconds startup took, whether a server started correctly, whether it is running well, or what the logs show, treat that as a console-check request.", + "Users may mention a server by bare name, lowercase, with quotes, with parentheses, or in messy wording. Resolve the intended accessible server and call the power tool.", + "Do not ask the user to prefix the name with the word server when the intended server is already clear.", + "Normalize messy phrasing into one action and one target before calling a tool.", + "Only claim an action succeeded after the matching tool succeeded.", + "Do not read, write, edit, list, or inspect server files.", + "Do not inspect server files, install plugins, create servers, or delete servers in this restricted mode.", + "If the user asks for anything outside those allowed capabilities, say briefly what you can do right now.", + "If the server name is still unclear, ask one short direct question.", + `Current authenticated user: ${String(userEmail || "unknown").trim() || "unknown"}.`, + ].join(" "); + } + + return [ + `You are ${appName} Assistant inside the ${appName} dashboard.`, + "Always reply in English.", + "Keep replies extremely short, natural, and easy to understand when spoken aloud.", + "Sound like a voice assistant, not a chatbot.", + "Default to one short sentence.", + "Use two short sentences only when the second sentence adds essential help.", + "Never give long explanations unless the user explicitly asks for detail.", + "Use previous messages as context, but always answer the user's latest message directly.", + "You receive the visible chat history shown in the dashboard. Use it when the user refers to earlier messages.", + "Do not ignore or override the user's latest request because of older context.", + "When an action succeeds, confirm it in one short sentence.", + "When you need missing information, ask one short direct question.", + "If you list choices, keep it to the best 3 options and keep the wording brief.", + "The wake phrase is optional. Respond normally even when the user does not say 'Hey ADPanel' first.", + "You can read context from previous messages in this chat and you can use tools to perform real ADPanel actions when they are actually needed.", + "Only claim an action succeeded after the matching tool succeeded.", + "If the user wants to change their password, email, or 2FA, never ask them to send secrets in chat. Use the open_account_flow tool instead.", + "If the user needs a recovery flow for password, email, or 2FA, use the matching recovery account flow instead of asking for sensitive codes in chat.", + "If a user wants to modify an existing file and you do not already have the current content, read the file first before writing a replacement.", + "When the user names a file path and a server, prefer reading or listing that path before saying it is unavailable.", + "If a request is missing critical details, ask one short follow-up question instead of guessing.", + "If the user lacks permission for an action, explain that clearly and do not attempt to bypass permissions.", + "General questions, casual chat, short phrases, or assistant-related questions should be answered directly without using server tools.", + "Use get_busiest_node for admin requests about the most loaded node right now.", + "Use get_busiest_server for requests about the most loaded accessible server right now.", + "Use diagnose_server for crash, startup, lag, and server health diagnosis requests.", + "Use update_minecraft_server_property for changing one server.properties value on one Minecraft server or across all accessible Minecraft servers.", + "Users may mention a server by its bare name, in lowercase, in parentheses, or without the word server. Treat that as the server reference when it matches an accessible server.", + "Do not ask the user to prefix a server name with the word server when the intended server is already clear.", + "For server.properties key changes, pass only the raw value like false or 40. Never include instructions such as 'if it is true' inside the value string.", + "If the user says to change a server.properties key only when it currently has a certain value, use onlyIfCurrent instead of writing that condition into the file content.", + "If the user also wants a restart after a server.properties update, set restartAfter true instead of describing restart inside the value.", + "When the user wants the same server.properties change on every accessible Minecraft server, use scope all_accessible_minecraft.", + "Do not assume a random word or short phrase is a server name.", + "If the user only says one or two ambiguous words, ask a brief clarifying question instead of calling tools.", + "If the user wants to create a new server, gather the required creation details: template, node, server name, and host port.", + "RAM, CPU, and storage limits are optional. Use them only when the user provided them or explicitly asks for limits.", + "If the user explicitly says to use defaults, you may use the template default port and leave optional resource limits unset.", + "If the user already provided a node, template, port, RAM, CPU, storage, or server name earlier in this chat, reuse it instead of asking again unless it is ambiguous.", + "For server creation, use list_templates and list_nodes when needed so you can offer concrete choices with node capacity and port information.", + "When the user asks to create a server but has not chosen a node or template yet, ask a short direct question listing the best available options.", + "For provisioning, never reply with generic phrases like 'I need more detail' or 'tell me more'. Name the exact missing field instead.", + "If the user already gave enough information to create the server, call create_server immediately.", + "If the user replies with a short follow-up like 'yes', 'go ahead', a port number, a node name, or a resource value, use the earlier provisioning context instead of restarting the flow.", + "Do not call create_server until you have enough information to create the server correctly.", + "If the user also asked for plugins during server creation, remember that request and install the plugins after the server exists.", + "Use install_plugin for Minecraft plugin requests. Prefer the server's known fork or version when available, otherwise use the latest compatible plugin build.", + "Never delete a server immediately from chat. Use request_delete_server first so the browser can show a confirmation modal, and wait for the user's confirmation there.", + "You can assist any accessible server regardless of docker image or template for file and power actions, as long as the user has permission.", + "If the user wants every accessible server started, stopped, restarted, or killed, use power_accessible_servers instead of calling power_server repeatedly.", + "If a named server request does not resolve immediately, use the available server tools and closest candidates before saying you cannot see that server.", + "For browser-queued read actions like diagnosis or busiest node checks, say checking now, not done.", + "For browser-queued actions, say starting, stopping, restarting, killing, or opening now. Do not claim the final action already completed before the browser runs it.", + "If a server name is unclear, use the available tools to discover or confirm the correct server before taking action.", + `Current authenticated user: ${String(userEmail || "unknown").trim() || "unknown"}.`, + ].join(" "); +} + +function parseToolArguments(raw) { + if (!raw) return {}; + if (typeof raw === "object") return raw; + try { + const parsed = JSON.parse(String(raw)); + return parsed && typeof parsed === "object" ? parsed : {}; + } catch { + return {}; + } +} + +function buildMaskedError(message, extra = {}) { + return Object.assign({ ok: false, error: message }, extra); +} + +function buildSuccess(data) { + return Object.assign({ ok: true }, data); +} + +function normalizeRelativePath(input) { + return String(input || "").replace(/\0/g, "").trim(); +} + +function safeJoinUnix(baseDir, relativePath) { + const base = path.posix.normalize(String(baseDir ?? "")).replace(/\0/g, ""); + const raw = String(relativePath ?? "").replace(/\0/g, ""); + if (path.posix.isAbsolute(raw)) { + throw new Error("Absolute path not allowed"); + } + + const normalized = path.posix.normalize(`/${raw}`).replace(/^\/+/, ""); + if (normalized === ".." || normalized.startsWith("../") || normalized.includes("/../")) { + throw new Error("Unix path traversal detected"); + } + + return path.posix.join(base, normalized); +} + +function truncateText(text, limit = FILE_PREVIEW_LIMIT) { + const value = String(text ?? ""); + if (value.length <= limit) { + return { content: value, truncated: false, originalLength: value.length }; + } + return { + content: `${value.slice(0, limit)}\n\n[Truncated by ADPanel Assistant]`, + truncated: true, + originalLength: value.length, + }; +} + +function coerceNumber(value) { + if (value === undefined || value === null || value === "") return null; + const num = Number(value); + return Number.isFinite(num) ? num : null; +} + +function normalizeLooseText(value) { + return String(value || "").toLowerCase().replace(/[^a-z0-9]+/g, " ").trim(); +} + +function compareMcVersionsDesc(left, right) { + const leftParts = String(left || "").split(".").map((part) => parseInt(part, 10) || 0); + const rightParts = String(right || "").split(".").map((part) => parseInt(part, 10) || 0); + const maxLength = Math.max(leftParts.length, rightParts.length); + for (let index = 0; index < maxLength; index += 1) { + const delta = (rightParts[index] || 0) - (leftParts[index] || 0); + if (delta !== 0) return delta; + } + return 0; +} + +function normalizePluginLoader(value) { + const normalized = String(value || "").trim().toLowerCase(); + if (!normalized) return ""; + if (normalized === "bungee" || normalized === "bungeecord") return "bungeecord"; + if (normalized === "waterfall" || normalized === "velocity") return normalized; + if (normalized === "paper" || normalized === "purpur" || normalized === "spigot" || normalized === "bukkit") return normalized; + if (normalized === "neo" || normalized === "neo-forge" || normalized === "neoforge") return "neoforge"; + if (normalized === "forge" || normalized === "fabric" || normalized === "quilt") return normalized; + return normalized; +} + +function inferServerPluginLoader(entry) { + const candidates = [ + entry?.mcFork, + entry?.runtime?.providerId, + entry?.runtime?.versionId, + entry?.runtime?.command, + entry?.runtime?.startupCommand, + entry?.startupCommand, + entry?.template, + ].map((value) => String(value || "").toLowerCase()); + + for (const loader of MODRINTH_PLUGIN_LOADERS) { + if (candidates.some((candidate) => candidate.includes(loader))) { + return loader; + } + } + + if (String(entry?.template || "").trim().toLowerCase() === "minecraft") { + return normalizePluginLoader(entry?.mcFork || "paper"); + } + return ""; +} + +function inferServerMinecraftVersion(entry) { + return String(entry?.mcVersion || "").trim(); +} + +function scoreModrinthHit(hit, query) { + const queryText = normalizeLooseText(query); + const slug = normalizeLooseText(hit?.slug); + const title = normalizeLooseText(hit?.title); + let score = 0; + if (slug === queryText || title === queryText) score += 12; + if (slug.replace(/\s+/g, "") === queryText.replace(/\s+/g, "")) score += 10; + if (title.includes(queryText)) score += 5; + if (slug.includes(queryText)) score += 4; + score += Math.min(Number(hit?.downloads || 0), 500000) / 500000; + if (hit?.featured) score += 1; + return score; +} + +async function fetchJsonOrError(deps, url) { + const response = await deps.httpRequestJson(url, "GET", { + "Accept": "application/json", + "User-Agent": "ADPanel-Assistant", + }, null, 20_000); + if (response.status !== 200 || !response.json) { + return { error: `Request failed (${response.status || 0}).` }; + } + return { json: response.json }; +} + +async function resolveModrinthProject(deps, pluginName) { + const query = String(pluginName || "").trim(); + if (!query) { + return { error: "A plugin name is required." }; + } + + const facets = encodeURIComponent('[["project_type:plugin"]]'); + const url = `${MODRINTH_API_BASE}/search?limit=8&query=${encodeURIComponent(query)}&facets=${facets}`; + const { json, error } = await fetchJsonOrError(deps, url); + if (error) return { error: `Modrinth search failed. ${error}` }; + + const hits = Array.isArray(json?.hits) ? json.hits : []; + if (!hits.length) { + return { error: `No Modrinth plugin matched "${query}".` }; + } + + const sorted = hits + .slice() + .sort((left, right) => scoreModrinthHit(right, query) - scoreModrinthHit(left, query)); + const best = sorted[0]; + if (!best?.project_id) { + return { error: `No Modrinth plugin matched "${query}".` }; + } + + return { + project: { + id: best.project_id, + slug: best.slug || "", + title: best.title || best.slug || query, + description: best.description || "", + }, + }; +} + +async function fetchModrinthProjectVersions(deps, projectId) { + const url = `${MODRINTH_API_BASE}/project/${encodeURIComponent(projectId)}/version`; + const { json, error } = await fetchJsonOrError(deps, url); + if (error) return { error: `Failed to load plugin versions. ${error}` }; + const versions = Array.isArray(json) ? json : []; + return { versions }; +} + +function chooseBestPluginVersion(versions, { platform, gameVersion }) { + const normalizedPlatform = normalizePluginLoader(platform); + const normalizedVersion = String(gameVersion || "").trim(); + + const candidates = (Array.isArray(versions) ? versions : []) + .filter((entry) => Array.isArray(entry?.files) && entry.files.some((file) => file?.url)) + .map((entry) => { + const loaders = Array.isArray(entry?.loaders) ? entry.loaders.map(normalizePluginLoader).filter(Boolean) : []; + const gameVersions = Array.isArray(entry?.game_versions) ? entry.game_versions.map((value) => String(value || "").trim()).filter(Boolean) : []; + let score = 0; + if (normalizedPlatform && loaders.includes(normalizedPlatform)) score += 8; + if (!normalizedPlatform && loaders.some((loader) => MODRINTH_PLUGIN_LOADERS.includes(loader))) score += 2; + if (normalizedVersion && gameVersions.includes(normalizedVersion)) score += 8; + if (!normalizedVersion && gameVersions.length) score += 1; + if (entry?.featured) score += 1; + return { entry, loaders, gameVersions, score }; + }) + .filter((item) => { + if (normalizedPlatform && !item.loaders.includes(normalizedPlatform)) return false; + if (normalizedVersion && !item.gameVersions.includes(normalizedVersion)) return false; + return true; + }); + + const pool = candidates.length ? candidates : (Array.isArray(versions) ? versions : []) + .filter((entry) => Array.isArray(entry?.files) && entry.files.some((file) => file?.url)) + .map((entry) => ({ + entry, + loaders: Array.isArray(entry?.loaders) ? entry.loaders.map(normalizePluginLoader).filter(Boolean) : [], + gameVersions: Array.isArray(entry?.game_versions) ? entry.game_versions.map((value) => String(value || "").trim()).filter(Boolean) : [], + score: 0, + })); + + if (!pool.length) return null; + + pool.sort((left, right) => { + if (right.score !== left.score) return right.score - left.score; + const versionCompare = compareMcVersionsDesc(left.gameVersions[0] || "", right.gameVersions[0] || ""); + if (versionCompare !== 0) return versionCompare; + return new Date(right.entry?.date_published || 0).getTime() - new Date(left.entry?.date_published || 0).getTime(); + }); + return pool[0]; +} + +function getServerAliases(entry) { + const aliases = new Set(); + for (const value of [ + entry?.name, + entry?.displayName, + entry?.id, + entry?.bot, + entry?.legacyId, + ]) { + const cleaned = String(value || "").trim(); + if (cleaned) { + aliases.add(cleaned); + const spaced = cleaned.replace(/[_./-]+/g, " ").replace(/\s+/g, " ").trim(); + if (spaced) aliases.add(spaced); + } + } + return Array.from(aliases); +} + +function stripLookupDiacritics(value) { + return String(value || "").normalize("NFKD").replace(/[\u0300-\u036f]/g, ""); +} + +function normalizeLookupPhrase(value) { + return stripLookupDiacritics(value) + .toLowerCase() + .replace(/[`"'“”‘’]/g, " ") + .replace(/[_./-]+/g, " ") + .replace(/[^a-z0-9 ]+/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function compactLookupPhrase(value) { + return normalizeLookupPhrase(value).replace(/\s+/g, ""); +} + +function stripServerLookupFiller(value) { + return normalizeLookupPhrase(value) + .replace(/\b(?:the|my|our|please|pls|now|right|right now|server|servers|serverul|serverele|servere|srv|named|called|bot|instance|start|run|boot|bring|spin|restart|reboot|stop|shutdown|shut|kill|terminate|turn|power|on|off|up|down|porneste|pornește|opreste|oprește|inchide|închide|reporneste|repornește|omoara|omoară|ucide|for|on|la|pe)\b/g, " ") + .replace(/\s+/g, " ") + .trim(); +} + +function addLookupForms(set, value) { + const raw = String(value || "").trim().toLowerCase(); + if (raw) set.add(raw); + + const normalized = normalizeLookupPhrase(value); + if (normalized) set.add(normalized); + + const compact = compactLookupPhrase(value); + if (compact) set.add(compact); +} + +function buildRequestedServerForms(requestedServer) { + const forms = new Set(); + const raw = String(requestedServer || "").trim(); + if (!raw) return forms; + + addLookupForms(forms, raw); + addLookupForms(forms, stripServerLookupFiller(raw)); + + const quoted = raw.match(/["'`“”]([^"'`“”]{1,120})["'`“”]/); + if (quoted) { + addLookupForms(forms, quoted[1]); + addLookupForms(forms, stripServerLookupFiller(quoted[1])); + } + + const wrappedMatches = Array.from(raw.matchAll(/[\(\[]([^()\[\]]{1,120})[\)\]]/g)); + for (const match of wrappedMatches) { + addLookupForms(forms, match[1]); + addLookupForms(forms, stripServerLookupFiller(match[1])); + } + + return forms; +} + +function scoreServerAliasMatch(alias, requestedForms) { + const aliasRaw = String(alias || "").trim().toLowerCase(); + const aliasNormalized = normalizeLookupPhrase(alias); + const aliasCompact = compactLookupPhrase(alias); + const aliasTokens = new Set(aliasNormalized.split(" ").filter(Boolean)); + let best = 0; + + for (const requested of Array.from(requestedForms || [])) { + const needle = String(requested || "").trim().toLowerCase(); + if (!needle) continue; + + if (needle === aliasRaw || needle === aliasNormalized || needle === aliasCompact) { + return 1000; + } + + const needleNormalized = normalizeLookupPhrase(needle); + const needleCompact = compactLookupPhrase(needle); + if (!needleNormalized && !needleCompact) continue; + + if (needleCompact && aliasCompact && (aliasCompact.startsWith(needleCompact) || needleCompact.startsWith(aliasCompact))) { + best = Math.max(best, 260 - Math.abs(aliasCompact.length - needleCompact.length)); + } + if (needleCompact && aliasCompact && (aliasCompact.includes(needleCompact) || needleCompact.includes(aliasCompact))) { + best = Math.max(best, 210 - Math.abs(aliasCompact.length - needleCompact.length)); + } + if (needleNormalized && aliasNormalized && (aliasNormalized.startsWith(needleNormalized) || needleNormalized.startsWith(aliasNormalized))) { + best = Math.max(best, 180 - Math.abs(aliasNormalized.length - needleNormalized.length)); + } + if (needleNormalized && aliasNormalized && (aliasNormalized.includes(needleNormalized) || needleNormalized.includes(aliasNormalized))) { + best = Math.max(best, 150 - Math.abs(aliasNormalized.length - needleNormalized.length)); + } + + const needleTokens = needleNormalized.split(" ").filter(Boolean); + const overlap = needleTokens.filter((token) => aliasTokens.has(token)).length; + if (overlap > 0) { + best = Math.max(best, overlap * 40 - Math.max(0, aliasTokens.size - overlap) * 4); + } + } + + return best; +} + +function getTemplateAliases(entry) { + const aliases = new Set(); + for (const value of [entry?.id, entry?.name]) { + const cleaned = String(value || "").trim(); + if (cleaned) aliases.add(cleaned); + } + return Array.from(aliases); +} + +function resolveTemplateFromList(templates, requestedTemplate) { + const requested = String(requestedTemplate || "").trim().toLowerCase(); + if (!requested) { + return { error: "A template is required." }; + } + + const exactMatches = templates.filter((entry) => + getTemplateAliases(entry).some((alias) => alias.toLowerCase() === requested) + ); + if (exactMatches.length === 1) { + return { entry: exactMatches[0] }; + } + if (exactMatches.length > 1) { + return { + error: "Multiple templates matched that name.", + candidates: exactMatches.map((entry) => entry.id || entry.name), + }; + } + + const partialMatches = templates.filter((entry) => + getTemplateAliases(entry).some((alias) => alias.toLowerCase().includes(requested)) + ); + if (partialMatches.length === 1) { + return { entry: partialMatches[0] }; + } + if (partialMatches.length > 1) { + return { + error: "The template name is ambiguous.", + candidates: partialMatches.slice(0, 10).map((entry) => entry.id || entry.name), + }; + } + + return { error: "No template matched that name." }; +} + +function getNodeAliases(entry) { + const aliases = new Set(); + for (const value of [entry?.id, entry?.uuid, entry?.name]) { + const cleaned = String(value || "").trim(); + if (cleaned) aliases.add(cleaned); + } + return Array.from(aliases); +} + +function resolveNodeFromList(nodes, requestedNode) { + const requested = String(requestedNode || "").trim().toLowerCase(); + if (!requested) { + return { error: "A node is required." }; + } + + const exactMatches = nodes.filter((entry) => + getNodeAliases(entry).some((alias) => alias.toLowerCase() === requested) + ); + if (exactMatches.length === 1) { + return { entry: exactMatches[0] }; + } + if (exactMatches.length > 1) { + return { + error: "Multiple nodes matched that name.", + candidates: exactMatches.map((entry) => entry.name || entry.id || entry.uuid), + }; + } + + const partialMatches = nodes.filter((entry) => + getNodeAliases(entry).some((alias) => alias.toLowerCase().includes(requested)) + ); + if (partialMatches.length === 1) { + return { entry: partialMatches[0] }; + } + if (partialMatches.length > 1) { + return { + error: "The node name is ambiguous.", + candidates: partialMatches.slice(0, 10).map((entry) => entry.name || entry.id || entry.uuid), + }; + } + + return { error: "No node matched that name." }; +} + +function getNodeResourceLimits(node) { + const buildConfig = node?.buildConfig && typeof node.buildConfig === "object" ? node.buildConfig : {}; + const ramMb = coerceNumber(node?.ram_mb ?? buildConfig.ram_mb ?? buildConfig.ramMb) || 0; + const cpuCores = coerceNumber(node?.cpu_cores ?? buildConfig.cpu_cores ?? buildConfig.cpuCores) || 0; + const diskGb = coerceNumber(node?.disk_gb ?? buildConfig.disk_gb ?? buildConfig.diskGb) || 0; + return { + ramMb, + cpuCores, + diskGb, + diskMb: diskGb > 0 ? Math.round(diskGb * 1024) : 0, + }; +} + +function describeNodePorts(node) { + const ports = node?.ports && typeof node.ports === "object" ? node.ports : {}; + if (ports.mode === "range" && coerceNumber(ports.start) > 0 && coerceNumber(ports.count) > 0) { + const start = Number(ports.start); + const end = start + Number(ports.count) - 1; + return { + mode: "range", + start, + end, + description: `${start}-${end}`, + }; + } + if (ports.mode === "list" && Array.isArray(ports.ports) && ports.ports.length > 0) { + const normalizedPorts = ports.ports + .map((value) => Number(value)) + .filter((value) => Number.isInteger(value) && value > 0) + .slice(0, 50); + return { + mode: "list", + ports: normalizedPorts, + description: normalizedPorts.slice(0, 12).join(", ") + (normalizedPorts.length > 12 ? "..." : ""), + }; + } + return { + mode: "unknown", + description: "not declared", + }; +} + +async function createAccessibleServerCache(deps, userEmail) { + const list = (await deps.loadServersIndex()) || []; + const user = await deps.findUserByEmail(userEmail); + if (user?.admin) return list.filter(Boolean); + + const accessList = (await deps.getAccessListForEmail(userEmail)) || []; + const lowered = new Set(accessList.map((item) => String(item || "").trim().toLowerCase())); + if (lowered.has("all")) return list.filter(Boolean); + + return list.filter((entry) => entry?.name && lowered.has(String(entry.name).toLowerCase())); +} + +function resolveServerFromList(accessibleServers, requestedServer) { + const requested = String(requestedServer || "").trim(); + if (!requested) { + return { error: "A server name is required." }; + } + + const requestedForms = buildRequestedServerForms(requested); + const scoredEntries = accessibleServers + .filter(Boolean) + .map((entry) => { + const aliases = getServerAliases(entry); + const score = aliases.reduce((best, alias) => Math.max(best, scoreServerAliasMatch(alias, requestedForms)), 0); + return { entry, score }; + }); + + const exactMatches = scoredEntries.filter((item) => item.score >= 1000).map((item) => item.entry); + if (exactMatches.length === 1) { + return { entry: exactMatches[0] }; + } + if (exactMatches.length > 1) { + return { + error: "Multiple servers matched that name.", + candidates: exactMatches.map((entry) => entry.name), + }; + } + + const partialMatches = scoredEntries + .filter((item) => item.score >= 120) + .sort((left, right) => right.score - left.score) + .map((item) => item.entry); + if (partialMatches.length === 1) { + return { entry: partialMatches[0] }; + } + if (partialMatches.length > 1) { + const topScore = scoredEntries + .filter((item) => item.score >= 120) + .sort((left, right) => right.score - left.score); + if (topScore[0] && topScore[1] && topScore[0].score >= topScore[1].score + 50) { + return { entry: topScore[0].entry }; + } + return { + error: "The server name is ambiguous.", + candidates: partialMatches.slice(0, 10).map((entry) => entry.displayName || entry.name), + }; + } + + const candidates = scoredEntries + .filter((item) => item.score > 0) + .sort((left, right) => right.score - left.score) + .slice(0, 5) + .map((item) => item.entry.displayName || item.entry.name); + + return { + error: "No accessible server matched that name.", + candidates, + }; +} + +function normalizePowerAction(value) { + const action = String(value || "").trim().toLowerCase(); + return ["start", "stop", "restart", "kill"].includes(action) ? action : ""; +} + +function normalizeAssistantMetric(value) { + const metric = String(value || "").trim().toLowerCase(); + return ["balanced", "cpu", "memory", "disk"].includes(metric) ? metric : "balanced"; +} + +function normalizeAssistantMetricList(value) { + const rawList = Array.isArray(value) ? value : [value]; + const seen = new Set(); + const metrics = []; + + rawList.forEach((entry) => { + const metric = normalizeAssistantMetric(entry); + if (metric === "balanced" || seen.has(metric)) return; + seen.add(metric); + metrics.push(metric); + }); + + return metrics; +} + +function getRequiredPermsForPowerAction(action) { + if (action === "start") return ["server_start"]; + if (action === "restart") return ["server_stop", "server_start"]; + if (action === "stop" || action === "kill") return ["server_stop"]; + return []; +} + +function describePowerPermissionAction(action) { + if (action === "start") return "start"; + if (action === "restart") return "restart"; + if (action === "stop") return "stop"; + if (action === "kill") return "kill"; + return "control"; +} + +function normalizeServerPropertyKey(value) { + const key = String(value || "").trim(); + if (!key) return ""; + return /^[A-Za-z0-9._-]+$/.test(key) ? key : ""; +} + +function getEntryDisplayName(entry) { + return String(entry?.displayName || entry?.name || "").trim() || "that server"; +} + +function getNormalizedEntryTemplate(deps, entry) { + if (typeof deps?.normalizeTemplateId === "function") { + return String(deps.normalizeTemplateId(entry?.template) || "").trim().toLowerCase(); + } + return String(entry?.template || "").trim().toLowerCase(); +} + +function isMinecraftServerEntry(deps, entry) { + const template = getNormalizedEntryTemplate(deps, entry); + if (template === "minecraft") return true; + + const mcFork = String(entry?.mcFork || "").trim(); + const mcVersion = String(entry?.mcVersion || "").trim(); + const startFile = String(entry?.start || "").trim().toLowerCase(); + const image = String(entry?.runtime?.image || entry?.docker?.image || "").trim().toLowerCase(); + + return !!( + mcFork || + mcVersion || + startFile === "server.jar" || + image.includes("minecraft") + ); +} + +async function collectPowerTargets(deps, entries, userEmail, action) { + const requiredPerms = getRequiredPermsForPowerAction(action); + const targets = []; + const skipped = []; + + for (const entry of Array.isArray(entries) ? entries : []) { + if (!entry?.name) continue; + + const displayName = entry.displayName || entry.name; + const nodeId = String(entry.nodeId || "").trim().toLowerCase(); + if (!nodeId || nodeId === "local") { + skipped.push({ + server: entry.name, + displayName, + reason: "not_attached_to_node", + message: `${displayName} is not attached to a node.`, + }); + continue; + } + + const perms = await deps.getEffectivePermsForUserOnServer(userEmail, entry.name); + const missingPerm = requiredPerms.find((perm) => !perms?.[perm]); + if (missingPerm) { + skipped.push({ + server: entry.name, + displayName, + reason: "permission_denied", + permission: missingPerm, + message: `You do not have permission to ${describePowerPermissionAction(action)} ${displayName}.`, + }); + continue; + } + + const hostPort = coerceNumber(entry.port); + const target = { + server: entry.name, + displayName, + }; + if (Number.isInteger(hostPort) && hostPort > 0) { + target.hostPort = hostPort; + } + targets.push(target); + } + + return { targets, skipped, requiredPerms }; +} + +async function collectFileTargets(deps, entries, userEmail, requiredPerms = ["files_read", "files_create"]) { + const targets = []; + const skipped = []; + + for (const entry of Array.isArray(entries) ? entries : []) { + if (!entry?.name) continue; + + const displayName = getEntryDisplayName(entry); + if (!entry.nodeId) { + skipped.push({ + server: entry.name, + displayName, + reason: "not_attached_to_node", + message: `${displayName} is not attached to a node.`, + }); + continue; + } + + const perms = await deps.getEffectivePermsForUserOnServer(userEmail, entry.name); + const missingPerm = requiredPerms.find((perm) => !perms?.[perm]); + if (missingPerm) { + skipped.push({ + server: entry.name, + displayName, + reason: "permission_denied", + permission: missingPerm, + message: `You do not have permission to edit files on ${displayName}.`, + }); + continue; + } + + targets.push({ + server: entry.name, + displayName, + template: getNormalizedEntryTemplate(deps, entry) || null, + }); + } + + return { targets, skipped, requiredPerms }; +} + +function createDashboardAssistantToolRunner(deps) { + if (!deps || typeof deps !== "object") { + throw new Error("Dashboard assistant tool dependencies are required."); + } + + return async function runTool({ name, args, userEmail, userIp, clientActions }) { + const toolName = String(name || "").trim(); + const parsedArgs = parseToolArguments(args); + const accessibleServers = await createAccessibleServerCache(deps, userEmail); + + const resolveServerOrError = async (requestedServer, permKey = null) => { + const resolved = resolveServerFromList(accessibleServers, requestedServer); + if (!resolved.entry) { + return { error: buildMaskedError(resolved.error || "Server not found.", resolved.candidates ? { candidates: resolved.candidates } : {}) }; + } + + const entry = resolved.entry; + const perms = await deps.getEffectivePermsForUserOnServer(userEmail, entry.name); + if (permKey && !perms[permKey]) { + return { + error: buildMaskedError(`You do not have permission to ${permKey.replace(/_/g, " ")} on ${entry.name}.`), + }; + } + + return { entry, perms }; + }; + + switch (toolName) { + case "list_templates": { + const templates = (typeof deps.loadTemplatesFile === "function" ? deps.loadTemplatesFile() : []) || []; + return buildSuccess({ + templates: templates.slice(0, 100).map((entry) => ({ + id: entry?.id || "", + name: entry?.name || entry?.id || "", + description: entry?.description || "", + defaultPort: entry?.defaultPort ?? null, + })), + }); + } + + case "list_nodes": { + const currentUser = await deps.findUserByEmail(userEmail); + if (!(currentUser && currentUser.admin)) { + return buildMaskedError("Only administrators can create servers on nodes."); + } + + const nodes = (typeof deps.loadNodes === "function" ? await deps.loadNodes() : []) || []; + return buildSuccess({ + nodes: nodes.slice(0, 100).map((entry) => ({ + ...getNodeResourceLimits(entry), + id: entry?.id || null, + uuid: entry?.uuid || null, + name: entry?.name || entry?.id || entry?.uuid || "", + address: entry?.address || null, + online: !!entry?.online, + apiPort: entry?.api_port ?? 8080, + portAllocation: describeNodePorts(entry), + })), + }); + } + + case "create_server": { + const currentUser = await deps.findUserByEmail(userEmail); + if (!(currentUser && currentUser.admin)) { + return buildMaskedError("Only administrators can create new servers."); + } + + const rawName = String(parsedArgs.name || "").trim(); + const name = typeof deps.sanitizeServerName === "function" ? deps.sanitizeServerName(rawName) : rawName; + if (!name) { + return buildMaskedError("A valid server name is required."); + } + + const rawDisplayName = String(parsedArgs.displayName || rawName || "").trim(); + const displayName = typeof deps.sanitizeDisplayName === "function" + ? (deps.sanitizeDisplayName(rawDisplayName) || name) + : (rawDisplayName || name); + + const templates = (typeof deps.loadTemplatesFile === "function" ? deps.loadTemplatesFile() : []) || []; + const resolvedTemplate = resolveTemplateFromList(templates, parsedArgs.templateId); + if (!resolvedTemplate.entry) { + return buildMaskedError( + resolvedTemplate.error || "Template not found.", + resolvedTemplate.candidates ? { candidates: resolvedTemplate.candidates } : {} + ); + } + const template = resolvedTemplate.entry; + const normalizedTemplateId = typeof deps.normalizeTemplateId === "function" + ? deps.normalizeTemplateId(template.id || parsedArgs.templateId) + : String(template.id || parsedArgs.templateId || "").trim().toLowerCase(); + + const nodes = (typeof deps.loadNodes === "function" ? await deps.loadNodes() : []) || []; + const resolvedNode = resolveNodeFromList(nodes, parsedArgs.nodeId); + if (!resolvedNode.entry) { + return buildMaskedError( + resolvedNode.error || "Node not found.", + resolvedNode.candidates ? { candidates: resolvedNode.candidates } : {} + ); + } + const node = resolvedNode.entry; + if (node?.online === false) { + return buildMaskedError("That node is offline right now."); + } + + if (typeof deps.loadServersIndex === "function") { + const existingServers = await deps.loadServersIndex(); + const requestedNameLower = String(name || "").trim().toLowerCase(); + const conflictingServer = Array.isArray(existingServers) + ? existingServers.find((entry) => { + if (!entry || !requestedNameLower) return false; + const canonical = String(entry.name || "").trim().toLowerCase(); + const technical = String(entry.bot || "").trim().toLowerCase(); + return canonical === requestedNameLower || technical === requestedNameLower; + }) + : null; + if (conflictingServer) { + return buildMaskedError("That server name is already in use.", { + detail: `The name "${name}" matches an existing server or technical alias.`, + }); + } + } + + let hostPortRaw = coerceNumber(parsedArgs.hostPort); + if (hostPortRaw == null && template.defaultPort != null) { + hostPortRaw = coerceNumber(template.defaultPort); + } + if (hostPortRaw == null) { + return buildMaskedError("A port is required for that server. Tell me which port to allocate, or explicitly say to use defaults if the template has one."); + } + if (!Number.isInteger(hostPortRaw) || hostPortRaw < 1 || hostPortRaw > 65535) { + return buildMaskedError("The port must be a whole number between 1 and 65535."); + } + + const resolvedPort = hostPortRaw != null ? Number(hostPortRaw) : (coerceNumber(template.defaultPort) || 0); + if (resolvedPort > 0 && typeof deps.isPortInNodeAllocation === "function" && !deps.isPortInNodeAllocation(node, resolvedPort)) { + return buildMaskedError(`Port ${resolvedPort} is not in this node's allocated ports.`, { + allocation: describeNodePorts(node), + }); + } + + const inputResources = parsedArgs.resources && typeof parsedArgs.resources === "object" ? parsedArgs.resources : {}; + const startFile = normalizedTemplateId === "minecraft" + ? "server.jar" + : (normalizedTemplateId === "nodejs" || normalizedTemplateId === "discord-bot" + ? "index.js" + : (normalizedTemplateId === "python" ? "main.py" : null)); + const mcFork = normalizedTemplateId === "minecraft" + ? String(parsedArgs.mcFork || "paper").trim().toLowerCase() + : undefined; + const mcVersion = normalizedTemplateId === "minecraft" + ? String(parsedArgs.mcVersion || "1.21.8").trim() + : undefined; + const importUrl = parsedArgs.importUrl ? String(parsedArgs.importUrl).trim() : null; + + if (importUrl) { + if (typeof deps.isValidArchiveUrl === "function" && !deps.isValidArchiveUrl(importUrl)) { + return buildMaskedError("The import URL must be http(s) and point to a supported archive file."); + } + if (typeof deps.assertSafeRemoteUrl === "function") { + try { + await deps.assertSafeRemoteUrl(importUrl); + } catch (error) { + return buildMaskedError("The import URL is not allowed.", { + detail: error?.message || String(error), + }); + } + } + } + + const resources = {}; + if (inputResources.ramMb != null) resources.ramMb = parseInt(inputResources.ramMb, 10) || null; + if (inputResources.cpuCores != null) resources.cpuCores = parseFloat(inputResources.cpuCores) || null; + if (inputResources.storageMb != null) resources.storageMb = parseInt(inputResources.storageMb, 10) || null; + else if (inputResources.storageGb != null) resources.storageMb = (parseInt(inputResources.storageGb, 10) || 0) * 1024 || null; + if (inputResources.swapMb != null) resources.swapMb = parseInt(inputResources.swapMb, 10); + if (inputResources.backupsMax != null) resources.backupsMax = parseInt(inputResources.backupsMax, 10) || 0; + if (inputResources.maxSchedules != null) resources.maxSchedules = parseInt(inputResources.maxSchedules, 10) || 0; + + const nodeLimits = getNodeResourceLimits(node); + if (resources.ramMb != null && resources.ramMb <= 0) { + return buildMaskedError("RAM must be greater than 0 MB."); + } + if (resources.cpuCores != null && resources.cpuCores <= 0) { + return buildMaskedError("CPU cores must be greater than 0."); + } + if (resources.storageMb != null && resources.storageMb <= 0) { + return buildMaskedError("Storage must be greater than 0 MB."); + } + if (nodeLimits.ramMb > 0 && resources.ramMb != null && resources.ramMb > nodeLimits.ramMb) { + return buildMaskedError(`RAM cannot exceed this node's limit (${nodeLimits.ramMb} MB).`); + } + if (nodeLimits.cpuCores > 0 && resources.cpuCores != null && resources.cpuCores > nodeLimits.cpuCores) { + return buildMaskedError(`CPU cannot exceed this node's limit (${nodeLimits.cpuCores} cores).`); + } + if (nodeLimits.diskMb > 0 && resources.storageMb != null && resources.storageMb > nodeLimits.diskMb) { + return buildMaskedError(`Storage cannot exceed this node's limit (${nodeLimits.diskMb} MB).`); + } + + let sanitizedDocker = sanitizeDockerTemplatePayload(template.docker); + if (sanitizedDocker && Array.isArray(sanitizedDocker.ports) && sanitizedDocker.ports.length > 1) { + sanitizedDocker.ports = [sanitizedDocker.ports[0]]; + } + + const payload = { + name, + templateId: template.id || normalizedTemplateId, + mcFork, + mcVersion, + hostPort: hostPortRaw, + docker: sanitizedDocker, + autoStart: true, + importUrl, + resources: Object.keys(resources).length > 0 ? resources : null, + }; + + let createResult = null; + try { + createResult = await deps.createOnRemoteNode(node, payload); + } catch (error) { + return buildMaskedError("Failed to create that server.", { + detail: error?.message || String(error), + }); + } + const technicalServerName = extractTechnicalServerNameFromNodeCreateResult(createResult, name) || name; + + let savedPort = null; + if (hostPortRaw != null) { + savedPort = typeof deps.clampPort === "function" ? deps.clampPort(hostPortRaw) : hostPortRaw; + } else if (template.defaultPort) { + savedPort = typeof deps.clampPort === "function" ? deps.clampPort(template.defaultPort) : template.defaultPort; + } else if (normalizedTemplateId === "minecraft") { + savedPort = 25565; + } else if (normalizedTemplateId === "nodejs" || normalizedTemplateId === "discord-bot") { + savedPort = 3000; + } + + const serverEntry = { + name, + displayName, + bot: technicalServerName && technicalServerName !== name ? technicalServerName : null, + template: template.id || normalizedTemplateId, + mcFork: normalizedTemplateId === "minecraft" ? mcFork : undefined, + mcVersion: normalizedTemplateId === "minecraft" ? mcVersion : undefined, + start: normalizedTemplateId === "minecraft" + ? "server.jar" + : (normalizedTemplateId === "nodejs" || normalizedTemplateId === "discord-bot" + ? "index.js" + : (normalizedTemplateId === "python" ? "main.py" : null)), + nodeId: node.uuid || node.id || node.name, + ip: node.address || null, + }; + if (savedPort != null) serverEntry.port = savedPort; + if (Object.keys(resources).length > 0) serverEntry.resources = resources; + if (sanitizedDocker) serverEntry.docker = sanitizedDocker; + if (sanitizedDocker) { + serverEntry.runtime = { + image: sanitizedDocker.image, + tag: sanitizedDocker.tag, + command: sanitizedDocker.command, + volumes: sanitizedDocker.volumes, + env: sanitizedDocker.env, + ports: sanitizedDocker.ports, + }; + } + + if (typeof deps.upsertServerIndexEntry === "function") { + await deps.upsertServerIndexEntry(serverEntry); + } + + if (typeof deps.recordActivity === "function") { + deps.recordActivity(name, "server_create", { + template: template.id || normalizedTemplateId, + nodeId: node.uuid || node.id || node.name, + }, userEmail, userIp); + } + + return buildSuccess({ + created: true, + server: { + name, + displayName, + template: template.id || normalizedTemplateId, + templateName: template.name || template.id || normalizedTemplateId, + nodeId: node.uuid || node.id || node.name, + nodeName: node.name || node.id || node.uuid, + port: savedPort, + }, + }); + } + + case "list_servers": { + return buildSuccess({ + servers: accessibleServers.slice(0, 100).map((entry) => ({ + name: entry.name, + displayName: entry.displayName || entry.name, + status: entry.status || "unknown", + template: entry.template || "custom", + })), + }); + } + + case "inspect_server": { + const { entry, perms, error } = await resolveServerOrError(parsedArgs.server); + if (error) return error; + + return buildSuccess({ + server: { + name: entry.name, + displayName: entry.displayName || entry.name, + status: entry.status || "unknown", + template: entry.template || "custom", + nodeId: entry.nodeId || null, + ip: entry.ip || null, + port: entry.port ?? null, + mcFork: entry.mcFork || null, + mcVersion: entry.mcVersion || null, + permissions: perms, + }, + }); + } + + case "get_busiest_node": { + const currentUser = await deps.findUserByEmail(userEmail); + if (!(currentUser && currentUser.admin)) { + return buildMaskedError("Only administrators can inspect node-wide load."); + } + + const nodes = (typeof deps.loadNodes === "function" ? await deps.loadNodes() : []) || []; + if (!nodes.length) { + return buildMaskedError("No nodes are available."); + } + + const metric = normalizeAssistantMetric(parsedArgs.metric); + const includeMetrics = normalizeAssistantMetricList(parsedArgs.includeMetrics); + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_find_busiest_node", + metric, + includeMetrics, + nodes: nodes.slice(0, 100).map((node) => ({ + id: node?.id || node?.uuid || node?.name || "", + name: node?.name || node?.id || node?.uuid || "", + })).filter((node) => node.id), + }); + } + + return buildSuccess({ + browserActionQueued: true, + metric, + includeMetrics, + nodeCount: nodes.length, + nodes: nodes.slice(0, 100).map((node) => ({ + id: node?.id || node?.uuid || node?.name || "", + name: node?.name || node?.id || node?.uuid || "", + })).filter((node) => node.id), + }); + } + + case "get_busiest_server": { + if (!accessibleServers.length) { + return buildMaskedError("You do not have access to any servers."); + } + + const metric = normalizeAssistantMetric(parsedArgs.metric); + const includeMetrics = normalizeAssistantMetricList(parsedArgs.includeMetrics); + const targets = accessibleServers + .filter((entry) => entry?.name && entry?.nodeId) + .slice(0, 200) + .map((entry) => ({ + server: entry.name, + displayName: getEntryDisplayName(entry), + template: getNormalizedEntryTemplate(deps, entry) || null, + nodeId: entry.nodeId || null, + })); + if (!targets.length) { + return buildMaskedError("No accessible servers are attached to a node right now."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_find_busiest_server", + metric, + includeMetrics, + targets, + }); + } + + return buildSuccess({ + browserActionQueued: true, + metric, + includeMetrics, + count: targets.length, + targets, + }); + } + + case "check_server_console": { + const query = String(parsedArgs.query || parsedArgs.server || "").trim(); + const question = String(parsedArgs.question || "").trim(); + if (!query) { + return buildMaskedError("A server name is required."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_check_server_console", + query, + question: question || query, + }); + } + + return buildSuccess({ + browserActionQueued: true, + resolutionRequired: true, + query, + question: question || query, + }); + } + + case "check_server_limits": { + const query = String(parsedArgs.query || parsedArgs.server || "").trim(); + const question = String(parsedArgs.question || "").trim(); + const includeMetrics = normalizeAssistantMetricList(parsedArgs.includeMetrics); + if (!query) { + return buildMaskedError("A server name is required."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_check_server_limits", + query, + question: question || query, + includeMetrics, + }); + } + + return buildSuccess({ + browserActionQueued: true, + resolutionRequired: true, + query, + question: question || query, + includeMetrics, + }); + } + + case "diagnose_server": { + const { entry, perms, error } = await resolveServerOrError(parsedArgs.server); + if (error) return error; + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_diagnose_server", + server: entry.name, + displayName: getEntryDisplayName(entry), + template: getNormalizedEntryTemplate(deps, entry) || null, + permissions: perms, + }); + } + + return buildSuccess({ + browserActionQueued: true, + server: entry.name, + displayName: getEntryDisplayName(entry), + template: getNormalizedEntryTemplate(deps, entry) || null, + permissions: perms, + }); + } + + case "update_minecraft_server_property": { + const property = normalizeServerPropertyKey(parsedArgs.property); + if (!property) { + return buildMaskedError("A valid server.properties key is required."); + } + + if (parsedArgs.value === undefined || parsedArgs.value === null) { + return buildMaskedError("A value is required."); + } + + const value = String(parsedArgs.value); + const onlyIfCurrent = parsedArgs.onlyIfCurrent === undefined || parsedArgs.onlyIfCurrent === null + ? "" + : String(parsedArgs.onlyIfCurrent).trim(); + const restartAfter = !!parsedArgs.restartAfter; + const scope = String(parsedArgs.scope || "").trim().toLowerCase(); + let candidateEntries = []; + + if (scope === "single_server") { + const { entry, error } = await resolveServerOrError(parsedArgs.server); + if (error) return error; + candidateEntries = [entry]; + } else if (scope === "all_accessible_minecraft") { + candidateEntries = accessibleServers.filter((entry) => isMinecraftServerEntry(deps, entry)); + } else { + return buildMaskedError("Invalid Minecraft property update scope."); + } + + if (!candidateEntries.length) { + return buildMaskedError(scope === "single_server" ? "That server could not be found." : "No accessible Minecraft servers were found."); + } + + const nonMinecraft = candidateEntries.filter((entry) => !isMinecraftServerEntry(deps, entry)); + if (nonMinecraft.length === candidateEntries.length) { + return buildMaskedError(scope === "single_server" + ? `${getEntryDisplayName(candidateEntries[0])} is not a Minecraft server.` + : "No accessible Minecraft servers were found."); + } + + const minecraftEntries = candidateEntries.filter((entry) => isMinecraftServerEntry(deps, entry)); + const { targets, skipped } = await collectFileTargets(deps, minecraftEntries, userEmail, ["files_read", "files_create"]); + if (!targets.length) { + return buildMaskedError( + scope === "single_server" + ? `You do not have permission to edit server.properties on ${getEntryDisplayName(minecraftEntries[0] || candidateEntries[0])}.` + : "You do not have permission to edit server.properties on any matching Minecraft servers.", + skipped.length ? { skipped } : {} + ); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_update_minecraft_server_property", + property, + value, + scope, + path: "server.properties", + onlyIfCurrent: onlyIfCurrent || null, + restartAfter, + targets, + skipped, + }); + } + + return buildSuccess({ + browserActionQueued: true, + property, + value, + scope, + path: "server.properties", + onlyIfCurrent: onlyIfCurrent || null, + restartAfter, + count: targets.length, + targets, + skipped, + }); + } + + case "install_plugin": { + const { entry, perms, error } = await resolveServerOrError(parsedArgs.server, "files_create"); + if (error) return error; + + if (!entry?.nodeId) { + return buildMaskedError("This server is not attached to a node."); + } + + if (typeof deps.applyRemoteAssetToServer !== "function") { + return buildMaskedError("Plugin installation is not available here."); + } + + const requestedPlugin = String(parsedArgs.pluginName || "").trim(); + if (!requestedPlugin) { + return buildMaskedError("A plugin name is required."); + } + + const projectResult = await resolveModrinthProject(deps, requestedPlugin); + if (!projectResult.project) { + return buildMaskedError(projectResult.error || "Plugin not found."); + } + + const inferredPlatform = normalizePluginLoader(parsedArgs.platform || inferServerPluginLoader(entry) || "paper"); + const inferredGameVersion = String(parsedArgs.gameVersion || inferServerMinecraftVersion(entry) || "").trim(); + + const versionResult = await fetchModrinthProjectVersions(deps, projectResult.project.id); + if (!versionResult.versions) { + return buildMaskedError(versionResult.error || "Failed to load plugin versions."); + } + + const chosen = chooseBestPluginVersion(versionResult.versions, { + platform: inferredPlatform, + gameVersion: inferredGameVersion, + }); + if (!chosen) { + return buildMaskedError(`No compatible Modrinth version was found for ${projectResult.project.title}.`, { + platform: inferredPlatform || null, + gameVersion: inferredGameVersion || null, + }); + } + + const file = chosen.entry.files.find((item) => item?.primary && item?.url) || chosen.entry.files.find((item) => item?.url); + if (!file?.url) { + return buildMaskedError("That plugin version does not provide a downloadable file."); + } + + const pluginFileName = String(file.filename || file.url.split("/").pop() || `${projectResult.project.slug || "plugin"}.jar`).trim(); + const applyResult = await deps.applyRemoteAssetToServer({ + serverName: entry.name, + entry, + url: file.url, + destPath: `plugins/${pluginFileName}`, + }); + + if (!applyResult?.ok) { + return buildMaskedError("Failed to install that plugin.", { + detail: applyResult?.detail || applyResult?.error || "unknown-error", + }); + } + + if (typeof deps.recordActivity === "function") { + deps.recordActivity(entry.name, "plugin_install", { + plugin: projectResult.project.slug || projectResult.project.title, + file: pluginFileName, + platform: inferredPlatform || null, + gameVersion: inferredGameVersion || null, + }, userEmail, userIp); + } + + return buildSuccess({ + server: entry.name, + plugin: { + name: projectResult.project.title, + slug: projectResult.project.slug || "", + loader: chosen.loaders[0] || inferredPlatform || null, + gameVersion: chosen.gameVersions[0] || inferredGameVersion || null, + versionId: chosen.entry.id || null, + fileName: pluginFileName, + }, + destPath: `plugins/${pluginFileName}`, + permissions: perms, + }); + } + + case "request_delete_server": { + const currentUser = await deps.findUserByEmail(userEmail); + if (!(currentUser && currentUser.admin)) { + return buildMaskedError("Only administrators can delete servers."); + } + + const resolved = resolveServerFromList(accessibleServers, parsedArgs.server); + const serverName = resolved.entry?.name || String(parsedArgs.server || "").trim(); + if (!serverName) { + return buildMaskedError("A server name is required."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "confirm_delete_server", + server: serverName, + displayName: resolved.entry?.displayName || serverName, + }); + } + + return buildSuccess({ + server: serverName, + confirmationRequired: true, + }); + } + + case "list_files": { + const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_read"); + if (error) return error; + + const ctx = await deps.resolveRemoteFsContext(entry.name); + if (!ctx.remote || !ctx.node) { + return buildMaskedError("This server is not attached to a node."); + } + + try { + const fullPath = safeJoinUnix(ctx.baseDir, normalizeRelativePath(parsedArgs.path)); + const { status, json } = await deps.nodeFsPost(ctx.node, "/v1/fs/list", { path: fullPath }, 60_000); + if (status !== 200 || !json || !json.ok) { + return buildMaskedError("Failed to list files for that path.", { + detail: json?.error || `status ${status}`, + }); + } + + return buildSuccess({ + server: entry.name, + path: normalizeRelativePath(parsedArgs.path), + entries: (Array.isArray(json.entries) ? json.entries : []).slice(0, 200).map((item) => ({ + name: item?.name || "", + isDir: !!item?.isDir, + size: item?.size ?? null, + modifiedAt: item?.modifiedAt || item?.mtime || null, + })), + }); + } catch (err) { + return buildMaskedError(err?.message || "Invalid path."); + } + } + + case "read_file": { + const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_read"); + if (error) return error; + + const filePath = normalizeRelativePath(parsedArgs.path); + if (!filePath) { + return buildMaskedError("A file path is required."); + } + + const ctx = await deps.resolveRemoteFsContext(entry.name); + if (!ctx.remote || !ctx.node) { + return buildMaskedError("This server is not attached to a node."); + } + + try { + const fullPath = safeJoinUnix(ctx.baseDir, filePath); + const { status, json } = await deps.nodeFsPost(ctx.node, "/v1/fs/read", { path: fullPath, encoding: "utf8" }, 120_000); + if (status !== 200 || !json || !json.ok) { + return buildMaskedError("Failed to read that file.", { + detail: json?.error || `status ${status}`, + }); + } + + const preview = truncateText(json.content || ""); + return buildSuccess({ + server: entry.name, + path: filePath, + content: preview.content, + truncated: preview.truncated, + originalLength: preview.originalLength, + }); + } catch (err) { + return buildMaskedError(err?.message || "Invalid path."); + } + } + + case "write_file": { + const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_create"); + if (error) return error; + + const filePath = normalizeRelativePath(parsedArgs.path); + if (!filePath) { + return buildMaskedError("A file path is required."); + } + + const ctx = await deps.resolveRemoteFsContext(entry.name); + if (!ctx.remote || !ctx.node) { + return buildMaskedError("This server is not attached to a node."); + } + + try { + const fullPath = safeJoinUnix(ctx.baseDir, filePath); + const desiredContent = String(parsedArgs.content ?? ""); + const { status, json } = await deps.nodeFsPost( + ctx.node, + "/v1/fs/write", + { path: fullPath, content: desiredContent, encoding: "utf8" }, + 120_000 + ); + if (status !== 200 || !json || !json.ok) { + return buildMaskedError("Failed to write that file.", { + detail: json?.error || `status ${status}`, + }); + } + + const verifyResult = await deps.nodeFsPost( + ctx.node, + "/v1/fs/read", + { path: fullPath, encoding: "utf8" }, + 120_000 + ); + if (verifyResult.status !== 200 || !verifyResult.json || !verifyResult.json.ok) { + return buildMaskedError("The file write could not be verified.", { + detail: verifyResult.json?.error || `status ${verifyResult.status}`, + }); + } + + if (String(verifyResult.json.content ?? "") !== desiredContent) { + return buildMaskedError("The file write could not be verified."); + } + + if (typeof deps.recordActivity === "function") { + deps.recordActivity(entry.name, "file_edit", { path: filePath }, userEmail, userIp); + } + + return buildSuccess({ server: entry.name, path: filePath, written: true, verified: true }); + } catch (err) { + return buildMaskedError(err?.message || "Invalid path."); + } + } + + case "create_directory": { + const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_create"); + if (error) return error; + + const dirPath = normalizeRelativePath(parsedArgs.path); + if (!dirPath) { + return buildMaskedError("A directory path is required."); + } + + const ctx = await deps.resolveRemoteFsContext(entry.name); + if (!ctx.remote || !ctx.node) { + return buildMaskedError("This server is not attached to a node."); + } + + try { + const fullPath = safeJoinUnix(ctx.baseDir, dirPath); + const { status, json } = await deps.nodeFsPost(ctx.node, "/v1/fs/mkdir", { path: fullPath }, 120_000); + if (status !== 200 || !json || !json.ok) { + return buildMaskedError("Failed to create that directory.", { + detail: json?.error || `status ${status}`, + }); + } + + if (typeof deps.recordActivity === "function") { + deps.recordActivity(entry.name, "file_mkdir", { path: dirPath }, userEmail, userIp); + } + + return buildSuccess({ server: entry.name, path: dirPath, created: true }); + } catch (err) { + return buildMaskedError(err?.message || "Invalid path."); + } + } + + case "rename_path": { + const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_rename"); + if (error) return error; + + const source = normalizeRelativePath(parsedArgs.source); + const destination = normalizeRelativePath(parsedArgs.destination); + if (!source || !destination) { + return buildMaskedError("Both source and destination paths are required."); + } + + const ctx = await deps.resolveRemoteFsContext(entry.name); + if (!ctx.remote || !ctx.node) { + return buildMaskedError("This server is not attached to a node."); + } + + try { + const src = safeJoinUnix(ctx.baseDir, source); + const dest = safeJoinUnix(ctx.baseDir, destination); + const { status, json } = await deps.nodeFsPost(ctx.node, "/v1/fs/rename", { src, dest }, 120_000); + if (status !== 200 || !json || !json.ok) { + return buildMaskedError("Failed to rename that path.", { + detail: json?.error || `status ${status}`, + }); + } + + if (typeof deps.recordActivity === "function") { + deps.recordActivity(entry.name, "file_rename", { src: source, dest: destination }, userEmail, userIp); + } + + return buildSuccess({ server: entry.name, source, destination, renamed: true }); + } catch (err) { + return buildMaskedError(err?.message || "Invalid path."); + } + } + + case "delete_path": { + const { entry, error } = await resolveServerOrError(parsedArgs.server, "files_delete"); + if (error) return error; + + const targetPath = normalizeRelativePath(parsedArgs.path); + if (!targetPath) { + return buildMaskedError("A path is required."); + } + + const ctx = await deps.resolveRemoteFsContext(entry.name); + if (!ctx.remote || !ctx.node) { + return buildMaskedError("This server is not attached to a node."); + } + + try { + const fullPath = safeJoinUnix(ctx.baseDir, targetPath); + const { status, json } = await deps.nodeFsPost( + ctx.node, + "/v1/fs/delete", + { path: fullPath, isDir: !!parsedArgs.isDirectory }, + 120_000 + ); + if (status !== 200 || !json || !json.ok) { + return buildMaskedError("Failed to delete that path.", { + detail: json?.error || `status ${status}`, + }); + } + + if (typeof deps.recordActivity === "function") { + deps.recordActivity(entry.name, "file_delete", { path: targetPath, isDir: !!parsedArgs.isDirectory }, userEmail, userIp); + } + + return buildSuccess({ server: entry.name, path: targetPath, deleted: true }); + } catch (err) { + return buildMaskedError(err?.message || "Invalid path."); + } + } + + case "power_server": { + const action = normalizePowerAction(parsedArgs.action); + if (!action) { + return buildMaskedError("Invalid power action."); + } + + const requestedServer = String(parsedArgs.server || "").trim(); + if (!requestedServer) { + return buildMaskedError("A server name is required."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_resolve_power_server", + action, + query: requestedServer, + }); + } + + return buildSuccess({ + action, + query: requestedServer, + resolutionRequired: true, + browserActionQueued: true, + }); + } + + case "power_accessible_servers": { + const action = normalizePowerAction(parsedArgs.action); + if (!action) { + return buildMaskedError("Invalid power action."); + } + + if (!accessibleServers.length) { + return buildMaskedError("You do not have access to any servers."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_power_accessible_servers", + action, + }); + } + + return buildSuccess({ + action, + scope: "accessible", + browserActionQueued: true, + }); + } + + case "open_server_page": { + const requestedServer = String(parsedArgs.server || "").trim(); + const section = String(parsedArgs.section || "").trim(); + const allowedSections = new Set([ + "console", + "info", + "files", + "activity", + "backups", + "scheduler", + "store", + "resource_stats", + "subdomains", + "reinstall", + "ai_help", + ]); + + if (!requestedServer) { + return buildMaskedError("A server name is required."); + } + if (section && !allowedSections.has(section)) { + return buildMaskedError("Invalid server page section."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_open_server_page", + query: requestedServer, + section: section || "console", + }); + } + + return buildSuccess({ + query: requestedServer, + section: section || "console", + resolutionRequired: true, + browserActionQueued: true, + }); + } + + case "open_settings_destination": { + const currentUser = await deps.findUserByEmail(userEmail); + if (!(currentUser && currentUser.admin)) { + return buildMaskedError("Only administrators can open settings tools."); + } + + const panel = String(parsedArgs.panel || "").trim(); + const action = String(parsedArgs.action || "").trim(); + const allowedPanels = new Set([ + "preferences", + "customization", + "account", + "security", + "databases", + "nodes", + "templates", + "servers", + "webhooks", + "panelinfo", + ]); + const allowedActions = new Set([ + "create_user", + "branding", + "login_watermark", + "login_background", + "alert", + "quick_action_admin", + "quick_action_user", + "database_setup", + "pgadmin_setup", + "mongodb_setup", + "captcha", + "maintenance", + "create_node", + "create_template", + "add_webhook", + ]); + + if (!panel && !action) { + return buildMaskedError("A settings destination is required."); + } + if (panel && !allowedPanels.has(panel)) { + return buildMaskedError("Invalid settings panel."); + } + if (action && !allowedActions.has(action)) { + return buildMaskedError("Invalid settings action."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ + type: "assistant_open_settings_destination", + panel, + action, + }); + } + + return buildSuccess({ + panel, + action, + browserActionQueued: true, + }); + } + + case "open_account_flow": { + const flow = String(parsedArgs.flow || "").trim(); + if (![ + "change_password", + "change_email", + "change_2fa", + "recover_password", + "recover_email", + "recover_2fa", + ].includes(flow)) { + return buildMaskedError("Invalid account flow."); + } + + if (Array.isArray(clientActions)) { + clientActions.push({ type: "open_account_flow", flow }); + } + + return buildSuccess({ flow, browserActionQueued: true }); + } + + default: + return buildMaskedError(`Unknown tool: ${toolName}`); + } + }; +} + +module.exports = { + TOOL_DEFINITIONS, + POWER_TOOL_DEFINITIONS, + buildSystemPrompt, + createDashboardAssistantToolRunner, +}; diff --git a/utils/db-proxy.js b/utils/db-proxy.js new file mode 100644 index 0000000..956d3f6 --- /dev/null +++ b/utils/db-proxy.js @@ -0,0 +1,395 @@ +"use strict"; + +const crypto = require("crypto"); +const httpMod = require("http"); +const fs = require("fs"); +const path = require("path"); +const ipRangeCheck = require("ip-range-check"); + +// ─── Configuration ────────────────────────────────────────────── +const TOKEN_TTL_MS = 30 * 60 * 1000; // 30 minutes +const TOKEN_BYTES = 16; +const CLEANUP_INTERVAL_MS = 60 * 1000; // sweep every 60s +const MAX_SESSIONS = 500; // hard cap to prevent RAM bloat +const PHPMYADMIN_INTERNAL_PORT = 9082; + +// ─── Token Store (self-cleaning Map) ──────────────────────────── +const sessions = new Map(); + +function scheduleExpiryTimer(token, ttlMs) { + const timer = setTimeout(() => { + sessions.delete(token); + }, ttlMs); + if (timer.unref) timer.unref(); + return timer; +} + +function setSessionExpiry(token, sess, ttlMs = TOKEN_TTL_MS) { + if (!sess) return false; + if (sess._timer) clearTimeout(sess._timer); + sess.expiresAt = Date.now() + ttlMs; + sess._timer = scheduleExpiryTimer(token, ttlMs); + return true; +} + +// Periodic sweep for expired sessions +const _cleanupTimer = setInterval(() => { + const now = Date.now(); + for (const [token, sess] of sessions) { + if (now > sess.expiresAt) { + clearTimeout(sess._timer); + sessions.delete(token); + } + } +}, CLEANUP_INTERVAL_MS); +if (_cleanupTimer.unref) _cleanupTimer.unref(); + +// ─── Service Targets ──────────────────────────────────────────── +const SERVICE_TARGETS = { + phpmyadmin: { + host: "127.0.0.1", + port: PHPMYADMIN_INTERNAL_PORT, + backendPath: "/phpmyadmin", + label: "phpMyAdmin" + }, + pgadmin: { + host: "127.0.0.1", + port: 5050, + backendPath: "/pgadmin4", + label: "pgAdmin4" + } +}; + +// ─── Helpers ──────────────────────────────────────────────────── + +function normalizeIp(ip) { + if (!ip || typeof ip !== "string") return ""; + let normalized = ip.trim(); + if (normalized.startsWith("::ffff:")) normalized = normalized.slice(7); + return normalized; +} + +function loadTrustedSubnets() { + try { + const secPath = path.join(__dirname, "..", "security.json"); + const sec = JSON.parse(fs.readFileSync(secPath, "utf8")); + if (Array.isArray(sec.trusted_subnets)) { + return sec.trusted_subnets.filter(s => typeof s === "string" && s.length > 0); + } + } catch { /* ignore */ } + return []; +} + +function isIpAuthorized(requestIp, sessionIp) { + const normReq = normalizeIp(requestIp); + const normSess = normalizeIp(sessionIp); + + if (normReq === normSess) return true; + + const subnets = loadTrustedSubnets(); + if (subnets.length > 0) { + const reqInSubnet = ipRangeCheck(normReq, subnets); + const sessInSubnet = ipRangeCheck(normSess, subnets); + if (reqInSubnet && sessInSubnet) return true; + } + + return false; +} + +// ─── Token Management ─────────────────────────────────────────── + +function generateToken(service, userIp, username, sessionId = null) { + if (!SERVICE_TARGETS[service]) return null; + + if (sessions.size >= MAX_SESSIONS) { + let oldestToken = null, oldestTime = Infinity; + for (const [t, s] of sessions) { + if (s.createdAt < oldestTime) { oldestTime = s.createdAt; oldestToken = t; } + } + if (oldestToken) { + clearTimeout(sessions.get(oldestToken)._timer); + sessions.delete(oldestToken); + } + } + + const token = "v-tmp-" + crypto.randomBytes(TOKEN_BYTES).toString("hex"); + const now = Date.now(); + const expiresAt = now + TOKEN_TTL_MS; + + const _timer = scheduleExpiryTimer(token, TOKEN_TTL_MS); + + sessions.set(token, { + service, + userIp: normalizeIp(userIp), + username, + sessionId: sessionId ? String(sessionId) : null, + createdAt: now, + expiresAt, + _timer + }); + + return { token, expiresAt }; +} + +function validateToken(token) { + if (!token || typeof token !== "string") return null; + const sess = sessions.get(token); + if (!sess) return null; + if (Date.now() > sess.expiresAt) { + clearTimeout(sess._timer); + sessions.delete(token); + return null; + } + return sess; +} + +function touchToken(token, ttlMs = TOKEN_TTL_MS) { + if (!token || typeof token !== "string") return false; + const sess = sessions.get(token); + if (!sess) return false; + if (Date.now() > sess.expiresAt) { + clearTimeout(sess._timer); + sessions.delete(token); + return false; + } + return setSessionExpiry(token, sess, ttlMs); +} + +function revokeToken(token) { + const sess = sessions.get(token); + if (sess) { + clearTimeout(sess._timer); + sessions.delete(token); + } +} + +function revokeAllForUser(username) { + for (const [token, sess] of sessions) { + if (sess.username === username) { + clearTimeout(sess._timer); + sessions.delete(token); + } + } +} + +// ─── Streaming Proxy Middleware ───────────────────────────────── + +function rewriteCookiePaths(headers, backendPath, tokenPath) { + const raw = headers["set-cookie"]; + if (!raw) return; + const cookies = Array.isArray(raw) ? raw : [raw]; + headers["set-cookie"] = cookies.map(c => + c.replace(new RegExp("path=" + backendPath.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") + "/?", "gi"), "path=" + tokenPath) + ); +} + +function stripUpstreamSecurityHeaders(headers) { + // Remove backend security headers that conflict with our proxy context + delete headers["x-frame-options"]; + delete headers["content-security-policy"]; + delete headers["x-content-security-policy"]; + delete headers["x-webkit-csp"]; + delete headers["x-xss-protection"]; + delete headers["x-robots-tag"]; + delete headers["x-permitted-cross-domain-policies"]; + delete headers["server"]; + delete headers["x-powered-by"]; + delete headers["via"]; + delete headers["x-generator"]; + delete headers["x-aspnet-version"]; +} + +function buildHeartbeatScript(token) { + const safeToken = JSON.stringify(String(token || "")); + return ``; +} + +function createProxyMiddleware() { + const DB_ACCESS_PREFIX = "/db-access/"; + + return function dbProxyMiddleware(req, res, next) { + if (!req.url.startsWith(DB_ACCESS_PREFIX)) return next(); + + // Parse: /db-access//... + const withoutPrefix = req.url.slice(DB_ACCESS_PREFIX.length); + const slashIdx = withoutPrefix.indexOf("/"); + const token = slashIdx === -1 ? withoutPrefix : withoutPrefix.slice(0, slashIdx); + const remainingPath = slashIdx === -1 ? "/" : withoutPrefix.slice(slashIdx); + + const sess = validateToken(token); + if (!sess) { res.status(404).end(); return; } + + const requestIp = req.ip || req.connection?.remoteAddress || ""; + const requestSessionId = req.sessionID ? String(req.sessionID) : ""; + const requestUser = req.session?.user ? String(req.session.user) : ""; + const sessionMatched = !!( + sess.sessionId && + requestSessionId && + sess.sessionId === requestSessionId && + requestUser && + requestUser === sess.username + ); + + if (!sessionMatched && !isIpAuthorized(requestIp, sess.userIp)) { + res.status(404).end(); + return; + } + + // Sliding TTL while actively used so refreshes in an active session keep working. + touchToken(token); + + const target = SERVICE_TARGETS[sess.service]; + if (!target) { res.status(404).end(); return; } + + const tokenPath = DB_ACCESS_PREFIX + token + "/"; + const proxyPath = target.backendPath + (remainingPath === "/" ? "/" : remainingPath); + + // Rewrite cookies coming from the browser: change tokenPath back to backendPath + const incomingCookie = req.headers["cookie"]; + if (incomingCookie) { + req.headers["cookie"] = incomingCookie; + } + + const proxyHeaders = Object.assign({}, req.headers); + delete proxyHeaders["connection"]; + delete proxyHeaders["upgrade"]; + if (sess.service === "phpmyadmin") { + proxyHeaders["host"] = "127.0.0.1:" + PHPMYADMIN_INTERNAL_PORT; + } + + // Request uncompressed content for text so we can rewrite paths + const likelyText = req.method === "GET" && ( + remainingPath === "/" || + remainingPath.endsWith(".php") || + remainingPath.endsWith(".html") || + !remainingPath.includes(".") + ); + if (likelyText) { + proxyHeaders["accept-encoding"] = "identity"; + } + + const proxyOpts = { + hostname: target.host, + port: target.port, + path: proxyPath, + method: req.method, + headers: proxyHeaders, + timeout: 300000 + }; + + const proxyReq = httpMod.request(proxyOpts, (proxyRes) => { + // Rewrite Location headers + const location = proxyRes.headers["location"]; + if (location) { + let rewritten = location; + if (sess.service === "phpmyadmin" && location.includes("/phpmyadmin")) { + rewritten = location.replace(/\/phpmyadmin/g, DB_ACCESS_PREFIX + token); + } else if (sess.service === "pgadmin") { + if (location.includes("/pgadmin4")) { + rewritten = location.replace(/\/pgadmin4/g, DB_ACCESS_PREFIX + token); + } else if (location.includes("/pgadmin")) { + rewritten = location.replace(/\/pgadmin/g, DB_ACCESS_PREFIX + token); + } + } + proxyRes.headers["location"] = rewritten; + } + + // Rewrite Set-Cookie paths so cookies work on the proxy URL + rewriteCookiePaths(proxyRes.headers, target.backendPath, tokenPath); + // Remove upstream security headers to avoid conflicts with our proxy + stripUpstreamSecurityHeaders(proxyRes.headers); + + // Clear any headers previously set by Express middleware (helmet, etc.) + // to prevent them from leaking into the proxied response + const prevHeaders = res.getHeaderNames ? res.getHeaderNames() : []; + for (const h of prevHeaders) res.removeHeader(h); + + const respContentType = (proxyRes.headers["content-type"] || "").toLowerCase(); + const isHtmlContent = respContentType.includes("text/html"); + const isTextContent = respContentType.includes("text/html") || respContentType.includes("javascript") || respContentType.includes("text/css"); + + if (isTextContent) { + delete proxyRes.headers["content-length"]; + const encoding = proxyRes.headers["content-encoding"]; + delete proxyRes.headers["content-encoding"]; + + res.writeHead(proxyRes.statusCode, proxyRes.headers); + + const chunks = []; + let totalSize = 0; + const MAX_REWRITE_SIZE = 5 * 1024 * 1024; + + proxyRes.on("data", (chunk) => { + totalSize += chunk.length; + if (totalSize <= MAX_REWRITE_SIZE) chunks.push(chunk); + }); + proxyRes.on("end", () => { + let body = Buffer.concat(chunks); + if (encoding === "gzip") { + try { body = require("zlib").gunzipSync(body); } catch { /* use as-is */ } + } else if (encoding === "deflate") { + try { body = require("zlib").inflateSync(body); } catch { /* use as-is */ } + } + let text = body.toString("utf8"); + if (sess.service === "pgadmin") { + text = text.replace(/\/pgadmin4\//g, tokenPath); + text = text.replace(/"\/pgadmin4"/g, '"' + DB_ACCESS_PREFIX + token + '"'); + text = text.replace(/'\/pgadmin4'/g, "'" + DB_ACCESS_PREFIX + token + "'"); + } else if (sess.service === "phpmyadmin") { + text = text.replace(/\/phpmyadmin\//g, tokenPath); + text = text.replace(/"\/phpmyadmin"/g, '"' + DB_ACCESS_PREFIX + token + '"'); + text = text.replace(/'\/phpmyadmin'/g, "'" + DB_ACCESS_PREFIX + token + "'"); + } + + if (isHtmlContent) { + const hb = buildHeartbeatScript(token); + if (/<\/body>/i.test(text)) { + text = text.replace(/<\/body>/i, hb + ""); + } else { + text += hb; + } + } + + res.end(text); + }); + proxyRes.on("error", () => res.end()); + } else { + // Stream directly — no buffering + res.writeHead(proxyRes.statusCode, proxyRes.headers); + proxyRes.pipe(res, { end: true }); + } + }); + + proxyReq.on("error", (err) => { + console.error("[db-proxy] Proxy error:", err.message); + if (!res.headersSent) res.status(502).end(); + }); + + proxyReq.on("timeout", () => { + proxyReq.destroy(); + if (!res.headersSent) res.status(504).end(); + }); + + req.pipe(proxyReq, { end: true }); + }; +} + +// ─── Stats ────────────────────────────────────────────────────── +function getSessionCount() { + return sessions.size; +} + +module.exports = { + generateToken, + validateToken, + touchToken, + revokeToken, + revokeAllForUser, + createProxyMiddleware, + getSessionCount, + normalizeIp, + isIpAuthorized, + SERVICE_TARGETS, + TOKEN_TTL_MS, + PHPMYADMIN_INTERNAL_PORT +}; diff --git a/utils/memory-scaling.js b/utils/memory-scaling.js new file mode 100644 index 0000000..b09f78b --- /dev/null +++ b/utils/memory-scaling.js @@ -0,0 +1,21 @@ +"use strict"; + +const os = require("os"); + +const TOTAL_MEM_BYTES = os.totalmem(); +const BASELINE_MEM_BYTES = 4 * 1024 * 1024 * 1024; // 4 GB reference +const MEM_SCALE = Math.min(1.0, Math.max(0.125, TOTAL_MEM_BYTES / BASELINE_MEM_BYTES)); +const LOW_MEMORY = TOTAL_MEM_BYTES <= 1024 * 1024 * 1024; // ≤1 GB + +/** + * Scale a capacity value proportionally to available system RAM. + * On 4 GB the value is unchanged; on 512 MB it shrinks to 1/8th. + * @param {number} base - The baseline value (tuned for a 4 GB box). + * @param {number} [floor=10] - Minimum value to return. + * @returns {number} + */ +function scaleForMemory(base, floor = 10) { + return Math.max(floor, Math.round(base * MEM_SCALE)); +} + +module.exports = { scaleForMemory, MEM_SCALE, LOW_MEMORY, TOTAL_MEM_BYTES }; diff --git a/utils/server-asset-apply.js b/utils/server-asset-apply.js new file mode 100644 index 0000000..8c6a1ff --- /dev/null +++ b/utils/server-asset-apply.js @@ -0,0 +1,261 @@ +"use strict"; + +const crypto = require("crypto"); +const fs = require("fs"); +const fsp = require("fs/promises"); +const httpMod = require("http"); +const https = require("https"); +const os = require("os"); +const path = require("path"); +const FormData = require("form-data"); +const { getTechnicalServerName } = require("./server-name"); + +function safeJoinUnix(baseDir, rel) { + const base = path.posix.normalize(String(baseDir || "")).replace(/\0/g, ""); + const raw = String(rel || "").replace(/\0/g, ""); + if (path.posix.isAbsolute(raw)) { + throw new Error("Absolute path not allowed"); + } + const normalized = path.posix.normalize(`/${raw}`).replace(/^\/+/, ""); + if (normalized === ".." || normalized.startsWith("../") || normalized.includes("/../")) { + throw new Error("Path traversal detected"); + } + return path.posix.join(base, normalized); +} + +async function uploadFileToNode({ + node, + uploadUrl, + headers, + filePath, + filename, + targetDir, +}) { + const form = new FormData(); + form.append("dir", targetDir); + form.append("file", fs.createReadStream(filePath), { filename }); + + const requestHeaders = Object.assign({}, headers); + delete requestHeaders["Content-Type"]; + Object.assign(requestHeaders, form.getHeaders()); + + const parsedUrl = new URL(uploadUrl); + const lib = uploadUrl.startsWith("https:") ? https : httpMod; + + await new Promise((resolve, reject) => { + const req = lib.request({ + method: "POST", + hostname: parsedUrl.hostname, + port: parsedUrl.port || (uploadUrl.startsWith("https:") ? 443 : 80), + path: parsedUrl.pathname + parsedUrl.search, + headers: requestHeaders, + timeout: 600_000, + }, (res) => { + const chunks = []; + let total = 0; + res.on("data", (chunk) => { + if (total < 65_536) { + chunks.push(chunk); + total += chunk.length; + } + }); + res.on("end", () => { + if (res.statusCode === 200) { + resolve(); + return; + } + const body = Buffer.concat(chunks).toString().slice(0, 2000); + const error = new Error(`Node upload failed: ${res.statusCode} ${body}`); + error.nodeStatusCode = res.statusCode; + error.nodeBody = body; + reject(error); + }); + }); + + req.on("error", reject); + req.on("timeout", () => { + req.destroy(); + reject(new Error("Upload request timed out")); + }); + form.pipe(req); + }); +} + +async function applyRemoteAssetToServer(deps, { serverName, entry, url, destPath }) { + if (!deps || typeof deps !== "object") { + throw new Error("Asset apply dependencies are required."); + } + + const bot = String(serverName || entry?.name || "").trim(); + if (!bot) { + return { ok: false, statusCode: 400, error: "missing-bot" }; + } + + const resolvedEntry = entry || (typeof deps.findServer === "function" ? await deps.findServer(bot) : null); + if (!resolvedEntry) { + return { ok: false, statusCode: 404, error: "server-not-found" }; + } + if (!deps.isRemoteEntry(resolvedEntry)) { + return { ok: false, statusCode: 400, error: "server-not-on-node" }; + } + + const node = await deps.findNodeByIdOrName(resolvedEntry.nodeId); + if (!node) { + return { ok: false, statusCode: 400, error: "node-not-found" }; + } + + const underCloudflare = typeof deps.nodeUnderCloudflare === "function" + ? deps.nodeUnderCloudflare(node) + : !!node.under_cloudflare; + const baseUrl = deps.buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, underCloudflare); + if (!baseUrl) { + return { ok: false, statusCode: 400, error: "invalid-node-address" }; + } + + const headers = deps.nodeAuthHeadersFor(node, true); + const technicalName = getTechnicalServerName(resolvedEntry, bot); + + let safeUrl = String(url || "").trim(); + if (!safeUrl) { + return { ok: false, statusCode: 400, error: "missing-url" }; + } + + try { + const validated = await deps.assertSafeRemoteUrl(safeUrl); + safeUrl = validated.toString(); + } catch { + return { ok: false, statusCode: 400, error: "invalid-url" }; + } + + let destRel = String(destPath || "").trim(); + if (!destRel) destRel = "server.jar"; + destRel = destRel.replace(/^\/+/, ""); + if (destRel.includes("..") || destRel.includes("\\")) { + return { ok: false, statusCode: 400, error: "invalid-destPath" }; + } + + const destFile = path.posix.basename(destRel); + if (!destFile || destFile === "." || destFile === "..") { + return { ok: false, statusCode: 400, error: "invalid-destPath" }; + } + + if (deps.remoteApplyProxyDownload) { + const ctx = await deps.resolveRemoteFsContext(bot); + if (!ctx.remote || !ctx.node) { + return { ok: false, statusCode: 404, error: "server-not-on-node" }; + } + + try { + const pingRes = await deps.nodeFsPost(ctx.node, "/v1/fs/list", { path: ctx.baseDir, depth: 0 }, 5000); + if (pingRes.status === 401) { + return { + ok: false, + statusCode: 502, + error: "node-auth-failed", + detail: "Token mismatch. Re-deploy config.yml to the node.", + }; + } + if (pingRes.status === 0) { + return { + ok: false, + statusCode: 502, + error: "node-unreachable", + detail: "Cannot connect to node agent.", + }; + } + } catch { + } + + let buffer; + try { + buffer = await deps.httpGetRaw(safeUrl, { + maxBytes: deps.remoteApplyMaxBytes, + timeoutMs: deps.remoteApplyTimeoutMs, + maxRedirects: deps.remoteFetchMaxRedirects, + }); + } catch { + return { ok: false, statusCode: 400, error: "remote-download-failed" }; + } + + let targetDir = ctx.baseDir; + try { + const destDirRel = path.posix.dirname(destRel); + targetDir = safeJoinUnix(ctx.baseDir, destDirRel === "." ? "" : destDirRel); + } catch { + return { ok: false, statusCode: 400, error: "invalid-destPath" }; + } + + const tmpFile = path.join(os.tmpdir(), `adpanel-apply-${crypto.randomBytes(8).toString("hex")}`); + try { + await fsp.writeFile(tmpFile, buffer); + const uploadUrl = `${baseUrl}/v1/fs/upload`; + await uploadFileToNode({ + node: ctx.node, + uploadUrl, + headers, + filePath: tmpFile, + filename: destFile, + targetDir, + }); + return { ok: true, remote: true, msg: "downloaded-and-uploaded", destPath: destRel }; + } catch (error) { + const detail = error.message || "stream-upload-failed"; + if (error.nodeStatusCode === 507) { + try { + const nodeJson = JSON.parse(error.nodeBody); + if (nodeJson.error === "disk_limit_exceeded") { + return Object.assign({ ok: false, statusCode: 507 }, nodeJson); + } + } catch { + } + } + if (detail.includes("401")) { + return { + ok: false, + statusCode: 502, + error: "node-auth-failed", + detail: "Token mismatch. Re-deploy config.yml to the node.", + }; + } + return { ok: false, statusCode: 502, error: "node_upload_failed", detail }; + } finally { + try { + await fsp.unlink(tmpFile); + } catch { + } + } + } + + const forwardUrl = `${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/apply-version`; + const response = await deps.httpRequestJson( + forwardUrl, + "POST", + headers, + { url: safeUrl, nodeId: resolvedEntry.nodeId, destPath: destRel }, + 60_000 + ); + + if (response.status === 507 && response.json?.error === "disk_limit_exceeded") { + return Object.assign({ ok: false, statusCode: 507 }, response.json); + } + if (response.status !== 200 || !(response.json && response.json.ok)) { + const detail = response.json && (response.json.detail || response.json.error) + ? (response.json.detail || response.json.error) + : `node-status-${response.status}`; + if (response.status === 401 || response.status === 403) { + return { + ok: false, + statusCode: 502, + error: "node-auth-failed", + detail: "Token or HMAC mismatch. Re-deploy config.yml to the node.", + }; + } + return { ok: false, statusCode: 502, error: detail || `node-forward-failed-${response.status}` }; + } + + return { ok: true, remote: true, msg: "forwarded-to-node", destPath: destRel }; +} + +module.exports = { + applyRemoteAssetToServer, +}; diff --git a/utils/server-delete.js b/utils/server-delete.js new file mode 100644 index 0000000..85f2814 --- /dev/null +++ b/utils/server-delete.js @@ -0,0 +1,95 @@ +"use strict"; + +const { getTechnicalServerName } = require("./server-name"); + +async function deleteServerByName(deps, rawName) { + if (!deps || typeof deps !== "object") { + throw new Error("Server delete dependencies are required."); + } + + let nameParam = rawName || ""; + try { + nameParam = decodeURIComponent(nameParam); + } catch { + } + + const name = String(nameParam || "").trim(); + if (!name) { + return { ok: false, statusCode: 400, error: "missing name" }; + } + + const entry = await deps.findServer(name); + if (!entry) { + await deps.deleteServerSchedules(name); + await deps.removeServerIndexEntry(name); + return { ok: true }; + } + const technicalName = getTechnicalServerName(entry, name); + + if (!deps.isRemoteEntry(entry)) { + return { ok: false, statusCode: 400, error: "server-not-on-node" }; + } + + const node = await deps.findNodeByIdOrName(entry.nodeId); + if (!node) { + return { ok: false, statusCode: 400, error: "node not found for server" }; + } + + const underCloudflare = typeof deps.nodeUnderCloudflare === "function" + ? deps.nodeUnderCloudflare(node) + : !!node.under_cloudflare; + const baseUrl = deps.buildNodeBaseUrl(node.address, node.api_port || 8080, node.ssl_enabled, underCloudflare); + if (!baseUrl) { + return { ok: false, statusCode: 400, error: "invalid node address" }; + } + + 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}`); + } + + 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}`); + } + } + } catch (error) { + console.log(`[delete] Could not delete backups for ${name}: ${error.message}`); + } + + 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 }; + } + + try { + await deps.removeAccessForServerName(name); + } catch { + } + + await deps.removeServerIndexEntry(name); + return { ok: true, remote: true }; +} + +module.exports = { + deleteServerByName, +}; diff --git a/utils/server-name.js b/utils/server-name.js new file mode 100644 index 0000000..aed8d67 --- /dev/null +++ b/utils/server-name.js @@ -0,0 +1,57 @@ +"use strict"; + +function sanitizeServerToken(raw) { + let name = String(raw || "").trim(); + if (!name) return ""; + if (name.includes("..") || /[\/\\]/.test(name) || name.length > 120) return ""; + name = name.replace(/\s+/g, "-").replace(/[^\w\-_.]/g, "").replace(/^-+|-+$/g, ""); + return name; +} + +function getCanonicalServerName(entry, fallback = "") { + return sanitizeServerToken(entry?.name || fallback || ""); +} + +function getTechnicalServerName(entry, fallback = "") { + const technical = sanitizeServerToken(entry?.bot || ""); + if (technical) return technical; + return getCanonicalServerName(entry, fallback); +} + +function escapeRegExp(value) { + return String(value || "").replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} + +function rewriteStartupCommandServerName(command, oldName, newName) { + const cleanCommand = String(command || "").trim(); + const cleanOldName = sanitizeServerToken(oldName); + const cleanNewName = sanitizeServerToken(newName); + + if (!cleanCommand || !cleanOldName || !cleanNewName || cleanOldName === cleanNewName) { + return cleanCommand; + } + + const escapedOld = escapeRegExp(cleanOldName); + const patterns = [ + new RegExp(`(^|\\s)(--name\\s+)(["']?)${escapedOld}\\3(?=\\s|$)`, "g"), + new RegExp(`(^|\\s)(--name=)(["']?)${escapedOld}\\3(?=\\s|$)`, "g"), + new RegExp(`(^|\\s)(container_name=)(["']?)${escapedOld}\\3(?=\\s|$)`, "g"), + ]; + + let rewritten = cleanCommand; + for (const pattern of patterns) { + rewritten = rewritten.replace(pattern, (_match, prefix, flag, quote) => { + const safeQuote = quote || ""; + return `${prefix}${flag}${safeQuote}${cleanNewName}${safeQuote}`; + }); + } + + return rewritten; +} + +module.exports = { + getCanonicalServerName, + getTechnicalServerName, + rewriteStartupCommandServerName, + sanitizeServerToken, +}; diff --git a/utils/server-startup-command.js b/utils/server-startup-command.js new file mode 100644 index 0000000..6d6d1d8 --- /dev/null +++ b/utils/server-startup-command.js @@ -0,0 +1,507 @@ +"use strict"; + +const { sanitizeServerToken } = require("./server-name"); + +function cleanString(value) { + return String(value || "").trim(); +} + +function toPositiveNumber(value) { + const numeric = Number(value); + return Number.isFinite(numeric) && numeric > 0 ? numeric : 0; +} + +function parseStrictPort(value) { + if (value === undefined || value === null) return null; + if (typeof value === "number") { + if (!Number.isInteger(value) || value < 1 || value > 65535) return null; + return value; + } + const str = cleanString(value); + if (!/^[1-9]\d{0,4}$/.test(str)) return null; + const numeric = Number(str); + if (!Number.isInteger(numeric) || numeric < 1 || numeric > 65535) return null; + return numeric; +} + +function parseShellArgs(input) { + const src = cleanString(input); + const args = []; + let current = ""; + let quote = ""; + let escapeNext = false; + + for (let i = 0; i < src.length; i++) { + const ch = src[i]; + if (escapeNext) { + current += ch; + escapeNext = false; + continue; + } + if (ch === "\\") { + escapeNext = true; + continue; + } + if (quote) { + if (ch === quote) { + quote = ""; + } else { + current += ch; + } + continue; + } + if (ch === '"' || ch === "'") { + quote = ch; + continue; + } + if (ch === " " || ch === "\t" || ch === "\n" || ch === "\r") { + if (current) { + args.push(current); + current = ""; + } + continue; + } + current += ch; + } + + if (current) args.push(current); + return args; +} + +function extractHostPortFromMapping(mapping) { + let value = cleanString(mapping); + const slashIdx = value.indexOf("/"); + if (slashIdx >= 0) value = value.slice(0, slashIdx); + const parts = value.split(":"); + if (parts.length === 2) return parseStrictPort(parts[0]) || 0; + if (parts.length === 3) return parseStrictPort(parts[1]) || 0; + return 0; +} + +function normalizeDockerImage(raw) { + let image = cleanString(raw); + if (!image) return ""; + const digestIdx = image.indexOf("@"); + if (digestIdx > 0) image = image.slice(0, digestIdx); + const tagIdx = image.lastIndexOf(":"); + if (tagIdx > 0) { + const afterColon = image.slice(tagIdx + 1); + if (!afterColon.includes("/")) image = image.slice(0, tagIdx); + } + image = image.toLowerCase().replace(/^docker\.io\//, "").replace(/^index\.docker\.io\//, ""); + if (!image.includes("/")) image = `library/${image}`; + return image; +} + +const DOCKER_RUN_FLAGS_WITH_VALUE = new Set([ + "-e", "--env", "-v", "--volume", "-p", "--publish", "-w", "--workdir", + "--name", "-m", "--memory", "--cpus", "--memory-swap", "--memory-reservation", "--cpu-period", "--cpu-quota", + "-u", "--user", "-h", "--hostname", "--network", "--net", "--restart", + "-l", "--label", "--entrypoint", "--mount", "--tmpfs", "--device", + "--pid", "--ipc", "--userns", "--uts", "--cgroupns", "--shm-size", + "--ulimit", "--dns", "--dns-search", "--add-host", "--log-driver", "--log-opt", + "--stop-signal", "--stop-timeout", "--health-cmd", "--health-interval", + "--health-retries", "--health-timeout", "--runtime", "--platform", "--pull", + "--ip", "--ip6", "--mac-address", "--expose", "--link", "--cidfile", +]); + +const DOCKER_RUN_SAFE_STANDALONE_FLAGS = new Set([ + "-d", "--detach", "-i", "--interactive", "-t", "--tty", "--rm", "--init", "--read-only", +]); + +const DOCKER_RUN_BLOCKED_FLAGS = new Set([ + "--privileged", + "--cap-add", + "--cap-drop", + "--security-opt", + "--volumes-from", + "--env-file", + "--device", + "--device-cgroup-rule", + "--sysctl", + "--oom-kill-disable", + "--oom-score-adj", +]); + +const DOCKER_RUN_HOST_NAMESPACE_FLAGS = new Set([ + "--network", "--net", "--pid", "--userns", "--ipc", "--uts", "--cgroupns", +]); + +function isSafeShortDockerFlagCluster(flag) { + return /^-[dit]+$/i.test(flag); +} + +function readDockerFlagValue(args, index, inlineValue) { + if (inlineValue) return { value: inlineValue, nextIndex: index }; + if (index + 1 >= args.length) return { value: "", nextIndex: index }; + return { value: args[index + 1], nextIndex: index + 1 }; +} + +function extractDockerImageFromCommand(cmdStr) { + const cmd = cleanString(cmdStr); + if (!/^docker run(?:\s|$)/i.test(cmd)) return ""; + const args = parseShellArgs(cmd.slice("docker run".length).trim()); + for (let i = 0; i < args.length; i++) { + const token = cleanString(args[i]); + if (!token) continue; + const tokenLower = token.toLowerCase(); + if (!tokenLower.startsWith("-")) return token; + + let flagName = tokenLower; + let inlineValue = ""; + if (tokenLower.startsWith("--") && tokenLower.includes("=")) { + const cutIdx = tokenLower.indexOf("="); + flagName = tokenLower.slice(0, cutIdx); + inlineValue = token.slice(cutIdx + 1); + } + + if (isSafeShortDockerFlagCluster(flagName) || DOCKER_RUN_SAFE_STANDALONE_FLAGS.has(flagName)) { + continue; + } + if (DOCKER_RUN_FLAGS_WITH_VALUE.has(flagName)) { + const valueInfo = readDockerFlagValue(args, i, inlineValue); + i = valueInfo.nextIndex; + } + } + return ""; +} + +function validateDockerRunCommandSafety(command, options = {}) { + const cmd = cleanString(command); + if (!cmd) return null; + if (!/^docker run(?:\s|$)/i.test(cmd)) { + return "Startup command must start with 'docker run'."; + } + if (/[\u0000-\u0008\u000B\u000C\u000E-\u001F]/.test(cmd)) { + return "Startup command contains unsupported control characters."; + } + + const allowedHostPorts = new Set( + (Array.isArray(options.allowedHostPorts) ? options.allowedHostPorts : []) + .map((entry) => parseStrictPort(entry)) + .filter((entry) => entry != null) + ); + const reservedHostPorts = new Set( + (Array.isArray(options.reservedHostPorts) ? options.reservedHostPorts : []) + .map((entry) => parseStrictPort(entry)) + .filter((entry) => entry != null) + ); + const expectedImageRef = cleanString(options.expectedImageRef); + const args = parseShellArgs(cmd.slice("docker run".length).trim()); + + for (let i = 0; i < args.length; i++) { + const token = cleanString(args[i]); + if (!token) continue; + const tokenLower = token.toLowerCase(); + + if (!tokenLower.startsWith("-")) { + if (expectedImageRef) { + const normalizedExpected = normalizeDockerImage(expectedImageRef); + const normalizedCommand = normalizeDockerImage(token); + if (normalizedExpected && normalizedCommand && normalizedExpected !== normalizedCommand) { + return `The Docker image in the startup command (${token}) does not match the configured image (${expectedImageRef}).`; + } + } + return null; + } + + let flagName = tokenLower; + let inlineValue = ""; + if (tokenLower.startsWith("--") && tokenLower.includes("=")) { + const cutIdx = tokenLower.indexOf("="); + flagName = tokenLower.slice(0, cutIdx); + inlineValue = token.slice(cutIdx + 1); + } + + if (DOCKER_RUN_BLOCKED_FLAGS.has(flagName)) { + return `Blocked dangerous Docker flag: ${flagName}`; + } + + if (flagName === "--mount") { + const valueInfo = readDockerFlagValue(args, i, inlineValue); + const mountValue = cleanString(valueInfo.value).toLowerCase(); + if (!mountValue) return "Docker flag --mount requires a value."; + if (mountValue.includes("type=bind")) { + return "Blocked dangerous Docker flag: --mount with bind"; + } + i = valueInfo.nextIndex; + continue; + } + + if (flagName === "--tmpfs") { + const valueInfo = readDockerFlagValue(args, i, inlineValue); + const tmpfsValue = cleanString(valueInfo.value).toLowerCase(); + if (!tmpfsValue) return "Docker flag --tmpfs requires a value."; + if (tmpfsValue.includes("exec")) { + return "Blocked dangerous Docker flag: --tmpfs with exec"; + } + i = valueInfo.nextIndex; + continue; + } + + if (DOCKER_RUN_HOST_NAMESPACE_FLAGS.has(flagName)) { + const valueInfo = readDockerFlagValue(args, i, inlineValue); + const nsMode = cleanString(valueInfo.value).toLowerCase(); + if (!nsMode) return `Docker flag ${flagName} requires a value.`; + if (nsMode === "host") { + return `Blocked dangerous Docker flag: ${flagName}=host`; + } + i = valueInfo.nextIndex; + continue; + } + + if (flagName === "-p" || flagName === "--publish" || flagName === "-p=" || flagName === "--publish=") { + const valueInfo = readDockerFlagValue(args, i, inlineValue); + const mapping = cleanString(valueInfo.value); + if (!mapping) return "Docker publish flag is missing a port mapping."; + if (!mapping.includes("{PORT}")) { + const hostPort = extractHostPortFromMapping(mapping); + if (!hostPort) return `Invalid Docker port mapping: ${mapping}`; + if (!allowedHostPorts.has(hostPort)) { + return 'Port config through docker edit command is not allowed. Add or remove a port through Port Management.'; + } + if (reservedHostPorts.has(hostPort)) { + return `Port ${hostPort} in the Docker command conflicts with a port forwarding rule.`; + } + } + i = valueInfo.nextIndex; + continue; + } + + if (isSafeShortDockerFlagCluster(flagName) || DOCKER_RUN_SAFE_STANDALONE_FLAGS.has(flagName)) { + continue; + } + + if (DOCKER_RUN_FLAGS_WITH_VALUE.has(flagName)) { + const valueInfo = readDockerFlagValue(args, i, inlineValue); + if (!cleanString(valueInfo.value)) { + return `Docker flag ${flagName} requires a value.`; + } + i = valueInfo.nextIndex; + continue; + } + + return `Unsupported Docker flag in startup command: ${flagName}`; + } + + return "Startup command must include a Docker image."; +} + +function getDockerImageRef(docker) { + const image = cleanString(docker?.image); + if (!image) return ""; + const tag = cleanString(docker?.tag) || "latest"; + return `${image}:${tag}`; +} + +function resolveTemplateDockerConfig(source) { + if (!source || typeof source !== "object") return null; + + if (source.docker && typeof source.docker === "object") { + return source.docker; + } + + const image = cleanString(source.image || source.dockerImage); + const tag = cleanString(source.tag || source.dockerTag); + const command = cleanString(source.command); + const startupCommand = cleanString(source.startupCommand); + const restart = cleanString(source.restart || source.restartPolicy); + const ports = Array.isArray(source.ports) ? source.ports : []; + const volumes = Array.isArray(source.volumes) ? source.volumes : []; + const env = source.env && typeof source.env === "object" && !Array.isArray(source.env) ? source.env : {}; + + if (!image && !tag && !command && !startupCommand && !restart && !ports.length && !volumes.length && !Object.keys(env).length) { + return null; + } + + return { + image, + tag, + command, + startupCommand, + restart, + ports, + volumes, + env, + }; +} + +function normalizeStartupCommandForCreate(command, docker) { + const cleanCommand = cleanString(command); + if (!cleanCommand) return ""; + const imageRef = getDockerImageRef(resolveTemplateDockerConfig(docker) || docker); + if (!imageRef) return cleanCommand; + return cleanCommand.replace(/\{IMAGE\}/gi, imageRef).trim(); +} + +function getDockerVolumes(docker, templateId) { + const configuredVolumes = Array.isArray(docker?.volumes) + ? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean) + : []; + if (configuredVolumes.length) { + return configuredVolumes; + } + + const normalizedTemplateId = cleanString(templateId).toLowerCase(); + if (["nodejs", "discord-bot", "python", "runtime"].includes(normalizedTemplateId)) { + return ["{DATA_DIR}:/app"]; + } + return ["{DATA_DIR}:/data"]; +} + +function getRuntimeCommand(templateId, docker, startFile) { + const explicit = cleanString(docker?.command); + if (explicit) return explicit; + + const normalizedTemplateId = cleanString(templateId).toLowerCase(); + const resolvedStartFile = cleanString(startFile); + if (normalizedTemplateId === "python") { + return `python /app/${resolvedStartFile || "main.py"}`; + } + if (normalizedTemplateId === "nodejs" || normalizedTemplateId === "discord-bot") { + return `cd /app && npm install && node /app/${resolvedStartFile || "index.js"}`; + } + return ""; +} + +function getContainerPort(templateId, docker, hostPort) { + const normalizedTemplateId = cleanString(templateId).toLowerCase(); + if (["nodejs", "discord-bot", "python", "runtime"].includes(normalizedTemplateId)) { + return toPositiveNumber(hostPort); + } + + const ports = Array.isArray(docker?.ports) ? docker.ports : []; + for (const entry of ports) { + const port = toPositiveNumber(entry); + if (port > 0) return port; + } + return toPositiveNumber(hostPort); +} + +function buildResourceArgs(resources) { + const args = []; + const ramMb = toPositiveNumber(resources?.ramMb); + const cpuCores = toPositiveNumber(resources?.cpuCores); + + if (ramMb > 0) { + args.push("--memory", `${Math.floor(ramMb)}m`); + args.push("--memory-reservation", `${Math.max(1, Math.floor((ramMb * 90) / 100))}m`); + } + + if (cpuCores > 0) { + args.push("--cpus", String(cpuCores)); + } + + return args; +} + +function buildDefaultStartupCommand({ name, templateId, docker, hostPort, resources, startFile }) { + const normalizedTemplateId = cleanString(templateId).toLowerCase(); + if (!docker || typeof docker !== "object") return ""; + if (normalizedTemplateId === "minecraft") return ""; + + const imageRef = getDockerImageRef(docker); + if (!imageRef) return ""; + + 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"]; + + parts.push(...buildResourceArgs(resources)); + + if (externalPort > 0 && containerPort > 0) { + parts.push("-p", `${externalPort}:${containerPort}`); + } + + for (const volume of getDockerVolumes(docker, normalizedTemplateId)) { + parts.push("-v", volume); + } + + const env = docker?.env && typeof docker.env === "object" ? docker.env : {}; + for (const [key, value] of Object.entries(env)) { + const envKey = cleanString(key); + if (!envKey) continue; + parts.push("-e", `${envKey}=${String(value ?? "")}`); + } + if (externalPort > 0) { + parts.push("-e", `PORT=${externalPort}`); + } + + parts.push(imageRef); + + const runtimeCommand = getRuntimeCommand(normalizedTemplateId, docker, startFile); + if (runtimeCommand) { + parts.push("sh", "-lc", JSON.stringify(runtimeCommand)); + } + + return parts.join(" ").trim(); +} + +function resolveStartupCommandForCreate({ requestedStartupCommand, template, templateId, name, hostPort, resources, startFile }) { + const templateDocker = resolveTemplateDockerConfig(template); + const requested = normalizeStartupCommandForCreate(requestedStartupCommand, templateDocker); + if (requested) return requested; + + const templateStartupCommand = normalizeStartupCommandForCreate(templateDocker?.startupCommand, templateDocker); + if (templateStartupCommand) return templateStartupCommand; + + return buildDefaultStartupCommand({ + name, + templateId: templateId || template?.id || "", + docker: templateDocker, + hostPort, + resources, + startFile, + }); +} + +function extractStartupCommandFromNodeCreateResult(result) { + if (!result || typeof result !== "object") return ""; + + const direct = cleanString(result.startupCommand); + if (direct) return direct; + + const metaStartup = cleanString(result.meta?.startupCommand); + if (metaStartup) return metaStartup; + + const runtimeStartup = cleanString(result.meta?.runtime?.startupCommand); + if (runtimeStartup) return runtimeStartup; + + return ""; +} + +function extractTechnicalServerNameFromNodeCreateResult(result, fallback = "") { + const candidates = [ + result?.technicalName, + result?.serverTechnicalName, + result?.server?.technicalName, + result?.meta?.technicalName, + result?.meta?.serverTechnicalName, + result?.meta?.server?.technicalName, + result?.serverName, + result?.server?.name, + result?.name, + result?.meta?.serverName, + result?.meta?.server?.name, + result?.meta?.name, + result?.created?.technicalName, + result?.created?.serverName, + result?.created?.name, + fallback, + ]; + + for (const candidate of candidates) { + const sanitized = sanitizeServerToken(candidate); + if (sanitized) return sanitized; + } + return ""; +} + +module.exports = { + buildDefaultStartupCommand, + resolveStartupCommandForCreate, + extractStartupCommandFromNodeCreateResult, + extractTechnicalServerNameFromNodeCreateResult, + validateDockerRunCommandSafety, +}; diff --git a/utils/server-template-payload.js b/utils/server-template-payload.js new file mode 100644 index 0000000..e78e65a --- /dev/null +++ b/utils/server-template-payload.js @@ -0,0 +1,149 @@ +"use strict"; + +function cleanString(value) { + return String(value ?? "").trim(); +} + +function cleanScript(value, maxLength = 262144) { + return String(value ?? "") + .replace(/\0/g, "") + .replace(/\r\n?/g, "\n") + .trim() + .slice(0, maxLength); +} + +function toFiniteNumber(value) { + const numeric = Number(value); + return Number.isFinite(numeric) ? numeric : null; +} + +function cleanAbsoluteContainerPath(value, fallback = "") { + let raw = cleanString(value).replace(/\0/g, "").replace(/\\/g, "/"); + if (!raw) return fallback; + if (!raw.startsWith("/")) return fallback; + raw = raw.replace(/\/+/g, "/"); + if (raw.length > 1) raw = raw.replace(/\/+$/, ""); + return raw || fallback; +} + +function sanitizeEnvPayload(env) { + if (!env || typeof env !== "object" || Array.isArray(env)) return null; + const out = {}; + for (const [key, value] of Object.entries(env)) { + const envKey = cleanString(key); + if (!envKey) continue; + out[envKey] = String(value ?? ""); + } + return Object.keys(out).length ? out : null; +} + +function sanitizeDockerInstallPayload(install) { + if (!install || typeof install !== "object" || Array.isArray(install)) return null; + + const script = cleanScript(install.script || install.installScript || install.install_script); + 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" + ); + const runtimePath = cleanAbsoluteContainerPath( + install.runtimePath || install.runtime_path || install.homePath || install.home_path, + "/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 payload = { + image, + script, + entrypoint, + mountPath, + runtimePath, + timeoutSeconds, + }; + if (minimumStorageMb > 0) payload.minimumStorageMb = minimumStorageMb; + + const env = sanitizeEnvPayload(install.env); + if (env) payload.env = env; + + return payload; +} + +function sanitizeDockerTemplatePayload(docker) { + if (!docker || typeof docker !== "object") return null; + + const image = cleanString(docker.image); + if (!image) return null; + + const payload = { + image, + }; + + const tag = cleanString(docker.tag) || "latest"; + if (tag) payload.tag = tag; + + const command = cleanString(docker.command); + if (command) payload.command = command; + + const workdir = cleanString(docker.workdir || docker.workingDir || docker.working_dir); + if (workdir) payload.workdir = workdir; + + const restart = cleanString(docker.restart); + if (restart) payload.restart = restart; + + const restartPolicy = cleanString(docker.restartPolicy); + if (restartPolicy) payload.restartPolicy = restartPolicy; + + const ports = Array.isArray(docker.ports) + ? docker.ports + .map((entry) => { + const port = toFiniteNumber(entry); + return Number.isInteger(port) && port > 0 ? port : null; + }) + .filter((entry) => entry != null) + : []; + if (ports.length) payload.ports = ports; + + const volumes = Array.isArray(docker.volumes) + ? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean) + : []; + if (volumes.length) payload.volumes = volumes; + + const env = sanitizeEnvPayload(docker.env); + if (env && Object.keys(env).length) payload.env = env; + + const adpanelStartup = cleanScript( + docker.adpanelStartup || + docker.adpanel_startup || + docker.pterodactylStartup || + docker.pterodactyl_startup || + docker.startup, + 32768 + ); + if (adpanelStartup) payload.adpanelStartup = adpanelStartup; + + const install = sanitizeDockerInstallPayload(docker.install || docker.installation); + if (install) payload.install = install; + + if (docker.console !== undefined) { + payload.console = docker.console; + } + + return payload; +} + +module.exports = { + sanitizeDockerTemplatePayload, + sanitizeDockerInstallPayload, + sanitizeEnvPayload, +}; diff --git a/utils/stealth.js b/utils/stealth.js new file mode 100644 index 0000000..e9f9606 --- /dev/null +++ b/utils/stealth.js @@ -0,0 +1,114 @@ +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const crypto = require("crypto"); + +const STEALTH_CONFIG_PATH = path.join(__dirname, "..", "data", "stealth.json"); +const DEFAULT_COOKIE_NAME = "adpanel_gate"; +const DEFAULT_STEALTH_CONFIG = { + enabled: true, + cookieName: DEFAULT_COOKIE_NAME, + cookieSecret: "", + cookieTtlDays: 30, + challengeSecret: "", + htmlVariantSalt: "", + createdAt: null, + rotatedAt: null, +}; + +function randomToken(bytes = 32) { + return crypto.randomBytes(bytes).toString("base64url"); +} + +function sanitizeCookieName(value) { + const raw = String(value || "").trim(); + if (!raw) return DEFAULT_COOKIE_NAME; + return /^[A-Za-z0-9._-]{3,64}$/.test(raw) ? raw : DEFAULT_COOKIE_NAME; +} + +function normalizeStealthConfig(input = {}) { + const now = new Date().toISOString(); + const normalized = { + ...DEFAULT_STEALTH_CONFIG, + ...(input && typeof input === "object" ? input : {}), + }; + + normalized.enabled = normalized.enabled !== false; + normalized.cookieName = sanitizeCookieName(normalized.cookieName); + normalized.cookieSecret = String(normalized.cookieSecret || "").trim() || randomToken(48); + + const ttlDays = parseInt(String(normalized.cookieTtlDays || "").trim(), 10); + normalized.cookieTtlDays = Number.isFinite(ttlDays) && ttlDays > 0 ? Math.min(ttlDays, 365) : 30; + + normalized.challengeSecret = String(normalized.challengeSecret || "").trim() || randomToken(48); + normalized.htmlVariantSalt = String(normalized.htmlVariantSalt || "").trim() || randomToken(24); + normalized.createdAt = String(normalized.createdAt || "").trim() || now; + normalized.rotatedAt = String(normalized.rotatedAt || "").trim() || normalized.createdAt; + + return normalized; +} + +function readStealthConfigFile() { + try { + if (!fs.existsSync(STEALTH_CONFIG_PATH)) return null; + const raw = fs.readFileSync(STEALTH_CONFIG_PATH, "utf8"); + return JSON.parse(raw); + } catch (err) { + console.warn("[stealth] Failed to read config:", err.message); + return null; + } +} + +function writeStealthConfigFile(config) { + const normalized = normalizeStealthConfig(config); + const dir = path.dirname(STEALTH_CONFIG_PATH); + fs.mkdirSync(dir, { recursive: true }); + const tmpPath = `${STEALTH_CONFIG_PATH}.tmp`; + fs.writeFileSync(tmpPath, JSON.stringify(normalized, null, 2), { mode: 0o600 }); + fs.renameSync(tmpPath, STEALTH_CONFIG_PATH); + return normalized; +} + +function loadStealthConfig() { + const existing = readStealthConfigFile(); + if (!existing) { + return writeStealthConfigFile(DEFAULT_STEALTH_CONFIG); + } + + const normalized = normalizeStealthConfig(existing); + if (JSON.stringify(existing) !== JSON.stringify(normalized)) { + return writeStealthConfigFile(normalized); + } + return normalized; +} + +function saveStealthConfig(partial) { + const current = loadStealthConfig(); + return writeStealthConfigFile({ + ...current, + ...(partial && typeof partial === "object" ? partial : {}), + }); +} + +function ensureStealthConfig(defaults = {}) { + const current = loadStealthConfig(); + const merged = normalizeStealthConfig({ + ...current, + ...(defaults && typeof defaults === "object" ? defaults : {}), + }); + if (JSON.stringify(current) !== JSON.stringify(merged)) { + return writeStealthConfigFile(merged); + } + return merged; +} + +module.exports = { + DEFAULT_COOKIE_NAME, + DEFAULT_STEALTH_CONFIG, + STEALTH_CONFIG_PATH, + ensureStealthConfig, + loadStealthConfig, + saveStealthConfig, + sanitizeCookieName, +}; diff --git a/versions.json b/versions.json new file mode 100644 index 0000000..6f078f8 --- /dev/null +++ b/versions.json @@ -0,0 +1,278 @@ +{ + "providers": [ + { + "id": "vanilla", + "name": "Vanilla", + "description": "Vanilla Minecraft with no features", + "logo": "https://cdn.freebiesupply.com/logos/large/2x/minecraft-1-logo-png-transparent.png", + "versions": [] + }, + { + "id": "papermc", + "name": "PaperMC", + "description": "Fast, highly optimized Spigot fork with great plugin compatibility.", + "logo": "https://assets.papermc.io/brand/papermc_logo.256.png", + "versions": [] + }, + { + "id": "pufferfish", + "name": "Pufferfish", + "description": "A fork optimized to work on well on every host.", + "logo": "https://s3-eu-west-1.amazonaws.com/tpd/logos/615d0e460899bf001dd4eacb/0x0.png", + "versions": [ + { + "id": "pufferfish-1.21.8", + "name": "1.21.8", + "label": "Pufferfish 1.21.8", + "mcVersion": "1.21.8", + "releaseDate": "2025-09-14", + "tags": [ + "STABLE", + "OPTIMIZED" + ], + "url": "https://ci.pufferfish.host/job/Pufferfish-1.21/33/artifact/pufferfish-server/build/libs/pufferfish-paperclip-1.21.8-R0.1-SNAPSHOT-mojmap.jar" + }, + { + "id": "pufferfish-1.20.4", + "name": "1.20.4", + "label": "Pufferfish 1.20.4", + "mcVersion": "1.20.4", + "releaseDate": "2024-07-06", + "tags": [ + "STABLE", + "OPTIMIZED" + ], + "url": "https://ci.pufferfish.host/job/Pufferfish-1.20/52/artifact/build/libs/pufferfish-paperclip-1.20.4-R0.1-SNAPSHOT-reobf.jar" + }, + { + "id": "pufferfish-1.19.4", + "name": "1.19.4", + "label": "Pufferfish 1.19.4", + "mcVersion": "1.19.4", + "releaseDate": "2023-06-06", + "tags": [ + "STABLE", + "OPTIMIZED" + ], + "url": "https://ci.pufferfish.host/job/Pufferfish-1.19/73/artifact/build/libs/pufferfish-paperclip-1.19.4-R0.1-SNAPSHOT-reobf.jar" + }, + { + "id": "pufferfish-1.18.2", + "name": "1.18.2", + "label": "Pufferfish 1.18.2", + "mcVersion": "1.18.2", + "releaseDate": "2022-06-18", + "tags": [ + "STABLE", + "OPTIMIZED" + ], + "url": "https://ci.pufferfish.host/job/Pufferfish-1.18/72/artifact/build/libs/pufferfish-paperclip-1.18.2-R0.1-SNAPSHOT-reobf.jar" + }, + { + "id": "pufferfish-1.17.1", + "name": "1.17.1", + "label": "Pufferfish 1.17.1", + "mcVersion": "1.17.1", + "releaseDate": "2022-02-02", + "tags": [ + "STABLE", + "OPTIMIZED" + ], + "url": "https://ci.pufferfish.host/job/Pufferfish-1.17/22/artifact/build/libs/Pufferfish-1.17.1-R0.1-SNAPSHOT.jar" + } + ] + }, + { + "id": "purpur", + "name": "Purpur", + "description": "A fork of PaperMC but with more options.", + "logo": "https://purpurmc.org/docs/images/purpur-small.png", + "versions": [ + { + "id": "purpur-1.20.4", + "name": "1.20.4", + "label": "Purpur 1.20.4", + "mcVersion": "1.20.4", + "releaseDate": "2024-03-01", + "tags": [ + "latest", + "feature-rich" + ], + "url": "https://api.purpurmc.org/v2/purpur/1.20.4/latest/download" + } + ] + }, + { + "id": "velocity", + "name": "Velocity", + "description": "A stable way for your proxy and very secure", + "logo": "https://assets.papermc.io/brand/velocity_logo_blue.min.svg", + "versions": [] + }, + { + "id": "waterfall", + "name": "Waterfall", + "description": "A Bungeecord fork from PaperMC", + "logo": "https://static.vecteezy.com/system/resources/previews/009/663/548/non_2x/water-drop-icon-transparent-free-png.png", + "versions": [] + }, + { + "id": "folia", + "name": "Folia", + "description": "A fork of PaperMC optimized for high performance", + "logo": "https://files.catbox.moe/4b3qex.png", + "versions": [] + }, + { + "id": "leaves", + "name": "Leaves", + "description": "A fork of PaperMC balanced in features and performance", + "logo": "https://docs.leavesmc.org/logo.svg", + "versions": [] + }, + { + "id": "nukkit", + "name": "Nukkit", + "description": "The main platform for bedrock servers", + "logo": "https://avatars.githubusercontent.com/u/12780190?s=200&v=4", + "versions": [ + { + "id": "nukkit", + "name": "Nukkit", + "label": "Nukkit", + "mcVersion": "Newest", + "releaseDate": "", + "tags": [ + "LATEST", + "BEDROCK" + ], + "url": "https://repo.opencollab.dev/api/maven/latest/file/maven-snapshots/cn/nukkit/nukkit/1.0-SNAPSHOT?extension=jar" + } + ] + }, + { + "id": "spigot", + "name": "SpigotMC", + "description": "The official SpigotMC jar with basic features", + "logo": "https://avatars.githubusercontent.com/u/4350249?s=200&v=4", + "versions": [] + }, + { + "id": "fivem", + "template": "fivem", + "name": "FiveM", + "description": "Linux FXServer artifacts from the official Cfx.re runtime channel.", + "logo": "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/FiveM-Logo.webp", + "versions": [] + }, + { + "id": "nodejs", + "template": "discord-bot", + "name": "Node.js", + "description": "Official Node.js images for Discord bots.", + "logo": "https://nodejs.org/static/images/logo.svg", + "versions": [ + { + "id": "node-18", + "name": "18", + "label": "Node.js 18 (LTS)", + "releaseDate": "2024-04-23", + "tags": [ + "LTS" + ], + "docker": { + "image": "node", + "tag": "18-alpine", + "command": "node /app/index.js" + }, + "start": "index.js" + }, + { + "id": "node-20", + "name": "20", + "label": "Node.js 20 (Active LTS)", + "releaseDate": "2024-10-08", + "tags": [ + "LTS", + "RECOMMENDED" + ], + "docker": { + "image": "node", + "tag": "20-alpine", + "command": "node /app/index.js" + }, + "start": "index.js" + }, + { + "id": "node-22", + "name": "22", + "label": "Node.js 22 (Current)", + "releaseDate": "2025-04-23", + "tags": [ + "LATEST" + ], + "docker": { + "image": "node", + "tag": "22-alpine", + "command": "node /app/index.js" + }, + "start": "index.js" + } + ] + }, + { + "id": "python", + "template": "discord-bot", + "name": "Python", + "description": "With this you can run any project based on Python.", + "logo": "https://files.catbox.moe/shq5gp.webp", + "versions": [ + { + "id": "python-3.10", + "name": "3.10", + "label": "Python 3.10", + "releaseDate": "2023-12-05", + "tags": [ + "LTS" + ], + "docker": { + "image": "python", + "tag": "3.10-slim", + "command": "python /app/main.py" + }, + "start": "main.py" + }, + { + "id": "python-3.11", + "name": "3.11", + "label": "Python 3.11", + "releaseDate": "2024-10-01", + "tags": [ + "STABLE" + ], + "docker": { + "image": "python", + "tag": "3.11-slim", + "command": "python /app/main.py" + }, + "start": "main.py" + }, + { + "id": "python-3.12", + "name": "3.12", + "label": "Python 3.12", + "releaseDate": "2025-02-25", + "tags": [ + "LATEST" + ], + "docker": { + "image": "python", + "tag": "3.12-slim", + "command": "python /app/main.py" + }, + "start": "main.py" + } + ] + } + ] +} diff --git a/views/404.ejs b/views/404.ejs new file mode 100644 index 0000000..3cfe980 --- /dev/null +++ b/views/404.ejs @@ -0,0 +1,316 @@ + + + + + + + <%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> - Not Found + + + + + + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    + + + +
    + +
    +
    +
    404
    +
    Not Found
    + + + Back to Dashboard + +
    +
    +
    + + + diff --git a/views/access-denied.ejs b/views/access-denied.ejs new file mode 100644 index 0000000..ed04c75 --- /dev/null +++ b/views/access-denied.ejs @@ -0,0 +1,158 @@ + + + + + + + <%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> - Access Denied + + + + + + + + + + + +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    +
    + +
    +
    +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    + +

    403

    +

    No Access

    + +
    + +

    + You're logged in, but your account is not allowed
    + to view or control this server. +

    + +
    + + + <%= typeof bot !=='undefined' ? bot : 'Unknown Server' %> + +
    + + + + Back to Home + + + +
    +
    + + + diff --git a/views/bot.ejs b/views/bot.ejs new file mode 100644 index 0000000..12d4ee2 --- /dev/null +++ b/views/bot.ejs @@ -0,0 +1,2093 @@ + + + + + + + <%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> - <%= displayName %> + + <% const assetVersion = typeof themeVersion !== 'undefined' ? themeVersion : '1'; %> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    +

    If you're on mobile, turn on your Desktop Mode or use + Landscape to work

    +
    + + + + + + + + + + + + + +
    +
    +
    + +
    + + + + + + + + + + + + +
    +
    + +
    +
    +
    +
    + + Panel +
    +
    +
    + + + +
    Console — + <%= displayName %> +
    +
    +
    +
    Status: idle
    +
    +
    + +
    + + + +
    +
    + +
    
    +
    +          
    + + + +
    +
    +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/views/db-open.ejs b/views/db-open.ejs new file mode 100644 index 0000000..970ebee --- /dev/null +++ b/views/db-open.ejs @@ -0,0 +1,187 @@ + + + + + + Opening <%= serviceLabel %>... + + + +
    +
    +

    Opening <%= serviceLabel %>

    +

    Generating a secure one-time link and preparing a safe session for this tab.

    +
    Requesting secure token...
    +
    +
    + + Back to Settings +
    +
    +
    + + + + diff --git a/views/forgot-password.ejs b/views/forgot-password.ejs new file mode 100644 index 0000000..7c7614e --- /dev/null +++ b/views/forgot-password.ejs @@ -0,0 +1,74 @@ + + + Forgot password? + + + + + + + + + + + +

    + [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. +

    +

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

    + + + diff --git a/views/index.ejs b/views/index.ejs new file mode 100644 index 0000000..b0e3d00 --- /dev/null +++ b/views/index.ejs @@ -0,0 +1,1979 @@ + + + + + + + + <%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> + + + + + + + + + + + + +
    + + + + + + + + + + + +
    +
    + +
    +

    ADPanel

    +

    Your intelligent dashboard

    +
    +
    + + <% if (typeof globalAlert !=='undefined' && globalAlert && globalAlert.message) { %> +
    + + + <%= globalAlert.message %> + +
    + <% } %> + +
    +
    + <% if (isAdmin) { %> + + <% } %> + + <% if (isAdmin) { %> + + <% } else { %> + + <% } %> + + <% if (showDashboardAssistant) { %> +
    + + + +
    + <% } %> + + +
    +
    +
    + + + +
    +
    +
    +

    Welcome back!

    +

    + Monitor, deploy, and orchestrate servers with ease. Launch new experiences for your community in + seconds. +

    + +
    + + <% if (isAdmin) { %> + + <% } %> +
    +
    + +
    +
    +
    + +
    +
    +

    Active servers

    +

    + <%= bots.length %> +

    +
    +
    + +
    +
    + +
    +
    +

    Status

    +

    Operational

    +
    +
    + +
    +
    + +
    +
    +

    Server Uptime

    +

    0s

    +
    +
    +
    +
    + + <% if (quickActions && quickActions.length> 0) { %> +
    +

    Quick actions

    +
    + <% quickActions.forEach(function(action) { %> + + <% }); %> +
    +
    + <% } %> + +
    +
    +
    +

    Your servers

    +

    Browse and jump straight into any workspace.

    +
    +
    + +
    +
    + +
    + <% bots.forEach(function(bot){ const coverStyle=bot.templateImage ? + `--bot-cover:url('${String(bot.templateImage).replace(/'/g, "\\'" )}');` : '' ; const ipPort=bot.port ? + `${bot.ip}:${bot.port}` : bot.ip; const memory=bot.memory || {}; const disk=bot.disk || {}; const + cpuPercent=bot.cpuPercent !==null && bot.cpuPercent !==undefined ? bot.cpuPercent : 0; const + cpuLimit=bot.cpuLimit || 100; const cpuBarWidth=cpuLimit > 0 ? Math.min(100, (cpuPercent / cpuLimit) * 100) : 0; const + statusClass=bot.status==='online' ? 'status-online' : (bot.status==='stopped' ? 'status-stopped' + : 'status-unknown' ) ; const nodeOffline=bot.nodeOnline===false; %> +
    +
    +
    +
    Can't establish connection to the server
    +
    +
    +
    +
    +
    +
    +
    +
    +

    + <%= bot.displayName || bot.name %> +

    +

    Node: <%= bot.nodeName %> +

    +
    +
    + +
    +
    +
    + + <%= ipPort %> + + + <%= bot.templateId || 'Custom' %> + +
    +
    +
    + +
    +
    +
    +
    +
    +
    Memory
    +
    + <%= memory.label || 'N/A' %> +
    +
    +
    + +
    +
    +
    +
    +
    +
    +
    Disk
    +
    + <%= disk.label || 'N/A' %> +
    +
    +
    +
    +
    +
    +
    +
    +
    CPU
    +
    + <%= bot.cpu || 'N/A' %> +
    +
    +
    +
    +
    + + +
    +
    + <% }) %> +
    + <% if (pagination && pagination.totalPages > 1) { %> +
    +
    + <%= ((pagination.page - 1) * pagination.limit) + 1 %>–<%= Math.min(pagination.page * pagination.limit, pagination.total) %> of <%= pagination.total %> servers +
    + + Page <%= pagination.page %> / <%= pagination.totalPages %> + +
    +
    +
    + <% } %> +
    + +
    + + + + + + + +
    +
    +
    +
    +
    + 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! +
    +
    + + +
    +
    + + + <% if (isAdmin) { %> +
    + +
    + <% } %> + + + + <% if (isAdmin) { %> + + + + + + + + + + + + + <% } %> + + + + +
    +
    +
    +
    + +
    +
    + + ADPanel +
    +

    Wish you merry christmas!

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

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

    +
    +
    +
    + + + + + +
    + © 2026-<%= new Date().getFullYear() %> ADPanel Dashboard +
    + + + diff --git a/views/login.ejs b/views/login.ejs new file mode 100644 index 0000000..c9d711d --- /dev/null +++ b/views/login.ejs @@ -0,0 +1,629 @@ +<% 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' ; %> + + + + + + Login - <%= (branding && branding.appName) ? branding.appName : 'Panel' %> + + + + + <% if (loginBackgroundType==='image' && loginBackgroundUrl) { %> + + <% } %> + + + + + + +
    + + + <% if (loginBackgroundType==='video' ) { %> + + <% } %> + + + +
    +
    +
    +
    + Security Verification +
    +
    Complete the challenge below to continue
    +
    + + +
    + <% if (showLocalCaptcha && captchaQuestion) { %> +
    +
    + <%= captchaQuestion.prompt %> +
    +
    + <% captchaQuestion.images.forEach(function(imgUrl, idx) { %> +
    + captcha image +
    +
    + <% }); %> +
    + +
    +
    + <% } %> +
    +
    + + + + + + + + + +
    + watermark is not available +
    + + + <% if (useExternalCaptcha) { %> + <% if (["cloudflare","turnstile","cf"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %> + + <% } else { %> + + <% } %> + <% } %> + + <% if (showLocalCaptcha && captchaQuestion) { %> + + <% } %> + + + + + + + + diff --git a/views/maintenance.ejs b/views/maintenance.ejs new file mode 100644 index 0000000..78ced44 --- /dev/null +++ b/views/maintenance.ejs @@ -0,0 +1,179 @@ + + + + + + <%= (branding && branding.appName) ? branding.appName : 'Panel' %> - Maintenance + + + + + + + + + +
    +
    + +
    +

    Under Maintenance

    +

    + The panel is currently undergoing scheduled maintenance. We're working on improvements + and will be back shortly. Thank you for your patience. +

    + <% if (typeof reason !== 'undefined' && reason) { %> +
    + + <%= reason %> +
    + <% } %> +
    + +
    + + diff --git a/views/resource-popup.ejs b/views/resource-popup.ejs new file mode 100644 index 0000000..a8a41a3 --- /dev/null +++ b/views/resource-popup.ejs @@ -0,0 +1,138 @@ + + + + + + Resources - <%= bot %> + + + + + + + + +
    +
    +
    Resource Usage
    + + +
    + +
    +
    +
    +
    +
    Memory
    +
    Loading...
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    Storage
    +
    Loading...
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    CPU
    +
    Loading...
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    Network Inbound
    +
    Loading...
    +
    +
    + +
    +
    +
    +
    Network Outbound
    +
    Loading...
    +
    +
    + +
    +
    +
    +
    Uptime
    +
    Loading...
    +
    +
    +
    +
    + + + + + diff --git a/views/settings.ejs b/views/settings.ejs new file mode 100644 index 0000000..df43cf9 --- /dev/null +++ b/views/settings.ejs @@ -0,0 +1,3537 @@ + + + + + + + + + + + + + <%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> Settings + + + + + + + + + + + + + + + + + + +
    +
    + + ESC +
    +
    + +
    + + +
    +
    +

    Settings

    + +
    +
    +
    +
    +
    +
    +
    Preferences
    +
    Bring ADPanel to your style.
    +
    +
    + +
    +
    +
    +
    +
    Background + Selection
    +
    First, you need a unique look
    +
    + +
    +
    +
    +
    Main color
    +
    +
    #ffffff
    +
    Preview area
    +
    +
    +
    + +
    +
    + +
    +
    + + + +
    +
    + +
    + +
    +
    Upload
    + + + +
    +
    +
    +
    + +
    +
    Thumbnail Previews
    +
    +
    + +
    Note: background set here will be applied to the dashboard and main style + files.
    +
    +
    + +
    +
    +
    +
    Saved + Background
    +
    +
    None
    +
    +
    +
    +
    + +
    +
    +
    +
    Customization
    +
    Personalize your dashboard experience
    +
    +
    + + <% if (user && user.admin) { %> +
    +
    + +
    + +
    +
    +
    + For Admins + +
    + +
    + + +
    + + 0/6 actions +
    +
    + +
    + +
    +
    + For Normal Users + +
    + +
    + + +
    + + 0/6 actions +
    +
    + +
    +
    + <% } %> + +
    +
    + + +
    +
    + + <% if (user && user.admin) { %> +
    +
    + + +
    +
    + +
    +
    + + +
    +
    + +
    +
    + + +
    +
    + <% } %> + +
    + +
    + + + +
    + +
    +
    Security
    +
    ADPanel helps you to handle attacks
    + +
    +
    +
    +
    +
    +
    Rate Limiter
    +
    Limit requests per IP to prevent abuse
    +
    +
    + +
    + +
    +
    +
    +
    + + +
    +
    + + +
    +
    + +
    +
    +
    +
    + +
    +
    +
    +
    +
    +
    Enable captcha at login
    +
    Protect against simple bots using reCAPTCHA/Turnstile/hCaptcha
    +
    +
    + +
    + +
    +
    + + Captcha is configured and active +
    +
    + To update keys, toggle off and back on. +
    +
    +
    + + <% if (user && user.admin) { %> +
    +
    +
    +
    + +
    +
    +
    Maintenance Mode
    +
    Lock the panel for non-admin users during updates or fixes
    +
    +
    + +
    + +
    + + +
    + When active, all normal users will see a maintenance page, leaving admins to do their work peacefully on ADPanel. +
    +
    +
    + <% } %> + +
    + + <% if (user && user.admin) { %> +
    +
    +
    +
    Sessions
    +
    Manage all ADPanel Sessions.
    +
    +
    + 0 active +
    +
    + +
    +
    +
    + + +
    +
    + Loading active browser sessions... +
    +
    + +
    + +
    +
    + + Loading active sessions... +
    +
    + +
    +
    +
    + <% } %> + +
    +
    +
    +
    Database Management
    +
    Install and manage database servers
    +
    +
    + +
    +
    +
    +
    +
    phpMyAdmin
    +
    +
    phpMyAdmin
    +
    MySQL/MariaDB web management interface
    +
    +
    + +
    + +
    +
    +
    + + Checking status... +
    +
    +
    +
    + + + + + +
    +
    +
    +
    pgAdmin4
    +
    +
    pgAdmin4
    +
    PostgreSQL web management interface
    +
    +
    + +
    + +
    +
    +
    + + Checking status... +
    +
    +
    +
    + + + +
    +
    +
    +
    MongoDB
    +
    +
    MongoDB
    +
    NoSQL document database
    +
    +
    + +
    + +
    +
    +
    + + Checking status... +
    +
    +
    +
    + + +
    +
    + +
    +
    +
    +
    Nodes
    +
    Manage your infrastructure
    +
    +
    +
    + + +
    + +
    +
    + +
    +
    +
    + +
    +
    +
    +
    Templates
    +
    Manage your server templates.
    +
    +
    +
    + + +
    + +
    +
    +
    +
    +
    +
    + +
    +
    +
    +
    Servers
    +
    All servers in one place.
    +
    + +
    + + +
    +
    + + +
    +
    + +
    +
    +
    + +
    + +
    + <% if (user && user.admin) { %> +
    +
    +
    Panel Information
    +
    Version details and updates
    +
    +
    + +
    +
    +
    +
    +
    ADPanel Version
    +
    +
    Loading...
    + +
    +
    +
    +
    Built on
    +
    +
    Loading...
    + +
    +
    +
    +
    + +
    +
    + + +
    +
    +
    Install specific version
    +
    + + +
    +
    +
    + +
    +
    + <% } else { %> +
    +
    +
    Panel Information
    +
    Only admins can view panel information
    +
    +
    + <% } %> +
    + +
    + <% if (user && user.admin) { %> +
    +
    +
    Webhooks
    +
    Send ADPanel activity logs to Discord
    +
    + +
    + +
    + + +
    + +
    +
    +
    + +

    No webhook configured

    + Click "Add" to set up a Discord webhook +
    +
    + + + <% } else { %> +
    +
    +
    Webhooks
    +
    Only admins can manage webhooks
    +
    +
    + <% } %> +
    + +
    +
    +
    + +
    +
    +
    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + <% if (user && user.admin) { %> + + <% } %> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +