Fix: apply .gitignore and remove untracked files

This commit is contained in:
antonn committed 2026-05-08 19:09:25 +00:00
commit b0bf3b7167
94 files changed
+123744

No files matched your search

View File
Whitespace-only changes.
+76
View File
@@ -0,0 +1,76 @@
<div align="center">
<a href="https://ad-panel.com">
<img src="https://cdn.jsdelivr.net/gh/antonndev/ADCDn/ADPanel-Banner.svg" alt="ADPanel Banner" width="100%" />
</a>
<br />
**"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)
<br />
<br />
### ⚡ Quick Deployment
</div>
### 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.
+10
View File
@@ -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
+2
View File
@@ -0,0 +1,2 @@
#!/bin/bash
nice -n 19 ionice -c 3 npm audit fix --package-lock-only
+12
View File
@@ -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"
}
+1
View File
@@ -0,0 +1 @@
[]
+13
View File
@@ -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
}
+6
View File
@@ -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
+91
View File
@@ -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();
},
};
+375
View File
@@ -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)
}
+20
View File
@@ -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"
}
}
]
};
+20
View File
@@ -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"
}
}
]
};
+28491
View File
File diff suppressed because it is too large. Load diff
+24
View File
@@ -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();
Executable
+4501
View File
File diff suppressed because it is too large. Load diff
+46
View File
@@ -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 };
+189
View File
@@ -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;
+3102
View File
File diff suppressed because it is too large. Load diff
+4944
View File
File diff suppressed because it is too large. Load diff
+61
View File
@@ -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": "<div align=\"center\"> <a href=\"https://ad-panel.com\"> <img src=\"https://cdn.jsdelivr.net/gh/antonndev/ADCDn/ADPanel-Banner.svg\" alt=\"ADPanel Banner\" width=\"100%\" /> </a>",
"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"
}
+7
View File
@@ -0,0 +1,7 @@
[
{
"panel-version": "v1.0.0",
"panel-architecture": "ADPanel Architecture",
"panel-auto-update": false
}
]
+19
View File
@@ -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");
}
+13263
View File
File diff suppressed because it is too large. Load diff
+855
View File
@@ -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);
}
}
File diff suppressed because it is too large. Load diff
+10
View File
@@ -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;
}
+4208
View File
File diff suppressed because it is too large. Load diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.1 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 88 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 21 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 241 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 430 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 89 KiB

+11325
View File
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+208
View File
@@ -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();
});
})();
+11608
View File
File diff suppressed because it is too large. Load diff
+694
View File
@@ -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;
}
+8501
View File
File diff suppressed because it is too large. Load diff
+579
View File
@@ -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
}
}
+52
View File
@@ -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
}
+231
View File
@@ -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;
};
+300
View File
@@ -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}(?<!-)(\.[a-z0-9-]{1,63})*\.[a-z]{2,}$/;
if (!hostnameRegex.test(domain)) {
return res.status(400).json({ error: "invalid domain format" });
}
let expectedIp = req.server.ip;
if (!expectedIp && req.server.node_id) {
try {
const nodeRows = await db.query("SELECT address FROM nodes WHERE id = ?", [req.server.node_id]);
if (nodeRows.length) expectedIp = nodeRows[0].address;
} catch (e) {
console.error("Node IP lookup failed:", e);
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(domain);
const matched = addresses.some(addr => 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;
+37
View File
@@ -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
+44
View File
@@ -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
+341
View File
@@ -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();
+145
View File
@@ -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" <<EOF
TOTAL_CORES=${TOTAL_CORES}
TOTAL_RAM_MB=${TOTAL_RAM_MB}
SAFE_RAM_MB=${SAFE_RAM_MB}
INSTANCES=${INSTANCES}
WORKER_RAM_MB=${WORKER_RAM_MB}
MAX_OLD_SPACE_MB=${MAX_OLD_SPACE_MB}
EOF
CHANGED=0
if [ ! -f "$OUTPUT_FILE" ] || ! cmp -s "$tmp_ecosystem" "$OUTPUT_FILE"; then
mv "$tmp_ecosystem" "$OUTPUT_FILE"
CHANGED=1
else
rm -f "$tmp_ecosystem"
fi
if [ ! -f "$STATE_FILE" ] || ! cmp -s "$tmp_state" "$STATE_FILE"; then
mv "$tmp_state" "$STATE_FILE"
CHANGED=1
else
rm -f "$tmp_state"
fi
if [ "$QUIET" -eq 0 ]; then
echo "Generated ${OUTPUT_FILE} using ${TOTAL_CORES} cores and ${TOTAL_RAM_MB} MB RAM." >&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"
+301
View File
@@ -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")
+6
View File
@@ -0,0 +1,6 @@
{
"rate_limiting": false,
"limit": 25,
"window_seconds": 120,
"trusted_subnets": []
}
+70
View File
@@ -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."
+1
View File
@@ -0,0 +1 @@
{}
+167
View File
@@ -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"
}
}
}
]
+19
View File
@@ -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;
}
+580
View File
@@ -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(/<adpanel_tool_plan>\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 <adpanel_tool_plan> 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: <adpanel_tool_plan>{"reply":"Starting it now.","tool_calls":[{"name":"power_server","args":{"server":"current server","action":"start"}}]}</adpanel_tool_plan>',
'Example for status check: <adpanel_tool_plan>{"reply":"Checking it now.","tool_calls":[{"name":"inspect_server","args":{"server":"current server"}}]}</adpanel_tool_plan>',
'Example for status plus console check: <adpanel_tool_plan>{"reply":"Checking that now.","tool_calls":[{"name":"inspect_server","args":{"server":"current server"}},{"name":"query_console","args":{"server":"current server","limit":60}}]}</adpanel_tool_plan>',
'Example for an explicit console command: <adpanel_tool_plan>{"reply":"Sending it now.","tool_calls":[{"name":"send_console_command","args":{"server":"current server","command":"say hello"}}]}</adpanel_tool_plan>',
"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,
};
+550
View File
@@ -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("<svg") || text.includes("<?xml")) {
const fullText = buffer.toString("utf8").toLowerCase();
if (fullText.includes("<script") || fullText.includes("javascript:") || /\bon[a-z]+\s*=/.test(fullText)) {
return { valid: false, error: "SVG contains potentially dangerous content" };
}
validType = true;
}
}
if (!validType) {
return { valid: false, error: "Unrecognized image format" };
}
return { valid: true, data: buffer };
} catch (err) {
return { valid: false, error: "Failed to decode image data" };
}
}
function getValidatedExtension(filename) {
if (!filename || typeof filename !== "string") {
return null;
}
const parts = filename.toLowerCase().split(".");
if (parts.length < 2) {
return null;
}
const ext = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
if (ALLOWED_EXTENSIONS.includes(ext)) {
return ext;
}
return null;
}
function getValidatedVideoExtension(filename) {
if (!filename || typeof filename !== "string") {
return null;
}
const parts = filename.toLowerCase().split(".");
if (parts.length < 2) {
return null;
}
const ext = parts[parts.length - 1].replace(/[^a-z0-9]/g, "");
if (ALLOWED_VIDEO_EXTENSIONS.includes(ext)) {
return ext;
}
return null;
}
function getMimeTypeForExtension(extension) {
if (!extension || typeof extension !== "string") {
return null;
}
const normalized = extension.toLowerCase().replace(/[^a-z0-9]/g, "");
if (normalized === "png") return "image/png";
if (normalized === "jpg" || normalized === "jpeg") return "image/jpeg";
if (normalized === "webp") return "image/webp";
if (normalized === "ico") return "image/x-icon";
if (normalized === "svg") return "image/svg+xml";
return VIDEO_MIME_TYPES[normalized] || null;
}
function getMediaTypeFromFilename(filename) {
if (getValidatedExtension(filename)) return "image";
if (getValidatedVideoExtension(filename)) return "video";
return null;
}
function getMediaTypeFromUrl(url) {
if (!url || typeof url !== "string") {
return null;
}
try {
const parsed = new URL(url);
const pathname = (parsed.pathname || "").toLowerCase();
const ext = pathname.includes(".") ? pathname.slice(pathname.lastIndexOf(".") + 1) : "";
if (!ext) return null;
if (ALLOWED_EXTENSIONS.includes(ext)) return "image";
if (ALLOWED_VIDEO_EXTENSIONS.includes(ext)) return "video";
} catch (err) {
return null;
}
return null;
}
function getExtensionFromUrl(url) {
if (!url || typeof url !== "string") {
return null;
}
try {
const parsed = new URL(url);
const pathname = (parsed.pathname || "").toLowerCase();
if (!pathname.includes(".")) return null;
const ext = pathname.slice(pathname.lastIndexOf(".") + 1).replace(/[^a-z0-9]/g, "");
if (ALLOWED_EXTENSIONS.includes(ext) || ALLOWED_VIDEO_EXTENSIONS.includes(ext)) {
return ext;
}
} catch (err) {
return null;
}
return null;
}
function validateBase64Video(base64Data, expectedExt) {
try {
let cleanBase64 = base64Data;
let declaredMime = "";
if (typeof base64Data === "string" && base64Data.startsWith("data:")) {
const match = base64Data.match(/^data:([^;,]+)[;,]/i);
declaredMime = match ? String(match[1] || "").toLowerCase() : "";
}
if (typeof base64Data === "string" && base64Data.includes(",")) {
cleanBase64 = base64Data.split(",")[1];
}
const buffer = Buffer.from(cleanBase64, "base64");
if (buffer.length < 32) {
return { valid: false, error: "Video data too small" };
}
if (buffer.length > 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
};
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+395
View File
@@ -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 `<script>(function(){try{var t=${safeToken};if(!t)return;var beat=function(){fetch('/api/settings/database/access-heartbeat',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({token:t}),keepalive:true}).catch(function(){});};beat();setInterval(beat,45000);window.addEventListener('pageshow',beat);}catch(e){}})();</script>`;
}
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/<token>/...
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 + "</body>");
} 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
};
+21
View File
@@ -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 };
+261
View File
@@ -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,
};
+95
View File
@@ -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,
};
+57
View File
@@ -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,
};
+507
View File
@@ -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,
};
+149
View File
@@ -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,
};
+114
View File
@@ -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,
};
+278
View File
@@ -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"
}
]
}
]
}
+316
View File
@@ -0,0 +1,316 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> - Not Found</title>
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
<link rel="icon" type="image/webp" href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha384-nRgPTkuX86pH8yjPJUAFuASXQSSl2/bBUiNV47vSYpKFxHJhbcrGnmlYpYJMeD7a" crossorigin="anonymous" referrerpolicy="no-referrer">
<style nonce="<%= cspNonce %>">
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
height: 100%;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Inter', sans-serif;
background: #0a0c10;
color: #fff;
overflow: hidden;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
img {
-webkit-user-drag: none;
-khtml-user-drag: none;
-moz-user-drag: none;
-o-user-drag: none;
user-drag: none;
pointer-events: none;
}
.page-container {
min-height: 100vh;
display: flex;
flex-direction: column;
position: relative;
}
.grid-pattern {
position: fixed;
inset: 0;
background-image:
linear-gradient(rgba(255, 255, 255, 0.02) 1px, transparent 1px),
linear-gradient(90deg, rgba(255, 255, 255, 0.02) 1px, transparent 1px);
background-size: 60px 60px;
pointer-events: none;
z-index: 0;
}
.orb {
position: fixed;
border-radius: 50%;
filter: blur(80px);
pointer-events: none;
z-index: 0;
}
.orb-1 {
width: 500px;
height: 500px;
background: radial-gradient(circle, rgba(99, 102, 241, 0.12) 0%, transparent 70%);
top: 20%;
left: 10%;
}
.orb-2 {
width: 400px;
height: 400px;
background: radial-gradient(circle, rgba(139, 92, 246, 0.08) 0%, transparent 70%);
bottom: 10%;
right: 15%;
}
.orb-3 {
width: 300px;
height: 300px;
background: radial-gradient(circle, rgba(59, 130, 246, 0.06) 0%, transparent 70%);
top: 60%;
left: 60%;
}
.geo-shape {
position: fixed;
border: 1px solid rgba(255, 255, 255, 0.04);
pointer-events: none;
z-index: 0;
}
.geo-1 {
width: 200px;
height: 200px;
border-radius: 24px;
top: 15%;
right: 20%;
transform: rotate(15deg);
}
.geo-2 {
width: 120px;
height: 120px;
border-radius: 50%;
bottom: 25%;
left: 15%;
}
.geo-3 {
width: 80px;
height: 80px;
border-radius: 16px;
top: 70%;
right: 10%;
transform: rotate(-20deg);
}
.geo-4 {
width: 60px;
height: 60px;
border-radius: 50%;
top: 30%;
left: 8%;
background: rgba(99, 102, 241, 0.03);
}
.header {
padding: 32px 0 0 48px;
position: relative;
z-index: 10;
}
.header-logo {
width: 65px;
height: auto;
pointer-events: auto;
}
.header a {
display: inline-block;
pointer-events: auto;
}
.main-content {
flex: 1;
display: flex;
align-items: center;
justify-content: center;
padding: 0 40px;
margin-top: -60px;
position: relative;
z-index: 10;
}
.error-wrapper {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
}
.error-code {
font-size: 220px;
font-weight: 800;
line-height: 1;
letter-spacing: -0.06em;
position: relative;
display: inline-block;
background: linear-gradient(to top,
rgba(255, 255, 255, 1) 0%,
rgba(255, 255, 255, 1) 10%,
rgba(255, 255, 255, 0.4) 30%,
rgba(255, 255, 255, 0) 80%);
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
}
.error-title {
font-size: 28px;
font-weight: 600;
color: rgba(255, 255, 255, 0.9);
margin-top: 16px;
margin-bottom: 32px;
}
.back-btn {
display: inline-flex;
align-items: center;
gap: 10px;
padding: 16px 32px;
background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
color: #fff;
font-size: 15px;
font-weight: 600;
border: none;
border-radius: 14px;
text-decoration: none;
cursor: pointer;
transition: transform 0.2s ease, opacity 0.2s ease;
pointer-events: auto;
}
.back-btn:hover {
transform: scale(1.05);
opacity: 0.95;
}
.back-btn:active {
transform: scale(0.98);
}
.back-btn i {
font-size: 16px;
}
.deco-line {
position: fixed;
background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.03), transparent);
height: 1px;
pointer-events: none;
z-index: 0;
}
.deco-line-1 {
width: 40%;
top: 30%;
left: 0;
}
.deco-line-2 {
width: 30%;
bottom: 35%;
right: 0;
}
.deco-line-3 {
width: 25%;
top: 65%;
left: 10%;
}
.corner-accent {
position: fixed;
width: 100px;
height: 100px;
pointer-events: none;
z-index: 0;
}
.corner-accent-tl {
top: 0;
left: 0;
border-top: 1px solid rgba(255, 255, 255, 0.03);
border-left: 1px solid rgba(255, 255, 255, 0.03);
border-top-left-radius: 20px;
}
.corner-accent-br {
bottom: 0;
right: 0;
border-bottom: 1px solid rgba(255, 255, 255, 0.03);
border-right: 1px solid rgba(255, 255, 255, 0.03);
border-bottom-right-radius: 20px;
}
body {
-webkit-touch-callout: none;
}
</style>
</head>
<body oncontextmenu="return false;">
<div class="grid-pattern"></div>
<div class="orb orb-1"></div>
<div class="orb orb-2"></div>
<div class="orb orb-3"></div>
<div class="geo-shape geo-1"></div>
<div class="geo-shape geo-2"></div>
<div class="geo-shape geo-3"></div>
<div class="geo-shape geo-4"></div>
<div class="deco-line deco-line-1"></div>
<div class="deco-line deco-line-2"></div>
<div class="deco-line deco-line-3"></div>
<div class="corner-accent corner-accent-tl"></div>
<div class="corner-accent corner-accent-br"></div>
<div class="page-container">
<header class="header">
<a href="/">
<img src="https://cdn.jsdelivr.net/gh/antonndev/ADCDn/adpanel-dark.webp" alt="ADPanel" class="header-logo"
draggable="false">
</a>
</header>
<main class="main-content">
<div class="error-wrapper">
<div class="error-code">404</div>
<div class="error-title">Not Found</div>
<a href="/" class="back-btn">
<i class="fa-solid fa-arrow-left"></i>
<span>Back to Dashboard</span>
</a>
</div>
</main>
</div>
</body>
</html>
+158
View File
@@ -0,0 +1,158 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> - Access Denied</title>
<link rel="stylesheet" href="/style.css">
<link rel="stylesheet" href="/css/bot.css?v=<%= typeof themeVersion !== 'undefined' ? themeVersion : Date.now() %>">
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
<link id="favicon" rel="icon" type="image/webp" href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha384-nRgPTkuX86pH8yjPJUAFuASXQSSl2/bBUiNV47vSYpKFxHJhbcrGnmlYpYJMeD7a" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style nonce="<%= cspNonce %>">
*,
*::before,
*::after {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
img,
video,
canvas {
-webkit-user-drag: none;
user-drag: none;
}
</style>
<script nonce="<%= cspNonce %>">
document.addEventListener('contextmenu', e => e.preventDefault());
document.addEventListener('dragstart', e => e.preventDefault());
document.addEventListener('selectstart', e => e.preventDefault());
document.addEventListener('copy', e => e.preventDefault());
document.addEventListener('cut', e => e.preventDefault());
document.addEventListener('keydown', e => {
if ((e.ctrlKey || e.metaKey) && ['c', 'C', 'a', 'A', 's', 'S', 'u', 'U'].includes(e.key)) e.preventDefault();
});
</script>
</head>
<body>
<div class="access-denied-container">
<div class="access-denied-particles">
<div class="access-denied-particle"></div>
<div class="access-denied-particle"></div>
<div class="access-denied-particle"></div>
<div class="access-denied-particle"></div>
<div class="access-denied-particle"></div>
<div class="access-denied-particle"></div>
<div class="access-denied-particle"></div>
<div class="access-denied-particle"></div>
<div class="access-denied-particle"></div>
</div>
<div class="access-denied-card">
<div class="access-denied-decor access-denied-decor-1"></div>
<div class="access-denied-decor access-denied-decor-2"></div>
<div class="sad-robot-container">
<svg class="sad-robot" viewBox="0 0 130 140" xmlns="http://www.w3.org/2000/svg">
<defs>
<linearGradient id="robot-head-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:#4b5563" />
<stop offset="50%" style="stop-color:#374151" />
<stop offset="100%" style="stop-color:#1f2937" />
</linearGradient>
<linearGradient id="robot-body-gradient" x1="0%" y1="0%" x2="0%" y2="100%">
<stop offset="0%" style="stop-color:#374151" />
<stop offset="100%" style="stop-color:#1f2937" />
</linearGradient>
<filter id="glow">
<feGaussianBlur stdDeviation="3" result="coloredBlur" />
<feMerge>
<feMergeNode in="coloredBlur" />
<feMergeNode in="SourceGraphic" />
</feMerge>
</filter>
</defs>
<ellipse class="sad-robot-shadow" cx="65" cy="135" rx="35" ry="5" />
<rect class="sad-robot-antenna" x="62" y="15" width="6" height="15" rx="2" />
<circle class="sad-robot-antenna-ball" cx="65" cy="12" r="8" filter="url(#glow)" />
<rect class="sad-robot-head" x="25" y="30" width="80" height="65" rx="12" fill="url(#robot-head-gradient)" />
<rect x="32" y="40" width="66" height="45" rx="8" fill="#1e293b" opacity="0.6" />
<g class="sad-robot-eye" transform-origin="50 58">
<ellipse cx="50" cy="58" rx="10" ry="12" fill="#1e293b" />
<ellipse class="sad-robot-eye-glow" cx="50" cy="58" rx="6" ry="8" fill="#ef4444" />
<ellipse cx="48" cy="55" rx="2" ry="2" fill="#fff" opacity="0.6" />
</g>
<g class="sad-robot-eye" transform-origin="80 58">
<ellipse cx="80" cy="58" rx="10" ry="12" fill="#1e293b" />
<ellipse class="sad-robot-eye-glow" cx="80" cy="58" rx="6" ry="8" fill="#ef4444" />
<ellipse cx="78" cy="55" rx="2" ry="2" fill="#fff" opacity="0.6" />
</g>
<path d="M 40 48 Q 50 52 58 48" stroke="#6b7280" stroke-width="2" fill="none" stroke-linecap="round" />
<path d="M 72 48 Q 80 52 90 48" stroke="#6b7280" stroke-width="2" fill="none" stroke-linecap="round" />
<path class="sad-robot-mouth" d="M 50 78 Q 65 68 80 78" stroke="#374151" stroke-width="3" fill="none"
stroke-linecap="round" />
<g class="sad-robot-tear" transform-origin="50 70">
<ellipse cx="50" cy="72" rx="3" ry="5" fill="#60a5fa" />
</g>
<g class="sad-robot-tear" transform-origin="80 70">
<ellipse cx="80" cy="72" rx="3" ry="5" fill="#60a5fa" />
</g>
<rect x="35" y="100" width="60" height="30" rx="6" fill="url(#robot-body-gradient)" />
<circle cx="55" cy="112" r="4" fill="#4b5563" />
<circle cx="75" cy="112" r="4" fill="#4b5563" />
<rect x="50" y="120" width="30" height="4" rx="2" fill="#4b5563" />
<rect x="15" y="50" width="10" height="20" rx="3" fill="#374151" />
<rect x="105" y="50" width="10" height="20" rx="3" fill="#374151" />
</svg>
</div>
<h1 class="access-denied-code">403</h1>
<h2 class="access-denied-title">No Access</h2>
<div class="access-denied-divider"></div>
<p class="access-denied-message">
You're logged in, but your account is not allowed<br>
to view or control this server.
</p>
<div class="access-denied-server">
<i class="fa-solid fa-server"></i>
<span>
<%= typeof bot !=='undefined' ? bot : 'Unknown Server' %>
</span>
</div>
<a href="/" class="access-denied-btn">
<i class="fa-solid fa-arrow-left"></i>
<span>Back to Home</span>
</a>
<div class="access-denied-footer">
<p class="access-denied-footer-text">
<i class="fa-solid fa-shield-halved"></i>
Contact an administrator if you believe this is an error
</p>
</div>
</div>
</div>
</body>
</html>
+2093
View File
File diff suppressed because it is too large. Load diff
+187
View File
@@ -0,0 +1,187 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1" />
<title>Opening <%= serviceLabel %>...</title>
<style>
:root {
color-scheme: light;
}
html, body {
margin: 0;
padding: 0;
font-family: Inter, system-ui, -apple-system, Segoe UI, Roboto, sans-serif;
background: #0b1220;
color: #e7eefc;
height: 100%;
}
.wrap {
min-height: 100%;
display: grid;
place-items: center;
padding: 24px;
box-sizing: border-box;
}
.card {
width: min(560px, 100%);
background: linear-gradient(160deg, rgba(18, 28, 48, 0.96), rgba(13, 20, 34, 0.98));
border: 1px solid rgba(255, 255, 255, 0.12);
border-radius: 16px;
padding: 24px;
box-sizing: border-box;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.35);
}
.title {
font-size: 20px;
font-weight: 700;
margin: 0 0 8px;
letter-spacing: 0.2px;
}
.subtitle {
margin: 0;
color: #b6c5e5;
font-size: 14px;
line-height: 1.55;
}
.status {
margin-top: 18px;
display: flex;
align-items: center;
gap: 10px;
color: #d5e2ff;
font-size: 14px;
}
.spinner {
width: 16px;
height: 16px;
border-radius: 999px;
border: 2px solid rgba(255, 255, 255, 0.26);
border-top-color: #8fc8ff;
animation: spin 0.9s linear infinite;
}
.error {
margin-top: 16px;
display: none;
color: #ffd4d4;
background: rgba(255, 80, 80, 0.14);
border: 1px solid rgba(255, 80, 80, 0.28);
border-radius: 10px;
padding: 10px 12px;
font-size: 13px;
line-height: 1.5;
white-space: pre-wrap;
word-break: break-word;
}
.actions {
margin-top: 16px;
display: none;
gap: 10px;
flex-wrap: wrap;
}
.btn {
border: 0;
border-radius: 10px;
padding: 10px 14px;
color: #eaf1ff;
background: #2a3c5f;
text-decoration: none;
font-size: 13px;
cursor: pointer;
display: inline-flex;
align-items: center;
gap: 8px;
}
.btn.secondary {
background: #192742;
border: 1px solid rgba(255, 255, 255, 0.14);
}
@keyframes spin {
to { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="wrap">
<div class="card" data-service="<%= service %>">
<h1 class="title">Opening <%= serviceLabel %></h1>
<p class="subtitle">Generating a secure one-time link and preparing a safe session for this tab.</p>
<div class="status"><span class="spinner"></span><span id="statusText">Requesting secure token...</span></div>
<div id="errorBox" class="error"></div>
<div id="actionBox" class="actions">
<button id="retryBtn" class="btn" type="button">Retry</button>
<a class="btn secondary" href="/settings">Back to Settings</a>
</div>
</div>
</div>
<script nonce="<%= cspNonce %>">
(function () {
'use strict';
const card = document.querySelector('.card');
const service = String(card?.dataset?.service || '').trim();
const statusText = document.getElementById('statusText');
const errorBox = document.getElementById('errorBox');
const actionBox = document.getElementById('actionBox');
const retryBtn = document.getElementById('retryBtn');
async function start() {
if (!service) {
showError('Missing service identifier.');
return;
}
setStatus('Requesting secure token...');
hideError();
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(function () { return {}; });
if (!res.ok || !payload || !payload.url) {
throw new Error(payload?.error || 'Failed to generate secure link.');
}
setStatus('Redirecting to secure session...');
window.location.replace(payload.url);
} catch (err) {
showError(err && err.message ? err.message : 'Unexpected error while opening database tool.');
}
}
function setStatus(msg) {
if (statusText) statusText.textContent = msg;
}
function showError(msg) {
setStatus('Unable to open secure session.');
if (errorBox) {
errorBox.style.display = 'block';
errorBox.textContent = msg;
}
if (actionBox) actionBox.style.display = 'flex';
}
function hideError() {
if (errorBox) {
errorBox.style.display = 'none';
errorBox.textContent = '';
}
if (actionBox) actionBox.style.display = 'none';
}
if (retryBtn) {
retryBtn.addEventListener('click', function () {
start();
});
}
start();
})();
</script>
</body>
</html>
+74
View File
@@ -0,0 +1,74 @@
<!DOCTYPE html>
<head>
<title>Forgot password?</title>
<link id="favicon" rel="icon" type="image/webp" href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>" />
<style nonce="<%= cspNonce %>">
strong {
background-color: gray;
color: white;
}
</style>
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
<script nonce="<%= cspNonce %>">
(function () {
const CHRISTMAS_IMG = '/auth-assets/christmas-logo';
function isChristmasPeriod() {
const now = new Date();
const month = now.getMonth();
const day = now.getDate();
return month === 11 && day >= 25 && day <= 28;
}
function applyChristmasTheme() {
if (!isChristmasPeriod()) return;
const favicon = document.getElementById('favicon') || document.querySelector('link[rel="icon"]');
if (favicon) favicon.href = CHRISTMAS_IMG;
document.querySelectorAll('img').forEach(img => {
if (img.src && (img.src.includes('ADPanel-dark.webp') || img.src.includes('i.imgur.com/k5agjYf'))) {
img.src = CHRISTMAS_IMG;
}
});
}
document.addEventListener('DOMContentLoaded', applyChristmasTheme);
})();
</script>
<style nonce="<%= cspNonce %>">
*,
*::before,
*::after {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
img,
video,
canvas {
-webkit-user-drag: none;
user-drag: none;
}
</style>
<script nonce="<%= cspNonce %>">
document.addEventListener('contextmenu', e => e.preventDefault());
document.addEventListener('dragstart', e => e.preventDefault());
document.addEventListener('selectstart', e => e.preventDefault());
document.addEventListener('copy', e => e.preventDefault());
document.addEventListener('cut', e => e.preventDefault());
document.addEventListener('keydown', e => {
if ((e.ctrlKey || e.metaKey) && ['c', 'C', 'a', 'A', 's', 'S', 'u', 'U'].includes(e.key)) e.preventDefault();
});
</script>
</head>
<body>
<html>
<p>
[Dashboard] Due to security reasons you can only reset your password
directly from the terminal using the command
<strong>bash initialize.sh</strong> from the ADPanel directory or switching to an admin account and resetting it for the specific user from Accounts settings category.
</p>
<p>This panel version doesn't support change password feature directly from normal user UI.</p>
</html>
</body>
+1979
View File
File diff suppressed because it is too large. Load diff
+629
View File
@@ -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' ; %>
<!DOCTYPE html>
<html lang="ro">
<head>
<meta charset="UTF-8" />
<title>Login - <%= (branding && branding.appName) ? branding.appName : 'Panel' %></title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha384-nRgPTkuX86pH8yjPJUAFuASXQSSl2/bBUiNV47vSYpKFxHJhbcrGnmlYpYJMeD7a" crossorigin="anonymous" referrerpolicy="no-referrer">
<link id="favicon" rel="icon" type="image/webp" sizes="16x16"
href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>" />
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
<% if (loginBackgroundType==='image' && loginBackgroundUrl) { %>
<link rel="preload" as="image" href="<%= loginBackgroundUrl %>" fetchpriority="high" />
<% } %>
<script nonce="<%= cspNonce %>">
(function () {
const CHRISTMAS_IMG = '/auth-assets/christmas-logo';
function isChristmasPeriod() {
const now = new Date();
const month = now.getMonth();
const day = now.getDate();
return month === 11 && day >= 25 && day <= 28;
}
function applyChristmasTheme() {
if (!isChristmasPeriod()) return;
const favicon = document.getElementById('favicon') || document.querySelector('link[rel="icon"]');
if (favicon) favicon.href = CHRISTMAS_IMG;
document.querySelectorAll('img').forEach(img => {
if (img.src && (img.src.includes('/auth-assets/logo') || img.src.includes('ADPanel-dark.webp') || img.src.includes('i.imgur.com/k5agjYf'))) {
img.src = CHRISTMAS_IMG;
}
});
}
document.addEventListener('DOMContentLoaded', applyChristmasTheme);
})();
</script>
<style nonce="<%= cspNonce %>">
<%- loginCss || "" %>
*,
*::before,
*::after {
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
img,
video,
canvas {
-webkit-user-drag: none;
user-drag: none;
}
<% if (loginBackgroundType === 'image' && loginBackgroundUrl) { %>
body.login-body--image {
background-image: url(<%- JSON.stringify(String(loginBackgroundUrl)) %>);
}
<% } %>
</style>
<script nonce="<%= cspNonce %>">
document.addEventListener('contextmenu', e => e.preventDefault());
document.addEventListener('dragstart', e => e.preventDefault());
document.addEventListener('selectstart', e => e.preventDefault());
document.addEventListener('copy', e => e.preventDefault());
document.addEventListener('cut', e => e.preventDefault());
document.addEventListener('keydown', e => {
if ((e.ctrlKey || e.metaKey) && ['c', 'C', 'a', 'A', 's', 'S', 'u', 'U'].includes(e.key)) e.preventDefault();
});
</script>
</head>
<body class="<%= loginBackgroundType === 'image' && loginBackgroundUrl ? 'login-body--image' : '' %>">
<div id="toastHost" class="toast-host" aria-live="polite" aria-atomic="true"></div>
<script nonce="<%= cspNonce %>">
(() => {
const msg = <%- JSON.stringify(String(error || "")).replace(/</g, "\\u003c") %>;
if (!msg) return;
const host = document.getElementById("toastHost");
if (!host) return;
function showToast(text, duration = 4500) {
const toast = document.createElement("div");
toast.className = "toast";
toast.innerHTML = `
<div class="toast-inner">
<div class="toast-msg"></div>
<div class="toast-bar"></div>
</div>
`;
toast.querySelector(".toast-msg").textContent = text;
host.appendChild(toast);
requestAnimationFrame(() => toast.classList.add("toast-show"));
const leaveAt = Math.max(0, duration - 320);
setTimeout(() => toast.classList.add("toast-hide"), leaveAt);
setTimeout(() => toast.remove(), duration + 450);
}
showToast(msg, 4500);
})();
</script>
<% if (loginBackgroundType==='video' ) { %>
<video id="bgVideo" autoplay muted loop playsinline preload="metadata" class="video">
<source src="<%= loginBackgroundUrl %>" type="<%= loginBackgroundMimeType %>" />
Your browser does not support instant-video.
</video>
<% } %>
<form method="POST" action="/login" class="login-form">
<input type="text" name="company" tabindex="-1" autocomplete="off" aria-hidden="true" hidden>
<input type="hidden" name="botProof" id="botProofInput" value="<%= botProofSeed || '' %>" autocomplete="off">
<input type="hidden" name="_csrf" value="<%= csrfToken %>" autocomplete="off">
<div class="input-holder">
<i class="input-icon fa-solid fa-envelope" aria-hidden="true"></i>
<input class="login-input" type="email" name="email" placeholder="Email" required />
</div>
<div class="input-holder">
<i class="input-icon fa-solid fa-lock" aria-hidden="true"></i>
<input class="login-input" type="password" name="password" placeholder="Password" required />
</div>
<div class="input-holder">
<i class="input-icon fa-solid fa-fingerprint" aria-hidden="true"></i>
<input class="login-input" type="text" name="code" placeholder="2FA Code" required />
</div>
<input type="hidden" name="captchaToken" id="captchaTokenInput" value="" />
<button type="submit" class="get-started">
<span>Access</span>
<img class="get-started__logo" src="/auth-assets/logo" alt="D Logo" draggable="false" />
<span>Panel</span>
</button>
<a class="forgot-password" href="/forgot-password">Forgot password?</a>
<div class="circle-icon">
<i class="fa-solid fa-arrow-right-to-bracket circle-icon__glyph"></i>
</div>
</form>
<div id="captchaModal" class="captcha-modal<%= (useExternalCaptcha || showLocalCaptcha) ? ' show' : '' %>"
data-provider="<%= (externalCaptchaProvider || 'recaptcha').toLowerCase() %>"
data-challenge="<%= (useExternalCaptcha || showLocalCaptcha) ? '1' : '0' %>"
aria-hidden="<%= (useExternalCaptcha || showLocalCaptcha) ? 'false' : 'true' %>">
<div class="captcha-modal__backdrop"></div>
<div class="captcha-modal__card">
<div class="captcha-modal__title">
<i class="fa-solid fa-shield-halved captcha-modal__title-icon"></i>Security Verification
</div>
<div class="captcha-modal__desc">Complete the challenge below to continue</div>
<div class="captcha-modal__widget">
<div id="recaptchaWidget" hidden></div>
<div id="cf-turnstile" hidden></div>
</div>
<% if (showLocalCaptcha && captchaQuestion) { %>
<div id="localCaptchaUI" class="local-captcha" data-token="<%= captchaQuestion.token %>"
data-step="<%= captchaQuestion.step %>" data-total="<%= captchaQuestion.total %>">
<div class="local-captcha__prompt" id="captchaPrompt">
<%= captchaQuestion.prompt %>
</div>
<div class="local-captcha__grid" id="captchaGrid">
<% captchaQuestion.images.forEach(function(imgUrl, idx) { %>
<div class="local-captcha__cell" data-idx="<%= idx %>">
<img src="<%= imgUrl %>" alt="captcha image" draggable="false" loading="lazy" />
<div class="local-captcha__check"><i class="fa-solid fa-check"></i></div>
</div>
<% }); %>
</div>
<div class="local-captcha__footer">
<span class="local-captcha__step" id="captchaStep">Step <%= captchaQuestion.step %> of <%= captchaQuestion.total %></span>
<button type="button" id="captchaSubmitLocal" class="local-captcha__submit">Verify</button>
</div>
<div id="captchaLocalStatus" class="local-captcha__status"></div>
</div>
<% } %>
</div>
</div>
<div class="menu"></div>
<div class="sign-up-subline">
<a class="sign-up-sublines"> and make something special </a>
</div>
<div class="sign-ups">
<a class="sign-up-desc"> Securely manage your applications with style </a>
</div>
<div>
<a class="sign-up"> Sign in with email </a>
</div>
<div class="watermark" id="watermark">
<img
src="<%= protectedLoginWatermarkUrl %>"
alt="watermark is not available" draggable="false" />
</div>
<script nonce="<%= cspNonce %>">
(() => {
const cfg = {
enabled: <%- useExternalCaptcha ? "true" : "false" %>,
required: <%- externalCaptchaAutoStart ? "true" : "false" %>,
provider: <%- JSON.stringify((externalCaptchaProvider || "recaptcha").toLowerCase()) %>,
siteKey: <%- JSON.stringify(externalCaptchaSiteKey || "") %>,
hasError: <%- error ? "true" : "false" %>,
showLocal: <%- showLocalCaptcha ? "true" : "false" %>,
challengeActive: <%- (useExternalCaptcha || showLocalCaptcha) ? "true" : "false" %>,
};
const form = document.querySelector("form");
const modal = document.getElementById("captchaModal");
const tokenInput = document.getElementById("captchaTokenInput");
const recaptchaHost = document.getElementById("recaptchaWidget");
const turnstileHost = document.getElementById("cf-turnstile");
const statusEl = modal ? modal.querySelector(".captcha-modal__desc") : null;
const defaultStatusText = statusEl ? statusEl.textContent : "";
let recaptchaId = null;
let turnstileId = null;
let started = false;
let timeoutHandle = null;
const disableForm = () => {
if (!form) return;
form.querySelectorAll("input:not([type=hidden]), button[type=submit]").forEach(el => { el.disabled = true; });
form.classList.add("login-form--blocked");
};
const enableForm = () => {
if (!form) return;
form.querySelectorAll("input, button").forEach(el => { el.disabled = false; });
form.classList.remove("login-form--blocked");
};
const showModal = () => {
if (modal) modal.classList.add("show");
disableForm();
};
const hideModal = () => {
if (modal) {
modal.classList.remove("show");
modal.dataset.challenge = "0";
}
enableForm();
if (timeoutHandle) {
clearTimeout(timeoutHandle);
timeoutHandle = null;
}
};
const resetStatus = () => {
if (statusEl) statusEl.textContent = defaultStatusText;
};
const markTimeout = () => {
if (statusEl) {
statusEl.textContent = "Captcha unavailable. Try again.";
}
};
function renderRecaptcha() {
if (!cfg.enabled || recaptchaId !== null) return recaptchaId;
if (!window.grecaptcha || typeof window.grecaptcha.render !== "function") return null;
if (turnstileHost) turnstileHost.hidden = true;
if (recaptchaHost) recaptchaHost.hidden = false;
recaptchaId = window.grecaptcha.render("recaptchaWidget", {
sitekey: cfg.siteKey,
size: "normal",
theme: "dark",
callback: (token) => {
tokenInput.value = token || "";
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
fetch("/api/captcha/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
credentials: "same-origin",
}).catch(() => { });
hideModal();
},
"expired-callback": () => { tokenInput.value = ""; },
"error-callback": () => { tokenInput.value = ""; },
});
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
resetStatus();
return recaptchaId;
}
function ensureRecaptcha(attempt = 0) {
if (recaptchaId === null) renderRecaptcha();
if (recaptchaId !== null) return;
if (attempt < 50) setTimeout(() => ensureRecaptcha(attempt + 1), 200);
}
function renderTurnstile() {
if (!cfg.enabled || turnstileId !== null) return turnstileId;
if (!window.turnstile || typeof window.turnstile.render !== "function") return null;
if (recaptchaHost) recaptchaHost.hidden = true;
if (turnstileHost) turnstileHost.hidden = false;
turnstileId = window.turnstile.render("#cf-turnstile", {
sitekey: cfg.siteKey,
size: "normal",
theme: "dark",
callback: (token) => {
tokenInput.value = token || "";
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
fetch("/api/captcha/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
credentials: "same-origin",
}).catch(() => { });
hideModal();
},
"expired-callback": () => { tokenInput.value = ""; },
"error-callback": () => { tokenInput.value = ""; },
});
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
resetStatus();
return turnstileId;
}
function ensureTurnstile(attempt = 0) {
if (turnstileId === null) renderTurnstile();
if (turnstileId !== null) return;
if (attempt < 50) setTimeout(() => ensureTurnstile(attempt + 1), 200);
}
function startCaptchaFlow() {
started = true;
showModal();
resetStatus();
if (timeoutHandle) clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(markTimeout, 30000);
if (["cloudflare", "turnstile", "cf"].includes(cfg.provider)) return ensureTurnstile();
return ensureRecaptcha();
}
if (form) {
form.addEventListener("submit", (e) => {
if (modal && modal.dataset.challenge === "1") {
e.preventDefault();
e.stopImmediatePropagation();
if (cfg.enabled && !tokenInput.value) startCaptchaFlow();
return false;
}
if (cfg.enabled && !tokenInput.value) {
e.preventDefault();
startCaptchaFlow();
return false;
}
}, true);
}
if (cfg.challengeActive) {
disableForm();
if (cfg.enabled && !started) startCaptchaFlow();
} else if (cfg.enabled && cfg.required && !started) {
startCaptchaFlow();
}
window.initRecaptcha = function initRecaptcha() {
if (!cfg.enabled) return;
ensureRecaptcha();
};
window.initTurnstile = function initTurnstile() {
if (!cfg.enabled) return;
ensureTurnstile();
};
window.__adCaptchaResolved = hideModal;
})();
</script>
<% if (useExternalCaptcha) { %>
<% if (["cloudflare","turnstile","cf"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %>
<script nonce="<%= cspNonce %>"
src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=initTurnstile&render=explicit" async
defer></script>
<% } else { %>
<script nonce="<%= cspNonce %>"
src="https://www.google.com/recaptcha/api.js?onload=initRecaptcha&render=explicit" async
defer></script>
<% } %>
<% } %>
<% if (showLocalCaptcha && captchaQuestion) { %>
<script nonce="<%= cspNonce %>">
(function () {
var grid = document.getElementById("captchaGrid");
var submitBtn = document.getElementById("captchaSubmitLocal");
var statusEl = document.getElementById("captchaLocalStatus");
var localUI = document.getElementById("localCaptchaUI");
var promptEl = document.getElementById("captchaPrompt");
var stepEl = document.getElementById("captchaStep");
if (!grid || !submitBtn || !localUI) return;
var selected = new Set();
function setLocalStatus(message, state) {
if (!statusEl) return;
statusEl.textContent = message || "";
statusEl.dataset.state = state || "";
}
grid.addEventListener("click", function (e) {
var cell = e.target.closest(".local-captcha__cell");
if (!cell) return;
var idx = parseInt(cell.dataset.idx, 10);
if (isNaN(idx)) return;
if (selected.has(idx)) {
selected.delete(idx);
cell.classList.remove("selected");
} else {
selected.add(idx);
cell.classList.add("selected");
}
});
submitBtn.addEventListener("click", function () {
if (selected.size === 0) {
setLocalStatus("Select at least one image", "error");
return;
}
var token = localUI.dataset.token;
submitBtn.disabled = true;
setLocalStatus("Verifying...", "muted");
fetch("/api/captcha/local", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "same-origin",
body: JSON.stringify({ action: "verify", token: token, selection: Array.from(selected) }),
})
.then(function (resp) { return resp.json(); })
.then(function (data) {
if (data.ok && data.done) {
setLocalStatus("Verified!", "success");
if (typeof window.__adCaptchaResolved === "function") window.__adCaptchaResolved();
return;
}
if (data.ok && !data.done && data.question) {
selected.clear();
rebuildGrid(data.question);
setLocalStatus("", "");
submitBtn.disabled = false;
return;
}
setLocalStatus(data.error === "expired" ? "Expired. Reloading..." : "Incorrect selection. Reloading...", "error");
setTimeout(function () { window.location.reload(); }, 1800);
})
.catch(function () {
setLocalStatus("Network error. Retrying...", "error");
setTimeout(function () { window.location.reload(); }, 2000);
});
});
function rebuildGrid(question) {
localUI.dataset.token = question.token;
localUI.dataset.step = String(question.step);
localUI.dataset.total = String(question.total);
if (promptEl) promptEl.textContent = question.prompt;
if (stepEl) stepEl.textContent = "Step " + question.step + " of " + question.total;
grid.innerHTML = "";
(question.images || []).forEach(function (imgUrl, idx) {
var cell = document.createElement("div");
cell.className = "local-captcha__cell";
cell.dataset.idx = String(idx);
var img = document.createElement("img");
img.src = imgUrl;
img.alt = "captcha image";
img.draggable = false;
img.loading = "lazy";
var check = document.createElement("div");
check.className = "local-captcha__check";
check.innerHTML = '<i class="fa-solid fa-check"></i>';
cell.appendChild(img);
cell.appendChild(check);
grid.appendChild(cell);
});
}
})();
</script>
<% } %>
<script nonce="<%= cspNonce %>">
document.addEventListener("DOMContentLoaded", () => {
const form = document.querySelector("form");
const videoEl = document.getElementById("bgVideo");
if (!videoEl) return;
const tryPlay = () => {
const p = videoEl.play();
if (p && typeof p.then === "function") {
p.catch(() => {
});
}
};
videoEl.addEventListener(
"canplay",
() => {
tryPlay();
},
{ once: true }
);
const resumeOnUserGesture = () => {
tryPlay();
window.removeEventListener("click", resumeOnUserGesture);
window.removeEventListener("keydown", resumeOnUserGesture);
window.removeEventListener("touchstart", resumeOnUserGesture);
};
window.addEventListener("click", resumeOnUserGesture);
window.addEventListener("keydown", resumeOnUserGesture);
window.addEventListener("touchstart", resumeOnUserGesture);
videoEl.addEventListener("error", () => {
});
});
</script>
<script nonce="<%= cspNonce %>">
(function () {
var challengeActive = <%- (showLocalCaptcha || (useExternalCaptcha && externalCaptchaAutoStart)) ? "true" : "false" %>;
if (!challengeActive) return;
var modal = document.getElementById("captchaModal");
var form = document.querySelector("form");
if (!modal) return;
if (form) {
form.addEventListener("submit", function (e) {
if (modal.dataset.challenge === "1") {
e.preventDefault();
e.stopImmediatePropagation();
return false;
}
}, true);
}
var restoring = false;
var observer = new MutationObserver(function () {
if (restoring) return;
var m = document.getElementById("captchaModal");
if (!m) {
restoring = true;
window.location.reload();
return;
}
if (m.dataset.challenge === "0") return;
if (!m.classList.contains("show")) m.classList.add("show");
var st = m.getAttribute("style") || "";
if (st && (st.indexOf("display") !== -1 || st.indexOf("visibility") !== -1 || st.indexOf("opacity") !== -1)) {
m.removeAttribute("style");
}
});
observer.observe(document.documentElement, {
childList: true,
subtree: true,
attributes: true,
attributeFilter: ["class", "style", "hidden"],
});
var integrityInterval = setInterval(function () {
var m = document.getElementById("captchaModal");
if (!m) {
clearInterval(integrityInterval);
window.location.reload();
return;
}
if (m.dataset.challenge === "0") {
clearInterval(integrityInterval);
observer.disconnect();
return;
}
if (!m.classList.contains("show")) m.classList.add("show");
var cs = getComputedStyle(m);
if (cs.display === "none" || cs.visibility === "hidden" || parseFloat(cs.opacity) < 0.5) {
m.removeAttribute("style");
m.classList.add("show");
}
if (form && m.dataset.challenge === "1") {
form.classList.add("login-form--blocked");
}
}, 800);
try {
var origRemove = modal.remove;
Object.defineProperty(modal, "remove", {
value: function () {
if (modal.dataset.challenge === "1") return;
return origRemove.call(this);
},
writable: false,
configurable: false,
});
} catch (ex) { }
try {
var origSetAttr = modal.setAttribute.bind(modal);
modal.setAttribute = function (name, value) {
if (modal.dataset.challenge !== "1") return origSetAttr(name, value);
if (name === "style" && typeof value === "string" && (/display\s*:\s*none|visibility\s*:\s*hidden|opacity\s*:\s*0/i).test(value)) return;
if (name === "class" && typeof value === "string" && !value.includes("show")) return;
if (name === "hidden") return;
return origSetAttr(name, value);
};
} catch (ex) { }
modal.addEventListener("contextmenu", function (e) { e.preventDefault(); });
})();
</script>
</body>
</html>
+179
View File
@@ -0,0 +1,179 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><%= (branding && branding.appName) ? branding.appName : 'Panel' %> - Maintenance</title>
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
<link rel="icon" type="image/webp" sizes="16x16" href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>" />
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;600;700;800&display=swap" rel="stylesheet" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha384-nRgPTkuX86pH8yjPJUAFuASXQSSl2/bBUiNV47vSYpKFxHJhbcrGnmlYpYJMeD7a" crossorigin="anonymous" referrerpolicy="no-referrer" />
<style nonce="<%= cspNonce %>">
*, *::before, *::after { margin: 0; padding: 0; box-sizing: border-box; -webkit-user-select: none; -moz-user-select: none; user-select: none; }
html, body { height: 100%; overflow: hidden; }
body {
font-family: 'Inter', system-ui, -apple-system, sans-serif;
background: #0a0a0f;
color: #e2e8f0;
display: flex;
align-items: center;
justify-content: center;
position: relative;
}
body::before {
content: '';
position: fixed;
inset: 0;
background:
radial-gradient(ellipse 600px 400px at 20% 30%, rgba(239, 68, 68, 0.06), transparent),
radial-gradient(ellipse 500px 350px at 80% 70%, rgba(168, 85, 247, 0.05), transparent),
radial-gradient(ellipse 400px 300px at 50% 50%, rgba(59, 130, 246, 0.04), transparent);
z-index: 0;
}
body::after {
content: '';
position: fixed;
inset: 0;
background-image:
linear-gradient(rgba(255,255,255,0.015) 1px, transparent 1px),
linear-gradient(90deg, rgba(255,255,255,0.015) 1px, transparent 1px);
background-size: 60px 60px;
z-index: 0;
}
.maintenance-container {
position: relative;
z-index: 1;
text-align: center;
max-width: 560px;
padding: 48px 40px;
background: rgba(15, 15, 25, 0.85);
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 24px;
backdrop-filter: blur(20px);
box-shadow: 0 32px 80px rgba(0, 0, 0, 0.5), 0 0 0 1px rgba(255, 255, 255, 0.03);
}
.maintenance-icon {
width: 80px;
height: 80px;
margin: 0 auto 28px;
background: linear-gradient(135deg, rgba(239, 68, 68, 0.15), rgba(168, 85, 247, 0.15));
border-radius: 20px;
display: flex;
align-items: center;
justify-content: center;
font-size: 32px;
color: #ef4444;
}
.maintenance-title {
font-size: 26px;
font-weight: 800;
letter-spacing: -0.5px;
margin-bottom: 12px;
background: linear-gradient(135deg, #fff 0%, #94a3b8 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.maintenance-message {
font-size: 15px;
line-height: 1.7;
color: #94a3b8;
margin-bottom: 28px;
}
.maintenance-reason {
display: inline-flex;
align-items: center;
gap: 8px;
padding: 10px 18px;
background: rgba(255, 255, 255, 0.04);
border: 1px solid rgba(255, 255, 255, 0.06);
border-radius: 12px;
font-size: 13px;
color: #cbd5e1;
margin-bottom: 28px;
}
.maintenance-reason i {
color: #f59e0b;
font-size: 14px;
}
.maintenance-divider {
height: 1px;
background: rgba(255, 255, 255, 0.06);
margin: 0 -40px 20px;
}
.maintenance-footer {
font-size: 12px;
color: #475569;
display: flex;
align-items: center;
justify-content: center;
gap: 6px;
}
.maintenance-footer i {
font-size: 11px;
}
.maintenance-dot {
width: 6px;
height: 6px;
background: #ef4444;
border-radius: 50%;
display: inline-block;
}
.maintenance-container * { pointer-events: none; }
</style>
<script nonce="<%= cspNonce %>">
document.addEventListener('contextmenu', e => e.preventDefault());
document.addEventListener('keydown', e => {
if (e.key === 'F12' || (e.ctrlKey && e.shiftKey && (e.key === 'I' || e.key === 'J' || e.key === 'C')) || (e.ctrlKey && e.key === 'u')) {
e.preventDefault();
}
});
(function enforceMaintenanceIntegrity() {
const checkInterval = setInterval(async () => {
try {
const res = await fetch('/api/maintenance/status', { credentials: 'include' });
if (res.ok) {
const data = await res.json();
if (data.active) return;
}
clearInterval(checkInterval);
window.location.reload();
} catch (e) {
}
}, 15000);
const observer = new MutationObserver(() => {
if (!document.querySelector('.maintenance-container')) {
window.location.reload();
}
});
observer.observe(document.body, { childList: true, subtree: true });
})();
</script>
</head>
<body>
<div class="maintenance-container">
<div class="maintenance-icon">
<i class="fa-solid fa-wrench"></i>
</div>
<h1 class="maintenance-title">Under Maintenance</h1>
<p class="maintenance-message">
The panel is currently undergoing scheduled maintenance. We're working on improvements
and will be back shortly. Thank you for your patience.
</p>
<% if (typeof reason !== 'undefined' && reason) { %>
<div class="maintenance-reason">
<i class="fa-solid fa-circle-info"></i>
<span><%= reason %></span>
</div>
<% } %>
<div class="maintenance-divider"></div>
<div class="maintenance-footer">
<span class="maintenance-dot"></span>
<span>Maintenance in progress</span>
</div>
</div>
</body>
</html>
+138
View File
@@ -0,0 +1,138 @@
<!DOCTYPE html>
<html lang="en" data-bot="<%= bot %>">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Resources - <%= bot %></title>
<link rel="stylesheet" href="/style.css?v=<%= Date.now() %>">
<link rel="stylesheet" href="/css/bot.css?v=<%= typeof themeVersion !== 'undefined' ? themeVersion : Date.now() %>">
<link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.7.2/css/all.min.css" integrity="sha384-nRgPTkuX86pH8yjPJUAFuASXQSSl2/bBUiNV47vSYpKFxHJhbcrGnmlYpYJMeD7a" crossorigin="anonymous" referrerpolicy="no-referrer">
<style nonce="<%= cspNonce %>">
body {
margin: 0;
padding: 0;
height: 100vh;
overflow: hidden;
display: flex;
align-items: center;
justify-content: center;
background-color: #0b0f14;
}
.resource-stats-popup {
position: relative;
top: auto;
left: auto;
transform: none !important;
opacity: 1 !important;
visibility: visible !important;
pointer-events: auto !important;
width: 100%;
height: 100%;
border-radius: 0;
border: none;
box-shadow: none;
display: flex;
flex-direction: column;
background: transparent !important;
-webkit-backdrop-filter: none !important;
backdrop-filter: none !important;
}
.screen-fill-container {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
background: linear-gradient(135deg, rgba(15, 20, 30, 0.92) 0%, rgba(10, 15, 25, 0.95) 100%);
}
.resource-stats-header {
border-radius: 0;
}
.resource-stats-body {
flex: 1;
overflow-y: auto;
}
#resourceStatsClose, #openResourceStatsTab {
display: none;
}
</style>
</head>
<body>
<div class="resource-stats-popup visible screen-fill-container" id="resourceStatsPopup">
<div class="resource-stats-header">
<div class="resource-stats-title"><i class="fa-solid fa-chart-pie"></i> Resource Usage</div>
<button class="resource-stats-action" id="openResourceStatsTab"><i class="fa-solid fa-arrow-up-right-from-square"></i></button>
<button class="resource-stats-close" id="resourceStatsClose"><i class="fa-solid fa-xmark"></i></button>
</div>
<div class="resource-stats-body">
<div class="resource-stat-row">
<div class="resource-stat-icon memory-icon"><i class="fa-solid fa-memory"></i></div>
<div class="resource-stat-info">
<div class="resource-stat-label">Memory</div>
<div class="resource-stat-value" id="resMemoryLabel">Loading...</div>
</div>
<div class="resource-stat-bar">
<div class="resource-stat-fill memory-fill" id="resMemoryBar" style="width:0%"></div>
</div>
</div>
<div class="resource-stat-row">
<div class="resource-stat-icon disk-icon"><i class="fa-solid fa-hard-drive"></i></div>
<div class="resource-stat-info">
<div class="resource-stat-label">Storage</div>
<div class="resource-stat-value" id="resDiskLabel">Loading...</div>
</div>
<div class="resource-stat-bar">
<div class="resource-stat-fill disk-fill" id="resDiskBar" style="width:0%"></div>
</div>
</div>
<div class="resource-stat-row">
<div class="resource-stat-icon cpu-icon"><i class="fa-solid fa-microchip"></i></div>
<div class="resource-stat-info">
<div class="resource-stat-label">CPU</div>
<div class="resource-stat-value" id="resCpuLabel">Loading...</div>
</div>
<div class="resource-stat-bar">
<div class="resource-stat-fill cpu-fill" id="resCpuBar" style="width:0%"></div>
</div>
</div>
<div class="resource-stat-row">
<div class="resource-stat-icon network-inbound-icon"><i class="fa-solid fa-arrow-down"></i></div>
<div class="resource-stat-info">
<div class="resource-stat-label">Network Inbound</div>
<div class="resource-stat-value" id="resNetworkInboundLabel">Loading...</div>
</div>
</div>
<div class="resource-stat-row">
<div class="resource-stat-icon network-outbound-icon"><i class="fa-solid fa-arrow-up"></i></div>
<div class="resource-stat-info">
<div class="resource-stat-label">Network Outbound</div>
<div class="resource-stat-value" id="resNetworkOutboundLabel">Loading...</div>
</div>
</div>
<div class="resource-stat-row">
<div class="resource-stat-icon uptime-icon"><i class="fa-solid fa-clock"></i></div>
<div class="resource-stat-info">
<div class="resource-stat-label">Uptime</div>
<div class="resource-stat-value" id="resUptimeLabel">Loading...</div>
</div>
</div>
</div>
</div>
<script nonce="<%= cspNonce %>" src="/socket.io/socket.io.js"></script>
<script nonce="<%= cspNonce %>" src="/js/resource-popup.js?v=<%= Date.now() %>"></script>
</body>
</html>
+3537
View File
File diff suppressed because it is too large. Load diff