Initial upload

This commit is contained in:
antonn committed 2026-06-10 17:04:11 +00:00
1 parent b0bf3b7167
commit a022f29e34
65 files changed
+45987 -3842

No files matched your search

+12
View File
@@ -0,0 +1,12 @@
network:
version: 2
ethernets:
enp6s18:
addresses:
- 10.0.0.6/8
nameservers:
addresses: [1.1.1.1, 8.8.8.8]
routes:
- to: default
via: 10.0.0.1
mtu: 1280
+5 -1
View File
@@ -13,6 +13,10 @@
<br /> <br />
<br /> <br />
### Compatibility: Currently works only with Ubuntu/Debian systems, we work hard to make compatibility to all Linux Distros
<br>
### ⚡ Quick Deployment ### ⚡ Quick Deployment
</div> </div>
@@ -26,7 +30,7 @@ sudo mkdir -p /var/www && sudo git clone https://github.com/antonndev/ADPanel.gi
### ADaemon ### ADaemon
```bash ```bash
curl -fsSL https://raw.githubusercontent.com/antonndev/ADPanel-Daemon/main/install-daemon.sh | tr -d '\r' | sudo bash -s -- --yes curl -fsSL https://raw.githubusercontent.com/antonndev/ADaemon/main/install.sh | tr -d '\r' | sudo bash -s -- --yes
``` ```
--- ---
+2287
View File
File diff suppressed because it is too large. Load diff
BIN
View File
Binary file not shown.
+108
View File
@@ -0,0 +1,108 @@
package main
import (
"crypto/ed25519"
"net"
"os"
"path/filepath"
"strings"
"testing"
"golang.org/x/crypto/ssh"
)
func mkKey(t *testing.T) ssh.PublicKey {
t.Helper()
pub, _, err := ed25519.GenerateKey(nil)
if err != nil {
t.Fatal(err)
}
k, err := ssh.NewPublicKey(pub)
if err != nil {
t.Fatal(err)
}
return k
}
func TestTOFUPerUserPinning(t *testing.T) {
dir := t.TempDir()
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
real := mkKey(t)
trap := mkKey(t)
userA := tofuHostKeyCallback(store, "userA", false)
// userA first use pins real key.
if err := userA("srv.example:22", addr, real); err != nil {
t.Fatalf("userA first-use should pin, got: %v", err)
}
// userA reconnect with same key is fine.
if err := userA("srv.example:22", addr, real); err != nil {
t.Fatalf("userA same key should be allowed, got: %v", err)
}
// userA presented a DIFFERENT key on reconnect => MITM, rejected.
if err := userA("srv.example:22", addr, trap); err == nil {
t.Fatal("userA mismatched key MUST be rejected")
}
}
// Core of the reported attack: a malicious user pre-pins a TRAP key; the victim
// must NOT inherit it. The victim either pins the real key for themselves, or
// (if the attacker also intercepts the victim) sees a divergence rejection.
func TestTOFUPrePinningDoesNotPoisonVictim(t *testing.T) {
dir := t.TempDir()
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
real := mkKey(t)
trap := mkKey(t)
attacker := tofuHostKeyCallback(store, "attacker", false)
victim := tofuHostKeyCallback(store, "victim", false)
// Attacker pre-pins a trap key for the host (their own store only).
if err := attacker("newsrv:22", addr, trap); err != nil {
t.Fatalf("attacker pre-pin setup failed: %v", err)
}
// Victim connects to the REAL server (sees the real key). Because the
// attacker recorded a different key globally, the victim must be WARNED
// (divergence) rather than silently trusting anything.
if err := victim("newsrv:22", addr, real); err == nil {
t.Fatal("victim must be warned about divergence, not silently allowed")
} else if !strings.Contains(strings.ToLower(err.Error()), "divergence") {
t.Fatalf("expected divergence error, got: %v", err)
}
// Critically: the victim is NEVER bound to the attacker's trap key.
st := loadKnownHosts(store)
if got := st.Pins[userHostKey("victim", "newsrv:22")]; got == hostKeyFingerprint(trap) {
t.Fatal("victim must NOT inherit the attacker's pinned key")
}
// After explicit, informed acceptance, the victim pins the REAL key only.
victimAccept := tofuHostKeyCallback(store, "victim", true)
if err := victimAccept("newsrv:22", addr, real); err != nil {
t.Fatalf("victim explicit-accept of real key failed: %v", err)
}
st = loadKnownHosts(store)
if got := st.Pins[userHostKey("victim", "newsrv:22")]; got != hostKeyFingerprint(real) {
t.Fatalf("victim should be pinned to the REAL key, got %q", got)
}
}
func TestTOFUFailsClosedOnUnwritableStore(t *testing.T) {
dir := t.TempDir()
blocker := filepath.Join(dir, "blocker")
if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
store := filepath.Join(blocker, "data", "known.json")
cb := tofuHostKeyCallback(store, "u", false)
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
if err := cb("h:22", addr, mkKey(t)); err == nil {
t.Fatal("must fail closed when the key store is unavailable")
}
}
+1
View File
@@ -0,0 +1 @@
{"Tests":[{"line":"pl","ts":1778787350028,"source":"command","seq":0,"at":0},{"line":"pl","ts":1778865559475,"source":"command","seq":0,"at":0}],"da":[{"line":"pl","ts":1780081780409,"source":"command","seq":1513,"at":0},{"line":"pl","ts":1780081783489,"source":"command","seq":1514,"at":0},{"line":"pl","ts":1780081785809,"source":"command","seq":1515,"at":0},{"line":"help","ts":1780081787849,"source":"command","seq":1516,"at":0}],"test":[{"line":"pl","ts":1780131002803,"source":"command","seq":3213,"at":0},{"line":"pl","ts":1780132314446,"source":"command","seq":3262,"at":0}],"Testing":[{"line":"pl","ts":1780167742031,"source":"command","seq":75,"at":0},{"line":"pl","ts":1780168307468,"source":"command","seq":403,"at":0},{"line":"pl","ts":1780168307478,"source":"command","seq":404,"at":0},{"line":"help","ts":1780168309703,"source":"command","seq":406,"at":0},{"line":"pl","ts":1780168486609,"source":"command","seq":400,"at":0}],"Testingss":[{"line":"pl","ts":1780170899112,"source":"command","seq":76,"at":0}]}
+1
View File
@@ -0,0 +1 @@
{"da":1780081763302,"test":1780130983909,"Teste":1780764582187,"Testingss":1780170897236,"dsaf":1780242907441,"das":1780326849890,"Pe-Stick":1780852878638}
+5
View File
@@ -0,0 +1,5 @@
{
"type": "image",
"value": "/images/waves.png",
"updatedAt": "2026-06-05T19:05:09.162Z"
}
-6
View File
@@ -1,6 +0,0 @@
TOTAL_CORES=2
TOTAL_RAM_MB=7941
SAFE_RAM_MB=6352
INSTANCES=1
WORKER_RAM_MB=6352
MAX_OLD_SPACE_MB=5399
+338
View File
@@ -0,0 +1,338 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"strings"
"testing"
"time"
)
func TestDockerAttachAPIStdinTTYSmoke(t *testing.T) {
if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" {
t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test")
}
name := fmt.Sprintf("adpanel-attach-smoke-%d", time.Now().UnixNano())
_ = exec.Command("docker", "rm", "-f", name).Run()
t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() })
if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh").CombinedOutput(); err != nil {
t.Fatalf("docker run failed: %v: %s", err, string(out))
}
d := Docker{}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
stream, err := d.attachContainerAPI(ctx, name, dockerAttachOptions{Stdout: true, Stderr: true})
if err != nil {
t.Fatalf("attach stdout failed: %v", err)
}
defer stream.Close()
lines := make(chan string, 32)
go func() {
sc := bufio.NewScanner(stream)
for sc.Scan() {
lines <- sc.Text()
}
close(lines)
}()
stdin, err := d.attachContainerAPI(ctx, name, dockerAttachOptions{Stdin: true})
if err != nil {
t.Fatalf("attach stdin failed: %v", err)
}
defer stdin.Close()
if _, err := io.WriteString(stdin, "echo READY\n"); err != nil {
t.Fatalf("stdin write failed: %v", err)
}
deadline := time.After(5 * time.Second)
for {
select {
case line := <-lines:
if strings.Contains(line, "READY") {
return
}
case <-deadline:
t.Fatal("did not receive command output from attach stream")
}
}
}
func TestDockerSendCommandPrefersAttachBeforeTargetFallback(t *testing.T) {
if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" {
t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test")
}
name := fmt.Sprintf("adpanel-attach-target-smoke-%d", time.Now().UnixNano())
_ = exec.Command("docker", "rm", "-f", name).Run()
t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() })
startScript := `tail -f /dev/null < /dev/null & while read line; do echo "CONSOLE:$line"; done`
if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil {
t.Fatalf("docker run failed: %v: %s", err, string(out))
}
d := Docker{}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
stream, err := d.attachContainerAPI(ctx, name, dockerAttachOptions{Stdout: true, Stderr: true})
if err != nil {
t.Fatalf("attach stdout failed: %v", err)
}
defer stream.Close()
lines := make(chan string, 32)
go func() {
sc := bufio.NewScanner(stream)
for sc.Scan() {
lines <- sc.Text()
}
close(lines)
}()
stdinMgr := newStdinManager(&d, false)
defer stdinMgr.stop()
if err := d.sendCommand(ctx, stdinMgr, name, "hello-from-attach", []string{"tail"}); err != nil {
t.Fatalf("sendCommand failed: %v", err)
}
deadline := time.After(5 * time.Second)
for {
select {
case line := <-lines:
if strings.Contains(line, "CONSOLE:hello-from-attach") {
return
}
case <-deadline:
t.Fatal("did not receive command output from attached console")
}
}
}
func TestLogManagerLiveAttachWritesTTYStdin(t *testing.T) {
if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" {
t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test")
}
t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "api")
name := fmt.Sprintf("adpanel-live-attach-stdin-smoke-%d", time.Now().UnixNano())
_ = exec.Command("docker", "rm", "-f", name).Run()
t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() })
startScript := `while read line; do echo "CONSOLE:$line"; done`
if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil {
t.Fatalf("docker run failed: %v: %s", err, string(out))
}
d := Docker{}
lm := newLogManager(d, false)
ch := make(chan string, 16)
tail := lm.getOrCreate(name)
tail.mu.Lock()
tail.clients[ch] = struct{}{}
tail.mu.Unlock()
deadline := time.Now().Add(8 * time.Second)
for time.Now().Before(deadline) {
if err := lm.writeCommand(name, "hello-from-live-attach"); err == nil {
break
}
time.Sleep(100 * time.Millisecond)
}
timeout := time.After(time.Until(deadline))
for {
select {
case line := <-ch:
if strings.Contains(line, "CONSOLE:hello-from-live-attach") {
lm.killTail(name)
return
}
case <-timeout:
lm.killTail(name)
t.Fatal("did not receive command output from live attach stream")
}
}
}
func TestDockerSendCommandForcedCLITransportKeepsTTYStdin(t *testing.T) {
if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" {
t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test")
}
t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "cli")
name := fmt.Sprintf("adpanel-cli-tty-stdin-smoke-%d", time.Now().UnixNano())
_ = exec.Command("docker", "rm", "-f", name).Run()
t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() })
startScript := `while read line; do echo "CONSOLE:$line"; done`
if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil {
t.Fatalf("docker run failed: %v: %s", err, string(out))
}
d := Docker{}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
stdinMgr := newStdinManager(&d, false)
defer stdinMgr.stop()
if err := d.sendCommand(ctx, stdinMgr, name, "hello-from-tty-attach", []string{"sh"}); err != nil {
t.Fatalf("sendCommand failed: %v", err)
}
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
out, err := exec.Command("docker", "logs", name).CombinedOutput()
if err == nil && strings.Contains(string(out), "CONSOLE:hello-from-tty-attach") {
return
}
time.Sleep(100 * time.Millisecond)
}
out, _ := exec.Command("docker", "logs", name).CombinedOutput()
t.Fatalf("did not receive command output from TTY stdin attach; logs=%s", string(out))
}
func TestDockerSendCommandCLIPTYTransportWritesTTYStdin(t *testing.T) {
if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" {
t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test")
}
t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "pty")
name := fmt.Sprintf("adpanel-cli-pty-stdin-smoke-%d", time.Now().UnixNano())
_ = exec.Command("docker", "rm", "-f", name).Run()
t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() })
startScript := `while read line; do echo "CONSOLE:$line"; done`
if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil {
t.Fatalf("docker run failed: %v: %s", err, string(out))
}
d := Docker{}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
stdinMgr := newStdinManager(&d, false)
defer stdinMgr.stop()
if err := d.sendCommand(ctx, stdinMgr, name, "hello-from-cli-pty", []string{"sh"}); err != nil {
t.Fatalf("sendCommand failed: %v", err)
}
deadline := time.Now().Add(5 * time.Second)
for time.Now().Before(deadline) {
out, err := exec.Command("docker", "logs", name).CombinedOutput()
if err == nil && strings.Contains(string(out), "CONSOLE:hello-from-cli-pty") {
return
}
time.Sleep(100 * time.Millisecond)
}
out, _ := exec.Command("docker", "logs", name).CombinedOutput()
t.Fatalf("did not receive command output from Docker CLI PTY stdin attach; logs=%s", string(out))
}
func TestDockerLogsCLITransportCapturesTTYOutput(t *testing.T) {
if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" {
t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test")
}
t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "cli")
name := fmt.Sprintf("adpanel-cli-tty-logs-smoke-%d", time.Now().UnixNano())
_ = exec.Command("docker", "rm", "-f", name).Run()
t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() })
startScript := `sleep 1; echo "CONSOLE:hello-from-docker-logs"; sleep 30`
if out, err := exec.Command("docker", "run", "-d", "--name", name, "-it", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil {
t.Fatalf("docker run failed: %v: %s", err, string(out))
}
d := Docker{}
lm := newLogManager(d, false)
ch := make(chan string, 16)
tail := &logTail{
name: name,
clients: map[chan string]struct{}{ch: {}},
recentN: logTailRecentMaxLines,
stopCh: make(chan struct{}),
}
done := make(chan error, 1)
go func() {
done <- lm.followDockerLogsCLI(tail)
}()
stopTail := func() {
tail.mu.Lock()
cmd := tail.cmd
tail.mu.Unlock()
select {
case <-tail.stopCh:
default:
close(tail.stopCh)
}
if cmd != nil && cmd.Process != nil {
_ = cmd.Process.Kill()
}
}
defer stopTail()
deadline := time.After(6 * time.Second)
for {
select {
case line := <-ch:
if strings.Contains(line, "CONSOLE:hello-from-docker-logs") {
stopTail()
select {
case <-done:
case <-time.After(2 * time.Second):
}
return
}
case err := <-done:
t.Fatalf("docker logs follow exited before output: %v", err)
case <-deadline:
t.Fatal("did not receive TTY output from docker logs follow")
}
}
}
func TestDockerSendCommandRejectsClosedContainerStdin(t *testing.T) {
if os.Getenv("ADPANEL_DOCKER_ATTACH_SMOKE") != "1" {
t.Skip("set ADPANEL_DOCKER_ATTACH_SMOKE=1 to run Docker attach smoke test")
}
name := fmt.Sprintf("adpanel-closed-stdin-smoke-%d", time.Now().UnixNano())
_ = exec.Command("docker", "rm", "-f", name).Run()
t.Cleanup(func() { _ = exec.Command("docker", "rm", "-f", name).Run() })
startScript := `while read line; do echo "CONSOLE:$line"; done; sleep 30`
if out, err := exec.Command("docker", "run", "-d", "--name", name, "-t", "alpine:3.20", "sh", "-c", startScript).CombinedOutput(); err != nil {
t.Fatalf("docker run failed: %v: %s", err, string(out))
}
d := Docker{}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
stdinMgr := newStdinManager(&d, false)
defer stdinMgr.stop()
err := d.sendCommand(ctx, stdinMgr, name, "hello-closed-stdin", []string{"sh"})
if err == nil {
t.Fatal("expected closed container stdin to be rejected")
}
if !strings.Contains(err.Error(), "stdin is not open") {
t.Fatalf("expected stdin-not-open error, got %v", err)
}
}
+249 -3
View File
@@ -1,6 +1,7 @@
package main package main
import ( import (
"bufio"
"bytes" "bytes"
"context" "context"
"encoding/json" "encoding/json"
@@ -95,6 +96,22 @@ type dockerPullProgress struct {
Error string `json:"error"` Error string `json:"error"`
} }
type dockerAttachOptions struct {
Stdin bool
Stdout bool
Stderr bool
Logs bool
}
type dockerHijackedConn struct {
net.Conn
reader *bufio.Reader
}
func (c *dockerHijackedConn) Read(p []byte) (int, error) {
return c.reader.Read(p)
}
type dockerImageInspectConfig struct { type dockerImageInspectConfig struct {
Entrypoint []string `json:"Entrypoint"` Entrypoint []string `json:"Entrypoint"`
Cmd []string `json:"Cmd"` Cmd []string `json:"Cmd"`
@@ -232,6 +249,80 @@ func (d Docker) engineRequest(ctx context.Context, method, rawPath string, query
return respBody, resp.StatusCode, nil return respBody, resp.StatusCode, nil
} }
func (d Docker) attachContainerAPI(ctx context.Context, name string, opts dockerAttachOptions) (io.ReadWriteCloser, error) {
dockerName := dockerContainerName(name)
if dockerName == "" {
return nil, fmt.Errorf("missing container name")
}
if !opts.Stdin && !opts.Stdout && !opts.Stderr {
return nil, fmt.Errorf("no attach streams requested")
}
var dialer net.Dialer
conn, err := dialer.DialContext(ctx, "unix", dockerEngineSocketPath)
if err != nil {
return nil, err
}
_ = conn.SetDeadline(time.Now().Add(10 * time.Second))
query := url.Values{}
query.Set("stream", "1")
if opts.Stdin {
query.Set("stdin", "1")
}
if opts.Stdout {
query.Set("stdout", "1")
}
if opts.Stderr {
query.Set("stderr", "1")
}
if opts.Logs {
query.Set("logs", "1")
}
req, err := http.NewRequestWithContext(
ctx,
http.MethodPost,
"http://docker"+dockerAPIPath("/containers/"+url.PathEscape(dockerName)+"/attach", query),
nil,
)
if err != nil {
_ = conn.Close()
return nil, err
}
req.Header.Set("Connection", "Upgrade")
req.Header.Set("Upgrade", "tcp")
if err := req.Write(conn); err != nil {
_ = conn.Close()
return nil, err
}
reader := bufio.NewReader(conn)
resp, err := http.ReadResponse(reader, req)
if err != nil {
_ = conn.Close()
return nil, err
}
if resp.StatusCode != http.StatusSwitchingProtocols && resp.StatusCode != http.StatusOK {
detail := ""
if resp.Body != nil {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
_ = resp.Body.Close()
detail = decodeDockerAPIError(body)
}
_ = conn.Close()
if detail == "" {
detail = resp.Status
}
return nil, fmt.Errorf("failed to attach container %s: %s", dockerName, detail)
}
_ = conn.SetDeadline(time.Time{})
return &dockerHijackedConn{Conn: conn, reader: reader}, nil
}
func splitDockerImageRef(ref string) (string, string) { func splitDockerImageRef(ref string) (string, string) {
clean := strings.TrimSpace(ref) clean := strings.TrimSpace(ref)
if clean == "" { if clean == "" {
@@ -249,6 +340,47 @@ func splitDockerImageRef(ref string) (string, string) {
} }
func (d Docker) pullImageAPI(ctx context.Context, ref string) error { func (d Docker) pullImageAPI(ctx context.Context, ref string) error {
var lastErr error
for attempt := 1; attempt <= 3; attempt++ {
err := d.pullImageAPIOnce(ctx, ref)
if err == nil {
return nil
}
lastErr = err
if ctx.Err() != nil || !isTransientDockerPullError(err) || attempt == 3 {
break
}
delay := time.Duration(attempt*attempt) * time.Second
timer := time.NewTimer(delay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
return lastErr
}
func (d Docker) ensureImageAvailableAPI(ctx context.Context, ref string) error {
imageRef := strings.TrimSpace(ref)
if imageRef == "" {
return fmt.Errorf("missing image reference")
}
if d.imageExistsLocally(ctx, imageRef) {
return nil
}
if err := d.pullImageAPI(ctx, imageRef); err != nil {
if isTransientDockerPullError(err) && d.imageExistsLocally(ctx, imageRef) {
fmt.Printf("[docker] pull failed for %s with transient error, using cached image: %v\n", imageRef, err)
return nil
}
return err
}
return nil
}
func (d Docker) pullImageAPIOnce(ctx context.Context, ref string) error {
image, tag := splitDockerImageRef(ref) image, tag := splitDockerImageRef(ref)
if image == "" { if image == "" {
return fmt.Errorf("missing image reference") return fmt.Errorf("missing image reference")
@@ -290,12 +422,63 @@ func (d Docker) pullImageAPI(ctx context.Context, ref string) error {
return nil return nil
} }
func isTransientDockerPullError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
nonTransient := []string{
"manifest unknown",
"not found",
"pull access denied",
"repository does not exist",
"requested access to the resource is denied",
"unauthorized",
"authentication required",
"invalid reference format",
}
for _, marker := range nonTransient {
if strings.Contains(msg, marker) {
return false
}
}
transient := []string{
"tls: bad record mac",
"unexpected eof",
"connection reset",
"connection refused",
"connection timed out",
"i/o timeout",
"net/http",
"httpreadseeker",
"failed to copy",
"failed to do request",
"tls handshake timeout",
"temporary failure",
"503",
"502",
"504",
"too many requests",
}
for _, marker := range transient {
if strings.Contains(msg, marker) {
return true
}
}
return false
}
func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool) error { func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
query := url.Values{} query := url.Values{}
query.Set("v", "1")
if force { if force {
query.Set("force", "1") query.Set("force", "1")
} }
body, status, err := d.engineRequest(ctx, http.MethodDelete, "/containers/"+url.PathEscape(name), query, nil) body, status, err := d.engineRequest(ctx, http.MethodDelete, "/containers/"+url.PathEscape(dockerName), query, nil)
if err != nil { if err != nil {
return err return err
} }
@@ -303,11 +486,74 @@ func (d Docker) removeContainerAPI(ctx context.Context, name string, force bool)
return nil return nil
} }
if status < 200 || status >= 300 { if status < 200 || status >= 300 {
return fmt.Errorf("failed to remove container %s: %s", name, decodeDockerAPIError(body)) return fmt.Errorf("failed to remove container %s: %s", dockerName, decodeDockerAPIError(body))
} }
return nil return nil
} }
func (d Docker) killContainerAPI(ctx context.Context, name string) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
query := url.Values{}
query.Set("signal", "SIGKILL")
body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(dockerName)+"/kill", query, nil)
if err != nil {
return err
}
if status == http.StatusNotFound {
return nil
}
if status == http.StatusConflict {
msg := strings.ToLower(decodeDockerAPIError(body))
if strings.Contains(msg, "not running") || strings.Contains(msg, "is not running") {
return nil
}
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to kill container %s: %s", dockerName, decodeDockerAPIError(body))
}
return nil
}
func (d Docker) updateRestartNoAPI(ctx context.Context, name string) error {
dockerName := dockerContainerName(name)
if dockerName == "" {
return fmt.Errorf("missing container name")
}
req := dockerHostConfig{RestartPolicy: dockerRestartPolicy{Name: "no"}}
body, status, err := d.engineRequest(ctx, http.MethodPost, "/containers/"+url.PathEscape(dockerName)+"/update", nil, req)
if err != nil {
return err
}
if status == http.StatusNotFound {
return nil
}
if status < 200 || status >= 300 {
return fmt.Errorf("failed to disable restart policy for %s: %s", dockerName, decodeDockerAPIError(body))
}
return nil
}
func (d Docker) containerExistsAPI(ctx context.Context, name string) (bool, error) {
dockerName := dockerContainerName(name)
if dockerName == "" {
return false, fmt.Errorf("missing container name")
}
body, status, err := d.engineRequest(ctx, http.MethodGet, "/containers/"+url.PathEscape(dockerName)+"/json", nil, nil)
if err != nil {
return false, err
}
if status == http.StatusNotFound {
return false, nil
}
if status < 200 || status >= 300 {
return false, fmt.Errorf("failed to inspect container %s: %s", dockerName, decodeDockerAPIError(body))
}
return true, nil
}
func (d Docker) createContainerAPI(ctx context.Context, name string, req dockerContainerCreateRequest) (string, error) { func (d Docker) createContainerAPI(ctx context.Context, name string, req dockerContainerCreateRequest) (string, error) {
query := url.Values{} query := url.Values{}
query.Set("name", name) query.Set("name", name)
@@ -362,7 +608,7 @@ func (d Docker) runContainerAPI(ctx context.Context, name string, req dockerCont
removeCancel() removeCancel()
pullCtx, pullCancel := context.WithTimeout(ctx, 10*time.Minute) pullCtx, pullCancel := context.WithTimeout(ctx, 10*time.Minute)
if err := d.pullImageAPI(pullCtx, req.Image); err != nil { if err := d.ensureImageAvailableAPI(pullCtx, req.Image); err != nil {
pullCancel() pullCancel()
return err return err
} }
+268
View File
@@ -0,0 +1,268 @@
package main
import (
"errors"
"path/filepath"
"testing"
)
func TestIsTransientDockerPullError(t *testing.T) {
transient := []string{
`failed to pull image eclipse-temurin:17-jre: failed to copy: httpReadSeeker: failed open: failed to do request: local error: tls: bad record MAC`,
`unexpected EOF`,
`Get "https://registry-1.docker.io/v2/": net/http: TLS handshake timeout`,
`received unexpected HTTP status: 503 Service Unavailable`,
}
for _, msg := range transient {
if !isTransientDockerPullError(errors.New(msg)) {
t.Fatalf("expected transient pull error for %q", msg)
}
}
permanent := []string{
`manifest unknown`,
`pull access denied, repository does not exist or may require authorization`,
`unauthorized: authentication required`,
`invalid reference format`,
}
for _, msg := range permanent {
if isTransientDockerPullError(errors.New(msg)) {
t.Fatalf("expected permanent pull error for %q", msg)
}
}
}
func TestPreferDockerAPIConsoleTransportByDefault(t *testing.T) {
t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "")
if preferDockerCLIConsoleTransport() {
t.Fatalf("expected Docker API attach transport by default")
}
}
func TestPreferDockerCLIConsoleTransportOverride(t *testing.T) {
t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "cli")
if !preferDockerCLIConsoleTransport() {
t.Fatalf("expected Docker CLI transport override to be honored")
}
t.Setenv("ADPANEL_DOCKER_STREAM_TRANSPORT", "docker-api")
if preferDockerCLIConsoleTransport() {
t.Fatalf("expected Docker API transport override to be honored")
}
}
func TestEnterpriseLinuxOSReleaseDetection(t *testing.T) {
if !isEnterpriseLinuxOSRelease("ID=rocky\nID_LIKE=\"rhel centos fedora\"\n") {
t.Fatalf("expected Rocky Linux to prefer enterprise Linux stdin fallback")
}
if !isEnterpriseLinuxOSRelease("ID=almalinux\nID_LIKE=\"rhel centos fedora\"\n") {
t.Fatalf("expected AlmaLinux to prefer enterprise Linux stdin fallback")
}
if isEnterpriseLinuxOSRelease("ID=ubuntu\nID_LIKE=debian\n") {
t.Fatalf("did not expect Ubuntu to prefer enterprise Linux stdin fallback")
}
}
func TestPreferDockerCLIPTYStdinTransportOverride(t *testing.T) {
t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "pty")
if !preferDockerCLIPTYStdinTransport() {
t.Fatalf("expected Docker CLI PTY stdin override to be honored")
}
t.Setenv("ADPANEL_DOCKER_STDIN_TRANSPORT", "docker-api")
if preferDockerCLIPTYStdinTransport() {
t.Fatalf("expected Docker API stdin override to be honored")
}
}
func TestParseDockerLogSnapshotEntriesKeepsTimestamps(t *testing.T) {
raw := "2026-05-14T19:20:01.123456789Z server starting\n" +
"2026-05-14T19:20:02Z Done (3.2s)! For help, type \"help\"\n"
entries := parseDockerLogSnapshotEntries(raw, 10)
if len(entries) != 2 {
t.Fatalf("expected 2 entries, got %#v", entries)
}
if entries[0].line != "server starting" {
t.Fatalf("expected timestamp prefix to be removed, got %q", entries[0].line)
}
if entries[0].ts != 1778786401123 {
t.Fatalf("expected nanosecond timestamp to be parsed as ms, got %d", entries[0].ts)
}
if entries[1].line != `Done (3.2s)! For help, type "help"` {
t.Fatalf("unexpected second line: %q", entries[1].line)
}
if entries[1].ts != 1778786402000 {
t.Fatalf("expected whole-second timestamp to be parsed as ms, got %d", entries[1].ts)
}
}
func TestPterodactylRustKeepsHomeContainerVolume(t *testing.T) {
cfg := imageConfig{
Entrypoint: []string{"/bin/bash", "/entrypoint.sh"},
Workdir: "/home/container",
Env: map[string]string{},
}
binds, dataDir := sanitizeCustomImageDefaultBinds(
"ghcr.io/pterodactyl/games:rust",
cfg,
[]string{"/srv/adpanel/rust:/home/container"},
"/home/container",
)
if len(binds) != 1 || binds[0] != "/srv/adpanel/rust:/home/container" {
t.Fatalf("expected /home/container bind to be preserved, got %#v", binds)
}
if dataDir != "/home/container" {
t.Fatalf("expected dataDir /home/container, got %q", dataDir)
}
}
func TestImageWorkdirBindIsKeptWhenItIsKnownGameDataPath(t *testing.T) {
cfg := imageConfig{
Entrypoint: []string{"/entrypoint.sh"},
Workdir: "/steamcmd/rust",
Env: map[string]string{},
}
binds, dataDir := sanitizeCustomImageDefaultBinds(
"didstopia/rust-server:full",
cfg,
[]string{"/srv/adpanel/rust:/steamcmd/rust"},
"/steamcmd/rust",
)
if len(binds) != 1 || binds[0] != "/srv/adpanel/rust:/steamcmd/rust" {
t.Fatalf("expected known data-path bind to be preserved, got %#v", binds)
}
if dataDir != "/steamcmd/rust" {
t.Fatalf("expected dataDir /steamcmd/rust, got %q", dataDir)
}
}
func TestRustRestartRecreatesContainer(t *testing.T) {
if !shouldRecreateContainerOnRestart(map[string]any{"type": "rust"}) {
t.Fatalf("expected rust template restart to recreate the container")
}
if !shouldRecreateContainerOnRestart(map[string]any{
"type": "custom",
"runtime": map[string]any{
"image": "ghcr.io/pterodactyl/games",
"tag": "rust",
},
}) {
t.Fatalf("expected pterodactyl rust image restart to recreate the container")
}
if shouldRecreateContainerOnRestart(map[string]any{"type": "minecraft"}) {
t.Fatalf("did not expect minecraft restart to use rust recreate path")
}
}
func TestRustGetsDefaultHighFileLimit(t *testing.T) {
resources := withRuntimeDefaultFileLimit(nil, "rust", "ghcr.io/pterodactyl/games:rust")
if resources == nil || resources.FileLimit == nil || *resources.FileLimit != maxFileLimit {
t.Fatalf("expected rust to default to max file limit, got %#v", resources)
}
customLimit := 65535
resources = withRuntimeDefaultFileLimit(&resourceLimits{FileLimit: &customLimit}, "rust", "ghcr.io/pterodactyl/games:rust")
if resources == nil || resources.FileLimit == nil || *resources.FileLimit != customLimit {
t.Fatalf("expected explicit file limit to be preserved, got %#v", resources)
}
if got := withRuntimeDefaultFileLimit(nil, "minecraft", "eclipse-temurin:21-jre"); got != nil {
t.Fatalf("did not expect non-rust runtime defaults, got %#v", got)
}
}
func TestCfxRuntimeLayoutStaysInsideMountedServerDir(t *testing.T) {
serverDir := t.TempDir()
if err := ensureDir(filepath.Join(serverDir, "serverfiles")); err != nil {
t.Fatalf("failed to create nested legacy dir: %v", err)
}
if err := writeFileNoFollow(filepath.Join(serverDir, "serverfiles", "server.cfg"), []byte("sv_maxclients 32\n"), 0o644); err != nil {
t.Fatalf("failed to create legacy cfg: %v", err)
}
runtimeObj := map[string]any{
"volumes": []any{"{BOT_DIR}:/serverdata"},
"workdir": "/serverdata",
"install": map[string]any{
"runtimePath": "/serverdata",
},
"env": map[string]any{
"DATA_DIR": "/serverdata",
"SERVER_DIR": "/serverdata/serverfiles",
"DATA_PERM": "770",
"SERVER_KEY": "keep-me",
"START_VARS": "+set gamename rdr3",
"GAME_CONFIG": "old.cfg",
},
}
if !normalizeCfxRuntimeLayout("redm", runtimeObj, serverDir) {
t.Fatalf("expected legacy CFX runtime to be normalized")
}
volumes := runtimeObj["volumes"].([]any)
if len(volumes) != 1 || volumes[0] != "{BOT_DIR}:/serverdata/serverfiles" {
t.Fatalf("expected server root to be mounted directly to CFX server dir, got %#v", volumes)
}
if runtimeObj["workdir"] != "/serverdata/serverfiles" {
t.Fatalf("expected CFX workdir inside mounted server dir, got %#v", runtimeObj["workdir"])
}
if runtimeObj["runAsRoot"] != true {
t.Fatalf("expected CFX entrypoint to keep image root bootstrap enabled, got %#v", runtimeObj["runAsRoot"])
}
env := runtimeObj["env"].(map[string]string)
for key, want := range map[string]string{
"DATA_DIR": "/serverdata/serverfiles",
"SERVER_DIR": "/serverdata/serverfiles",
"HOME": "/serverdata/serverfiles",
"DATA_PERM": "777",
"GAME_CONFIG": "server.cfg",
} {
if got := env[key]; got != want {
t.Fatalf("expected env %s=%q, got %q", key, want, got)
}
}
if env["SERVER_KEY"] != "keep-me" || env["START_VARS"] != "+set gamename rdr3" {
t.Fatalf("expected CFX-specific user env to be preserved, got %#v", env)
}
install := runtimeObj["install"].(map[string]any)
if install["runtimePath"] != "/serverdata/serverfiles" || install["mountPath"] != "/mnt/server" {
t.Fatalf("expected CFX install paths to stay aligned to mounted dir, got %#v", install)
}
if !pathExists(filepath.Join(serverDir, "server.cfg")) {
t.Fatalf("expected nested legacy serverfiles content to be migrated into server root")
}
}
func TestLegacyRustRuntimeMigratesToPterodactyl(t *testing.T) {
meta := map[string]any{
"type": "rust",
"template": "rust",
"runtime": map[string]any{
"image": "didstopia/rust-server",
"tag": "full",
"volumes": []any{"{BOT_DIR}:/steamcmd/rust"},
"workdir": "/",
"env": map[string]any{
"RUST_SERVER_NAME": "Legacy Rust",
"RUST_RCON_PASSWORD": "secret",
"RUST_SERVER_QUERYPORT": "28016",
},
},
}
if !normalizeRustRuntimeForPterodactyl(meta) {
t.Fatalf("expected legacy rust metadata to be migrated")
}
runtimeObj := meta["runtime"].(map[string]any)
if runtimeObj["image"] != "ghcr.io/pterodactyl/games" || runtimeObj["tag"] != "rust" {
t.Fatalf("expected pterodactyl rust runtime, got %#v:%#v", runtimeObj["image"], runtimeObj["tag"])
}
env := runtimeObj["env"].(map[string]string)
if env["SERVER_NAME"] != "Legacy Rust" || env["RCON_PASS"] != "secret" {
t.Fatalf("expected legacy env values to be preserved, got %#v", env)
}
volumes := runtimeObj["volumes"].([]any)
if len(volumes) != 1 || volumes[0] != "{BOT_DIR}:/home/container" {
t.Fatalf("expected home/container volume, got %#v", volumes)
}
}
+11
View File
@@ -0,0 +1,11 @@
const fs = require('fs');
let cssContent = fs.readFileSync('public/css/bot.css', 'utf8');
cssContent = cssContent.replace(/transition: opacity \.2s ease, transform \.25s ease;/g, 'transition: opacity .2s ease, max-width .25s cubic-bezier(0.4, 0, 0.2, 1);');
cssContent = cssContent.replace(/width: 150px;/g, 'max-width: 150px;');
cssContent = cssContent.replace(/width: 200px;/g, 'max-width: 200px;');
cssContent = cssContent.replace(/width: 0;/g, 'max-width: 0;');
fs.writeFileSync('public/css/bot.css', cssContent);
let ejsContent = fs.readFileSync('views/bot.ejs', 'utf8');
ejsContent = ejsContent.replace(/transition:\n\s*opacity 0\.2s cubic-bezier\(0\.4, 0, 0\.2, 1\),\n\s*transform 0\.25s cubic-bezier\(0\.4, 0, 0\.2, 1\);/g, 'transition: max-width 0.25s cubic-bezier(0.4, 0, 0.2, 1), opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);');
fs.writeFileSync('views/bot.ejs', ejsContent);
+10
View File
@@ -0,0 +1,10 @@
const fs = require('fs');
let cssContent = fs.readFileSync('public/css/bot.css', 'utf8');
cssContent = cssContent.replace(/will-change: opacity, transform;/g, 'will-change: opacity, max-width;');
fs.writeFileSync('public/css/bot.css', cssContent);
let ejsContent = fs.readFileSync('views/bot.ejs', 'utf8');
ejsContent = ejsContent.replace(/transform: translateZ\(0\);\n\s*backface-visibility: hidden;/g, 'transform: translateZ(0);');
fs.writeFileSync('views/bot.ejs', ejsContent);
+50
View File
@@ -0,0 +1,50 @@
package main
import (
"path/filepath"
"testing"
)
// adpanel:fs-scope - lock in the server-scoped FS confinement (#2). The generic
// /v1/fs/* handlers must, when a server name is supplied, reject any path that
// belongs to a *different* server on the same disk root, even though that path is
// still under a valid volumes root (so safeUnderVolumes alone would allow it).
func TestSafeUnderServerOrVolumes_ScopesToSingleServer(t *testing.T) {
a, vol := newTestAgent(t)
alphaFile := filepath.Join(vol, "alpha", "config", "app.cfg")
betaFile := filepath.Join(vol, "beta", "secrets.txt")
// No scope: behaves exactly like safeUnderVolumes (back-compat).
if got, ok := a.safeUnderServerOrVolumes("", alphaFile); !ok || got != filepath.Clean(alphaFile) {
t.Fatalf("empty scope should accept any in-volume path, got (%q,%v)", got, ok)
}
// Matching scope: accepted.
if got, ok := a.safeUnderServerOrVolumes("alpha", alphaFile); !ok || got != filepath.Clean(alphaFile) {
t.Fatalf("alpha scope should accept alpha path, got (%q,%v)", got, ok)
}
// The server root itself is accepted (e.g. listing the root directory).
if _, ok := a.safeUnderServerOrVolumes("alpha", a.serverDir("alpha")); !ok {
t.Fatalf("alpha scope should accept alpha root")
}
// Cross-server access is the key boundary: beta's files must be refused when
// the scope is alpha, even though betaFile is under a valid volumes root.
if _, ok := a.safeUnderServerOrVolumes("alpha", betaFile); ok {
t.Fatalf("alpha scope must reject beta's file %q", betaFile)
}
// A traversal that climbs out of alpha into beta must also be refused.
escape := filepath.Join(vol, "alpha", "..", "beta", "secrets.txt")
if _, ok := a.safeUnderServerOrVolumes("alpha", escape); ok {
t.Fatalf("alpha scope must reject traversal into beta: %q", escape)
}
// An unknown/invalid scope name resolves to a server dir that exists nowhere,
// so nothing matches and access is denied (fail-closed).
if _, ok := a.safeUnderServerOrVolumes("does-not-exist", alphaFile); ok {
t.Fatalf("unknown scope should not match alpha path")
}
}
+14
View File
@@ -0,0 +1,14 @@
module adpanel-node
go 1.24.0
toolchain go1.24.11
require (
github.com/creack/pty v1.1.24
github.com/ulikunitz/xz v0.5.14
golang.org/x/crypto v0.46.0
nhooyr.io/websocket v1.8.17
)
require golang.org/x/sys v0.39.0 // indirect
+12
View File
@@ -0,0 +1,12 @@
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
github.com/ulikunitz/xz v0.5.14 h1:uv/0Bq533iFdnMHZdRBTOlaNMdb1+ZxXIlHDZHIHcvg=
github.com/ulikunitz/xz v0.5.14/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=
golang.org/x/crypto v0.46.0 h1:cKRW/pmt1pKAfetfu+RCEvjvZkA9RimPbh7bhFjGVBU=
golang.org/x/crypto v0.46.0/go.mod h1:Evb/oLKmMraqjZ2iQTwDwvCtJkczlDuTmdJXoZVzqU0=
golang.org/x/sys v0.39.0 h1:CvCKL8MeisomCi6qNZ+wbb0DN9E5AATixKsvNtMoMFk=
golang.org/x/sys v0.39.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/term v0.38.0 h1:PQ5pkm/rLO6HnxFR7N2lJHOZX6Kez5Y1gDSJla6jo7Q=
golang.org/x/term v0.38.0/go.mod h1:bSEAKrOT1W+VSu9TSCMtoGEOUcKxOKgl3LE5QEF/xVg=
nhooyr.io/websocket v1.8.17 h1:KEVeLJkUywCKVsnLIDlD/5gtayKp8VoCkksHCGGfT9Y=
nhooyr.io/websocket v1.8.17/go.mod h1:rN9OFWIUwuxg4fR5tELlYC04bXYowCP9GX47ivo2l+c=
+5763 -679
View File
File diff suppressed because it is too large. Load diff
+1214 -122
View File
File diff suppressed because it is too large. Load diff
+20120
View File
File diff suppressed because it is too large. Load diff
+360
View File
@@ -0,0 +1,360 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
func newTestAgent(t *testing.T) (*Agent, string) {
t.Helper()
root := t.TempDir()
vol := filepath.Join(root, "servers")
if err := os.MkdirAll(vol, 0o750); err != nil {
t.Fatalf("mkdir volumes: %v", err)
}
if err := os.MkdirAll(filepath.Join(root, "backups"), 0o750); err != nil {
t.Fatalf("mkdir backups: %v", err)
}
return &Agent{dataRoot: root, volumesDir: vol}, vol
}
func registerTestDisk(t *testing.T, a *Agent, mount string, limitGb int64) NodeDisk {
t.Helper()
if err := os.MkdirAll(a.diskLayoutVolumes(mount), 0o750); err != nil {
t.Fatalf("mkdir disk volumes: %v", err)
}
if err := os.MkdirAll(a.diskLayoutBackups(mount), 0o750); err != nil {
t.Fatalf("mkdir disk backups: %v", err)
}
info := a.readNodeInformation()
d := NodeDisk{ID: "disk-test-" + filepath.Base(mount), MountPath: filepath.Clean(mount), LimitGb: limitGb}
info.Disks = append(info.Disks, d)
if err := a.writeNodeInformation(info); err != nil {
t.Fatalf("persist disk: %v", err)
}
a.invalidateServerDiskCache("")
return d
}
func TestSafeUnderVolumes_PrimaryOnly(t *testing.T) {
a, vol := newTestAgent(t)
in := filepath.Join(vol, "srv1", "file.txt")
got, ok := a.safeUnderVolumes(in)
if !ok || got != filepath.Clean(in) {
t.Fatalf("expected accept %q, got (%q,%v)", in, got, ok)
}
got, ok = a.safeUnderVolumes("srv1/x")
if !ok || got != filepath.Join(vol, "srv1", "x") {
t.Fatalf("relative anchor failed: (%q,%v)", got, ok)
}
if _, ok := a.safeUnderVolumes(vol); !ok {
t.Fatalf("expected root to be accepted")
}
for _, bad := range []string{
filepath.Join(vol, "..", "etc", "passwd"),
"/etc/passwd",
filepath.Dir(vol),
"",
" ",
} {
if _, ok := a.safeUnderVolumes(bad); ok {
t.Fatalf("expected reject for %q", bad)
}
}
if r := a.volumeRootFor(in); r != filepath.Clean(vol) {
t.Fatalf("volumeRootFor primary: got %q want %q", r, vol)
}
roots := a.allDiskVolumeRoots()
if len(roots) != 1 || roots[0] != filepath.Clean(vol) {
t.Fatalf("expected single primary root, got %v", roots)
}
}
func TestSafeUnderVolumes_SecondDisk(t *testing.T) {
a, vol := newTestAgent(t)
mount := t.TempDir()
registerTestDisk(t, a, mount, 50)
disk2 := a.diskLayoutVolumes(mount)
in := filepath.Join(disk2, "srvOnDisk2", "data.cfg")
got, ok := a.safeUnderVolumes(in)
if !ok || got != filepath.Clean(in) {
t.Fatalf("second-disk path rejected: (%q,%v)", got, ok)
}
if r := a.volumeRootFor(in); r != filepath.Clean(disk2) {
t.Fatalf("volumeRootFor disk2: got %q want %q", r, disk2)
}
prim := filepath.Join(vol, "srv1", "x")
if r := a.volumeRootFor(prim); r != filepath.Clean(vol) {
t.Fatalf("volumeRootFor primary with extra disk: got %q want %q", r, vol)
}
if _, ok := a.safeUnderVolumes("/etc/passwd"); ok {
t.Fatalf("expected reject for path outside all roots")
}
roots := a.allDiskVolumeRoots()
if len(roots) != 2 || roots[0] != filepath.Clean(vol) || roots[1] != filepath.Clean(disk2) {
t.Fatalf("unexpected roots: %v", roots)
}
}
func TestServerDirRoutingByDisk(t *testing.T) {
a, vol := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
if got := a.serverDir("alpha"); got != filepath.Join(vol, "alpha") {
t.Fatalf("primary serverDir: got %q", got)
}
a.setServerDiskMapping("beta", d.ID)
wantVol := filepath.Join(a.diskLayoutVolumes(mount), "beta")
if got := a.serverDir("beta"); got != wantVol {
t.Fatalf("disk2 serverDir: got %q want %q", got, wantVol)
}
wantBk := filepath.Join(a.diskLayoutBackups(mount), "beta")
if got := a.serverBackupsDir("beta"); got != wantBk {
t.Fatalf("disk2 serverBackupsDir: got %q want %q", got, wantBk)
}
if name := a.serverNameFromPath(filepath.Join(wantVol, "world", "level.dat")); name != "beta" {
t.Fatalf("serverNameFromPath disk2: got %q", name)
}
}
func TestCheckDiskCapacity(t *testing.T) {
a, _ := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 1)
oneGiB := int64(1024 * 1024 * 1024)
if err := a.checkDiskCapacity(d, oneGiB-1); err != nil {
t.Fatalf("expected allow at limit-1, got %v", err)
}
if err := a.checkDiskCapacity(d, oneGiB+1); err == nil {
t.Fatalf("expected capacity rejection")
}
if err := a.checkDiskCapacity(a.primaryDisk(), oneGiB*1000); err != nil {
t.Fatalf("primary disk must be unlimited, got %v", err)
}
}
func TestPathAllowedForDisk(t *testing.T) {
bad := []string{"", "relative/path", "/", "/etc", "/var/lib/node", "/var/lib/node/servers", "/proc/1", "/mnt/disk1/", "/mnt/./disk1"}
for _, p := range bad {
if _, err := pathAllowedForDisk(p); err == nil {
t.Fatalf("expected reject for %q", p)
}
}
good := []string{"/mnt/disk1", "/srv/storage/extra", "/data2"}
for _, p := range good {
if c, err := pathAllowedForDisk(p); err != nil || c != p {
t.Fatalf("expected allow for %q, got (%q,%v)", p, c, err)
}
}
}
func TestAllDiskVolumeRoots_NoDuplicatePrimary(t *testing.T) {
a, vol := newTestAgent(t)
registerTestDisk(t, a, a.dataRoot, 10)
roots := a.allDiskVolumeRoots()
if len(roots) != 1 || roots[0] != filepath.Clean(vol) {
t.Fatalf("expected single primary root, got %v", roots)
}
}
func TestEnumerateServerNamesAcrossDisks(t *testing.T) {
a, vol := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
if err := os.MkdirAll(filepath.Join(vol, "alpha"), 0o750); err != nil {
t.Fatalf("mkdir alpha: %v", err)
}
a.setServerDiskMapping("beta", d.ID)
if err := os.MkdirAll(a.serverDir("beta"), 0o750); err != nil {
t.Fatalf("mkdir beta: %v", err)
}
if err := os.MkdirAll(filepath.Join(vol, ".adpanel_meta"), 0o750); err != nil {
t.Fatalf("mkdir meta: %v", err)
}
names := a.enumerateServerNames()
found := map[string]bool{}
for _, n := range names {
if strings.HasPrefix(n, ".") {
t.Fatalf("dotfile leaked into enumeration: %q", n)
}
found[n] = true
}
if !found["alpha"] || !found["beta"] {
t.Fatalf("expected both alpha (primary) and beta (disk2), got %v", names)
}
}
func TestSecondDiskDeleteRoutesToOwningDisk(t *testing.T) {
a, _ := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
a.setServerDiskMapping("beta", d.ID)
wantVolRoot := filepath.Clean(a.diskLayoutVolumes(mount))
if got := a.serverVolumesRoot("beta"); got != wantVolRoot {
t.Fatalf("serverVolumesRoot disk2: got %q want %q", got, wantVolRoot)
}
wantBkRoot := filepath.Clean(a.diskLayoutBackups(mount))
if got := a.serverBackupsRoot("beta"); got != wantBkRoot {
t.Fatalf("serverBackupsRoot disk2: got %q want %q", got, wantBkRoot)
}
if err := os.MkdirAll(a.serverDir("beta"), 0o750); err != nil {
t.Fatalf("mkdir srv: %v", err)
}
if err := os.MkdirAll(a.serverBackupsDir("beta"), 0o750); err != nil {
t.Fatalf("mkdir bk: %v", err)
}
if !isUnder(wantVolRoot, a.serverDir("beta")) {
t.Fatalf("server dir not under its volumes root")
}
if !isUnder(wantBkRoot, a.serverBackupsDir("beta")) {
t.Fatalf("backup dir not under its backups root")
}
if _, exists, err := a.detachPathForAsyncDelete(wantVolRoot, a.serverDir("beta"), "server", "beta"); err != nil || !exists {
t.Fatalf("detach second-disk server failed: exists=%v err=%v", exists, err)
}
if _, exists, err := a.detachPathForAsyncDelete(wantBkRoot, a.serverBackupsDir("beta"), "backups", "beta"); err != nil || !exists {
t.Fatalf("detach second-disk backups failed: exists=%v err=%v", exists, err)
}
if _, statErr := os.Stat(a.serverDir("beta")); !os.IsNotExist(statErr) {
t.Fatalf("expected second-disk server dir to be detached, stat err=%v", statErr)
}
}
func TestDiskMonitorEnforcesSecondDiskQuota(t *testing.T) {
a, _ := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
a.setServerDiskMapping("beta", d.ID)
srvDir := a.serverDir("beta")
if err := os.MkdirAll(srvDir, 0o750); err != nil {
t.Fatalf("mkdir srv: %v", err)
}
meta := map[string]any{"resources": map[string]any{"storageMb": float64(20)}}
if err := a.saveMeta(srvDir, meta); err != nil {
t.Fatalf("saveMeta: %v", err)
}
names := a.enumerateServerNames()
if !contains(names, "beta") {
t.Fatalf("disk monitor would not see secondary-disk server: %v", names)
}
if got := a.getServerDiskLimitBytes(srvDir); got != 20*1024*1024 {
t.Fatalf("limit bytes: got %d want %d", got, 20*1024*1024)
}
big := filepath.Join(srvDir, "server.jar")
f, err := os.Create(big)
if err != nil {
t.Fatalf("create big: %v", err)
}
if err := f.Truncate(50 * 1024 * 1024); err != nil {
f.Close()
t.Skipf("sparse truncate unsupported: %v", err)
}
f.Close()
used, err := getDirSizeBytes(srvDir)
if err != nil {
t.Fatalf("size: %v", err)
}
if used <= a.getServerDiskLimitBytes(srvDir) {
t.Fatalf("expected usage %d to exceed limit %d", used, a.getServerDiskLimitBytes(srvDir))
}
}
func contains(ss []string, want string) bool {
for _, s := range ss {
if s == want {
return true
}
}
return false
}
func TestResolveStructuredBindsKeepsSecondDiskBind(t *testing.T) {
a, _ := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
a.setServerDiskMapping("beta", d.ID)
serverDir := a.serverDir("beta")
if err := os.MkdirAll(serverDir, 0o750); err != nil {
t.Fatalf("mkdir srv: %v", err)
}
runtimeObj := map[string]any{
"volumes": []any{"{SERVER_DIR}:/data"},
}
binds, _ := a.resolveStructuredBinds("minecraft", runtimeObj, serverDir)
if len(binds) != 1 {
t.Fatalf("expected the secondary-disk bind to be kept, got %v", binds)
}
wantHost := filepath.Clean(serverDir)
if !strings.HasPrefix(binds[0], wantHost+":") {
t.Fatalf("bind host path not routed to second disk: %q (want prefix %q:)", binds[0], wantHost)
}
}
func TestColdCacheDeleteRemovesSecondDiskFiles(t *testing.T) {
a, _ := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
a.setServerDiskMapping("beta", d.ID)
srvDir := a.serverDir("beta")
if err := os.MkdirAll(srvDir, 0o750); err != nil {
t.Fatalf("mkdir srv: %v", err)
}
bkDir := a.serverBackupsDir("beta")
if err := os.MkdirAll(bkDir, 0o750); err != nil {
t.Fatalf("mkdir bk: %v", err)
}
if err := a.saveMeta(srvDir, map[string]any{"__diskId": d.ID}); err != nil {
t.Fatalf("saveMeta: %v", err)
}
a.invalidateServerDiskCache("beta")
if got := a.serverDir("beta"); got != srvDir {
t.Fatalf("cold-cache serverDir: got %q want %q", got, srvDir)
}
a.invalidateServerDiskCache("beta")
volRoot := a.serverVolumesRoot("beta")
bkRoot := a.serverBackupsRoot("beta")
if _, exists, err := a.detachPathForAsyncDelete(volRoot, a.serverDir("beta"), "server", "beta"); err != nil || !exists {
t.Fatalf("cold-cache server detach failed: exists=%v err=%v", exists, err)
}
if _, exists, err := a.detachPathForAsyncDelete(bkRoot, a.serverBackupsDir("beta"), "backups", "beta"); err != nil || !exists {
t.Fatalf("cold-cache backups detach failed: exists=%v err=%v", exists, err)
}
if _, statErr := os.Stat(srvDir); !os.IsNotExist(statErr) {
t.Fatalf("expected disk2 server dir removed, stat err=%v", statErr)
}
if _, statErr := os.Stat(bkDir); !os.IsNotExist(statErr) {
t.Fatalf("expected disk2 backups dir removed, stat err=%v", statErr)
}
}
func TestLegacyServerWithoutDiskIdResolvesByScan(t *testing.T) {
a, _ := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
legacyDir := filepath.Join(a.diskLayoutVolumes(mount), "legacy")
if err := os.MkdirAll(legacyDir, 0o750); err != nil {
t.Fatalf("mkdir legacy: %v", err)
}
got := a.diskForServer("legacy")
if got.ID != d.ID {
t.Fatalf("legacy server mis-routed: got disk %q want %q", got.ID, d.ID)
}
if a.serverDir("legacy") != legacyDir {
t.Fatalf("serverDir for legacy: got %q want %q", a.serverDir("legacy"), legacyDir)
}
}
func TestPrimaryServerWithoutDiskIdStaysPrimary(t *testing.T) {
a, vol := newTestAgent(t)
mount := t.TempDir()
registerTestDisk(t, a, mount, 50)
if err := os.MkdirAll(filepath.Join(vol, "primaryonly"), 0o750); err != nil {
t.Fatalf("mkdir primaryonly: %v", err)
}
got := a.diskForServer("primaryonly")
if !(got.Primary || got.ID == primaryDiskID) {
t.Fatalf("primary-only server mis-routed to %q", got.ID)
}
}
+382
View File
@@ -0,0 +1,382 @@
package main
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"testing"
"time"
)
// signedAdminRequest builds an HTTP request carrying a valid panel-admin HMAC
// signature for (action, subject), mirroring verifyNodeAdminRequest exactly.
func signedAdminRequest(a *Agent, method, path, action, subject string, body any) *http.Request {
var buf bytes.Buffer
if body != nil {
_ = json.NewEncoder(&buf).Encode(body)
}
req := httptest.NewRequest(method, path, &buf)
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-panel-role", "admin")
secret := a.panelHMAC
if secret == "" {
secret = a.token
}
ts := strconv.FormatInt(time.Now().UnixMilli(), 10)
base := fmt.Sprintf("%s|%s|%s|%s|%s", a.uuid, action, subject, "admin", ts)
m := hmac.New(sha256.New, []byte(secret))
_, _ = m.Write([]byte(base))
req.Header.Set("x-panel-ts", ts)
req.Header.Set("x-panel-sign", hex.EncodeToString(m.Sum(nil)))
return req
}
func newSignedTestAgent(t *testing.T) (*Agent, string) {
t.Helper()
a, vol := newTestAgent(t)
a.uuid = "node-uuid-test"
a.token = "node-secret-token"
a.panelHMAC = "panel-hmac-secret"
return a, vol
}
func decodeJSONBody(t *testing.T, rr *httptest.ResponseRecorder) map[string]any {
t.Helper()
var m map[string]any
if err := json.Unmarshal(rr.Body.Bytes(), &m); err != nil {
t.Fatalf("decode response: %v (body=%q)", err, rr.Body.String())
}
return m
}
// --- Path traversal / symlink escape rejection across all disk roots ---
func TestSymlinkEscapeBlockedAcrossDisks(t *testing.T) {
a, vol := newSignedTestAgent(t)
mount := t.TempDir()
registerTestDisk(t, a, mount, 50)
disk2 := a.diskLayoutVolumes(mount)
// A symlink inside disk2 that points outside every registered root.
outside := t.TempDir()
if err := os.WriteFile(filepath.Join(outside, "secret"), []byte("x"), 0o600); err != nil {
t.Fatalf("write secret: %v", err)
}
link := filepath.Join(disk2, "escape")
if err := os.Symlink(outside, link); err != nil {
t.Skipf("symlinks unsupported: %v", err)
}
// The path itself is lexically under disk2 (passes safeUnderVolumes) but
// ensureResolvedUnder must reject it because it resolves outside.
target := filepath.Join(link, "secret")
if _, ok := a.safeUnderVolumes(target); !ok {
t.Fatalf("expected lexical accept under disk2")
}
if err := ensureResolvedUnder(a.volumeRootFor(target), target); err == nil {
t.Fatalf("expected symlink escape to be blocked on disk2")
}
// Traversal strings are rejected on the primary root too.
for _, bad := range []string{
filepath.Join(vol, "..", "..", "etc", "passwd"),
"/etc/shadow",
} {
if _, ok := a.safeUnderVolumes(bad); ok {
t.Fatalf("expected reject for %q", bad)
}
}
}
// --- Admin guard: non-admin role -> 403 ---
func TestDiskAdd_NonAdmin403(t *testing.T) {
a, _ := newSignedTestAgent(t)
mount := t.TempDir()
body := map[string]any{"mountPath": mount, "limitGb": 10}
buf, _ := json.Marshal(body)
req := httptest.NewRequest("POST", "/v1/disks", bytes.NewReader(buf))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-panel-role", "viewer") // not admin
rr := httptest.NewRecorder()
a.handleDiskAdd(rr, req)
if rr.Code != 403 {
t.Fatalf("expected 403 for non-admin, got %d (%s)", rr.Code, rr.Body.String())
}
}
// --- Signature: missing -> 401, forged -> 401 ---
func TestDiskAdd_MissingSignature401(t *testing.T) {
a, _ := newSignedTestAgent(t)
mount := t.TempDir()
body := map[string]any{"mountPath": mount, "limitGb": 10}
buf, _ := json.Marshal(body)
req := httptest.NewRequest("POST", "/v1/disks", bytes.NewReader(buf))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("x-panel-role", "admin") // admin but no signature headers
rr := httptest.NewRecorder()
a.handleDiskAdd(rr, req)
if rr.Code != 401 {
t.Fatalf("expected 401 for missing signature, got %d (%s)", rr.Code, rr.Body.String())
}
}
func TestDiskAdd_ForgedSignature401(t *testing.T) {
a, _ := newSignedTestAgent(t)
mount := t.TempDir()
req := signedAdminRequest(a, "POST", "/v1/disks", "disk-add", mount,
map[string]any{"mountPath": mount, "limitGb": 10})
// Tamper with the signature.
req.Header.Set("x-panel-sign", "deadbeef")
rr := httptest.NewRecorder()
a.handleDiskAdd(rr, req)
if rr.Code != 401 {
t.Fatalf("expected 401 for forged signature, got %d (%s)", rr.Code, rr.Body.String())
}
}
func TestDiskAdd_ValidSignatureSucceeds(t *testing.T) {
a, _ := newSignedTestAgent(t)
mount := t.TempDir() // real, writable, allowlisted (TempDir is under /tmp)
req := signedAdminRequest(a, "POST", "/v1/disks", "disk-add", filepath.Clean(mount),
map[string]any{"mountPath": mount, "limitGb": 1})
rr := httptest.NewRecorder()
a.handleDiskAdd(rr, req)
if rr.Code != 200 {
t.Fatalf("expected 200 for valid add, got %d (%s)", rr.Code, rr.Body.String())
}
got := decodeJSONBody(t, rr)
if ok, _ := got["ok"].(bool); !ok {
t.Fatalf("expected ok=true, got %v", got)
}
disks := a.registeredDisks()
if len(disks) != 1 || disks[0].MountPath != filepath.Clean(mount) {
t.Fatalf("disk not persisted: %v", disks)
}
}
// --- Quota math: 49 GiB used + 2 GiB write > 50 GiB limit -> 507-style reject ---
func TestPerDiskCapacityQuotaMath(t *testing.T) {
a, _ := newSignedTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50) // 50 GiB ceiling
gib := int64(1024 * 1024 * 1024)
// Simulate 49 GiB already used by writing a sparse file in the disk's volumes.
used := filepath.Join(a.diskLayoutVolumes(mount), "srv", "big.bin")
if err := os.MkdirAll(filepath.Dir(used), 0o750); err != nil {
t.Fatalf("mkdir: %v", err)
}
f, err := os.Create(used)
if err != nil {
t.Fatalf("create: %v", err)
}
if err := f.Truncate(49 * gib); err != nil {
f.Close()
t.Skipf("sparse truncate unsupported: %v", err)
}
f.Close()
// 49 + 2 = 51 > 50 -> reject.
if err := a.checkDiskCapacity(d, 2*gib); err == nil {
t.Fatalf("expected capacity rejection for 49+2>50 GiB")
}
// 49 + 0.5 = 49.5 <= 50 -> allow.
if err := a.checkDiskCapacity(d, gib/2); err != nil {
t.Fatalf("expected allow for 49+0.5<=50 GiB, got %v", err)
}
}
// --- Backup over per-server limit -> 507-style disk_limit_exceeded ---
func TestBackupOverServerLimitRejected(t *testing.T) {
a, vol := newSignedTestAgent(t)
// Create a server on the primary disk with a 1 MB storage quota in meta.
srvDir := filepath.Join(vol, "qsrv")
if err := os.MkdirAll(srvDir, 0o750); err != nil {
t.Fatalf("mkdir srv: %v", err)
}
meta := map[string]any{"resources": map[string]any{"storageMb": float64(1)}}
if err := a.saveMeta(srvDir, meta); err != nil {
t.Fatalf("saveMeta: %v", err)
}
// A 2 MB backup against a 1 MB limit must be rejected.
twoMB := int64(2 * 1024 * 1024)
if errPayload := a.checkDiskLimit(srvDir, twoMB); errPayload == nil {
t.Fatalf("expected backup-over-limit rejection")
} else if errPayload["error"] != "disk_limit_exceeded" {
t.Fatalf("expected disk_limit_exceeded, got %v", errPayload["error"])
}
// A 0-byte addition stays within limit.
if errPayload := a.checkDiskLimit(srvDir, 0); errPayload != nil {
t.Fatalf("expected allow within limit, got %v", errPayload)
}
}
// --- Existing backups count toward the storage limit (adpanel:backup-storage) ---
// Scenario from the field: small server files but backups saturate the quota.
// e.g. 20 MB of files, a 100 MB limit, and backups that already occupy ~85 MB.
// Even though the server FILES are well under the limit, the combined usage
// (files + backups) must be enforced so further writes/backups are rejected.
func TestBackupsCountTowardStorageLimit(t *testing.T) {
a, vol := newSignedTestAgent(t)
name := "bsrv"
srvDir := filepath.Join(vol, name)
if err := os.MkdirAll(srvDir, 0o750); err != nil {
t.Fatalf("mkdir srv: %v", err)
}
// 100 MB limit.
meta := map[string]any{"resources": map[string]any{"storageMb": float64(100)}}
if err := a.saveMeta(srvDir, meta); err != nil {
t.Fatalf("saveMeta: %v", err)
}
// 20 MB of server files.
writeNBytes(t, filepath.Join(srvDir, "world.dat"), 20*1024*1024)
// With only 20 MB of files used, a 30 MB write fits under the 100 MB limit.
if errPayload := a.checkDiskLimit(srvDir, 30*1024*1024); errPayload != nil {
t.Fatalf("expected 30 MB write allowed with only files present, got %v", errPayload)
}
// Now add 85 MB of backups (outside the server dir).
bkDir := a.serverBackupsDir(name)
if err := os.MkdirAll(bkDir, 0o750); err != nil {
t.Fatalf("mkdir backups: %v", err)
}
writeNBytes(t, filepath.Join(bkDir, "backup-1", "data", "world.dat"), 85*1024*1024)
// Combined usage is now 20 + 85 = 105 MB, already over the 100 MB limit, so
// even a 0-byte addition (e.g. starting a new backup) must be rejected.
if errPayload := a.checkDiskLimit(srvDir, 0); errPayload == nil {
t.Fatalf("expected rejection: files + backups exceed limit")
} else if errPayload["error"] != "disk_limit_exceeded" {
t.Fatalf("expected disk_limit_exceeded, got %v", errPayload["error"])
}
// The reported total usage must include the backups.
if got, want := a.getServerTotalUsage(srvDir), int64(105*1024*1024); got != want {
t.Fatalf("getServerTotalUsage = %d, want %d", got, want)
}
}
// writeNBytes creates parent dirs and writes exactly n zero bytes to path.
func writeNBytes(t *testing.T, path string, n int64) {
t.Helper()
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
t.Fatalf("mkdir for %s: %v", path, err)
}
if err := os.WriteFile(path, make([]byte, n), 0o600); err != nil {
t.Fatalf("write %s: %v", path, err)
}
}
// --- FS ops on a second-disk server succeed (safeUnderVolumes regression) ---
func TestFSWriteOnSecondDiskSucceeds(t *testing.T) {
a, _ := newSignedTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
a.setServerDiskMapping("beta", d.ID)
abs := filepath.Join(a.serverDir("beta"), "config", "app.cfg")
// The write path must accept this absolute path under the second disk root.
validated, ok := a.safeUnderVolumes(abs)
if !ok || validated != filepath.Clean(abs) {
t.Fatalf("second-disk write path rejected: (%q,%v)", validated, ok)
}
// Per-disk + per-server limit checks must not error for a small write.
if errPayload := a.checkDiskLimitForPath(abs, 1024); errPayload != nil {
t.Fatalf("expected small write allowed on second disk, got %v", errPayload)
}
// And the resolved root must be the second disk, not the primary.
if root := a.volumeRootFor(abs); root != filepath.Clean(a.diskLayoutVolumes(mount)) {
t.Fatalf("write routed to wrong disk: %q", root)
}
}
// --- limitGb greater than free space is rejected at add time ---
func TestDiskAdd_LimitExceedsFreeSpaceRejected(t *testing.T) {
a, _ := newSignedTestAgent(t)
mount := t.TempDir()
// Determine current free space, then request a limit far above it.
freeGb := freeDiskMb(mount) / 1024
if freeGb <= 0 {
t.Skip("could not determine free space for mount")
}
overGb := freeGb + 1_000_000 // 1 PB beyond free space
req := signedAdminRequest(a, "POST", "/v1/disks", "disk-add", filepath.Clean(mount),
map[string]any{"mountPath": mount, "limitGb": overGb})
rr := httptest.NewRecorder()
a.handleDiskAdd(rr, req)
if rr.Code != 400 {
t.Fatalf("expected 400 for limit>free, got %d (%s)", rr.Code, rr.Body.String())
}
if len(a.registeredDisks()) != 0 {
t.Fatalf("disk should not be persisted when limit exceeds free space")
}
}
// --- Disk delete blocked while referenced by a server -> 409 ---
func TestDiskDeleteBlockedWhileReferenced(t *testing.T) {
a, _ := newSignedTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
// Place a server directory under the disk's volumes root.
srvDir := filepath.Join(a.diskLayoutVolumes(mount), "tenant")
if err := os.MkdirAll(srvDir, 0o750); err != nil {
t.Fatalf("mkdir tenant: %v", err)
}
req := signedAdminRequest(a, "DELETE", "/v1/disks", "disk-remove", d.ID,
map[string]any{"id": d.ID})
rr := httptest.NewRecorder()
a.handleDiskDelete(rr, req)
if rr.Code != 409 {
t.Fatalf("expected 409 for referenced disk, got %d (%s)", rr.Code, rr.Body.String())
}
if len(a.registeredDisks()) != 1 {
t.Fatalf("referenced disk must not be removed")
}
// After the server dir is emptied, removal must succeed.
if err := os.RemoveAll(srvDir); err != nil {
t.Fatalf("cleanup: %v", err)
}
req2 := signedAdminRequest(a, "DELETE", "/v1/disks", "disk-remove", d.ID,
map[string]any{"id": d.ID})
rr2 := httptest.NewRecorder()
a.handleDiskDelete(rr2, req2)
if rr2.Code != 200 {
t.Fatalf("expected 200 after emptying disk, got %d (%s)", rr2.Code, rr2.Body.String())
}
if len(a.registeredDisks()) != 0 {
t.Fatalf("disk should be removed after cleanup")
}
}
+59 -1
View File
@@ -2,8 +2,11 @@ CREATE TABLE IF NOT EXISTS users (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
email VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL, password VARCHAR(255) NOT NULL,
secret VARCHAR(255) NOT NULL, secret VARCHAR(255) NULL,
admin TINYINT(1) NOT NULL DEFAULT 0, admin TINYINT(1) NOT NULL DEFAULT 0,
suspended TINYINT(1) NOT NULL DEFAULT 0,
suspended_at BIGINT UNSIGNED NULL,
suspended_by VARCHAR(255) NULL,
avatar_url VARCHAR(2048) NULL, avatar_url VARCHAR(2048) NULL,
preferences JSON NULL, preferences JSON NULL,
recovery_codes TEXT NULL, recovery_codes TEXT NULL,
@@ -48,6 +51,9 @@ CREATE TABLE IF NOT EXISTS servers (
ip VARCHAR(255) NULL, ip VARCHAR(255) NULL,
port INT NULL, port INT NULL,
status VARCHAR(32) NULL, status VARCHAR(32) NULL,
suspended TINYINT(1) NOT NULL DEFAULT 0,
suspended_at BIGINT UNSIGNED NULL,
suspended_by VARCHAR(255) NULL,
runtime JSON NULL, runtime JSON NULL,
docker JSON NULL, docker JSON NULL,
acl JSON NULL, acl JSON NULL,
@@ -63,6 +69,23 @@ CREATE TABLE IF NOT EXISTS servers (
CONSTRAINT fk_servers_node FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE SET NULL CONSTRAINT fk_servers_node FOREIGN KEY (node_id) REFERENCES nodes(id) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS server_delete_jobs (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
server_name VARCHAR(120) NOT NULL,
technical_name VARCHAR(120) NOT NULL,
node_id VARCHAR(64) NOT NULL,
status ENUM('queued','running','completed','failed') NOT NULL DEFAULT 'queued',
attempts INT UNSIGNED NOT NULL DEFAULT 0,
next_attempt_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_error TEXT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uniq_server_delete_jobs_server (server_name),
KEY idx_server_delete_jobs_status_next (status, next_attempt_at),
KEY idx_server_delete_jobs_node (node_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS user_access ( CREATE TABLE IF NOT EXISTS user_access (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_id BIGINT UNSIGNED NOT NULL, user_id BIGINT UNSIGNED NOT NULL,
@@ -72,6 +95,26 @@ CREATE TABLE IF NOT EXISTS user_access (
CONSTRAINT fk_user_access_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE CONSTRAINT fk_user_access_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS destructive_action_grants (
grant_id CHAR(64) NOT NULL,
user_id BIGINT UNSIGNED NOT NULL,
email VARCHAR(255) NOT NULL,
session_hash CHAR(64) NOT NULL,
secret_hash CHAR(64) NOT NULL,
ip_hash CHAR(64) NOT NULL,
ua_hash CHAR(64) NOT NULL,
verified_at BIGINT UNSIGNED NOT NULL,
expires_at BIGINT UNSIGNED NOT NULL,
revoked_at BIGINT UNSIGNED NULL,
subject VARCHAR(190) NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (grant_id),
KEY idx_destructive_grants_user_expires (user_id, expires_at),
KEY idx_destructive_grants_session (session_hash),
KEY idx_destructive_grants_expires (expires_at),
CONSTRAINT fk_destructive_grants_user FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE IF NOT EXISTS ai_chats ( CREATE TABLE IF NOT EXISTS ai_chats (
id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT, id BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
user_email VARCHAR(255) NOT NULL DEFAULT '', user_email VARCHAR(255) NOT NULL DEFAULT '',
@@ -187,3 +230,18 @@ CREATE TABLE IF NOT EXISTS subdomains (
KEY idx_subdomains_server (server_id), KEY idx_subdomains_server (server_id),
CONSTRAINT fk_subdomains_server FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE CONSTRAINT fk_subdomains_server FOREIGN KEY (server_id) REFERENCES servers(id) ON DELETE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
-- Round-robin style panel monitoring history. One averaged row per minute,
-- pruned to a fixed retention window (default ~31 days) so the table stays at a
-- small, predictable size. bucket_ts is the UTC epoch (ms) truncated to the
-- minute, used as a stable upsert key.
CREATE TABLE IF NOT EXISTS panel_metrics (
bucket_ts BIGINT UNSIGNED NOT NULL,
cpu_percent DECIMAL(5,1) NOT NULL DEFAULT 0,
mem_percent DECIMAL(5,1) NOT NULL DEFAULT 0,
disk_percent DECIMAL(5,1) NOT NULL DEFAULT 0,
net_rx_bps BIGINT UNSIGNED NOT NULL DEFAULT 0,
net_tx_bps BIGINT UNSIGNED NOT NULL DEFAULT 0,
rps DECIMAL(8,1) NOT NULL DEFAULT 0,
PRIMARY KEY (bucket_ts)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
+362 -63
View File
@@ -173,11 +173,15 @@ function sanitizeConsoleCommand(rawValue) {
let _getEffectivePermsForUserOnServer = null; let _getEffectivePermsForUserOnServer = null;
let _isAdmin = null; let _isAdmin = null;
let _userHasAccessToServer = null; let _userHasAccessToServer = null;
let _serverActionObserver = null;
function setPermissionCheckers(getPerms, isAdminFn, hasAccessFn) { function setPermissionCheckers(getPerms, isAdminFn, hasAccessFn) {
_getEffectivePermsForUserOnServer = getPerms; _getEffectivePermsForUserOnServer = getPerms;
_isAdmin = isAdminFn; _isAdmin = isAdminFn;
_userHasAccessToServer = hasAccessFn || null; _userHasAccessToServer = hasAccessFn || null;
} }
function setServerActionObserver(fn) {
_serverActionObserver = typeof fn === "function" ? fn : null;
}
async function checkUserPerm(req, serverName, permKey) { async function checkUserPerm(req, serverName, permKey) {
if (!_getEffectivePermsForUserOnServer || !_isAdmin) { if (!_getEffectivePermsForUserOnServer || !_isAdmin) {
@@ -191,6 +195,31 @@ async function checkUserPerm(req, serverName, permKey) {
return !!(perms && perms[permKey]); return !!(perms && perms[permKey]);
} }
// resolveFsWriteMode decides which write operations a user may perform and the
// constraint to hand the node so it can enforce create-vs-overwrite atomically
// (no panel-side TOCTOU). Returns:
// { ok:true, mode:"" } -> may create new AND overwrite existing (admin / both perms)
// { ok:true, mode:"create" } -> may only create new files (node 409s if it exists)
// { ok:true, mode:"update" } -> may only overwrite existing files (node 404s if missing)
// { ok:false, permission } -> no write capability at all
// Back-compat: an existing files_create grant continues to allow creating files;
// files_write is the new, separate capability for overwriting existing files.
async function resolveFsWriteMode(req, serverName) {
if (!_getEffectivePermsForUserOnServer || !_isAdmin) {
return { ok: false, permission: "files_create" };
}
const userEmail = req.session?.user;
if (!userEmail) return { ok: false, permission: "files_create" };
if (await _isAdmin(req)) return { ok: true, mode: "" };
const perms = await _getEffectivePermsForUserOnServer(userEmail, serverName);
const canCreate = !!(perms && perms.files_create);
const canWrite = !!(perms && perms.files_write);
if (canCreate && canWrite) return { ok: true, mode: "" };
if (canCreate) return { ok: true, mode: "create" };
if (canWrite) return { ok: true, mode: "update" };
return { ok: false, permission: "files_create" };
}
async function checkServerAccess(req, serverName) { async function checkServerAccess(req, serverName) {
const userEmail = req.session?.user; const userEmail = req.session?.user;
if (!userEmail) return { ok: false, status: 401, error: "not authenticated" }; if (!userEmail) return { ok: false, status: 401, error: "not authenticated" };
@@ -210,6 +239,9 @@ const UPLOAD_TIMEOUT_MS = 3600_000;
const NODE_BOOTSTRAP_TOKEN = (process.env.NODE_BOOTSTRAP_TOKEN || "").trim(); const NODE_BOOTSTRAP_TOKEN = (process.env.NODE_BOOTSTRAP_TOKEN || "").trim();
const PANEL_PUBLIC_URL = (process.env.PANEL_PUBLIC_URL || "").trim(); const PANEL_PUBLIC_URL = (process.env.PANEL_PUBLIC_URL || "").trim();
const PANEL_HMAC_SECRET = (process.env.PANEL_HMAC_SECRET || "").trim(); const PANEL_HMAC_SECRET = (process.env.PANEL_HMAC_SECRET || "").trim();
const DAEMON_INSTALL_SCRIPT_PATH = path.join(__dirname, "install-daemon.sh");
const NODE_INSTALLER_TOKEN_TTL_MS = parseInt(process.env.NODE_INSTALLER_TOKEN_TTL_MS || "", 10) || 60 * 60 * 1000;
const NODE_INSTALLER_TOKEN_SECRET = (process.env.NODE_INSTALLER_TOKEN_SECRET || process.env.SESSION_SECRET || "").trim();
(async () => { (async () => {
try { try {
@@ -244,6 +276,25 @@ function safeCompare(a, b) {
return crypto.timingSafeEqual(bufA, bufB); return crypto.timingSafeEqual(bufA, bufB);
} }
function b64urlEncode(input) {
const buf = Buffer.isBuffer(input) ? input : Buffer.from(String(input));
return buf.toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
}
function b64urlDecode(input) {
const value = String(input || "").trim().replace(/-/g, "+").replace(/_/g, "/");
const pad = value.length % 4 ? "=".repeat(4 - (value.length % 4)) : "";
return Buffer.from(value + pad, "base64");
}
function safeDecodeURIComponent(value) {
try {
return decodeURIComponent(String(value || ""));
} catch {
return String(value || "");
}
}
function parseDbJson(value, fallback) { function parseDbJson(value, fallback) {
if (value === undefined || value === null || value === "") return fallback; if (value === undefined || value === null || value === "") return fallback;
if (typeof value === "object") return value; if (typeof value === "object") return value;
@@ -985,6 +1036,108 @@ function defaultNodeTlsPaths(node) {
function yamlDoubleQuote(value) { function yamlDoubleQuote(value) {
return `"${String(value || "").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`; return `"${String(value || "").replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
} }
function replaceAllLiteral(value, search, replacement) {
return String(value).split(search).join(replacement);
}
function shellSingleQuote(value) {
return `'${String(value == null ? "" : value).replace(/'/g, `'\\''`)}'`;
}
function buildPanelPublicUrl(req) {
if (PANEL_PUBLIC_URL) return PANEL_PUBLIC_URL.replace(/\/+$/, "");
console.warn("[SECURITY] PANEL_PUBLIC_URL not set - node installer/config URLs are derived from request headers. Set PANEL_PUBLIC_URL for production.");
const host = req?.get?.("x-forwarded-host") || req?.get?.("host") || "localhost";
const proto = (req?.get?.("x-forwarded-proto") || req?.protocol || "http");
return `${proto}://${host}`.replace(/\/+$/, "");
}
function nodeInstallerSigningKey(node) {
return [
NODE_INSTALLER_TOKEN_SECRET,
node?.uuid || "",
node?.id || "",
node?.token_id || "",
node?.token || "",
].join("\n");
}
function signNodeInstallerPayload(payloadB64, node) {
return b64urlEncode(crypto.createHmac("sha256", nodeInstallerSigningKey(node)).update(payloadB64).digest());
}
function issueNodeInstallerToken(node) {
const payload = {
v: 1,
typ: "node-installer",
node: String(node?.uuid || node?.id || ""),
exp: Date.now() + NODE_INSTALLER_TOKEN_TTL_MS,
};
const payloadB64 = b64urlEncode(JSON.stringify(payload));
return `${payloadB64}.${signNodeInstallerPayload(payloadB64, node)}`;
}
function verifyNodeInstallerToken(token, node) {
const parts = String(token || "").trim().split(".");
if (parts.length !== 2) return false;
const expectedSig = signNodeInstallerPayload(parts[0], node);
if (!safeCompare(parts[1], expectedSig)) return false;
let payload;
try {
payload = JSON.parse(b64urlDecode(parts[0]).toString("utf8"));
} catch {
return false;
}
const allowedNodeIds = new Set([String(node?.uuid || ""), String(node?.id || "")].filter(Boolean));
return payload
&& payload.v === 1
&& payload.typ === "node-installer"
&& allowedNodeIds.has(String(payload.node || ""))
&& Number(payload.exp || 0) >= Date.now();
}
function getNodeInstallerTokenFromRequest(req) {
return String(req?.get?.("x-node-installer") || req?.query?.installer || "").trim();
}
function buildNodeInstallerUrl(node, req) {
const id = encodeURIComponent(String(node?.uuid || node?.id || ""));
const base = buildPanelPublicUrl(req);
const url = new URL(`/api/nodes/${id}/install-daemon.sh`, base);
url.searchParams.set("installer", issueNodeInstallerToken(node));
return url.toString();
}
function buildNodeConfigRestartCommand(configYml) {
const config = String(configYml || "").replace(/\r\n/g, "\n").replace(/\r/g, "\n").replace(/\n*$/, "\n");
return [
`if [ "$(id -u)" -eq 0 ]; then SUDO=""; elif command -v sudo >/dev/null 2>&1; then SUDO="sudo"; else echo "Run as root or install sudo, then retry." >&2; exit 1; fi`,
`$SUDO install -d -m 0750 /var/lib/node`,
`$SUDO tee /var/lib/node/config.yml >/dev/null <<'ADPANEL_CONFIG_YML'`,
config,
`ADPANEL_CONFIG_YML`,
`$SUDO chown adaemon:adaemon /var/lib/node/config.yml 2>/dev/null || true`,
`$SUDO chmod 0640 /var/lib/node/config.yml`,
`if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then`,
` $SUDO systemctl restart adaemon || $SUDO systemctl restart ADaemon`,
`elif command -v rc-service >/dev/null 2>&1; then`,
` $SUDO rc-service adaemon restart || $SUDO rc-service adaemon start`,
`else`,
` $SUDO service adaemon restart || $SUDO service adaemon start`,
`fi`,
].join("\n");
}
async function isOpenNodeInstallerRoute(req) {
if (String(req?.method || "GET").toUpperCase() !== "GET") return false;
const match = /^\/api\/nodes\/([^/]+)\/install-daemon\.sh$/.exec(String(req?.path || ""));
if (!match) return false;
const node = await findNodeByIdOrName(safeDecodeURIComponent(match[1]));
if (!node) return false;
return verifyNodeInstallerToken(getNodeInstallerTokenFromRequest(req), node);
}
async function resolveNodeForServer(serverName) { async function resolveNodeForServer(serverName) {
const name = String(serverName || "").trim(); const name = String(serverName || "").trim();
if (!name) return { server: null, node: null, nodeId: null }; if (!name) return { server: null, node: null, nodeId: null };
@@ -1124,15 +1277,7 @@ async function activeCheckNode(node, opts = { force: false }) {
} }
} }
function buildConfigYml(node, req) { function buildConfigYml(node, req) {
let panelUrl; const panelUrl = buildPanelPublicUrl(req);
if (PANEL_PUBLIC_URL) {
panelUrl = PANEL_PUBLIC_URL;
} else {
console.warn("[SECURITY] PANEL_PUBLIC_URL not set - config.yml panel URL derived from request headers. Set PANEL_PUBLIC_URL for production.");
const host = req.get("x-forwarded-host") || req.get("host") || "localhost";
const proto = (req.get("x-forwarded-proto") || req.protocol || "http");
panelUrl = `${proto}://${host}`;
}
const sslEnabled = !!node.ssl_enabled; const sslEnabled = !!node.ssl_enabled;
const tlsPaths = defaultNodeTlsPaths(node); const tlsPaths = defaultNodeTlsPaths(node);
const lines = [ const lines = [
@@ -1153,8 +1298,6 @@ function buildConfigYml(node, req) {
` upload_limit: ${node.max_upload_mb || 10240}`, ` upload_limit: ${node.max_upload_mb || 10240}`,
`system:`, `system:`,
` data: /var/lib/node`, ` data: /var/lib/node`,
` sftp:`,
` bind_port: ${node.sftp_port || 2022}`,
`allowed_mounts: []`, `allowed_mounts: []`,
`panel:`, `panel:`,
` url: ${panelUrl}`, ` url: ${panelUrl}`,
@@ -1165,34 +1308,30 @@ function buildConfigYml(node, req) {
} }
return lines.join("\n") + "\n"; return lines.join("\n") + "\n";
} }
function oneTimeCommand(node, req) { function buildDaemonInstallScript(node, req) {
let base; const configB64 = Buffer.from(buildConfigYml(node, req), "utf8").toString("base64");
if (PANEL_PUBLIC_URL) { if (!fs.existsSync(DAEMON_INSTALL_SCRIPT_PATH)) {
base = PANEL_PUBLIC_URL; throw new Error("install-daemon.sh not found");
} else {
const host = req.get("x-forwarded-host") || req.get("host") || "localhost";
const proto = (req.get("x-forwarded-proto") || req.protocol || "http");
base = `${proto}://${host}`;
} }
const url = `${base}/api/nodes/${encodeURIComponent(node.uuid)}/config.yml`; let script = fs.readFileSync(DAEMON_INSTALL_SCRIPT_PATH, "utf8");
const header = NODE_BOOTSTRAP_TOKEN ? `-H "X-Node-Bootstrap: ${NODE_BOOTSTRAP_TOKEN}" ` : "";
return `set -e if (script.includes("__ADPANEL_NODE_CONFIG_B64__")) {
mkdir -p /var/lib/node return [
curl -fsSL ${header}"${url}" -o /var/lib/node/config.yml ["__ADPANEL_NODE_CONFIG_B64__", configB64],
restart_adaemon() { ["__ADPANEL_NODE_API_PORT__", String(node.api_port || 8080)],
if command -v systemctl >/dev/null 2>&1 && [ -d /run/systemd/system ]; then ["__ADPANEL_NODE_SFTP_PORT__", String(node.sftp_port || 2022)],
systemctl restart ADaemon 2>/dev/null || systemctl restart adaemon 2>/dev/null || systemctl restart adpanel-daemon 2>/dev/null ].reduce((out, [search, replacement]) => replaceAllLiteral(out, search, replacement), script);
elif command -v rc-service >/dev/null 2>&1; then }
rc-service adaemon restart 2>/dev/null || rc-service ADaemon restart 2>/dev/null || rc-service adpanel-daemon restart 2>/dev/null
elif command -v service >/dev/null 2>&1; then return [
service adaemon restart 2>/dev/null || service ADaemon restart 2>/dev/null || service adpanel-daemon restart 2>/dev/null "export ADPANEL_NODE_CONFIG_B64=" + shellSingleQuote(configB64),
else "export ADPANEL_NODE_API_PORT=" + shellSingleQuote(String(node.api_port || 8080)),
echo "No supported service manager found; start ADaemon manually." >&2 "export ADPANEL_NODE_SFTP_PORT=" + shellSingleQuote(String(node.sftp_port || 2022)),
return 1 script,
fi ].join("\n");
} }
restart_adaemon function oneTimeCommand(node, req) {
echo "Config saved to /var/lib/node/config.yml and ADaemon restarted"`; return buildNodeConfigRestartCommand(buildConfigYml(node, req));
} }
const app = express(); const app = express();
app.use(express.json({ limit: "2mb" })); app.use(express.json({ limit: "2mb" }));
@@ -1240,7 +1379,8 @@ const NODES_PUBLIC_ROUTES = new Set([
const NODES_SERVER_ROUTES_PATTERN = /^\/api\/nodes\/server\/[^/]+\/(info|entries|file|logs|stats|action|command|delete|delete-batch|rename|upload|upload-url|create|extract|archive|backups(\/[^/]+)?(\/restore)?)$/; const NODES_SERVER_ROUTES_PATTERN = /^\/api\/nodes\/server\/[^/]+\/(info|entries|file|logs|stats|action|command|delete|delete-batch|rename|upload|upload-url|create|extract|archive|backups(\/[^/]+)?(\/restore)?)$/;
app.use((req, res, next) => { app.use(async (req, res, next) => {
try {
const path = req.path || ""; const path = req.path || "";
if (path === "/health") return next(); if (path === "/health") return next();
@@ -1249,13 +1389,18 @@ app.use((req, res, next) => {
if (NODES_SERVER_ROUTES_PATTERN.test(path)) return next(); if (NODES_SERVER_ROUTES_PATTERN.test(path)) return next();
if (await isOpenNodeInstallerRoute(req)) return next();
if (path.startsWith("/api/nodes")) { if (path.startsWith("/api/nodes")) {
if (!req.isAdmin) { if (!req.isAdmin) {
return res.status(403).json({ error: "admin required" }); return res.status(403).json({ error: "admin required" });
} }
} }
next(); return next();
} catch (err) {
return next(err);
}
}); });
app.get("/health", (_req, res) => res.json({ ok: true })); app.get("/health", (_req, res) => res.json({ ok: true }));
@@ -1322,6 +1467,19 @@ app.post("/api/nodes/:id/servers/create", async (req, res) => {
if (!name) return res.status(400).json({ error: "missing_name" }); if (!name) return res.status(400).json({ error: "missing_name" });
if (!hostPort) return res.status(400).json({ error: "invalid_host_port" }); if (!hostPort) return res.status(400).json({ error: "invalid_host_port" });
// adpanel:multidisk - resolve and verify the requested target disk belongs to
// this node before forwarding. Empty/"primary" => default primary disk.
let diskId = String(req.body?.diskId || "").trim();
if (diskId && diskId !== "primary") {
const diskRes = await callNodeApi(node, "/v1/disks", "GET", null, 8000);
const disks = (diskRes.status === 200 && diskRes.json?.ok && Array.isArray(diskRes.json.disks)) ? diskRes.json.disks : [];
if (!disks.some((d) => String(d.id) === diskId)) {
return res.status(400).json({ error: "invalid_disk", detail: "Target disk does not belong to this node." });
}
} else {
diskId = "";
}
if (hostPort > 0 && !isPortInNodeAllocation(node, hostPort)) { if (hostPort > 0 && !isPortInNodeAllocation(node, hostPort)) {
const alloc = node.ports || {}; const alloc = node.ports || {};
let allocDesc = "none"; let allocDesc = "none";
@@ -1339,7 +1497,7 @@ app.post("/api/nodes/:id/servers/create", async (req, res) => {
const { status, json } = await callNodeApi( const { status, json } = await callNodeApi(
node, "/v1/servers/create", "POST", node, "/v1/servers/create", "POST",
{ name, templateId, mcFork, mcVersion, hostPort, autoStart }, { name, templateId, mcFork, mcVersion, hostPort, autoStart, ...(diskId ? { diskId } : {}) },
LONG_NODE_TIMEOUT_MS LONG_NODE_TIMEOUT_MS
); );
if (status === 200 && json && json.ok) return res.json(json); if (status === 200 && json && json.ok) return res.json(json);
@@ -1532,10 +1690,35 @@ app.get("/api/nodes/:id/config.yml", async (req, res) => {
res.setHeader("Content-Type", "text/yaml; charset=utf-8"); res.setHeader("Content-Type", "text/yaml; charset=utf-8");
res.send(yml); res.send(yml);
}); });
app.get("/api/nodes/:id/install-daemon.sh", async (req, res) => {
const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).send("not found");
if (!req.isAdmin && !verifyNodeInstallerToken(getNodeInstallerTokenFromRequest(req), node)) {
return res.status(401).send("authentication required");
}
let script;
try {
script = buildDaemonInstallScript(node, req);
} catch (err) {
console.error("[nodes] Failed to build daemon installer:", err?.message || err);
return res.status(500).send("failed to build installer");
}
res.setHeader("Cache-Control", "no-store, no-cache, must-revalidate, private");
res.setHeader("Pragma", "no-cache");
res.setHeader("Content-Type", "text/x-shellscript; charset=utf-8");
res.send(script);
});
app.get("/api/nodes/:id/one-time-command", async (req, res) => { app.get("/api/nodes/:id/one-time-command", async (req, res) => {
if (!req.isAdmin) {
return res.status(403).json({ error: "admin required" });
}
const node = await findNodeByIdOrName(req.params.id); const node = await findNodeByIdOrName(req.params.id);
if (!node) return res.status(404).json({ error: "not found" }); if (!node) return res.status(404).json({ error: "not found" });
res.json({ command: oneTimeCommand(node, req) }); res.json({
command: oneTimeCommand(node, req),
});
}); });
app.post("/api/nodes/:id/heartbeat", async (req, res) => { app.post("/api/nodes/:id/heartbeat", async (req, res) => {
try { try {
@@ -1781,7 +1964,7 @@ async function fetchRemoteReplacementBytes(ctx, absDir, originalName, timeoutMs
return size && size > 0 ? size : 0; return size && size > 0 ? size : 0;
} }
function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb) { function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes, maxMb, serverName) {
return new Promise((resolve) => { return new Promise((resolve) => {
let settled = false; let settled = false;
let nodeReq = null; let nodeReq = null;
@@ -1798,6 +1981,13 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes,
const boundary = `----ADPanelUpload${crypto.randomBytes(16).toString("hex")}`; const boundary = `----ADPanelUpload${crypto.randomBytes(16).toString("hex")}`;
const safeOriginalName = String(originalName || "upload.bin").replace(/[\r\n"]/g, "_"); const safeOriginalName = String(originalName || "upload.bin").replace(/[\r\n"]/g, "_");
const safeServerName = String(serverName || "").replace(/[\r\n"]/g, "_");
const serverPart = safeServerName
? `--${boundary}\r\n` +
`Content-Disposition: form-data; name="server"\r\n\r\n` +
`${safeServerName}\r\n`
: "";
const dirPart = const dirPart =
`--${boundary}\r\n` + `--${boundary}\r\n` +
@@ -1811,7 +2001,7 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes,
const fileFooter = `\r\n--${boundary}--\r\n`; const fileFooter = `\r\n--${boundary}--\r\n`;
const preamble = Buffer.from(dirPart + fileHeader, "utf8"); const preamble = Buffer.from(serverPart + dirPart + fileHeader, "utf8");
const epilogue = Buffer.from(fileFooter, "utf8"); const epilogue = Buffer.from(fileFooter, "utf8");
const headers = { const headers = {
@@ -1890,9 +2080,22 @@ function streamUploadToNode(node, sourceStream, originalName, destDir, maxBytes,
} }
function safeJoinUnix(base, rel) { function safeJoinUnix(base, rel) {
// Reject NUL bytes outright: they can truncate paths in some syscalls and
// must never reach the node. (#3 hardening)
if (String(base || "").includes("\0") || String(rel || "").includes("\0")) {
throw new Error("path traversal");
}
const b = base.endsWith("/") ? base.slice(0, -1) : base; const b = base.endsWith("/") ? base.slice(0, -1) : base;
const raw = String(rel || "").replace(/\\/g, "/"); const raw = String(rel || "").replace(/\\/g, "/");
// Reject traversal segments in the raw value before normalization collapses
// them, so we never depend solely on the post-join prefix check.
if (raw.split("/").includes("..")) {
throw new Error("path traversal");
}
const norm = path.posix.normalize("/" + raw).replace(/^\/+/, ""); const norm = path.posix.normalize("/" + raw).replace(/^\/+/, "");
if (norm.split("/").includes("..")) {
throw new Error("path traversal");
}
const joined = `${b}/${norm}`; const joined = `${b}/${norm}`;
if (!joined.startsWith(b + "/") && joined !== b) throw new Error("path traversal"); if (!joined.startsWith(b + "/") && joined !== b) throw new Error("path traversal");
return joined; return joined;
@@ -1914,6 +2117,55 @@ function mapFsEntries(entries) {
}); });
return out; return out;
} }
// adpanel:multidisk - per-server base-dir cache (server may be on a secondary disk).
const _nodeServerBaseDirCache = new Map(); // key `${nodeKey}:${name}` -> { baseDir, at }
const NODE_SERVER_BASEDIR_TTL_MS = 5 * 60 * 1000;
// validateResolvedBaseDir hardens the node-reported base dir before the panel uses
// it as a prefix for safeJoinUnix. The node already enforces disk-root containment,
// but the panel independently rejects anything that is not a clean, absolute path
// whose final segment is exactly the sanitized server name. This prevents a
// compromised/spoofed node response from steering FS operations elsewhere and
// blocks traversal/NUL injection at the panel boundary.
function validateResolvedBaseDir(baseDir, expectedName) {
if (typeof baseDir !== "string" || !baseDir) return null;
if (baseDir.includes("\0")) return null;
// Reject traversal in the raw value *before* normalization collapses it.
if (baseDir.split("/").includes("..")) return null;
// POSIX-normalize; the node filesystem is always Unix.
const normalized = require("path").posix.normalize(baseDir).replace(/\/+$/, "");
if (!normalized.startsWith("/")) return null;
if (normalized === "/" || normalized === "") return null;
if (normalized.split("/").includes("..")) return null;
const safeName = sanitizeName(expectedName);
if (!safeName) return null;
// The directory that holds the server files must be named exactly after the
// sanitized server name (…/<root>/<server>). No suffix tricks, no parent.
const segments = normalized.split("/");
if (segments[segments.length - 1] !== safeName) return null;
return normalized;
}
async function resolveNodeServerBaseDir(node, nodeServerName) {
const nodeKey = String(node.uuid || node.id || node.name || "");
const safeName = sanitizeName(nodeServerName);
if (!nodeKey || !safeName) return null;
const cacheKey = `${nodeKey}:${safeName}`;
const cached = _nodeServerBaseDirCache.get(cacheKey);
if (cached && Date.now() - cached.at < NODE_SERVER_BASEDIR_TTL_MS) {
return cached.baseDir;
}
const { status, json } = await httpJson(
nodeUrl(node, `/v1/servers/${encodeURIComponent(safeName)}`),
{ method: "GET", headers: nodeHeaders(node), timeoutMs: 5000 }
);
if (status !== 200 || !json || json.ok !== true) return null;
const validated = validateResolvedBaseDir(json.baseDir, safeName);
if (!validated) return null;
_nodeServerBaseDirCache.set(cacheKey, { baseDir: validated, at: Date.now() });
return validated;
}
async function remoteContext(serverName) { async function remoteContext(serverName) {
const srv = await findServerByNameOrId(serverName); const srv = await findServerByNameOrId(serverName);
if (!srv) return { exists: false }; if (!srv) return { exists: false };
@@ -1923,7 +2175,15 @@ async function remoteContext(serverName) {
if (!node) return { exists: true, remote: false, info: buildServerInfo(srv) }; if (!node) return { exists: true, remote: false, info: buildServerInfo(srv) };
const volRoot = getNodeVolumesDir(node); const volRoot = getNodeVolumesDir(node);
const nodeServerName = sanitizeName(srv.name || serverName); const nodeServerName = sanitizeName(srv.name || serverName);
const baseDir = `${volRoot}/${nodeServerName}`; // adpanel:multidisk - the server may live on a secondary disk. Resolve its real
// base directory from the node (disk-aware) and fall back to the primary volumes
// root for older/unreachable nodes. The node remains the source of truth and
// re-validates every path, so this only affects which root the panel prefixes.
let baseDir = `${volRoot}/${nodeServerName}`;
try {
const resolved = await resolveNodeServerBaseDir(node, nodeServerName);
if (resolved) baseDir = resolved;
} catch (_) { /* fall back to primary path */ }
return { return {
exists: true, exists: true,
remote: true, remote: true,
@@ -1987,17 +2247,12 @@ app.get("/api/nodes/server/:name/entries", async (req, res) => {
const ctx = await remoteContext(serverName); const ctx = await remoteContext(serverName);
if (!ctx.exists) return res.status(404).json({ error: "server not found" }); if (!ctx.exists) return res.status(404).json({ error: "server not found" });
if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" }); if (!ctx.remote || !ctx.node) return res.status(400).json({ error: "not_remote" });
if (!_nodeVolumeDirCache.has(String(ctx.node.uuid || ctx.node.id || ""))) {
try { await activeCheckNode(ctx.node, { force: true }); } catch { }
const volRoot = getNodeVolumesDir(ctx.node);
ctx.baseDir = `${volRoot}/${sanitizeName(serverName)}`;
}
const rel = String(req.query.path || ""); const rel = String(req.query.path || "");
try { try {
const full = safeJoinUnix(ctx.baseDir, rel); const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson( const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/list"), nodeUrl(ctx.node, "/v1/fs/list"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, depth: 1 } } { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, depth: 1 } }
); );
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_list_failed" }); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_list_failed" });
return res.json({ path: rel, entries: mapFsEntries(json.entries || []) }); return res.json({ path: rel, entries: mapFsEntries(json.entries || []) });
@@ -2025,7 +2280,7 @@ app.get("/api/nodes/server/:name/file", async (req, res) => {
const full = safeJoinUnix(ctx.baseDir, rel); const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson( const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/read"), nodeUrl(ctx.node, "/v1/fs/read"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, encoding: "utf8" } } { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, encoding: "utf8" } }
); );
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_read_failed" }); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_read_failed" });
return res.json({ path: rel, content: typeof json.content === "string" ? json.content : "" }); return res.json({ path: rel, content: typeof json.content === "string" ? json.content : "" });
@@ -2052,7 +2307,7 @@ app.get("/api/nodes/server/:name/download", async (req, res) => {
try { try {
const full = safeJoinUnix(ctx.baseDir, rel); const full = safeJoinUnix(ctx.baseDir, rel);
const lib = nodeUrl(ctx.node, "").startsWith("https:") ? require("https") : require("http"); const lib = nodeUrl(ctx.node, "").startsWith("https:") ? require("https") : require("http");
const postData = JSON.stringify({ path: full }); const postData = JSON.stringify({ path: full, server: ctx.nodeServerName });
const url = new URL(nodeUrl(ctx.node, "/v1/fs/download")); const url = new URL(nodeUrl(ctx.node, "/v1/fs/download"));
const reqOpts = { const reqOpts = {
hostname: url.hostname, hostname: url.hostname,
@@ -2090,8 +2345,9 @@ app.post("/api/nodes/server/:name/file", async (req, res) => {
return res.status(accessCheck.status).json({ error: accessCheck.error }); return res.status(accessCheck.status).json({ error: accessCheck.error });
} }
if (!(await checkUserPerm(req, serverName, "files_create"))) { const writeMode = await resolveFsWriteMode(req, serverName);
return res.status(403).json({ error: "permission denied", permission: "files_create" }); if (!writeMode.ok) {
return res.status(403).json({ error: "permission denied", permission: writeMode.permission });
} }
const ctx = await remoteContext(serverName); const ctx = await remoteContext(serverName);
@@ -2103,15 +2359,23 @@ app.post("/api/nodes/server/:name/file", async (req, res) => {
const full = safeJoinUnix(ctx.baseDir, rel); const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson( const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/write"), nodeUrl(ctx.node, "/v1/fs/write"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, content, encoding: "utf8" } } { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, content, encoding: "utf8", mode: writeMode.mode } }
); );
if (status === 507 && json?.error === "disk_limit_exceeded") { if (status === 507 && json?.error === "disk_limit_exceeded") {
return res.status(507).json(json); return res.status(507).json(json);
} }
// The node enforces create-vs-overwrite atomically. Surface those as a 403
// so the user understands it is a permission boundary, not a generic failure.
if (status === 409) {
return res.status(403).json({ error: "permission denied", permission: "files_write", detail: "overwriting existing files requires the files_write permission" });
}
if (status === 404 && json && json.existed === false) {
return res.status(403).json({ error: "permission denied", permission: "files_create", detail: "creating new files requires the files_create permission" });
}
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_write_failed" }); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_write_failed" });
const userEmail = req.session?.user || "unknown"; const userEmail = req.session?.user || "unknown";
recordActivity(req.params.name, "file_edit", { path: rel }, userEmail, getRequestIp(req)); recordActivity(req.params.name, "file_edit", { path: rel, created: json.existed === false }, userEmail, getRequestIp(req));
return res.json({ ok: true }); return res.json({ ok: true });
} catch (e) { } catch (e) {
@@ -2135,7 +2399,7 @@ app.post("/api/nodes/server/:name/delete", async (req, res) => {
const full = safeJoinUnix(ctx.baseDir, rel); const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson( const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/delete"), nodeUrl(ctx.node, "/v1/fs/delete"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, isDir } } { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, isDir } }
); );
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_delete_failed" }); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_delete_failed" });
@@ -2179,7 +2443,7 @@ app.post("/api/nodes/server/:name/delete-batch", async (req, res) => {
{ {
method: "POST", method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)),
body: { items: fullItems }, body: { items: fullItems, server: ctx.nodeServerName },
timeoutMs: 120000 timeoutMs: 120000
} }
); );
@@ -2220,7 +2484,7 @@ app.post("/api/nodes/server/:name/rename", async (req, res) => {
const full = safeJoinUnix(ctx.baseDir, rel); const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson( const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/rename"), nodeUrl(ctx.node, "/v1/fs/rename"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, newName } } { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName, newName } }
); );
if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_rename_failed" }); if (status !== 200 || !json || !json.ok) return res.status(502).json({ error: "node_rename_failed" });
@@ -2248,7 +2512,7 @@ app.post("/api/nodes/server/:name/extract", async (req, res) => {
const full = safeJoinUnix(ctx.baseDir, rel); const full = safeJoinUnix(ctx.baseDir, rel);
const { status, json } = await httpJson( const { status, json } = await httpJson(
nodeUrl(ctx.node, "/v1/fs/extract"), nodeUrl(ctx.node, "/v1/fs/extract"),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full } } { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { path: full, server: ctx.nodeServerName } }
); );
if (status === 507 && json?.error === "disk_limit_exceeded") { if (status === 507 && json?.error === "disk_limit_exceeded") {
return res.status(507).json(json); return res.status(507).json(json);
@@ -2281,11 +2545,36 @@ app.post("/api/nodes/server/:name/archive", async (req, res) => {
if (!Array.isArray(paths) || paths.length === 0) { if (!Array.isArray(paths) || paths.length === 0) {
return res.status(400).json({ error: "missing paths" }); return res.status(400).json({ error: "missing paths" });
} }
if (paths.length > 1000) {
return res.status(400).json({ error: "too many paths (max 1000)" });
}
// #4 belt-and-suspenders: the per-server node endpoint already re-confines
// every path under the server root, but we also validate at the panel boundary
// so traversal/NUL/absolute inputs are rejected here regardless of which node
// endpoint they are ever routed to. We forward the original RELATIVE paths
// (the node prefixes its own server root); we only use safeJoinUnix as a
// throw-on-violation validator against the resolved baseDir.
const cleanPaths = [];
try {
for (const p of paths) {
const rel = String(p || "");
if (!rel) continue;
safeJoinUnix(ctx.baseDir, rel); // throws on traversal / NUL / absolute
cleanPaths.push(rel);
}
if (destDir) safeJoinUnix(ctx.baseDir, destDir);
} catch (e) {
return res.status(400).json({ error: maskPathErrorMessage(e) });
}
if (cleanPaths.length === 0) {
return res.status(400).json({ error: "missing paths" });
}
try { try {
const { status, json } = await httpJson( const { status, json } = await httpJson(
nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(req.params.name)}/files/archive`), nodeUrl(ctx.node, `/v1/servers/${encodeURIComponent(req.params.name)}/files/archive`),
{ method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { paths, destDir }, timeoutMs: 300000 } { method: "POST", headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), body: { paths: cleanPaths, destDir }, timeoutMs: 300000 }
); );
if (status === 507 && json?.error === "disk_limit_exceeded") { if (status === 507 && json?.error === "disk_limit_exceeded") {
return res.status(507).json(json); return res.status(507).json(json);
@@ -2363,7 +2652,7 @@ app.post("/api/nodes/server/:name/upload", async (req, res) => {
fileStream.resume(); fileStream.resume();
return { status: 507, json: diskLimitError }; return { status: 507, json: diskLimitError };
} }
return streamUploadToNode(ctx.node, fileStream, originalName, full, nodeMaxBytes, nodeMaxMb); return streamUploadToNode(ctx.node, fileStream, originalName, full, nodeMaxBytes, nodeMaxMb, ctx.nodeServerName);
})(); })();
uploadPromise.then((result) => { uploadPromise.then((result) => {
@@ -2504,7 +2793,7 @@ app.post("/api/nodes/server/:name/upload-url", async (req, res) => {
{ {
method: "POST", method: "POST",
headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)), headers: Object.assign({ "Content-Type": "application/json" }, nodeHeaders(ctx.node)),
body: { dir: full, url: validatedUrl.toString() }, body: { dir: full, server: ctx.nodeServerName, url: validatedUrl.toString() },
timeoutMs: 30 * 60 * 1000 timeoutMs: 30 * 60 * 1000
} }
); );
@@ -2641,6 +2930,13 @@ async function performPanelServerAction(req, serverName, cmdRaw) {
} }
const { status, json, error } = result; const { status, json, error } = result;
if ((status === 200 || status === 202) && json && (json.ok === true || json.ok === undefined)) { if ((status === 200 || status === 202) && json && (json.ok === true || json.ok === undefined)) {
if (_serverActionObserver && cmd !== "status") {
try {
await _serverActionObserver({ req, serverName: targetServer, action: cmd, result: json || { ok: true } });
} catch (observerErr) {
console.warn("[nodes-action] observer failed:", observerErr?.message || observerErr);
}
}
return { status: 200, body: json || { ok: true } }; return { status: 200, body: json || { ok: true } };
} }
const detail = (json && (json.detail || json.error || json.message)) || error || `HTTP ${status}`; const detail = (json && (json.detail || json.error || json.message)) || error || `HTTP ${status}`;
@@ -3087,11 +3383,14 @@ module.exports.nodeUrl = nodeUrl;
module.exports.nodeHeaders = nodeHeaders; module.exports.nodeHeaders = nodeHeaders;
module.exports.nodeUnderCloudflare = nodeUnderCloudflare; module.exports.nodeUnderCloudflare = nodeUnderCloudflare;
module.exports.callNodeApi = callNodeApi; module.exports.callNodeApi = callNodeApi;
module.exports.isOpenNodeInstallerRoute = isOpenNodeInstallerRoute;
module.exports.resolveNodeForServer = resolveNodeForServer; module.exports.resolveNodeForServer = resolveNodeForServer;
module.exports.recordActivity = recordActivity; module.exports.recordActivity = recordActivity;
module.exports.flushActivityLogs = flushActivityLogs;
module.exports.seedRuntimeOnNode = seedRuntimeOnNode; module.exports.seedRuntimeOnNode = seedRuntimeOnNode;
module.exports.setWebhookDispatcher = setWebhookDispatcher; module.exports.setWebhookDispatcher = setWebhookDispatcher;
module.exports.setPermissionCheckers = setPermissionCheckers; module.exports.setPermissionCheckers = setPermissionCheckers;
module.exports.setServerActionObserver = setServerActionObserver;
module.exports.startPayloadFor = startPayloadFor; module.exports.startPayloadFor = startPayloadFor;
module.exports.sanitizeConsoleCommand = sanitizeConsoleCommand; module.exports.sanitizeConsoleCommand = sanitizeConsoleCommand;
module.exports.performPanelServerAction = performPanelServerAction; module.exports.performPanelServerAction = performPanelServerAction;
+19
View File
@@ -0,0 +1,19 @@
{
"$schema": "https://opencode.ai/config.json",
"model": "openrouter/moonshotai/kimi-k2.6:free",
"provider": {
"openrouter": {
"npm": "@ai-sdk/openai-compatible",
"name": "OpenRouter",
"options": {
"baseURL": "https://openrouter.ai/api/v1",
"apiKey": "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"
},
"models": {
"moonshotai/kimi-k2.6:free": {
"name": "Kimi K2.6 Free"
}
}
}
}
}
+202
View File
@@ -0,0 +1,202 @@
const fs = require('fs');
let ejsContent = fs.readFileSync('views/bot.ejs', 'utf8');
const oldEjsStr = ` .sidebar-shell {
transition:
width 0.42s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.2s ease,
background-color 0.42s cubic-bezier(0.22, 1, 0.36, 1),
box-shadow 0.42s cubic-bezier(0.22, 1, 0.36, 1) !important;
will-change: width, background-color, box-shadow;
}`;
const newEjsStr = ` .sidebar-shell {
transition:
width 0.3s cubic-bezier(0.4, 0, 0.2, 1),
opacity 0.2s ease,
background-color 0.3s cubic-bezier(0.4, 0, 0.2, 1),
box-shadow 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
will-change: width, transform, opacity;
transform: translateZ(0);
backface-visibility: hidden;
perspective: 1000px;
}`;
const oldEjsStr2 = ` .sidebar-shell.open .sidebar-item .label,
.sidebar-shell.open .profile-meta {
transition:
max-width 0.36s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.26s ease,
transform 0.36s cubic-bezier(0.22, 1, 0.36, 1);
transition-delay: 0s;
}`;
const newEjsStr2 = ` .sidebar-shell.open .sidebar-item .label,
.sidebar-shell.open .profile-meta {
transition:
opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1),
transform 0.25s cubic-bezier(0.4, 0, 0.2, 1);
transition-delay: 0s;
transform: translateZ(0);
backface-visibility: hidden;
}`;
if (ejsContent.includes(oldEjsStr)) {
ejsContent = ejsContent.replace(oldEjsStr, newEjsStr);
console.log('Replaced sidebar-shell transitions');
} else {
console.log('Could not find old sidebar-shell transitions');
}
if (ejsContent.includes(oldEjsStr2)) {
ejsContent = ejsContent.replace(oldEjsStr2, newEjsStr2);
console.log('Replaced sidebar-item label transitions');
} else {
console.log('Could not find old sidebar-item label transitions');
}
fs.writeFileSync('views/bot.ejs', ejsContent);
let cssContent = fs.readFileSync('public/css/bot.css', 'utf8');
const oldCssStr = `.sidebar-shell.open .sidebar-item .label {
display: inline-block;
max-width: 0;
opacity: 0;
overflow: hidden;
transition: max-width .25s ease, opacity .25s ease, transform .25s ease;
}`;
const newCssStr = `.sidebar-shell.open .sidebar-item .label {
display: inline-block;
width: 0;
opacity: 0;
overflow: hidden;
transition: opacity .2s ease, transform .25s ease;
will-change: opacity, transform;
transform: translateZ(0);
}`;
const oldCssStr2 = `.sidebar-shell.open:hover .sidebar-item .label {
max-width: 150px;
opacity: 1;
transform: translateX(0);
}`;
const newCssStr2 = `.sidebar-shell.open:hover .sidebar-item .label {
width: 150px;
opacity: 1;
transform: translateX(0);
}`;
const oldCssStr3 = `.sidebar-shell.open .profile-meta {
display: flex;
flex-direction: column;
max-width: 0;
opacity: 0;
overflow: hidden;
transition: max-width .25s ease, opacity .25s ease;
white-space: nowrap;
}`;
const newCssStr3 = `.sidebar-shell.open .profile-meta {
display: flex;
flex-direction: column;
width: 0;
opacity: 0;
overflow: hidden;
transition: opacity .2s ease, transform .25s ease;
white-space: nowrap;
will-change: opacity, transform;
transform: translateZ(0);
}`;
const oldCssStr4 = `.sidebar-shell.open:hover .profile-meta {
max-width: 200px;
opacity: 1;
}`;
const newCssStr4 = `.sidebar-shell.open:hover .profile-meta {
width: 200px;
opacity: 1;
}`;
const oldCssStr5 = `.sidebar-shell {
position: fixed;
--sidebar-top: 75px;
--sidebar-height: 480px;
top: var(--sidebar-top);
left: 12px;
transform: none;
transform: none;
width: 68px !important;
height: var(--sidebar-height);
backdrop-filter: blur(5px);
-webkit-backdrop-filter: blur(5px);
background-color: rgba(255, 255, 255, 0.047);
border-radius: 18px;
isolation: isolate;
box-shadow: 0px 6px var(--outer-shadow-blur) rgba(0, 0, 0, 0.2);
padding: 14px 0;
display: flex;
flex-direction: column;
gap: 10px;
opacity: 0;
pointer-events: none;
transition: width .22s ease, opacity .18s ease, transform .22s ease;
z-index: 2200;
}`;
const newCssStr5 = `.sidebar-shell {
position: fixed;
--sidebar-top: 75px;
--sidebar-height: 480px;
top: var(--sidebar-top);
left: 12px;
transform: translateZ(0);
width: 68px !important;
height: var(--sidebar-height);
backdrop-filter: blur(5px);
-webkit-backdrop-filter: blur(5px);
background-color: rgba(255, 255, 255, 0.047);
border-radius: 18px;
isolation: isolate;
box-shadow: 0px 6px var(--outer-shadow-blur) rgba(0, 0, 0, 0.2);
padding: 14px 0;
display: flex;
flex-direction: column;
gap: 10px;
opacity: 0;
pointer-events: none;
transition: width .3s cubic-bezier(0.4, 0, 0.2, 1), opacity .2s ease, transform .3s cubic-bezier(0.4, 0, 0.2, 1);
z-index: 2200;
will-change: width, transform, opacity;
backface-visibility: hidden;
perspective: 1000px;
}`;
if (cssContent.includes(oldCssStr)) {
cssContent = cssContent.replace(oldCssStr, newCssStr);
console.log('Replaced bot.css label initial state');
}
if (cssContent.includes(oldCssStr2)) {
cssContent = cssContent.replace(oldCssStr2, newCssStr2);
console.log('Replaced bot.css label hover state');
}
if (cssContent.includes(oldCssStr3)) {
cssContent = cssContent.replace(oldCssStr3, newCssStr3);
console.log('Replaced bot.css profile initial state');
}
if (cssContent.includes(oldCssStr4)) {
cssContent = cssContent.replace(oldCssStr4, newCssStr4);
console.log('Replaced bot.css profile hover state');
}
if (cssContent.includes(oldCssStr5)) {
cssContent = cssContent.replace(oldCssStr5, newCssStr5);
console.log('Replaced bot.css sidebar main shell');
}
fs.writeFileSync('public/css/bot.css', cssContent);
+281 -852
View File
File diff suppressed because it is too large. Load diff
+7 -5
View File
@@ -14,13 +14,12 @@
"ansi_up": "^6.0.6", "ansi_up": "^6.0.6",
"bcrypt": "^6.0.0", "bcrypt": "^6.0.0",
"bcryptjs": "^3.0.3", "bcryptjs": "^3.0.3",
"busboy": "^1.6.0",
"bullmq": "^5.66.7", "bullmq": "^5.66.7",
"busboy": "^1.6.0",
"chalk": "^5.6.2", "chalk": "^5.6.2",
"compression": "^1.8.1", "compression": "^1.8.1",
"connect-redis": "^9.0.0", "connect-redis": "^9.0.0",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
"csurf": "^1.11.0",
"dotenv": "^17.2.3", "dotenv": "^17.2.3",
"ejs": "^3.1.10", "ejs": "^3.1.10",
"express": "^4.19.2", "express": "^4.19.2",
@@ -35,7 +34,7 @@
"mysql2": "^3.11.5", "mysql2": "^3.11.5",
"nodemon": "^3.1.14", "nodemon": "^3.1.14",
"ora": "^9.3.0", "ora": "^9.3.0",
"pm2": "^6.0.14", "pm2": "^7.0.1",
"qrcode": "^1.5.4", "qrcode": "^1.5.4",
"qrcode-terminal": "^0.12.0", "qrcode-terminal": "^0.12.0",
"rate-limit-redis": "^4.3.1", "rate-limit-redis": "^4.3.1",
@@ -44,7 +43,7 @@
"socket.io": "^4.8.3", "socket.io": "^4.8.3",
"speakeasy": "^2.0.0", "speakeasy": "^2.0.0",
"tar": "^7.5.13", "tar": "^7.5.13",
"ws": "^8.19.0" "ws": "^8.21.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>", "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": { "repository": {
@@ -57,5 +56,8 @@
"bugs": { "bugs": {
"url": "https://github.com/antonndev/ADPanel/issues" "url": "https://github.com/antonndev/ADPanel/issues"
}, },
"homepage": "https://github.com/antonndev/ADPanel#readme" "homepage": "https://github.com/antonndev/ADPanel#readme",
"overrides": {
"ws": "^8.21.0"
}
} }
+150
View File
@@ -0,0 +1,150 @@
const fs = require('fs');
const file = 'public/css/bot.css';
let content = fs.readFileSync(file, 'utf8');
const oldStr = `.sidebar-middle {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
justify-content: center;
position: relative;
}
.sidebar-bottom {
padding-top: 6px;
border-top: 1px solid rgba(255, 255, 255, 0.05);
position: relative;
margin: 0 9px;
}
.sidebar-item {
width: 100%;
display: flex;
align-items: center;
gap: 12px;
padding: 9px 19px;
border-radius: 12px;
background: transparent;
border: none;
color: #e3e9f3;
cursor: pointer;
justify-content: flex-start;
transition: background .15s ease, transform .15s ease, color .15s ease, padding .15s ease;
}
.sidebar-shell.open:not(:hover) .sidebar-item {
justify-content: center !important;
padding-left: 0 !important;
padding-right: 0 !important;
gap: 0 !important;
}
.sidebar-item .icon {
width: 28px;
height: 28px;
border-radius: 10px;
display: grid;
place-items: center;
background: transparent;
box-shadow: none;
font-size: 16px;
flex-shrink: 0;
}
.sidebar-item .label {
opacity: 0;
transform: translateX(-6px);
white-space: nowrap;
transition: opacity .12s ease, transform .12s ease;
}
.sidebar-shell.open .sidebar-item .label {
display: inline-block;
max-width: 0;
opacity: 0;
overflow: hidden;
transition: max-width .25s ease, opacity .25s ease, transform .25s ease;
}
.sidebar-shell.open:hover .sidebar-item {
padding: 9px 20px;
}
.sidebar-shell.open:hover .sidebar-item .label {
max-width: 150px;
opacity: 1;
transform: translateX(0);
}`;
const newStr = `.sidebar-middle {
flex: 1;
display: flex;
flex-direction: column;
gap: 8px;
justify-content: center;
position: relative;
margin: 0 9px;
}
.sidebar-bottom {
padding-top: 6px;
border-top: 1px solid rgba(255, 255, 255, 0.05);
position: relative;
margin: 0 9px;
}
.sidebar-item {
width: 100%;
display: flex;
align-items: center;
gap: 12px;
padding: 9px 11px;
border-radius: 12px;
background: transparent;
border: none;
color: #e3e9f3;
cursor: pointer;
justify-content: flex-start;
transition: background .15s ease, transform .15s ease, color .15s ease;
}
.sidebar-item .icon {
width: 28px;
height: 28px;
border-radius: 10px;
display: grid;
place-items: center;
background: transparent;
box-shadow: none;
font-size: 16px;
flex-shrink: 0;
}
.sidebar-item .label {
opacity: 0;
transform: translateX(-6px);
white-space: nowrap;
transition: opacity .12s ease, transform .12s ease;
}
.sidebar-shell.open .sidebar-item .label {
display: inline-block;
max-width: 0;
opacity: 0;
overflow: hidden;
transition: max-width .25s ease, opacity .25s ease, transform .25s ease;
}
.sidebar-shell.open:hover .sidebar-item .label {
max-width: 150px;
opacity: 1;
transform: translateX(0);
}`;
if (content.includes(oldStr)) {
fs.writeFileSync(file, content.replace(oldStr, newStr));
console.log('Successfully patched bot.css sidebar item');
} else {
console.log('Old string not found in bot.css!');
}
+100
View File
@@ -0,0 +1,100 @@
const fs = require('fs');
let cssContent = fs.readFileSync('public/css/bot.css', 'utf8');
const oldProfileStr = `.sidebar-shell.open .profile-card {
justify-content: flex-start;
padding: 9px 16px;
}
.sidebar-shell.open:not(:hover) .profile-card {
justify-content: center !important;
padding-left: 0 !important;
padding-right: 0 !important;
gap: 0 !important;
}
.sidebar-shell.open:hover .profile-card {
justify-content: flex-start;
padding: 9px 17px;
}`;
const newProfileStr = `.sidebar-shell.open .profile-card {
justify-content: flex-start;
padding: 9px 8px;
}`;
if (cssContent.includes(oldProfileStr)) {
fs.writeFileSync('public/css/bot.css', cssContent.replace(oldProfileStr, newProfileStr));
console.log('Successfully patched bot.css profile card');
} else {
console.log('Old string not found in bot.css profile card!');
}
let ejsContent = fs.readFileSync('views/bot.ejs', 'utf8');
const oldEjsStr = ` .sidebar-shell.open .sidebar-item,
.sidebar-shell.open .profile-card {
transition:
background 0.2s ease,
transform 0.2s ease,
color 0.2s ease,
padding 0.38s cubic-bezier(0.22, 1, 0.36, 1);
}
.sidebar-shell.open .sidebar-item .label,
.sidebar-shell.open .profile-meta {
transition:
max-width 0.36s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.26s ease,
transform 0.36s cubic-bezier(0.22, 1, 0.36, 1);
transition-delay: 0s;
}`;
const newEjsStr = ` .sidebar-shell.open .sidebar-item,
.sidebar-shell.open .profile-card {
transition:
background 0.2s ease,
transform 0.2s ease,
color 0.2s ease;
}
.sidebar-shell.open .sidebar-item .label,
.sidebar-shell.open .profile-meta {
transition:
max-width 0.36s cubic-bezier(0.22, 1, 0.36, 1),
opacity 0.26s ease,
transform 0.36s cubic-bezier(0.22, 1, 0.36, 1);
transition-delay: 0s;
}`;
if (ejsContent.includes(oldEjsStr)) {
fs.writeFileSync('views/bot.ejs', ejsContent.replace(oldEjsStr, newEjsStr));
console.log('Successfully patched bot.ejs transitions');
} else {
console.log('Old string not found in bot.ejs transitions!');
}
const oldEjsStr2 = ` .sidebar-shell.open:hover .sidebar-item .label,
.sidebar-shell.open:hover .profile-meta {
transition-delay: 0.08s;
}
.sidebar-shell.open:not(:hover) .sidebar-item .label,
.sidebar-shell.open:not(:hover) .profile-meta {
transition-delay: 0s;
}
#cmdInput,`;
const newEjsStr2 = ` .sidebar-shell.open:hover .sidebar-item .label,
.sidebar-shell.open:hover .profile-meta {
transition-delay: 0.08s;
}
.sidebar-shell.open:not(:hover) .sidebar-item .label,
.sidebar-shell.open:not(:hover) .profile-meta {
transition-delay: 0s;
}
#cmdInput,`;
// Just to check everything is fine
+575 -103
View File
File diff suppressed because it is too large. Load diff
+49 -14
View File
@@ -1,5 +1,5 @@
:root { :root {
--ui-bg: url("/images/waves.png?v=1776616961314"); --ui-bg: url("/images/waves.png?v=1780686309159");
} }
.btn-primary { .btn-primary {
@@ -32,6 +32,43 @@
filter: brightness(0.96); filter: brightness(0.96);
} }
/* ── Navbar Create pill — overrides for the later-loaded stylesheet ──
This file is loaded AFTER dashboard.css, so the pill animation rules
must be restated here or .btn-primary above would cancel them
(its `transition` omits width/border-radius/padding/gap, which made the
expand/collapse look instant). Open state is toggled via JS (.is-open). */
.btn-primary.create-btn {
position: relative;
overflow: hidden;
width: 44px;
height: 44px;
min-height: 44px;
padding: 0;
gap: 0;
border: none;
border-radius: 50%;
justify-content: center;
transition:
width 0.4s cubic-bezier(0.65, 0, 0.35, 1),
border-radius 0.4s cubic-bezier(0.65, 0, 0.35, 1),
padding 0.4s cubic-bezier(0.65, 0, 0.35, 1),
gap 0.4s cubic-bezier(0.65, 0, 0.35, 1),
filter 0.4s ease;
}
.btn-primary.create-btn:hover {
transform: none;
}
.btn-primary.create-btn.is-open,
.btn-primary.create-btn:focus-visible {
width: 124px;
padding: 0 18px;
gap: 9px;
border-radius: 999px;
filter: brightness(1.06);
}
.btn-ghost { .btn-ghost {
background: rgba(15, 23, 42, 0.85); background: rgba(15, 23, 42, 0.85);
border: none; border: none;
@@ -781,10 +818,6 @@
align-items: center; align-items: center;
} }
.faplusbutton {
margin-right: 6px;
}
.footer-inner { .footer-inner {
align-items: center; align-items: center;
gap: 16px; gap: 16px;
@@ -812,6 +845,10 @@
background: var(--ui-bg) center/cover no-repeat fixed !important; background: var(--ui-bg) center/cover no-repeat fixed !important;
} }
body.modal-open {
overflow: hidden;
}
/* Quick Action Custom Scale Animation - Independent Element Scaling */ /* Quick Action Custom Scale Animation - Independent Element Scaling */
.quick-action.qa-anim-scale { .quick-action.qa-anim-scale {
position: relative; position: relative;
@@ -909,11 +946,14 @@
} }
#topbar-spacer { #topbar-spacer {
height: 104px; height: 73px;
min-height: 73px;
flex-shrink: 0;
} }
.dashboard { .dashboard {
margin-top: 46px; margin-top: 20px;
min-height: auto;
} }
.top-bar { .top-bar {
@@ -972,6 +1012,8 @@
} }
.brand-title { .brand-title {
font-family: 'Inter', sans-serif;
font-weight: 700;
letter-spacing: -0.012em; letter-spacing: -0.012em;
} }
@@ -1019,13 +1061,6 @@
object-fit: cover; object-fit: cover;
} }
.btn-primary.create-btn {
border-radius: 999px;
padding-inline: 18px;
min-height: 42px;
outline: none;
}
.top-bar .btn-primary.create-btn:focus, .top-bar .btn-primary.create-btn:focus,
.top-bar .btn-primary.create-btn:focus-visible, .top-bar .btn-primary.create-btn:focus-visible,
.top-bar .btn-primary.create-btn:active { .top-bar .btn-primary.create-btn:active {
+399
View File
@@ -0,0 +1,399 @@
.adp-ssh-terminal-window {
position: fixed;
left: 0;
top: 0;
width: min(var(--adp-ssh-w, 960px), calc(100vw - 16px));
height: min(var(--adp-ssh-h, 640px), calc(100vh - 16px));
min-width: min(360px, calc(100vw - 16px));
min-height: 260px;
display: flex;
flex-direction: column;
overflow: hidden;
border-radius: 14px;
border: 1px solid rgba(148, 163, 184, 0.24);
background: #020617;
box-shadow: 0 18px 52px rgba(0, 0, 0, 0.48), 0 0 0 1px rgba(15, 23, 42, 0.64);
z-index: 2147483000;
opacity: 0;
transform: translate3d(var(--adp-ssh-x, 24px), var(--adp-ssh-y, 24px), 0) scale(0.985);
transform-origin: top left;
transition: opacity 140ms ease, transform 180ms cubic-bezier(0.2, 0.8, 0.2, 1);
contain: layout paint style;
isolation: isolate;
backface-visibility: hidden;
}
.adp-ssh-terminal-window::before,
.adp-ssh-terminal-window::after {
content: "";
position: absolute;
pointer-events: none;
border-radius: inherit;
}
.adp-ssh-terminal-window::before {
inset: 0;
z-index: 2;
background:
radial-gradient(circle at 18% 0%, rgba(255, 255, 255, 0.17), transparent 28%),
linear-gradient(145deg, rgba(255, 255, 255, 0.12), transparent 32%, rgba(45, 212, 191, 0.08) 72%, transparent);
opacity: 0.28;
}
.adp-ssh-terminal-window::after {
inset: -58%;
z-index: 6;
opacity: 0;
background:
radial-gradient(ellipse at 50% 50%, rgba(255, 255, 255, 0.34), rgba(45, 212, 191, 0.16) 28%, transparent 58%),
linear-gradient(105deg, transparent 34%, rgba(255, 255, 255, 0.42) 48%, transparent 62%);
transform: translate3d(-42%, -22%, 0) rotate(9deg) scale(0.78);
}
.adp-ssh-terminal-window.is-ready {
opacity: 1;
transform: translate3d(var(--adp-ssh-x, 24px), var(--adp-ssh-y, 24px), 0) scale(1);
}
.adp-ssh-terminal-window.is-liquid-motion {
will-change: transform, opacity;
}
.adp-ssh-terminal-window.is-liquid-motion::before {
opacity: 0.5;
}
.adp-ssh-terminal-window.is-liquid-motion::after {
animation: adp-ssh-tahoe-sheen 520ms cubic-bezier(0.16, 1, 0.3, 1) both;
will-change: transform, opacity;
}
.adp-ssh-terminal-window.is-motion-minimize::after {
animation-duration: 460ms;
}
.adp-ssh-terminal-window.is-motion-close::after {
animation-duration: 260ms;
animation-timing-function: cubic-bezier(0.4, 0, 1, 1);
}
.adp-ssh-terminal-window.is-motion-lite::after {
display: none;
}
.adp-ssh-terminal-window.is-interacting {
transition: none;
user-select: none;
will-change: transform, width, height;
}
.adp-ssh-terminal-window.is-interacting .adp-ssh-terminal-frame {
pointer-events: none;
}
.adp-ssh-terminal-window.is-minimized {
width: min(380px, calc(100vw - 24px));
height: 38px;
min-height: 38px;
border-radius: 12px;
border-color: rgba(45, 212, 191, 0.38);
}
.adp-ssh-terminal-titlebar {
position: relative;
z-index: 4;
height: 34px;
flex: 0 0 34px;
display: grid;
grid-template-columns: minmax(0, 1fr) auto minmax(0, 1fr);
align-items: center;
gap: 8px;
padding: 0 8px 0 11px;
border-bottom: 1px solid rgba(148, 163, 184, 0.15);
background: linear-gradient(180deg, rgba(15, 23, 42, 0.98), rgba(2, 6, 23, 0.98));
color: #d1d5db;
cursor: grab;
touch-action: none;
}
.adp-ssh-terminal-window.is-dragging .adp-ssh-terminal-titlebar {
cursor: grabbing;
}
.adp-ssh-terminal-title {
min-width: 0;
display: flex;
align-items: center;
gap: 8px;
font: 600 12px/1 Inter, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif;
color: rgba(226, 232, 240, 0.92);
letter-spacing: 0;
}
.adp-ssh-terminal-title i {
color: #2dd4bf;
font-size: 12px;
}
.adp-ssh-terminal-title span {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.adp-ssh-terminal-grip {
width: 58px;
height: 4px;
border-radius: 999px;
background: rgba(148, 163, 184, 0.42);
justify-self: center;
}
.adp-ssh-terminal-controls {
position: relative;
z-index: 7;
justify-self: end;
display: flex;
align-items: center;
gap: 6px;
}
.adp-ssh-terminal-control {
width: 24px;
height: 24px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 6px;
border: 1px solid rgba(148, 163, 184, 0.18);
background: rgba(15, 23, 42, 0.78);
color: rgba(226, 232, 240, 0.92);
cursor: pointer;
padding: 0;
transition: background-color 120ms ease, border-color 120ms ease, color 120ms ease;
}
.adp-ssh-terminal-control:hover {
background: rgba(51, 65, 85, 0.82);
border-color: rgba(148, 163, 184, 0.34);
}
.adp-ssh-terminal-control[data-adp-ssh-close]:hover {
background: rgba(239, 68, 68, 0.88);
border-color: rgba(248, 113, 113, 0.96);
color: #fff;
}
.adp-ssh-terminal-frame-wrap {
position: relative;
z-index: 1;
min-height: 0;
flex: 1 1 auto;
overflow: hidden;
background: #000;
}
.adp-ssh-terminal-window.is-minimized .adp-ssh-terminal-frame-wrap {
width: 1px;
height: 1px;
min-height: 0;
flex: 0 0 1px;
overflow: hidden;
opacity: 0;
pointer-events: none;
}
.adp-ssh-terminal-frame {
width: 100%;
height: 100%;
border: 0;
display: block;
background: #000;
}
.adp-ssh-terminal-resize {
position: absolute;
z-index: 5;
display: block;
touch-action: none;
}
@keyframes adp-ssh-tahoe-sheen {
0% {
opacity: 0;
transform: translate3d(-42%, -22%, 0) rotate(9deg) scale(0.78);
}
34% {
opacity: 0.95;
}
100% {
opacity: 0;
transform: translate3d(34%, 18%, 0) rotate(9deg) scale(1.14);
}
}
.adp-ssh-terminal-window.is-minimized .adp-ssh-terminal-resize {
display: none;
}
.adp-ssh-terminal-resize-n {
top: 0;
left: 16px;
right: 16px;
height: 7px;
cursor: ns-resize;
}
.adp-ssh-terminal-resize-e {
top: 16px;
right: 0;
bottom: 16px;
width: 7px;
cursor: ew-resize;
}
.adp-ssh-terminal-resize-s {
right: 16px;
bottom: 0;
left: 16px;
height: 7px;
cursor: ns-resize;
}
.adp-ssh-terminal-resize-w {
top: 16px;
bottom: 16px;
left: 0;
width: 7px;
cursor: ew-resize;
}
.adp-ssh-terminal-resize-ne,
.adp-ssh-terminal-resize-nw,
.adp-ssh-terminal-resize-se,
.adp-ssh-terminal-resize-sw {
width: 16px;
height: 16px;
}
.adp-ssh-terminal-resize-ne {
top: 0;
right: 0;
cursor: nesw-resize;
}
.adp-ssh-terminal-resize-nw {
top: 0;
left: 0;
cursor: nwse-resize;
}
.adp-ssh-terminal-resize-se {
right: 0;
bottom: 0;
cursor: nwse-resize;
}
.adp-ssh-terminal-resize-sw {
bottom: 0;
left: 0;
cursor: nesw-resize;
}
.adp-ssh-terminal-launcher {
position: fixed;
right: 18px;
bottom: 18px;
z-index: 2147482500;
width: 42px;
height: 42px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 8px;
border: none;
background: rgba(2, 6, 23, 0.86);
color: #d1d5db;
box-shadow: 0 10px 26px rgba(0, 0, 0, 0.34);
cursor: pointer;
transition: transform 140ms ease, color 140ms ease, box-shadow 140ms ease;
}
.adp-ssh-terminal-launcher:hover {
transform: translateY(-1px) scale(1.03);
color: #f8fafc;
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.42);
}
.adp-ssh-terminal-launcher.is-hidden {
display: none;
}
@media (max-width: 640px) {
.adp-ssh-terminal-window {
min-width: 280px;
min-height: 220px;
border-radius: 12px;
}
.adp-ssh-terminal-window.is-minimized {
width: min(340px, calc(100vw - 16px));
}
.adp-ssh-terminal-grip {
width: 42px;
}
}
@media (pointer: coarse) {
.adp-ssh-terminal-titlebar {
height: 38px;
flex-basis: 38px;
}
.adp-ssh-terminal-resize-n,
.adp-ssh-terminal-resize-s {
height: 12px;
}
.adp-ssh-terminal-resize-e,
.adp-ssh-terminal-resize-w {
width: 12px;
}
.adp-ssh-terminal-resize-ne,
.adp-ssh-terminal-resize-nw,
.adp-ssh-terminal-resize-se,
.adp-ssh-terminal-resize-sw {
width: 22px;
height: 22px;
}
}
@media (prefers-reduced-motion: reduce), (update: slow) {
.adp-ssh-terminal-window,
.adp-ssh-terminal-launcher {
transition-duration: 60ms;
}
.adp-ssh-terminal-window {
box-shadow: 0 12px 34px rgba(0, 0, 0, 0.42), 0 0 0 1px rgba(15, 23, 42, 0.58);
}
.adp-ssh-terminal-window::before {
opacity: 0.28;
}
.adp-ssh-terminal-window::after {
display: none;
}
}
@media (prefers-reduced-transparency: reduce) {
.adp-ssh-terminal-window::before,
.adp-ssh-terminal-window::after {
display: none;
}
}
+567
View File
@@ -0,0 +1,567 @@
/* Admin /status monitoring page styles.
* Apple 2026 + Dieter Rams aesthetic.
* Less, but better. Honest materials. Tabular numerics. No decoration without purpose.
*/
:root {
--monitor-font: -apple-system, BlinkMacSystemFont, "SF Pro Display", "SF Pro Text",
"Inter", "Manrope", "Segoe UI", system-ui, sans-serif;
--monitor-mono: ui-monospace, "SF Mono", "JetBrains Mono", "Menlo", "Consolas", monospace;
--monitor-surface: rgba(255, 255, 255, 0.035);
--monitor-surface-strong: rgba(255, 255, 255, 0.05);
--monitor-border: rgba(255, 255, 255, 0.07);
--monitor-border-soft: rgba(255, 255, 255, 0.045);
--monitor-text: rgba(255, 255, 255, 0.95);
--monitor-text-muted: rgba(255, 255, 255, 0.55);
--monitor-text-faint: rgba(255, 255, 255, 0.38);
--monitor-accent: #22d3ee;
--monitor-accent-soft: rgba(34, 211, 238, 0.18);
--monitor-radius-card: 22px;
--monitor-radius-row: 14px;
}
/* ===== Page shell ===== */
.monitor {
width: min(1180px, calc(100% - 48px));
margin: 0 auto;
padding: 8px 0 40px;
display: flex;
flex-direction: column;
gap: 22px;
font-family: var(--monitor-font);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* ===== Page header ===== */
.monitor-head {
display: flex;
align-items: flex-end;
justify-content: space-between;
flex-wrap: wrap;
gap: 16px;
padding: 4px 2px 0;
}
.monitor-head h2 {
font-size: clamp(1.6rem, 3.2vh, 2.1rem);
font-weight: 600;
letter-spacing: -0.02em;
color: var(--monitor-text);
line-height: 1.15;
}
.monitor-head p {
color: var(--monitor-text-muted);
font-size: 14px;
margin-top: 6px;
line-height: 1.5;
max-width: 56ch;
}
.monitor-head__meta {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.monitor-chip {
display: inline-flex;
align-items: center;
gap: 9px;
padding: 9px 14px;
border-radius: 999px;
background: rgba(255, 255, 255, 0.06);
border: 1px solid rgba(255, 255, 255, 0.12);
color: var(--monitor-text-muted);
font-size: 13px;
font-weight: 500;
letter-spacing: 0.005em;
font-variant-numeric: tabular-nums;
-webkit-backdrop-filter: blur(24px) saturate(180%);
backdrop-filter: blur(24px) saturate(180%);
box-shadow:
0 1px 0 rgba(255, 255, 255, 0.12) inset,
0 -1px 0 rgba(0, 0, 0, 0.18) inset,
0 8px 22px rgba(0, 0, 0, 0.28);
transition: transform 0.22s cubic-bezier(0.22, 0.61, 0.36, 1),
background 0.22s ease, border-color 0.22s ease;
}
.monitor-chip:hover {
background: rgba(255, 255, 255, 0.09);
border-color: rgba(255, 255, 255, 0.16);
transform: translateY(-1px);
}
.monitor-chip strong {
color: var(--monitor-text);
font-weight: 600;
}
.monitor-chip i {
color: var(--monitor-accent);
font-size: 12.5px;
width: 14px;
text-align: center;
}
/* ===== Card surface ===== */
.monitor-card {
background: var(--monitor-surface);
border: 1px solid var(--monitor-border-soft);
border-radius: var(--monitor-radius-card);
padding: 24px 26px;
box-shadow:
0 1px 0 rgba(255, 255, 255, 0.04) inset,
0 18px 40px rgba(0, 0, 0, 0.22);
-webkit-backdrop-filter: blur(14px) saturate(140%);
backdrop-filter: blur(14px) saturate(140%);
}
.monitor-card__title {
display: flex;
align-items: center;
gap: 9px;
font-size: 12.5px;
font-weight: 600;
letter-spacing: 0.04em;
text-transform: none;
color: var(--monitor-text-muted);
margin-bottom: 22px;
}
.monitor-card__title i {
color: var(--monitor-accent);
font-size: 13px;
width: 16px;
text-align: center;
}
/* ===== Metrics Hero Grid (Apple-inspired circular cards) ===== */
.metrics-hero {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 20px;
margin-bottom: 8px;
}
.metric-card {
position: relative;
background: var(--monitor-surface);
border: 1px solid var(--monitor-border-soft);
border-radius: var(--monitor-radius-card);
padding: 36px 28px 28px;
display: flex;
flex-direction: column;
align-items: center;
min-height: 260px;
box-shadow:
0 1px 0 rgba(255, 255, 255, 0.04) inset,
0 18px 40px rgba(0, 0, 0, 0.22);
-webkit-backdrop-filter: blur(14px) saturate(140%);
backdrop-filter: blur(14px) saturate(140%);
transition: transform 0.3s cubic-bezier(0.22, 0.61, 0.36, 1),
box-shadow 0.3s ease,
border-color 0.3s ease;
overflow: visible;
}
.metric-card:hover {
transform: translateY(-2px);
border-color: rgba(255, 255, 255, 0.12);
box-shadow:
0 1px 0 rgba(255, 255, 255, 0.06) inset,
0 24px 48px rgba(0, 0, 0, 0.3);
}
.metric-card__ring {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 240px;
height: 240px;
opacity: 0.5;
pointer-events: none;
z-index: 0;
}
.metric-card__ring svg {
width: 100%;
height: 100%;
transform: rotate(0deg);
}
.metric-card__ring-fill {
transition: stroke-dasharray 0.8s cubic-bezier(0.22, 0.61, 0.36, 1);
}
.metric-card__icon {
width: 28px;
height: 28px;
display: flex;
align-items: center;
justify-content: center;
font-size: 24px;
color: rgba(255, 255, 255, 0.5);
margin-bottom: 14px;
position: relative;
z-index: 1;
}
.metric-card__label {
font-size: 13px;
font-weight: 500;
color: var(--monitor-text-muted);
letter-spacing: 0.01em;
text-align: center;
margin-bottom: 20px;
position: relative;
z-index: 1;
}
.metric-card__value {
font-size: 48px;
font-weight: 700;
color: var(--monitor-text);
font-variant-numeric: tabular-nums;
letter-spacing: -0.03em;
line-height: 1;
margin-bottom: 8px;
position: relative;
z-index: 1;
}
.metric-card__detail {
font-size: 12px;
color: var(--monitor-text-muted);
font-variant-numeric: tabular-nums;
text-align: center;
letter-spacing: 0.01em;
display: flex;
align-items: center;
gap: 2px;
position: relative;
z-index: 1;
}
/* ===== Stats Row (Live metrics) ===== */
.stats-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 16px;
margin-bottom: 6px;
}
.stat-pill {
display: flex;
align-items: center;
gap: 16px;
padding: 20px 24px;
background: var(--monitor-surface);
border: 1px solid var(--monitor-border-soft);
border-radius: var(--monitor-radius-card);
box-shadow:
0 1px 0 rgba(255, 255, 255, 0.04) inset,
0 12px 30px rgba(0, 0, 0, 0.18);
-webkit-backdrop-filter: blur(14px) saturate(140%);
backdrop-filter: blur(14px) saturate(140%);
transition: transform 0.25s cubic-bezier(0.22, 0.61, 0.36, 1),
border-color 0.25s ease;
}
.stat-pill:hover {
transform: translateY(-1px);
border-color: rgba(255, 255, 255, 0.1);
}
.stat-pill__icon {
font-size: 24px;
line-height: 1;
color: rgba(255, 255, 255, 0.5);
display: flex;
align-items: center;
justify-content: center;
width: 32px;
flex-shrink: 0;
}
.stat-pill__body {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.stat-pill__label {
font-size: 12px;
color: var(--monitor-text-muted);
letter-spacing: 0.01em;
font-weight: 500;
}
.stat-pill__value {
font-size: 24px;
font-weight: 600;
color: var(--monitor-text);
font-variant-numeric: tabular-nums;
letter-spacing: -0.02em;
line-height: 1.1;
}
/* ===== Services grid ===== */
.svc-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
gap: 10px;
}
.svc-row {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 14px;
border-radius: var(--monitor-radius-row);
background: var(--monitor-surface-strong);
border: 1px solid var(--monitor-border-soft);
}
.svc-row__dot {
width: 8px;
height: 8px;
border-radius: 50%;
flex: none;
background: var(--monitor-text-faint);
transition: background 0.3s ease, box-shadow 0.3s ease;
}
.svc-row[data-state="ok"] .svc-row__dot {
background: #22c55e;
box-shadow: 0 0 0 3px rgba(34, 197, 94, 0.12);
}
.svc-row[data-state="warn"] .svc-row__dot {
background: #f59e0b;
box-shadow: 0 0 0 3px rgba(245, 158, 11, 0.14);
}
.svc-row[data-state="bad"] .svc-row__dot {
background: #ef4444;
box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.14);
}
.svc-row__body { min-width: 0; }
.svc-row__name {
font-size: 13.5px;
font-weight: 500;
color: var(--monitor-text);
letter-spacing: -0.005em;
}
.svc-row__val {
font-size: 12px;
color: var(--monitor-text-muted);
margin-top: 2px;
font-variant-numeric: tabular-nums;
}
/* ===== History graph + calendar ===== */
.graph-wrap {
display: flex;
flex-direction: column;
gap: 18px;
}
.graph-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
flex-wrap: wrap;
}
.graph-legend {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 4px;
border-radius: 999px;
background: var(--monitor-surface);
border: 1px solid var(--monitor-border-soft);
}
.graph-legend span {
display: inline-flex;
align-items: center;
gap: 7px;
font-size: 12px;
color: var(--monitor-text-muted);
font-variant-numeric: tabular-nums;
padding: 5px 11px;
border-radius: 999px;
font-weight: 500;
}
.graph-legend i {
width: 8px;
height: 8px;
border-radius: 50%;
display: inline-block;
}
#graphLabel {
font-size: 12.5px;
color: var(--monitor-text-muted);
font-variant-numeric: tabular-nums;
font-weight: 500;
letter-spacing: 0.01em;
}
#metricsGraph {
width: 100%;
height: 220px;
display: block;
border-radius: 14px;
background: var(--monitor-surface);
border: 1px solid var(--monitor-border-soft);
padding: 14px;
box-sizing: border-box;
}
/* Calendar */
.calendar { margin-top: 4px; }
.calendar-head {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 14px;
gap: 12px;
flex-wrap: wrap;
}
.calendar-nav {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 4px;
border-radius: 999px;
background: var(--monitor-surface);
border: 1px solid var(--monitor-border-soft);
}
.calendar-nav-btn {
width: 30px;
height: 30px;
display: inline-flex;
align-items: center;
justify-content: center;
border-radius: 999px;
border: none;
background: transparent;
color: var(--monitor-text-muted);
font-size: 11px;
cursor: pointer;
transition: background 0.18s ease, color 0.18s ease, transform 0.18s ease;
}
.calendar-nav-btn:hover:not(:disabled) {
background: var(--monitor-surface-strong);
color: var(--monitor-text);
}
.calendar-nav-btn:active:not(:disabled) {
transform: scale(0.94);
}
.calendar-nav-btn:disabled {
opacity: 0.3;
cursor: not-allowed;
}
.calendar-head__month {
font-size: 14.5px;
font-weight: 600;
color: var(--monitor-text);
letter-spacing: -0.01em;
padding: 0 10px;
min-width: 130px;
text-align: center;
font-variant-numeric: tabular-nums;
}
.calendar-head__hint {
font-size: 12px;
color: var(--monitor-text-faint);
}
.cal-grid {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 6px;
}
.cal-weekday {
text-align: center;
font-size: 10.5px;
font-weight: 600;
color: var(--monitor-text-faint);
text-transform: uppercase;
letter-spacing: 0.08em;
padding: 8px 0 10px;
}
.cal-cell {
position: relative;
aspect-ratio: 1 / 1;
border-radius: 12px;
border: 1px solid var(--monitor-border-soft);
background: var(--monitor-surface);
color: var(--monitor-text);
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
padding: 0;
font-family: var(--monitor-font);
transition:
transform 0.2s cubic-bezier(0.22, 0.61, 0.36, 1),
box-shadow 0.2s ease,
background 0.2s ease,
border-color 0.2s ease;
overflow: hidden;
}
.cal-cell:hover:not(.cal-cell--blank):not(.cal-cell--active) {
transform: translateY(-1px);
background: var(--monitor-surface-strong);
border-color: rgba(255, 255, 255, 0.1);
}
.cal-cell--blank {
background: transparent;
border-color: transparent;
cursor: default;
}
.cal-cell--blank:hover { transform: none; }
.cal-cell__num {
font-size: 13.5px;
font-weight: 500;
font-variant-numeric: tabular-nums;
letter-spacing: -0.01em;
line-height: 1;
}
/* Active/selected day: same look as unselected, just "pressed" (sunken). */
.cal-cell--active {
transform: scale(0.9);
background: rgba(0, 0, 0, 0.28);
border-color: rgba(255, 255, 255, 0.04);
box-shadow:
inset 0 2px 4px rgba(0, 0, 0, 0.45),
inset 0 -1px 0 rgba(255, 255, 255, 0.03);
}
.cal-cell--active .cal-cell__num { color: var(--monitor-text); }
/* Heat indicator + today dot are intentionally hidden — minimal cells. */
.cal-cell__heat,
.cal-cell--today .cal-cell__num::after { display: none; }
/* ===== Responsive ===== */
@media (max-width: 920px) {
.metrics-hero {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 720px) {
.monitor-head { align-items: flex-start; }
.monitor-head__meta { width: 100%; }
.monitor-chip { font-size: 12.5px; padding: 8px 12px; }
.calendar-head { flex-direction: column; align-items: flex-start; gap: 8px; }
.stats-row {
grid-template-columns: 1fr;
}
}
@media (max-width: 640px) {
.monitor { width: calc(100% - 28px); }
.monitor-card { padding: 20px 18px; }
.metric-card { padding: 32px 24px 28px; min-height: 240px; }
.metric-card__value { font-size: 40px; }
.metric-card__ring { width: 210px; height: 210px; }
.metrics-hero { grid-template-columns: 1fr; gap: 16px; }
.cal-cell { padding: 4px 2px 6px; gap: 3px; }
.cal-cell__num { font-size: 12.5px; }
.cal-cell__heat { height: 2.5px; }
.monitor-chip { font-size: 12px; padding: 7px 11px; }
.stat-pill { padding: 16px 20px; }
}
+315 -108
View File
@@ -38,8 +38,8 @@ body {
background: url("https://cdn.pixabay.com/photo/2024/07/19/08/16/waves-8905720_1280.png") center/cover no-repeat; background: url("https://cdn.pixabay.com/photo/2024/07/19/08/16/waves-8905720_1280.png") center/cover no-repeat;
background-attachment: fixed; background-attachment: fixed;
padding: 32px clamp(20px, 6vw, 72px); padding: 32px clamp(20px, 6vw, 72px);
scroll-snap-type: y mandatory;
overflow-y: scroll; overflow-y: scroll;
overscroll-behavior: none;
} }
::-webkit-scrollbar { ::-webkit-scrollbar {
@@ -193,14 +193,14 @@ html.skip-dashboard-splash #splash-screen {
width: 44px; width: 44px;
height: 44px; height: 44px;
border-radius: 50%; border-radius: 50%;
border: none; border: none !important;
outline: none; outline: none !important;
background: rgba(255, 255, 255, 0.08); background: rgba(255, 255, 255, 0.08);
color: var(--color-text); color: var(--color-text);
display: grid; display: grid;
place-items: center; place-items: center;
cursor: pointer; cursor: pointer;
transition: transform var(--transition-base), background var(--transition-base), border var(--transition-base); transition: transform var(--transition-base), background var(--transition-base);
} }
.icon-button:hover { .icon-button:hover {
@@ -217,6 +217,13 @@ html.skip-dashboard-splash #splash-screen {
background: rgb(0, 140, 254); background: rgb(0, 140, 254);
} }
.icon-button:focus,
.icon-button:focus-visible,
.icon-button:active {
border: none !important;
outline: none !important;
}
.icon-button:disabled { .icon-button:disabled {
cursor: not-allowed; cursor: not-allowed;
opacity: 0.6; opacity: 0.6;
@@ -280,12 +287,12 @@ html.skip-dashboard-splash #splash-screen {
display: grid; display: grid;
place-items: center; place-items: center;
cursor: pointer; cursor: pointer;
transition: transform var(--transition-base), background var(--transition-base), border var(--transition-base); transition: transform var(--transition-base), background var(--transition-base);
} }
.icon-butt { .icon-butt {
border: none; border: none !important;
outline: none; outline: none !important;
} }
.icon-butt i { .icon-butt i {
@@ -295,7 +302,15 @@ html.skip-dashboard-splash #splash-screen {
.icon-butt:hover:not(:disabled) { .icon-butt:hover:not(:disabled) {
transform: translateY(-2px) scale(1.03); transform: translateY(-2px) scale(1.03);
background: rgba(255, 0, 0, 0.841); background: rgba(255, 0, 0, 0.841);
border-color: rgba(0, 255, 213, 0); border: none !important;
outline: none !important;
}
.icon-butt:focus,
.icon-butt:focus-visible,
.icon-butt:active {
border: none !important;
outline: none !important;
} }
.icon-butt:disabled { .icon-butt:disabled {
@@ -306,7 +321,7 @@ html.skip-dashboard-splash #splash-screen {
.dashboard { .dashboard {
margin-top: 32px; margin-top: 32px;
display: grid; display: grid;
gap: clamp(28px, 4vw, 48px); gap: 30px;
} }
.hero { .hero {
@@ -314,16 +329,32 @@ html.skip-dashboard-splash #splash-screen {
grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr);
gap: clamp(24px, 4vw, 44px); gap: clamp(24px, 4vw, 44px);
align-items: stretch; align-items: stretch;
scroll-snap-align: start;
} }
.hero-copy { .hero-copy {
background: var(--color-surface); position: relative;
border: 1px solid var(--color-border); background: rgba(30, 30, 35, 0.7);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
padding: clamp(28px, 4vw, 40px); padding: clamp(28px, 4vw, 40px);
box-shadow: var(--shadow-lg); box-shadow: var(--shadow-lg), inset 0 1px 0 rgba(255, 255, 255, 0.06);
backdrop-filter: blur(18px); backdrop-filter: blur(40px) saturate(180%);
-webkit-backdrop-filter: blur(40px) saturate(180%);
transition: background var(--transition-base), border-color var(--transition-base);
}
.hero-copy::before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
pointer-events: none;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 25%);
}
.hero-copy:hover {
background: rgba(30, 30, 35, 0.78);
border-color: rgba(255, 255, 255, 0.14);
} }
.hero-copy h2 { .hero-copy h2 {
@@ -345,40 +376,57 @@ html.skip-dashboard-splash #splash-screen {
} }
.pill { .pill {
border-top: 20px solid black; border: none;
border-right: 5px solid black; border-radius: 999px;
border-bottom: 20px solid black;
border-left: 5px solid black;
border-radius: 5px;
padding: 10px 22px; padding: 10px 22px;
font-weight: 600; font-weight: 500;
font-size: 14px;
cursor: pointer; cursor: pointer;
background: linear-gradient(135deg, #7c5cff, #4f46e5); background: linear-gradient(135deg, #7c5cff, #4f46e5);
color: white; color: white;
transition: transform var(--transition-base), box-shadow var(--transition-base); transition: background 0.25s ease;
transition: filter 0.2s ease-in-out;
display: inline-flex;
align-items: center;
gap: 8px;
} }
.pill--outline { .pill--outline {
background: transparent; background: transparent;
color: var(--color-text); color: var(--color-text);
border: 2px solid rgba(255, 255, 255, 0.088); border: 1px solid rgba(255, 255, 255, 0.2);
}
.pill--outline:hover {
background: rgba(255, 255, 255, 0.08);
border-color: rgba(255, 255, 255, 0.3);
}
/* Buton Create independent cu hover gri */
.pill.pill--create-hero {
font-weight: 500;
font-size: 14px;
}
.pill.pill--create-hero:hover {
background: rgba(255, 255, 255, 0.12) !important;
border-color: rgba(255, 255, 255, 0.35) !important;
} }
.pill:hover { .pill:hover {
transform: translateY(-1px); background: linear-gradient(135deg, #7c5dff, #4f46e6);
border: 2px solid rgba(255, 255, 255, 0.168);
box-shadow: 0 12px 24px rgba(78, 70, 229, 0.129);
} }
.pills { .pills {
border: none; border: none;
border-radius: 999px; border-radius: 999px;
padding: 10px 22px; padding: 10px 22px;
font-weight: 600; font-weight: 500;
font-size: 14px;
cursor: pointer; cursor: pointer;
background: linear-gradient(135deg, #7c5cff, #4f46e5); background: linear-gradient(135deg, #7c5cff, #4f46e5);
color: white; color: white;
transition: transform var(--transition-base), box-shadow var(--transition-base); transition: background 0.25s ease;
} }
.pills--outline { .pills--outline {
@@ -388,8 +436,7 @@ html.skip-dashboard-splash #splash-screen {
} }
.pills:hover { .pills:hover {
transform: translateY(-1px); background: linear-gradient(135deg, #8c6cff, #6356f5);
box-shadow: 0 12px 24px rgba(79, 70, 229, 0.28);
} }
.hero-stats { .hero-stats {
@@ -398,55 +445,89 @@ html.skip-dashboard-splash #splash-screen {
} }
.stat-card { .stat-card {
position: relative;
display: flex; display: flex;
align-items: center; align-items: center;
gap: 18px; gap: 22px;
background: var(--color-surface); background: rgba(30, 30, 35, 0.7);
border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
padding: 20px; padding: 20px;
box-shadow: var(--shadow-md); box-shadow: var(--shadow-md), inset 0 1px 0 rgba(255, 255, 255, 0.05);
backdrop-filter: blur(20px); backdrop-filter: blur(40px) saturate(180%);
-webkit-backdrop-filter: blur(40px) saturate(180%);
transition: background var(--transition-base), border-color var(--transition-base);
}
.stat-card::before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
pointer-events: none;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 30%);
}
.stat-card:hover {
background: rgba(30, 30, 35, 0.78);
border-color: rgba(255, 255, 255, 0.14);
} }
.stat-card__icon { .stat-card__icon {
width: 56px; font-size: 2.2rem;
height: 56px; color: #818cf8;
border-radius: 18px; flex-shrink: 0;
display: grid;
place-items: center;
font-size: 1.3rem;
color: white;
} }
.stat-card__icon--active { .stat-card:first-child .stat-card__icon {
background: linear-gradient(135deg, #34d399, #059669); font-size: 2.5rem;
} }
.stat-card__icon--uptime { .stat-card__content {
background: linear-gradient(135deg, #38bdf8, #1d4ed8); display: flex;
} flex-direction: column;
gap: 2px;
.stat-card__icon--deploy { justify-content: center;
background: linear-gradient(135deg, #ffa600, #da4500);
} }
.stat-card__label { .stat-card__label {
font-size: 0.9rem; font-size: 0.9rem;
color: var(--color-text-muted); color: var(--color-text-muted);
margin: 0;
line-height: 1.1;
} }
.stat-card__value { .stat-card__value {
font-size: 1.7rem; font-size: 1.7rem;
font-weight: 700; font-weight: 700;
margin: 0;
line-height: 1.1;
} }
.quick-actions { .quick-actions {
background: var(--color-surface); position: relative;
background: rgba(30, 30, 35, 0.7);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
border: 1px solid var(--color-border); border: 1px solid rgba(255, 255, 255, 0.08);
box-shadow: var(--shadow-md); box-shadow: var(--shadow-md), inset 0 1px 0 rgba(255, 255, 255, 0.05);
padding: clamp(24px, 4vw, 36px); padding: clamp(24px, 4vw, 36px);
backdrop-filter: blur(14px); backdrop-filter: blur(40px) saturate(180%);
-webkit-backdrop-filter: blur(40px) saturate(180%);
transition: background var(--transition-base), border-color var(--transition-base);
}
.quick-actions::before {
content: "";
position: absolute;
inset: 0;
border-radius: inherit;
pointer-events: none;
background: linear-gradient(180deg, rgba(255, 255, 255, 0.02), transparent 30%);
}
.quick-actions:hover {
background: rgba(30, 30, 35, 0.78);
border-color: rgba(255, 255, 255, 0.14);
} }
.quick-actions h3 { .quick-actions h3 {
@@ -579,7 +660,7 @@ html.skip-dashboard-splash #splash-screen {
align-items: flex-end; align-items: flex-end;
justify-content: space-between; justify-content: space-between;
gap: 16px; gap: 16px;
margin-bottom: 20px; margin-bottom: 40px;
} }
.section-heading h3 { .section-heading h3 {
@@ -627,21 +708,73 @@ html.skip-dashboard-splash #splash-screen {
.bot-grid { .bot-grid {
display: grid; display: grid;
gap: 18px; gap: 20px;
grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); grid-template-columns: repeat(auto-fit, minmax(min(100%, 360px), 360px));
justify-content: center;
row-gap: 40px;
margin-top: 32px;
} }
.bots .bot-grid { .bots .bot-grid {
display: grid; display: grid;
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr)); grid-template-columns: repeat(auto-fit, minmax(min(100%, 360px), 360px));
gap: 16px; gap: 20px;
row-gap: 40px;
justify-content: center;
margin-top: 32px;
}
justify-items: center; .bot-card:only-child {
justify-self: center;
max-width: 360px;
}
@media (max-width: 400px) {
.bot-grid,
.bots .bot-grid {
grid-template-columns: 1fr;
}
}
@media (min-width: 401px) and (max-width: 800px) {
.bot-grid,
.bots .bot-grid {
grid-template-columns: repeat(auto-fit, minmax(320px, 360px));
}
}
@media (min-width: 801px) and (max-width: 1200px) {
.bot-grid,
.bots .bot-grid {
grid-template-columns: repeat(auto-fit, minmax(340px, 360px));
max-width: 760px;
margin-left: auto;
margin-right: auto;
}
}
@media (min-width: 1201px) and (max-width: 1600px) {
.bot-grid,
.bots .bot-grid {
grid-template-columns: repeat(auto-fit, minmax(350px, 360px));
max-width: 1140px;
margin-left: auto;
margin-right: auto;
}
}
@media (min-width: 1601px) {
.bot-grid,
.bots .bot-grid {
grid-template-columns: repeat(auto-fit, minmax(360px, 360px));
max-width: 1520px;
margin-left: auto;
margin-right: auto;
}
} }
.bots, .bots,
.quick-actions { .quick-actions {
scroll-snap-align: start;
scroll-margin-top: 20px; scroll-margin-top: 20px;
} }
@@ -651,48 +784,21 @@ html.skip-dashboard-splash #splash-screen {
flex-direction: column; flex-direction: column;
border-radius: 20px; border-radius: 20px;
overflow: hidden; overflow: hidden;
background: radial-gradient(circle at 10% -10%, rgba(34, 211, 238, 0.08), transparent 26%), background: linear-gradient(160deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.02));
radial-gradient(circle at 80% -20%, rgba(124, 92, 255, 0.12), transparent 32%),
linear-gradient(160deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.02));
border: 1px solid rgba(255, 255, 255, 0.14); border: 1px solid rgba(255, 255, 255, 0.14);
cursor: pointer; cursor: pointer;
box-shadow: 0 18px 42px rgba(0, 0, 0, 0.45); box-shadow: 0 18px 42px rgba(0, 0, 0, 0.45);
isolation: isolate; will-change: transform;
transition: transform 0.25s ease, box-shadow 0.25s ease, border-color 0.25s ease; transform: translateZ(0);
} backface-visibility: hidden;
transition: transform 0.2s ease, box-shadow 0.2s ease;
.bot-card::before,
.bot-card::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
transition: opacity 0.25s ease;
}
.bot-card::before {
border-radius: inherit;
background: linear-gradient(135deg, rgba(34, 211, 238, 0.2), rgba(29, 78, 216, 0.12));
opacity: 0.35;
}
.bot-card::after {
border-radius: inherit;
background: radial-gradient(circle at 20% 20%, rgba(255, 255, 255, 0.12), transparent 36%),
radial-gradient(circle at 80% 10%, rgba(14, 165, 233, 0.22), transparent 38%);
mix-blend-mode: screen;
opacity: 0.45;
} }
.bot-card:hover { .bot-card:hover {
transform: translateY(-1px) scale(1.005); transform: translateY(-1px) translateZ(0);
box-shadow: 0 22px 52px rgba(0, 0, 0, 0.55); box-shadow: 0 22px 52px rgba(0, 0, 0, 0.55);
} }
.bot-card:hover::after {
opacity: 0.75;
}
.bot-card__hero { .bot-card__hero {
position: relative; position: relative;
min-height: 210px; min-height: 210px;
@@ -705,7 +811,9 @@ html.skip-dashboard-splash #splash-screen {
background: var(--bot-cover); background: var(--bot-cover);
background-size: cover; background-size: cover;
background-position: center; background-position: center;
filter: saturate(1.5) brightness(1); opacity: 0.85;
will-change: transform;
transform: translateZ(0);
-webkit-mask-image: linear-gradient(180deg, #fff 0%, #fff 70%, rgba(255, 255, 255, 0.65) 82%, transparent 100%); -webkit-mask-image: linear-gradient(180deg, #fff 0%, #fff 70%, rgba(255, 255, 255, 0.65) 82%, transparent 100%);
mask-image: linear-gradient(180deg, #fff 0%, #fff 70%, rgba(255, 255, 255, 0.65) 82%, transparent 100%); mask-image: linear-gradient(180deg, #fff 0%, #fff 70%, rgba(255, 255, 255, 0.65) 82%, transparent 100%);
} }
@@ -713,9 +821,7 @@ html.skip-dashboard-splash #splash-screen {
.bot-card__hero-overlay { .bot-card__hero-overlay {
position: absolute; position: absolute;
inset: 0; inset: 0;
background: linear-gradient(180deg, rgba(2, 6, 23, 0.02) 0%, rgba(2, 6, 23, 0.373) 20%, rgba(2, 6, 23, 0.581) 20%), background: linear-gradient(180deg, rgba(2, 6, 23, 0.02) 0%, rgba(2, 6, 23, 0.45) 100%);
radial-gradient(circle at 30% 20%, rgba(34, 211, 238, 0.26), transparent 70%);
mix-blend-mode: lighten;
} }
.bot-card__hero-content { .bot-card__hero-content {
@@ -810,20 +916,20 @@ html.skip-dashboard-splash #splash-screen {
.bot-card.status-online .bot-card__status-dot { .bot-card.status-online .bot-card__status-dot {
color: #34d399; color: #34d399;
background: radial-gradient(circle at 35% 35%, #e6fff2 0%, #c1ffd7 30%, #34d399 70%); background: #34d399;
box-shadow: 0 0 0 5px rgba(52, 211, 153, 0.16), 0 0 22px rgba(52, 211, 153, 0.45); box-shadow: 0 0 0 5px rgba(52, 211, 153, 0.16), 0 0 12px rgba(52, 211, 153, 0.45);
} }
.bot-card.status-stopped .bot-card__status-dot { .bot-card.status-stopped .bot-card__status-dot {
color: #e64747; color: #e64747;
background: radial-gradient(circle at 35% 35%, #ffe4e8 0%, #ffc2cb 30%, #e64747 70%); background: #e64747;
box-shadow: 0 0 0 5px rgba(239, 68, 68, 0.18), 0 0 22px rgba(239, 68, 68, 0.45); box-shadow: 0 0 0 5px rgba(239, 68, 68, 0.18), 0 0 12px rgba(239, 68, 68, 0.45);
} }
.bot-card.status-unknown .bot-card__status-dot { .bot-card.status-unknown .bot-card__status-dot {
color: #f59e0b; color: #f59e0b;
background: radial-gradient(circle at 35% 35%, #fef3c7 0%, #fde68a 30%, #f59e0b 70%); background: #f59e0b;
box-shadow: 0 0 0 5px rgba(245, 158, 11, 0.16), 0 0 22px rgba(245, 158, 11, 0.35); box-shadow: 0 0 0 5px rgba(245, 158, 11, 0.16), 0 0 12px rgba(245, 158, 11, 0.35);
} }
.bot-card.status-unknown .bot-card__status-dot::before, .bot-card.status-unknown .bot-card__status-dot::before,
@@ -841,7 +947,6 @@ html.skip-dashboard-splash #splash-screen {
background: rgba(2, 6, 23, 0.6); background: rgba(2, 6, 23, 0.6);
border-radius: 14px; border-radius: 14px;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
} }
.bot-card__meta-row span { .bot-card__meta-row span {
@@ -862,7 +967,6 @@ html.skip-dashboard-splash #splash-screen {
background: linear-gradient(180deg, rgba(2, 6, 23, 0.86), rgba(2, 6, 23, 0.96)); background: linear-gradient(180deg, rgba(2, 6, 23, 0.86), rgba(2, 6, 23, 0.96));
border-top: 1px solid rgba(255, 255, 255, 0.1); border-top: 1px solid rgba(255, 255, 255, 0.1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04); box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
backdrop-filter: blur(18px);
} }
.bot-card__stat { .bot-card__stat {
@@ -1060,11 +1164,12 @@ html.skip-dashboard-splash #splash-screen {
.footer { .footer {
margin-top: 40px; margin-top: 40px;
background: var(--color-surface); background: rgba(255, 255, 255, 0.06);
border: 1px solid var(--color-border); border: 1px solid rgba(255, 255, 255, 0.08);
border-radius: var(--radius-lg); border-radius: var(--radius-lg);
box-shadow: var(--shadow-md); box-shadow: var(--shadow-md);
backdrop-filter: blur(14px); backdrop-filter: blur(14px) saturate(160%);
-webkit-backdrop-filter: blur(14px) saturate(160%);
} }
.footer-inner { .footer-inner {
@@ -1230,6 +1335,12 @@ html.skip-dashboard-splash #splash-screen {
transform: none; transform: none;
} }
.footer .btn-primary:hover {
background: linear-gradient(135deg, #10aff0, #1f52dc);
filter: none;
transform: none;
}
.btn-primary.create-btn:hover { .btn-primary.create-btn:hover {
transform: none; transform: none;
} }
@@ -1239,6 +1350,102 @@ html.skip-dashboard-splash #splash-screen {
filter: brightness(0.96); filter: brightness(0.96);
} }
/* ── Navbar Create pill — circle → pill expand ────────────────────────── */
/* Open/close is driven by JS (.is-open class on mouseenter/leave + focus) so
the collapse animation always plays, even after the cursor leaves. */
.create-btn {
position: relative;
overflow: hidden;
width: 44px;
height: 44px;
/* No horizontal padding in the circle state: the icon is centred purely by
flexbox, so the "+" sits dead-centre regardless of the (collapsed) label. */
padding: 0;
border-radius: 50%;
display: inline-flex;
align-items: center;
justify-content: center;
gap: 0;
/* 0.4s smooth expand / collapse */
transition:
width 0.4s cubic-bezier(0.65, 0, 0.35, 1),
border-radius 0.4s cubic-bezier(0.65, 0, 0.35, 1),
padding 0.4s cubic-bezier(0.65, 0, 0.35, 1),
gap 0.4s cubic-bezier(0.65, 0, 0.35, 1),
filter 0.4s ease;
}
.create-btn__icon {
flex: 0 0 auto;
display: flex;
align-items: center;
justify-content: center;
width: 14px;
height: 14px;
font-size: 14px;
line-height: 1;
/* Centred in the circle (no offset); only opacity eases when opening,
so the "+" stays dead-centre while still animating like the label. */
opacity: 0.9;
transition: opacity 0.25s cubic-bezier(0.65, 0, 0.35, 1);
}
.create-btn__label {
flex: 0 0 auto;
overflow: hidden;
white-space: nowrap;
/* Collapsed: pulled out of normal flow so it never offsets the centred icon */
position: absolute;
left: 100%;
max-width: 0;
opacity: 0;
font-family: 'Inter', 'Manrope', system-ui, sans-serif;
font-size: 14px;
font-weight: 500;
line-height: 1;
letter-spacing: 0.01em;
transform: translateX(8px);
pointer-events: none;
/* Closing: label fades/slides out while the box collapses */
transition:
max-width 0.25s cubic-bezier(0.65, 0, 0.35, 1),
opacity 0.2s cubic-bezier(0.65, 0, 0.35, 1),
transform 0.25s cubic-bezier(0.65, 0, 0.35, 1);
}
/* Open state — toggled by JS (.is-open) and mirrored on :focus-visible */
.create-btn.is-open,
.create-btn:focus-visible {
width: 124px;
border-radius: 999px;
/* Even left/right padding centres the icon+label group inside the pill */
padding: 0 18px;
gap: 9px;
filter: brightness(1.06);
}
.create-btn.is-open .create-btn__icon,
.create-btn:focus-visible .create-btn__icon {
opacity: 1;
transition: opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1) 0.08s;
}
.create-btn.is-open .create-btn__label,
.create-btn:focus-visible .create-btn__label {
/* Back into normal flow when open, so it sits next to the icon */
position: static;
left: auto;
max-width: 64px;
opacity: 1;
transform: translateX(0);
pointer-events: auto;
/* Opening: text eases in just after the box starts expanding */
transition:
max-width 0.35s cubic-bezier(0.16, 1, 0.3, 1) 0.08s,
opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1) 0.12s,
transform 0.35s cubic-bezier(0.16, 1, 0.3, 1) 0.08s;
}
.btn-ghost { .btn-ghost {
background: rgba(15, 23, 42, 0.85); background: rgba(15, 23, 42, 0.85);
border: none; border: none;
@@ -2735,7 +2942,7 @@ html.skip-dashboard-splash #splash-screen {
.account-page { .account-page {
max-width: 800px; max-width: 800px;
margin: 0 auto; margin: 0 auto;
padding: 40px 24px; padding: 80px 24px 40px;
animation: fadeInUp 0.4s ease; animation: fadeInUp 0.4s ease;
} }
Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 245 KiB

File diff suppressed because it is too large. Load diff
+890 -83
View File
File diff suppressed because it is too large. Load diff
+127 -11
View File
@@ -908,22 +908,64 @@
return els.messages.querySelectorAll(".dashboard-assistant-message--assistant").length; return els.messages.querySelectorAll(".dashboard-assistant-message--assistant").length;
} }
// Minimum viewport height (in CSS pixels) required to safely open the
// assistant. Below this the UI is too cramped to be usable (matches a
// phone-sized window or an extreme browser zoom-in).
const MIN_OPEN_HEIGHT = 480;
// Minimum viewport width. Below this the layout would clip horizontally.
const MIN_OPEN_WIDTH = 360;
function canOpenMenu() {
const h = window.innerHeight;
const w = window.innerWidth;
return h >= MIN_OPEN_HEIGHT && w >= MIN_OPEN_WIDTH;
}
function positionMenu() { function positionMenu() {
if (!state.open || !els.menu || !els.trigger) return; if (!state.open || !els.menu || !els.trigger) return;
const triggerRect = els.trigger.getBoundingClientRect(); const triggerRect = els.trigger.getBoundingClientRect();
const margin = 12;
const topGap = 10;
// Width: keep the designed width, never scale it. Clamp to viewport.
const preferredWidth = state.configured ? 580 : 430; const preferredWidth = state.configured ? 580 : 430;
const menuWidth = Math.min(preferredWidth, window.innerWidth - 24); const visualW = Math.min(preferredWidth, window.innerWidth - margin * 2);
const leftBias = 150;
// Center on trigger, then keep the panel fully visible in viewport. // Height: whatever fits between the trigger bottom and the viewport bottom.
const idealLeft = triggerRect.left + (triggerRect.width / 2) - (menuWidth / 2) - leftBias; // The messages area has `flex: 1` + `overflow-y: auto`, so it scrolls
const left = Math.max(12, Math.min(idealLeft, window.innerWidth - menuWidth - 12)); // naturally when content is taller than this — no clipping at the bottom.
const availableBelow = window.innerHeight - triggerRect.bottom - topGap - margin;
const availableAbove = triggerRect.top - topGap - margin;
// Prefer placing it below the trigger; fall back to above if no room.
const useAbove = availableBelow < 260 && availableAbove > availableBelow;
const visualH = Math.max(
260,
useAbove ? availableAbove : availableBelow
);
els.menu.style.width = `${menuWidth}px`; // Center horizontally on the trigger, then clamp to viewport.
const desiredLeft = triggerRect.left + (triggerRect.width / 2) - (visualW / 2) - 150;
const left = Math.max(margin, Math.min(desiredLeft, window.innerWidth - visualW - margin));
const top = useAbove
? Math.max(margin, triggerRect.top - visualH - topGap)
: Math.max(margin, triggerRect.bottom + topGap);
els.menu.style.width = `${visualW}px`;
els.menu.style.height = `${visualH}px`;
els.menu.style.left = `${left}px`; els.menu.style.left = `${left}px`;
els.menu.style.right = 'auto'; els.menu.style.right = "auto";
els.menu.style.top = `${triggerRect.bottom + 20}px`; els.menu.style.top = `${top}px`;
els.menu.style.bottom = 'auto'; els.menu.style.bottom = "auto";
els.menu.style.transform = "none";
els.menu.style.setProperty("--assistant-scale", "1");
// Relax the messages area's min-height when the viewport is tight,
// so the menu can shrink to fit without clipping the composer.
if (els.messages) {
const tight = visualH < 520;
els.messages.style.minHeight = tight ? "0px" : "";
}
} }
function stopSpeaking() { function stopSpeaking() {
@@ -1168,6 +1210,10 @@
} }
function openMenu() { function openMenu() {
if (!canOpenMenu()) {
showTooSmallNotice();
return;
}
state.open = true; state.open = true;
primeSpeechSynthesis(); primeSpeechSynthesis();
updateButtons(); updateButtons();
@@ -1178,6 +1224,24 @@
}); });
} }
function showTooSmallNotice() {
// Flash a transient inline notice near the trigger so the user understands
// why the assistant didn't open. Uses the existing status pipeline.
if (els.status) {
const prevState = els.status.dataset.state;
const prevText = els.status.textContent;
els.status.dataset.state = "warning";
els.status.textContent = "Screen too small to open the assistant. Try a larger window.";
els.status.classList.remove("is-hidden");
setTimeout(() => {
if (!state.open && els.status) {
els.status.dataset.state = prevState || "idle";
els.status.textContent = prevText || "";
}
}, 3500);
}
}
function closeMenu() { function closeMenu() {
state.open = false; state.open = false;
updateButtons(); updateButtons();
@@ -4696,6 +4760,11 @@
els.trigger?.addEventListener("click", (event) => { els.trigger?.addEventListener("click", (event) => {
event.stopPropagation(); event.stopPropagation();
if (!state.open) { if (!state.open) {
if (!canOpenMenu()) {
event.preventDefault();
showTooSmallNotice();
return;
}
openMenu(); openMenu();
return; return;
} }
@@ -4860,14 +4929,61 @@
}; };
} }
window.addEventListener("resize", positionMenu); // Re-position on window resize, scroll, AND browser zoom.
window.addEventListener("scroll", positionMenu, true); // `window.resize` doesn't always fire on Ctrl+/Ctrl- zoom, so we also
// listen to `visualViewport.resize` (covers pinch-zoom and most browser
// zoom cases) and fall back to a DPR poll for the rest.
let lastDpr = window.devicePixelRatio || 1;
const refit = () => {
if (!state.open) return;
if (!canOpenMenu()) {
// Viewport shrunk below the safe threshold (e.g. extreme zoom-in).
// Auto-close and inform the user.
closeMenu();
showTooSmallNotice();
return;
}
positionMenu();
};
window.addEventListener("resize", refit);
window.addEventListener("scroll", refit, true);
if (window.visualViewport) {
window.visualViewport.addEventListener("resize", refit);
window.visualViewport.addEventListener("scroll", refit);
}
// DPR poll: catches the few browsers/configs where neither resize nor
// visualViewport fires on zoom. Cheap (rAF-throttled).
const dprTick = () => {
const dpr = window.devicePixelRatio || 1;
if (dpr !== lastDpr) {
lastDpr = dpr;
refit();
}
requestAnimationFrame(dprTick);
};
requestAnimationFrame(dprTick);
window.addEventListener("beforeunload", () => { window.addEventListener("beforeunload", () => {
stopSpeaking(); stopSpeaking();
stopActiveStream(); stopActiveStream();
cleanupAudioGraph(); cleanupAudioGraph();
cleanupRecognition(); cleanupRecognition();
}); });
// Re-position when the menu's intrinsic size changes (e.g. messages streaming,
// config panel toggling, transcript appearing). Debounced with rAF.
if (typeof ResizeObserver !== "undefined" && els.menu) {
let rafId = 0;
const ro = new ResizeObserver(() => {
if (!state.open) return;
if (rafId) cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(() => {
rafId = 0;
positionMenu();
});
});
ro.observe(els.menu);
}
} }
function init() { function init() {
+315 -186
View File
@@ -94,19 +94,29 @@ window.addEventListener('DOMContentLoaded', () => {
const showSplashForFirstCacheMiss = () => { const showSplashForFirstCacheMiss = () => {
if (!splash) return; if (!splash) return;
const displayTime = 5000; const displayTime = 5000;
const hardTimeout = 7000;
const preload = new Image(); const preload = new Image();
let hideScheduled = false; let hideScheduled = false;
const hardTimer = window.setTimeout(() => {
if (hideScheduled) return;
markSplashCached();
hideSplash();
}, hardTimeout);
const scheduleHide = () => { const scheduleHide = () => {
if (hideScheduled) return; if (hideScheduled) return;
hideScheduled = true; hideScheduled = true;
window.clearTimeout(hardTimer);
markSplashCached(); markSplashCached();
window.setTimeout(hideSplash, displayTime); window.setTimeout(hideSplash, displayTime);
}; };
preload.decoding = 'async'; preload.decoding = 'async';
preload.onload = scheduleHide; preload.onload = scheduleHide;
preload.onerror = removeSplash; preload.onerror = () => {
window.clearTimeout(hardTimer);
removeSplash();
};
preload.src = splashImage; preload.src = splashImage;
if (preload.complete) { if (preload.complete) {
@@ -317,76 +327,19 @@ window.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('[data-href]').forEach(el => { document.querySelectorAll('[data-href]').forEach(el => {
el.addEventListener('click', (event) => { el.addEventListener('click', (event) => {
event.preventDefault();
event.stopPropagation();
const href = el.getAttribute('data-href'); const href = el.getAttribute('data-href');
if (!href) return; if (!href) return;
const target = el.getAttribute('data-target'); const target = el.getAttribute('data-target');
if (target === '_blank') { if (target === '_blank') {
window.open(href, '_blank'); window.open(href, '_blank', 'noopener,noreferrer');
} else { } else {
window.location.href = href; window.location.href = href;
} }
event.preventDefault();
}); });
}); });
function ensureSshTerminalModal() {
let overlay = document.getElementById('sshTerminalOverlay');
if (overlay) return overlay;
overlay = document.createElement('div');
overlay.id = 'sshTerminalOverlay';
overlay.className = 'ssh-terminal-overlay';
overlay.innerHTML = `
<section class="ssh-terminal-modal" role="dialog" aria-modal="true" aria-label="SSH Terminal">
<button id="sshTerminalCloseBtn" class="ssh-terminal-close" type="button" aria-label="Close terminal">
<i class="fa-solid fa-xmark"></i>
</button>
<div class="ssh-terminal-frame-wrap">
<iframe id="sshTerminalFrame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer"></iframe>
</div>
</section>
`;
document.body.appendChild(overlay);
const closeBtn = overlay.querySelector('#sshTerminalCloseBtn');
const closeModal = () => {
overlay.classList.remove('show');
const frame = overlay.querySelector('#sshTerminalFrame');
if (frame) frame.src = 'about:blank';
};
closeBtn?.addEventListener('click', closeModal);
overlay.addEventListener('click', (e) => {
if (e.target === overlay) closeModal();
});
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && overlay.classList.contains('show')) closeModal();
});
return overlay;
}
const sshTerminalBtn = document.getElementById('openSshTerminalBtn');
sshTerminalBtn?.addEventListener('click', async () => {
sshTerminalBtn.disabled = true;
try {
const res = await fetch('/api/ssh-terminal/session', { credentials: 'include' });
const data = await res.json().catch(() => ({}));
if (!res.ok || !data?.launchUrl) {
throw new Error(data?.error || 'Unable to open terminal');
}
const overlay = ensureSshTerminalModal();
const frame = overlay.querySelector('#sshTerminalFrame');
if (!frame) throw new Error('Terminal frame unavailable');
frame.src = data.launchUrl;
overlay.classList.add('show');
} catch (err) {
alert(err?.message || 'Failed to open SSH terminal.');
} finally {
sshTerminalBtn.disabled = false;
}
});
document.querySelectorAll('[data-bot-card]').forEach(card => { document.querySelectorAll('[data-bot-card]').forEach(card => {
const cover = card.dataset.cover; const cover = card.dataset.cover;
if (cover) card.style.setProperty('--bot-cover', `url("${cover.replace(/"/g, '\\"')}")`); if (cover) card.style.setProperty('--bot-cover', `url("${cover.replace(/"/g, '\\"')}")`);
@@ -415,6 +368,7 @@ window.addEventListener('DOMContentLoaded', () => {
_searchTimer = setTimeout(() => navigateDashboard(1, (searchInput?.value || '').trim()), 500); _searchTimer = setTimeout(() => navigateDashboard(1, (searchInput?.value || '').trim()), 500);
return; return;
} }
if (!botGrid) return;
const term = (searchInput?.value || '').trim().toLowerCase(); const term = (searchInput?.value || '').trim().toLowerCase();
const botCards = Array.from(botGrid.querySelectorAll('[data-bot-card]')); const botCards = Array.from(botGrid.querySelectorAll('[data-bot-card]'));
let visible = 0; let visible = 0;
@@ -437,7 +391,7 @@ window.addEventListener('DOMContentLoaded', () => {
clearTimeout(_searchTimer); clearTimeout(_searchTimer);
_searchTimer = setTimeout(updateBotVisibility, dashPagination ? 500 : 150); _searchTimer = setTimeout(updateBotVisibility, dashPagination ? 500 : 150);
}); });
if (!dashPagination) updateBotVisibility(); if (botGrid && !dashPagination) updateBotVisibility();
const urlParams = new URLSearchParams(window.location.search); const urlParams = new URLSearchParams(window.location.search);
if (searchInput && urlParams.get('search')) { if (searchInput && urlParams.get('search')) {
@@ -455,6 +409,7 @@ window.addEventListener('DOMContentLoaded', () => {
const topBar = document.getElementById('topBar'); const topBar = document.getElementById('topBar');
const spacer = document.getElementById('topbar-spacer'); const spacer = document.getElementById('topbar-spacer');
const spacerExtraOffset = spacer ? parseInt(spacer.getAttribute('data-topbar-extra-offset') || '0', 10) || 0 : 0;
function measureExpandedHeight() { function measureExpandedHeight() {
const hadCompact = topBar.classList.contains('top-bar--compact'); const hadCompact = topBar.classList.contains('top-bar--compact');
topBar.classList.remove('top-bar--compact'); topBar.classList.remove('top-bar--compact');
@@ -462,19 +417,23 @@ window.addEventListener('DOMContentLoaded', () => {
if (hadCompact) topBar.classList.add('top-bar--compact'); if (hadCompact) topBar.classList.add('top-bar--compact');
return h; return h;
} }
function applySpacerHeight() {
if (!spacer) return;
spacer.style.height = Math.max(0, expandedHeight - spacerExtraOffset) + 'px';
}
let expandedHeight = measureExpandedHeight(); let expandedHeight = measureExpandedHeight();
spacer.style.height = expandedHeight + 'px'; applySpacerHeight();
let resizeRAF = null; let resizeRAF = null;
window.addEventListener('resize', () => { window.addEventListener('resize', () => {
if (resizeRAF) cancelAnimationFrame(resizeRAF); if (resizeRAF) cancelAnimationFrame(resizeRAF);
resizeRAF = requestAnimationFrame(() => { resizeRAF = requestAnimationFrame(() => {
expandedHeight = measureExpandedHeight(); expandedHeight = measureExpandedHeight();
spacer.style.height = expandedHeight + 'px'; applySpacerHeight();
}); });
}); });
new ResizeObserver(() => { new ResizeObserver(() => {
expandedHeight = measureExpandedHeight(); expandedHeight = measureExpandedHeight();
spacer.style.height = expandedHeight + 'px'; applySpacerHeight();
fitHero(); fitHero();
}).observe(topBar); }).observe(topBar);
@@ -603,6 +562,7 @@ window.addEventListener('DOMContentLoaded', () => {
if (statusTextEl) statusTextEl.textContent = data.status || 'Available'; if (statusTextEl) statusTextEl.textContent = data.status || 'Available';
window._accountData = data; window._accountData = data;
syncAccountSecurityUi();
if (cooldownEl && data.usernameChangeCooldown) { if (cooldownEl && data.usernameChangeCooldown) {
const days = Math.ceil(data.usernameChangeCooldown / (24 * 60 * 60 * 1000)); const days = Math.ceil(data.usernameChangeCooldown / (24 * 60 * 60 * 1000));
@@ -840,10 +800,85 @@ window.addEventListener('DOMContentLoaded', () => {
const newSecretDisplay = document.getElementById('newSecretDisplay'); const newSecretDisplay = document.getElementById('newSecretDisplay');
const twofaError = document.getElementById('twofaError'); const twofaError = document.getElementById('twofaError');
const twofaSuccess = document.getElementById('twofaSuccess'); const twofaSuccess = document.getElementById('twofaSuccess');
const twofaStep1Text = document.getElementById('twofaStep1Text');
let pendingNewSecret = null; let pendingNewSecret = null;
let twoFaModalStep = 1; let twoFaModalStep = 1;
function accountHas2FA() {
return !window._accountData || window._accountData.has2FA !== false;
}
function setStepVisibility(input, visible) {
const step = input?.closest('.password-step, .email-step, .twofa-step');
if (step) step.style.display = visible ? '' : 'none';
}
function setStepNumber(input, number) {
const step = input?.closest('.password-step, .email-step, .twofa-step');
const badge = step?.querySelector('.password-step-num, .email-step-num, .twofa-step-num');
if (badge) badge.textContent = String(number);
}
function syncTwofaCard() {
const has2FA = accountHas2FA();
if (change2faBtn) {
change2faBtn.innerHTML = has2FA
? '<i class="fa-solid fa-rotate"></i> Change 2FA'
: '<i class="fa-solid fa-shield-halved"></i> Enable 2FA';
}
}
function configureTwofaModalSecurity() {
const has2FA = accountHas2FA();
const title = twofaModal?.querySelector('.twofa-modal-title');
const subtitle = twofaModal?.querySelector('.twofa-modal-subtitle');
if (title) title.textContent = has2FA ? 'Change 2FA Code' : 'Enable 2FA';
if (subtitle) subtitle.textContent = has2FA ? 'Update your authenticator app' : 'Add an authenticator app to this account';
if (twofaStep1Text) {
twofaStep1Text.textContent = has2FA ? 'Enter your current 2FA code' : 'Enter your current password';
}
if (currentCodeInput) {
currentCodeInput.type = has2FA ? 'text' : 'password';
currentCodeInput.placeholder = has2FA ? '000000' : 'Current password';
currentCodeInput.maxLength = has2FA ? 6 : 1024;
currentCodeInput.inputMode = has2FA ? 'numeric' : '';
currentCodeInput.autocomplete = has2FA ? 'one-time-code' : 'current-password';
currentCodeInput.classList.toggle('twofa-password-input', !has2FA);
}
const twofaForgotLink = document.getElementById('twofaForgotLink');
if (twofaForgotLink) twofaForgotLink.style.display = has2FA ? '' : 'none';
}
function configurePasswordModalSecurity() {
const has2FA = accountHas2FA();
const passwordCodeInput = document.getElementById('password2faInput');
const passwordNewInput = document.getElementById('newPasswordInput');
const passwordConfirmInput = document.getElementById('confirmPasswordInput');
setStepVisibility(passwordCodeInput, has2FA);
setStepNumber(passwordNewInput, has2FA ? 3 : 2);
setStepNumber(passwordConfirmInput, has2FA ? 4 : 3);
const passwordForgotLink = document.getElementById('passwordForgotLink');
if (passwordForgotLink) passwordForgotLink.style.display = has2FA ? '' : 'none';
}
function configureEmailModalSecurity() {
const has2FA = accountHas2FA();
const emailCodeInput = document.getElementById('email2faInput');
const emailNewInput = document.getElementById('newEmailInput');
setStepVisibility(emailCodeInput, has2FA);
setStepNumber(emailNewInput, has2FA ? 3 : 2);
const emailForgotLink = document.getElementById('emailForgotLink');
if (emailForgotLink) emailForgotLink.style.display = has2FA ? '' : 'none';
}
function syncAccountSecurityUi() {
syncTwofaCard();
configureTwofaModalSecurity();
configurePasswordModalSecurity();
configureEmailModalSecurity();
}
function resetTwofaModal() { function resetTwofaModal() {
twoFaModalStep = 1; twoFaModalStep = 1;
pendingNewSecret = null; pendingNewSecret = null;
@@ -854,7 +889,7 @@ window.addEventListener('DOMContentLoaded', () => {
if (twofaError) twofaError.classList.remove('show'); if (twofaError) twofaError.classList.remove('show');
if (twofaSuccess) twofaSuccess.classList.remove('show'); if (twofaSuccess) twofaSuccess.classList.remove('show');
if (twofaConfirmBtn) { if (twofaConfirmBtn) {
twofaConfirmBtn.textContent = 'Verify Current Code'; twofaConfirmBtn.textContent = accountHas2FA() ? 'Verify Current Code' : 'Verify Password';
twofaConfirmBtn.disabled = false; twofaConfirmBtn.disabled = false;
twofaConfirmBtn.style.display = ''; twofaConfirmBtn.style.display = '';
} }
@@ -862,8 +897,7 @@ window.addEventListener('DOMContentLoaded', () => {
const twofaStep1 = document.getElementById('twofaStep1'); const twofaStep1 = document.getElementById('twofaStep1');
if (twofaStep1) twofaStep1.style.display = ''; if (twofaStep1) twofaStep1.style.display = '';
const twofaForgotLink = document.getElementById('twofaForgotLink'); configureTwofaModalSecurity();
if (twofaForgotLink) twofaForgotLink.style.display = '';
const qrStepNum = qrCodeSection?.querySelector('.twofa-step-num'); const qrStepNum = qrCodeSection?.querySelector('.twofa-step-num');
const confirmStepNum = confirmSection?.querySelector('.twofa-step-num'); const confirmStepNum = confirmSection?.querySelector('.twofa-step-num');
@@ -903,11 +937,16 @@ window.addEventListener('DOMContentLoaded', () => {
hideTwofaError(); hideTwofaError();
if (twoFaModalStep === 1) { if (twoFaModalStep === 1) {
const currentCode = currentCodeInput?.value.trim() || ''; const has2FA = accountHas2FA();
if (!currentCode || currentCode.length !== 6 || !/^\d+$/.test(currentCode)) { const currentCredential = currentCodeInput?.value.trim() || '';
if (has2FA && (!currentCredential || currentCredential.length !== 6 || !/^\d+$/.test(currentCredential))) {
showTwofaError('Please enter a valid 6-digit code'); showTwofaError('Please enter a valid 6-digit code');
return; return;
} }
if (!has2FA && !currentCredential) {
showTwofaError('Please enter your current password');
return;
}
twofaConfirmBtn.disabled = true; twofaConfirmBtn.disabled = true;
twofaConfirmBtn.textContent = 'Verifying...'; twofaConfirmBtn.textContent = 'Verifying...';
@@ -917,7 +956,7 @@ window.addEventListener('DOMContentLoaded', () => {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
credentials: 'include', credentials: 'include',
body: JSON.stringify({ currentCode }) body: JSON.stringify(has2FA ? { currentCode: currentCredential } : { currentPassword: currentCredential })
}); });
const data = await res.json(); const data = await res.json();
@@ -934,7 +973,7 @@ window.addEventListener('DOMContentLoaded', () => {
twofaConfirmBtn.disabled = false; twofaConfirmBtn.disabled = false;
} catch (err) { } catch (err) {
showTwofaError(err.message); showTwofaError(err.message);
twofaConfirmBtn.textContent = 'Verify Current Code'; twofaConfirmBtn.textContent = accountHas2FA() ? 'Verify Current Code' : 'Verify Password';
twofaConfirmBtn.disabled = false; twofaConfirmBtn.disabled = false;
} }
} else if (twoFaModalStep === 2) { } else if (twoFaModalStep === 2) {
@@ -959,6 +998,8 @@ window.addEventListener('DOMContentLoaded', () => {
if (!res.ok) throw new Error(data.error || 'Failed to update 2FA'); if (!res.ok) throw new Error(data.error || 'Failed to update 2FA');
if (twofaSuccess) twofaSuccess.classList.add('show'); if (twofaSuccess) twofaSuccess.classList.add('show');
if (window._accountData) window._accountData.has2FA = true;
syncAccountSecurityUi();
twofaConfirmBtn.style.display = 'none'; twofaConfirmBtn.style.display = 'none';
if (twofaCancelBtn) twofaCancelBtn.textContent = 'Done'; if (twofaCancelBtn) twofaCancelBtn.textContent = 'Done';
@@ -974,10 +1015,13 @@ window.addEventListener('DOMContentLoaded', () => {
} }
}); });
[currentCodeInput, newCodeInput].forEach(input => { currentCodeInput?.addEventListener('input', (e) => {
input?.addEventListener('input', (e) => { if (accountHas2FA()) {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6); e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
}
}); });
newCodeInput?.addEventListener('input', (e) => {
e.target.value = e.target.value.replace(/\D/g, '').slice(0, 6);
}); });
const passwordModal = document.getElementById('passwordModal'); const passwordModal = document.getElementById('passwordModal');
@@ -1012,6 +1056,7 @@ window.addEventListener('DOMContentLoaded', () => {
passwordConfirmBtn.style.display = ''; passwordConfirmBtn.style.display = '';
} }
if (passwordCancelBtn) passwordCancelBtn.textContent = 'Cancel'; if (passwordCancelBtn) passwordCancelBtn.textContent = 'Cancel';
configurePasswordModalSecurity();
} }
function showPasswordError(msg) { function showPasswordError(msg) {
@@ -1053,7 +1098,7 @@ window.addEventListener('DOMContentLoaded', () => {
showPasswordError('Please enter your current password'); showPasswordError('Please enter your current password');
return; return;
} }
if (!code || code.length !== 6 || !/^\d+$/.test(code)) { if (accountHas2FA() && (!code || code.length !== 6 || !/^\d+$/.test(code))) {
showPasswordError('Please enter a valid 6-digit 2FA code'); showPasswordError('Please enter a valid 6-digit 2FA code');
return; return;
} }
@@ -1066,7 +1111,7 @@ window.addEventListener('DOMContentLoaded', () => {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
credentials: 'include', credentials: 'include',
body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: code }) body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: accountHas2FA() ? code : '' })
}); });
const data = await res.json(); const data = await res.json();
@@ -1105,7 +1150,7 @@ window.addEventListener('DOMContentLoaded', () => {
credentials: 'include', credentials: 'include',
body: JSON.stringify({ body: JSON.stringify({
currentPassword: currentPasswordInput?.value || '', currentPassword: currentPasswordInput?.value || '',
twoFactorCode: password2faInput?.value.trim() || '', twoFactorCode: accountHas2FA() ? (password2faInput?.value.trim() || '') : '',
newPassword: newPw newPassword: newPw
}) })
}); });
@@ -1180,6 +1225,7 @@ window.addEventListener('DOMContentLoaded', () => {
emailConfirmBtn.style.display = ''; emailConfirmBtn.style.display = '';
} }
if (emailCancelBtn) emailCancelBtn.textContent = 'Cancel'; if (emailCancelBtn) emailCancelBtn.textContent = 'Cancel';
configureEmailModalSecurity();
} }
function showEmailError(msg) { function showEmailError(msg) {
@@ -1221,7 +1267,7 @@ window.addEventListener('DOMContentLoaded', () => {
showEmailError('Please enter your password'); showEmailError('Please enter your password');
return; return;
} }
if (!code || code.length !== 6 || !/^\d+$/.test(code)) { if (accountHas2FA() && (!code || code.length !== 6 || !/^\d+$/.test(code))) {
showEmailError('Please enter a valid 6-digit 2FA code'); showEmailError('Please enter a valid 6-digit 2FA code');
return; return;
} }
@@ -1234,7 +1280,7 @@ window.addEventListener('DOMContentLoaded', () => {
method: 'POST', method: 'POST',
headers: { 'Content-Type': 'application/json' }, headers: { 'Content-Type': 'application/json' },
credentials: 'include', credentials: 'include',
body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: code }) body: JSON.stringify({ currentPassword: currentPw, twoFactorCode: accountHas2FA() ? code : '' })
}); });
const data = await res.json(); const data = await res.json();
@@ -1269,7 +1315,7 @@ window.addEventListener('DOMContentLoaded', () => {
credentials: 'include', credentials: 'include',
body: JSON.stringify({ body: JSON.stringify({
currentPassword: emailPasswordInput?.value || '', currentPassword: emailPasswordInput?.value || '',
twoFactorCode: email2faInput?.value.trim() || '', twoFactorCode: accountHas2FA() ? (email2faInput?.value.trim() || '') : '',
newEmail: newEmail newEmail: newEmail
}) })
}); });
@@ -1562,6 +1608,8 @@ window.addEventListener('DOMContentLoaded', () => {
const nodeRamLimitEl = document.getElementById('nodeRamLimit'); const nodeRamLimitEl = document.getElementById('nodeRamLimit');
const nodeCpuLimitEl = document.getElementById('nodeCpuLimit'); const nodeCpuLimitEl = document.getElementById('nodeCpuLimit');
const nodeStorageLimitEl = document.getElementById('nodeStorageLimit'); const nodeStorageLimitEl = document.getElementById('nodeStorageLimit');
const resourceDiskEl = document.getElementById('resourceDisk');
const resourceDiskHintEl = document.getElementById('resourceDiskHint');
const liveNodeCapacityCache = new Map(); const liveNodeCapacityCache = new Map();
const RESOURCE_NETWORK_LIMIT_MAX_MB = 1073741824; const RESOURCE_NETWORK_LIMIT_MAX_MB = 1073741824;
const RESOURCE_NETWORK_RESET_MAX_MINUTES = 43200; const RESOURCE_NETWORK_RESET_MAX_MINUTES = 43200;
@@ -1650,6 +1698,52 @@ window.addEventListener('DOMContentLoaded', () => {
return resolveEffectiveNodeCapacity(node, liveCapacity); return resolveEffectiveNodeCapacity(node, liveCapacity);
} }
function formatDiskOptionUsage(disk) {
const used = Number(disk?.usedGb || 0);
const limit = Number(disk?.limitGb || 0);
const usedStr = (used >= 10 ? used.toFixed(0) : used.toFixed(1)).replace(/\.0$/, '');
return limit > 0 ? `${usedStr}/${limit} GB` : `${usedStr} GB used`;
}
async function populateNodeDiskOptions(node) {
if (!resourceDiskEl) return;
const primaryOpt = '<option value="primary">Primary (/var/lib/node)</option>';
resourceDiskEl.innerHTML = primaryOpt;
resourceDiskEl.value = 'primary';
if (resourceDiskHintEl) resourceDiskHintEl.textContent = 'Server files are stored on the selected disk.';
const id = node && (node.id || node.uuid || node.name);
if (!id) return;
try {
const res = await fetch(`/api/nodes/${encodeURIComponent(id)}/disks`, { cache: 'no-store' });
const data = await res.json().catch(() => ({}));
if (!res.ok || !Array.isArray(data.disks)) return;
// Keep the modal in sync only if the same node is still selected.
const current = getSelectedNode();
if (!current || resolveNodeCacheKey(current) !== resolveNodeCacheKey(node)) return;
const options = [];
const additional = [];
for (const d of data.disks) {
const isPrimary = !!d.primary || String(d.id) === 'primary';
if (isPrimary) continue;
additional.push(d);
}
options.push(primaryOpt);
for (const d of additional) {
const label = `${d.mountPath} (${formatDiskOptionUsage(d)})`;
options.push(`<option value="${escapeHtml(String(d.id))}">${escapeHtml(label)}</option>`);
}
resourceDiskEl.innerHTML = options.join('');
resourceDiskEl.value = 'primary';
if (resourceDiskHintEl) {
resourceDiskHintEl.textContent = additional.length
? 'Primary is used by default. Select an additional disk to place this server elsewhere.'
: 'This node has only the primary disk available.';
}
} catch {
// Leave the primary-only default in place on failure.
}
}
if (resourceStorageEl) { if (resourceStorageEl) {
resourceStorageEl.addEventListener('input', () => { resourceStorageEl.addEventListener('input', () => {
const hint = resourceStorageEl.closest('.enterprise-field')?.querySelector('.enterprise-hint'); const hint = resourceStorageEl.closest('.enterprise-field')?.querySelector('.enterprise-hint');
@@ -1711,7 +1805,7 @@ window.addEventListener('DOMContentLoaded', () => {
let nodes = []; let nodes = [];
let selectedTemplateId = null; let selectedTemplateId = null;
let selectedForkId = null; let selectedForkId = null;
let selectedNodeId = "local"; let selectedNodeId = "";
let portBackTarget = "create"; let portBackTarget = "create";
let selectedStartupCommand = ""; let selectedStartupCommand = "";
let selectedStartupCommandMode = ""; let selectedStartupCommandMode = "";
@@ -1750,6 +1844,13 @@ window.addEventListener('DOMContentLoaded', () => {
function getDefaultPortForTemplate(templateId) { function getDefaultPortForTemplate(templateId) {
const id = (templateId || '').toString().toLowerCase(); const id = (templateId || '').toString().toLowerCase();
if (!id) return 25565; if (!id) return 25565;
const configuredTemplate = (templates || []).find(t => String(t?.id || '').trim().toLowerCase() === id);
const configuredPort = parseStrictPortValue(
configuredTemplate?.defaultPort ||
configuredTemplate?.default_port ||
configuredTemplate?.docker?.ports?.[0]
);
if (configuredPort) return configuredPort;
if (id.includes('minecraft') || id === 'mc') return 25565; if (id.includes('minecraft') || id === 'mc') return 25565;
if (id.includes('node') || id.includes('discord')) return 3000; if (id.includes('node') || id.includes('discord')) return 3000;
if (id.includes('http') || id.includes('web') || id.includes('proxy')) return 80; if (id.includes('http') || id.includes('web') || id.includes('proxy')) return 80;
@@ -1774,7 +1875,7 @@ window.addEventListener('DOMContentLoaded', () => {
} }
function getSelectedNode() { function getSelectedNode() {
if (!selectedNodeId || selectedNodeId === 'local') return null; if (!selectedNodeId) return null;
return (nodes || []).find(x => return (nodes || []).find(x =>
(x.uuid === selectedNodeId) || (x.uuid === selectedNodeId) ||
(x.id === selectedNodeId) || (x.id === selectedNodeId) ||
@@ -2034,11 +2135,16 @@ window.addEventListener('DOMContentLoaded', () => {
function startupCommandSourceLabel(source, imageRef) { function startupCommandSourceLabel(source, imageRef) {
const normalized = String(source || '').trim().toLowerCase(); const normalized = String(source || '').trim().toLowerCase();
if (normalized === 'adpanel-startup') return 'Using ADPanel STARTUP from this template. Edit it in the template settings.'; if (normalized === 'adpanel-startup') return 'Using the startup command defined by this template.';
if (normalized === 'image-default') {
return imageRef
? `Using Docker image default ENTRYPOINT/CMD (${imageRef}); ADPanel will not override it.`
: 'Using Docker image default ENTRYPOINT/CMD; ADPanel will not override it.';
}
if (normalized === 'image-inspect') { if (normalized === 'image-inspect') {
return imageRef return imageRef
? `Detected from Docker image inspect (${imageRef}).` ? `Detected from Docker image inspect (${imageRef}); ADPanel will use the image default.`
: 'Detected from Docker image inspect.'; : 'Detected from Docker image inspect; ADPanel will use the image default.';
} }
if (normalized === 'template-command') return 'Using process command defined by this template.'; if (normalized === 'template-command') return 'Using process command defined by this template.';
if (normalized === 'template-default') return 'Using template default process command.'; if (normalized === 'template-default') return 'Using template default process command.';
@@ -2200,7 +2306,7 @@ window.addEventListener('DOMContentLoaded', () => {
async function resolveStartupCommandForSelection(options = {}) { async function resolveStartupCommandForSelection(options = {}) {
const templateId = String(options.templateId ?? selectedTemplateId ?? '').trim(); const templateId = String(options.templateId ?? selectedTemplateId ?? '').trim();
const nodeId = String(options.nodeId ?? selectedNodeId ?? 'local').trim() || 'local'; const nodeId = String(options.nodeId ?? selectedNodeId ?? 'none').trim() || 'none';
const forceRefresh = !!options.forceRefresh; const forceRefresh = !!options.forceRefresh;
const showLoading = !!options.showLoading; const showLoading = !!options.showLoading;
setStartupCommandValidationError(''); setStartupCommandValidationError('');
@@ -2222,6 +2328,15 @@ window.addEventListener('DOMContentLoaded', () => {
template?.docker?.pterodactyl_startup || template?.docker?.pterodactyl_startup ||
'' ''
).trim(); ).trim();
const templateStartupDisplay = String(
template?.docker?.startupDisplay ||
template?.docker?.startup_display ||
template?.docker?.startupPreview ||
template?.docker?.startup_preview ||
template?.docker?.imageDefaultStartup ||
template?.docker?.image_default_startup ||
''
).trim();
if (startupCommandEl) startupCommandEl.readOnly = false; if (startupCommandEl) startupCommandEl.readOnly = false;
if (templateADPanelStartup) { if (templateADPanelStartup) {
selectedStartupCommand = templateADPanelStartup; selectedStartupCommand = templateADPanelStartup;
@@ -2231,7 +2346,21 @@ window.addEventListener('DOMContentLoaded', () => {
startupCommandEl.readOnly = true; startupCommandEl.readOnly = true;
} }
setStartupCommandValidationError(''); setStartupCommandValidationError('');
setStartupCommandSource('Using ADPanel STARTUP from this template. Edit it in template settings if needed.'); setStartupCommandSource('Using the startup command defined by this template.');
setStartupCommandLoading(false);
return selectedStartupCommand;
}
if (templateStartupDisplay) {
selectedStartupCommand = templateStartupDisplay;
selectedStartupCommandMode = 'image-default';
if (startupCommandEl && startupModal?.classList.contains('show')) {
startupCommandEl.value = selectedStartupCommand;
startupCommandEl.readOnly = true;
}
setStartupCommandValidationError('');
setStartupCommandSource(startupCommandSourceLabel('image-default', template?.docker?.image && template?.docker?.tag
? `${template.docker.image}:${template.docker.tag}`
: ''));
setStartupCommandLoading(false); setStartupCommandLoading(false);
return selectedStartupCommand; return selectedStartupCommand;
} }
@@ -2275,23 +2404,34 @@ window.addEventListener('DOMContentLoaded', () => {
if (detected?.ok) { if (detected?.ok) {
const data = detected.data || {}; const data = detected.data || {};
const sourceMode = String(data.source || '').trim().toLowerCase();
const usesDockerImageDefault = sourceMode === 'image-default' || sourceMode === 'image-inspect';
let detectedCommand = String(data.command || '').trim(); let detectedCommand = String(data.command || '').trim();
if (!detectedCommand && data.inspect) { if (!detectedCommand && data.inspect) {
detectedCommand = inferStartupFromInspectMeta(template, data.inspect, fallbackCommand, { allowUnsafe: false }); detectedCommand = inferStartupFromInspectMeta(template, data.inspect, fallbackCommand, { allowUnsafe: false });
} }
const detectedError = validateRuntimeProcessCommandInput(detectedCommand); if (!detectedCommand && usesDockerImageDefault && data.inspect) {
if (detectedCommand && !detectedError) { const entrypoint = Array.isArray(data.inspect.entrypoint)
const activeNodeId = String(selectedNodeId ?? 'local').trim() || 'local'; ? data.inspect.entrypoint.map((item) => String(item || '').trim()).filter(Boolean)
: [];
const cmd = Array.isArray(data.inspect.cmd)
? data.inspect.cmd.map((item) => String(item || '').trim()).filter(Boolean)
: [];
detectedCommand = joinStartupArgs([...entrypoint, ...cmd]);
}
const detectedError = usesDockerImageDefault ? null : validateRuntimeProcessCommandInput(detectedCommand);
if (detectedCommand && (!detectedError || usesDockerImageDefault)) {
const activeNodeId = String(selectedNodeId ?? 'none').trim() || 'none';
if (String(selectedTemplateId || '').trim() !== templateId || activeNodeId !== nodeId) { if (String(selectedTemplateId || '').trim() !== templateId || activeNodeId !== nodeId) {
return selectedStartupCommand; return selectedStartupCommand;
} }
selectedStartupCommand = detectedCommand; selectedStartupCommand = detectedCommand;
selectedStartupCommandMode = String(data.source || '').trim().toLowerCase() === 'adpanel-startup' selectedStartupCommandMode = sourceMode === 'adpanel-startup'
? 'adpanel-startup' ? 'adpanel-startup'
: ''; : (usesDockerImageDefault ? 'image-default' : '');
if (startupCommandEl && startupModal?.classList.contains('show')) { if (startupCommandEl && startupModal?.classList.contains('show')) {
startupCommandEl.value = selectedStartupCommand; startupCommandEl.value = selectedStartupCommand;
startupCommandEl.readOnly = selectedStartupCommandMode === 'adpanel-startup'; startupCommandEl.readOnly = selectedStartupCommandMode === 'adpanel-startup' || selectedStartupCommandMode === 'image-default';
} }
setStartupCommandSource(startupCommandSourceLabel(data.source, data.imageRef)); setStartupCommandSource(startupCommandSourceLabel(data.source, data.imageRef));
return selectedStartupCommand; return selectedStartupCommand;
@@ -2313,12 +2453,17 @@ window.addEventListener('DOMContentLoaded', () => {
} }
function openCreate() { function openCreate() {
if (!createModal) {
window.location.href = '/status';
return;
}
document.body.classList.add('modal-open');
createModal.classList.add('show'); createModal.classList.add('show');
createModal.setAttribute('aria-hidden', 'false'); createModal.setAttribute('aria-hidden', 'false');
selectedTemplateId = null; selectedTemplateId = null;
selectedForkId = null; selectedForkId = null;
selectedNodeId = 'local'; selectedNodeId = '';
portBackTarget = 'create'; portBackTarget = 'create';
selectedStartupCommand = ''; selectedStartupCommand = '';
selectedImportUrl = ''; selectedImportUrl = '';
@@ -2331,7 +2476,7 @@ window.addEventListener('DOMContentLoaded', () => {
if (summaryNameEl) summaryNameEl.textContent = '—'; if (summaryNameEl) summaryNameEl.textContent = '—';
if (summaryTemplateEl) summaryTemplateEl.textContent = '—'; if (summaryTemplateEl) summaryTemplateEl.textContent = '—';
if (summaryNodeEl) summaryNodeEl.textContent = 'Local node'; if (summaryNodeEl) summaryNodeEl.textContent = '—';
if (templateInfo2) templateInfo2.textContent = ''; if (templateInfo2) templateInfo2.textContent = '';
setStartupCommandSource('Using startup command from template.'); setStartupCommandSource('Using startup command from template.');
@@ -2340,6 +2485,8 @@ window.addEventListener('DOMContentLoaded', () => {
} }
function closeCreate() { function closeCreate() {
if (!createModal) return;
document.body.classList.remove('modal-open');
createModal.classList.remove('show'); createModal.classList.remove('show');
createModal.setAttribute('aria-hidden', 'true'); createModal.setAttribute('aria-hidden', 'true');
} }
@@ -2356,6 +2503,19 @@ window.addEventListener('DOMContentLoaded', () => {
}; };
createBtns.forEach(btn => btn.addEventListener('click', openCreate)); createBtns.forEach(btn => btn.addEventListener('click', openCreate));
// Navbar Create pill: expand to a pill on hover/focus, collapse back to a
// circle on leave. Driven by JS so the collapse animation always plays.
const navCreateBtn = document.getElementById('createBtn');
if (navCreateBtn) {
const openPill = () => navCreateBtn.classList.add('is-open');
const closePill = () => navCreateBtn.classList.remove('is-open');
navCreateBtn.addEventListener('mouseenter', openPill);
navCreateBtn.addEventListener('mouseleave', closePill);
navCreateBtn.addEventListener('focus', openPill);
navCreateBtn.addEventListener('blur', closePill);
}
createClose?.addEventListener('click', closeCreate); createClose?.addEventListener('click', closeCreate);
createCancel?.addEventListener('click', closeCreate); createCancel?.addEventListener('click', closeCreate);
document.addEventListener('keydown', (e) => { document.addEventListener('keydown', (e) => {
@@ -2449,16 +2609,19 @@ window.addEventListener('DOMContentLoaded', () => {
if (!nodes.length) { if (!nodes.length) {
const empty = document.createElement('div'); const empty = document.createElement('div');
empty.className = 'enterprise-hint'; empty.className = 'enterprise-hint';
empty.textContent = 'No remote nodes configured. Using local node.'; empty.textContent = 'No nodes configured. Add a node in Settings before creating a server.';
nodeGrid.appendChild(empty); nodeGrid.appendChild(empty);
if (summaryNodeEl) summaryNodeEl.textContent = 'Local node'; selectedNodeId = '';
if (summaryNodeEl) summaryNodeEl.textContent = 'No node available';
if (createConfirm) createConfirm.disabled = true;
return; return;
} }
const autoNode = nodes.find(n => n && n.online) || nodes[0]; const autoNode = nodes.find(n => n && n.online) || nodes[0];
if ((!selectedNodeId || selectedNodeId === 'local') && autoNode) { if (!selectedNodeId && autoNode) {
selectedNodeId = autoNode.uuid || autoNode.id || autoNode.name || selectedNodeId; selectedNodeId = autoNode.uuid || autoNode.id || autoNode.name || selectedNodeId;
} }
if (createConfirm) createConfirm.disabled = false;
nodes.forEach(n => { nodes.forEach(n => {
const online = !!n.online; const online = !!n.online;
@@ -2502,6 +2665,7 @@ window.addEventListener('DOMContentLoaded', () => {
} }
function openForkModal() { function openForkModal() {
document.body.classList.add('modal-open');
if (!forkModal) return; if (!forkModal) return;
if (forkGrid) forkGrid.innerHTML = ''; if (forkGrid) forkGrid.innerHTML = '';
selectedForkId = null; selectedForkId = null;
@@ -2538,6 +2702,7 @@ window.addEventListener('DOMContentLoaded', () => {
} }
function closeForkModal() { function closeForkModal() {
document.body.classList.remove('modal-open');
forkModal.classList.remove('show'); forkModal.classList.remove('show');
forkModal.setAttribute('aria-hidden', 'true'); forkModal.setAttribute('aria-hidden', 'true');
} }
@@ -2554,18 +2719,18 @@ window.addEventListener('DOMContentLoaded', () => {
function openPortModal(backFrom) { function openPortModal(backFrom) {
portBackTarget = backFrom || 'create'; portBackTarget = backFrom || 'create';
const selectedNode = getSelectedNode();
if (!selectedNode) {
alert('Please choose a node before configuring ports.');
return;
}
document.body.classList.add('modal-open');
if (serverPortEl) { if (serverPortEl) {
let defPort = getDefaultPortForTemplate(selectedTemplateId); let defPort = getDefaultPortForTemplate(selectedTemplateId);
if (selectedNodeId && selectedNodeId !== 'local') { if (selectedNode.ports) {
const node = (nodes || []).find(x => const alloc = selectedNode.ports;
(x.uuid === selectedNodeId) ||
(x.id === selectedNodeId) ||
(x.name === selectedNodeId)
);
if (node && node.ports) {
const alloc = node.ports;
let inRange = true; let inRange = true;
let firstPort = defPort; let firstPort = defPort;
if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) {
@@ -2577,7 +2742,6 @@ window.addEventListener('DOMContentLoaded', () => {
} }
if (!inRange) defPort = firstPort; if (!inRange) defPort = firstPort;
} }
}
serverPortEl.value = String(defPort); serverPortEl.value = String(defPort);
if (portDefaultValueEl) portDefaultValueEl.textContent = String(defPort); if (portDefaultValueEl) portDefaultValueEl.textContent = String(defPort);
@@ -2588,22 +2752,6 @@ window.addEventListener('DOMContentLoaded', () => {
serverIpEl.textContent = 'detecting…'; serverIpEl.textContent = 'detecting…';
} }
const ipv4Re = /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/;
function extractIP(s) {
if (!s) return null;
const str = String(s).trim();
const m = str.match(ipv4Re);
if (m) return m[0];
if (str.includes(':')) return str.replace(/^\[|\]$/g, '');
return null;
}
function pickIpFromJSON(j) {
return extractIP(j?.publicIp) ||
extractIP(j?.ip) ||
extractIP(j?.address) ||
extractIP(j?.host) ||
extractIP(j?.hostname);
}
function setIp(ip) { function setIp(ip) {
if (serverIpEl) serverIpEl.textContent = ip || 'unknown'; if (serverIpEl) serverIpEl.textContent = ip || 'unknown';
} }
@@ -2613,26 +2761,14 @@ window.addEventListener('DOMContentLoaded', () => {
if (portTitleTextEl) portTitleTextEl.textContent = 'Expose public port'; if (portTitleTextEl) portTitleTextEl.textContent = 'Expose public port';
if (portSubtitleEl) portSubtitleEl.textContent = `Choose the public port for ${templateLabel}.`; if (portSubtitleEl) portSubtitleEl.textContent = `Choose the public port for ${templateLabel}.`;
if (selectedNodeId && selectedNodeId !== 'local') { setIp(selectedNode.address || selectedNode.host || selectedNode.hostname);
const node = (nodes || []).find(x =>
(x.uuid === selectedNodeId) ||
(x.id === selectedNodeId) ||
(x.name === selectedNodeId)
);
const ip = node && (node.address || node.host || node.hostname);
setIp(ip);
} else {
fetch('/api/server-info')
.then(r => r.ok ? r.json() : Promise.reject())
.then(j => setIp(pickIpFromJSON(j)))
.catch(() => setIp(null));
}
portModal.classList.add('show'); portModal.classList.add('show');
portModal.setAttribute('aria-hidden', 'false'); portModal.setAttribute('aria-hidden', 'false');
} }
function closePortModal() { function closePortModal() {
document.body.classList.remove('modal-open');
portModal.classList.remove('show'); portModal.classList.remove('show');
portModal.setAttribute('aria-hidden', 'true'); portModal.setAttribute('aria-hidden', 'true');
} }
@@ -2684,21 +2820,20 @@ window.addEventListener('DOMContentLoaded', () => {
return; return;
} }
if (selectedNodeId !== 'local') { if (!nodes.length) {
const node = (nodes || []).find(x => alert('No nodes are configured. Add a node in Settings before creating a server.');
(x.uuid === selectedNodeId) || return;
(x.id === selectedNodeId) || }
(x.name === selectedNodeId)
); const node = getSelectedNode();
if (!node) { if (!node) {
alert('The chosen node no longer exists.'); alert('Please choose a node.');
return; return;
} }
if (!node.online) { if (!node.online) {
alert('The chosen node is offline.'); alert('The chosen node is offline.');
return; return;
} }
}
if (selectedTemplateId === 'minecraft') { if (selectedTemplateId === 'minecraft') {
closeCreate(); closeCreate();
@@ -2726,14 +2861,13 @@ window.addEventListener('DOMContentLoaded', () => {
return; return;
} }
if (selectedNodeId && selectedNodeId !== 'local') { const selectedNode = getSelectedNode();
const node = (nodes || []).find(x => if (!selectedNode) {
(x.uuid === selectedNodeId) || alert('Please choose a node.');
(x.id === selectedNodeId) || return;
(x.name === selectedNodeId) }
); if (selectedNode.ports) {
if (node && node.ports) { const alloc = selectedNode.ports;
const alloc = node.ports;
let allowed = true; let allowed = true;
if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) {
allowed = portVal >= alloc.start && portVal < alloc.start + alloc.count; allowed = portVal >= alloc.start && portVal < alloc.start + alloc.count;
@@ -2748,7 +2882,6 @@ window.addEventListener('DOMContentLoaded', () => {
return; return;
} }
} }
}
try { try {
if (portSpinner) portSpinner.classList.add('visible'); if (portSpinner) portSpinner.classList.add('visible');
@@ -2764,6 +2897,7 @@ window.addEventListener('DOMContentLoaded', () => {
}); });
async function openStartupModal() { async function openStartupModal() {
document.body.classList.add('modal-open');
if (!startupModal) return; if (!startupModal) return;
startupModal.classList.add('show'); startupModal.classList.add('show');
@@ -2778,6 +2912,7 @@ window.addEventListener('DOMContentLoaded', () => {
} }
function closeStartupModal() { function closeStartupModal() {
document.body.classList.remove('modal-open');
if (!startupModal) return; if (!startupModal) return;
startupModal.classList.remove('show'); startupModal.classList.remove('show');
startupModal.setAttribute('aria-hidden', 'true'); startupModal.setAttribute('aria-hidden', 'true');
@@ -2809,6 +2944,12 @@ window.addEventListener('DOMContentLoaded', () => {
openImportModal(); openImportModal();
return; return;
} }
if (selectedStartupCommandMode === 'image-default') {
setStartupCommandValidationError('');
closeStartupModal();
openImportModal();
return;
}
selectedStartupCommandMode = ''; selectedStartupCommandMode = '';
const startupCommandError = validateRuntimeProcessCommandInput(selectedStartupCommand); const startupCommandError = validateRuntimeProcessCommandInput(selectedStartupCommand);
if (startupCommandError && selectedStartupCommand) { if (startupCommandError && selectedStartupCommand) {
@@ -2853,6 +2994,7 @@ window.addEventListener('DOMContentLoaded', () => {
} }
function openImportModal() { function openImportModal() {
document.body.classList.add('modal-open');
if (!importModal) { if (!importModal) {
openResourcesModal(); openResourcesModal();
return; return;
@@ -2876,6 +3018,7 @@ window.addEventListener('DOMContentLoaded', () => {
} }
function closeImportModal() { function closeImportModal() {
document.body.classList.remove('modal-open');
if (!importModal) return; if (!importModal) return;
importModal.classList.remove('show'); importModal.classList.remove('show');
importModal.setAttribute('aria-hidden', 'true'); importModal.setAttribute('aria-hidden', 'true');
@@ -2932,6 +3075,13 @@ window.addEventListener('DOMContentLoaded', () => {
}); });
function openResourcesModal() { function openResourcesModal() {
const node = getSelectedNode();
if (!node) {
alert('Please choose a node.');
return;
}
document.body.classList.add('modal-open');
if (resourceRamEl) resourceRamEl.value = ''; if (resourceRamEl) resourceRamEl.value = '';
if (resourceCpuCoresEl) resourceCpuCoresEl.value = ''; if (resourceCpuCoresEl) resourceCpuCoresEl.value = '';
if (resourceSwapEl) resourceSwapEl.value = ''; if (resourceSwapEl) resourceSwapEl.value = '';
@@ -2946,35 +3096,23 @@ window.addEventListener('DOMContentLoaded', () => {
if (resourceNetworkOutboundLimitEl) resourceNetworkOutboundLimitEl.value = ''; if (resourceNetworkOutboundLimitEl) resourceNetworkOutboundLimitEl.value = '';
if (resourceNetworkResetMinutesEl) resourceNetworkResetMinutesEl.value = ''; if (resourceNetworkResetMinutesEl) resourceNetworkResetMinutesEl.value = '';
const node = (nodes || []).find(x =>
(x.uuid === selectedNodeId) ||
(x.id === selectedNodeId) ||
(x.name === selectedNodeId)
);
if (node) {
const cacheKey = resolveNodeCacheKey(node); const cacheKey = resolveNodeCacheKey(node);
applyNodeCapacityToResourceModal(resolveEffectiveNodeCapacity(node, null)); applyNodeCapacityToResourceModal(resolveEffectiveNodeCapacity(node, null));
populateNodeDiskOptions(node);
fetchLiveNodeCapacity(node).then((liveCapacity) => { fetchLiveNodeCapacity(node).then((liveCapacity) => {
if (!liveCapacity) return; if (!liveCapacity) return;
if (!resourcesModal?.classList.contains('show')) return; if (!resourcesModal?.classList.contains('show')) return;
const selectedNode = (nodes || []).find(x => const selectedNode = getSelectedNode();
(x.uuid === selectedNodeId) ||
(x.id === selectedNodeId) ||
(x.name === selectedNodeId)
);
if (!selectedNode || resolveNodeCacheKey(selectedNode) !== cacheKey) return; if (!selectedNode || resolveNodeCacheKey(selectedNode) !== cacheKey) return;
applyNodeCapacityToResourceModal(resolveEffectiveNodeCapacity(selectedNode, liveCapacity)); applyNodeCapacityToResourceModal(resolveEffectiveNodeCapacity(selectedNode, liveCapacity));
}); });
} else {
applyNodeCapacityToResourceModal({ ramMb: 0, cpuCores: 0, diskGb: 0 });
}
resourcesModal.classList.add('show'); resourcesModal.classList.add('show');
resourcesModal.setAttribute('aria-hidden', 'false'); resourcesModal.setAttribute('aria-hidden', 'false');
} }
function closeResourcesModal() { function closeResourcesModal() {
document.body.classList.remove('modal-open');
resourcesModal.classList.remove('show'); resourcesModal.classList.remove('show');
resourcesModal.setAttribute('aria-hidden', 'true'); resourcesModal.setAttribute('aria-hidden', 'true');
} }
@@ -3004,14 +3142,9 @@ window.addEventListener('DOMContentLoaded', () => {
return; return;
} }
if (selectedNodeId !== 'local') { const node = getSelectedNode();
const node = (nodes || []).find(x =>
(x.uuid === selectedNodeId) ||
(x.id === selectedNodeId) ||
(x.name === selectedNodeId)
);
if (!node) { if (!node) {
alert('The chosen node no longer exists.'); alert('Please choose a node.');
return; return;
} }
if (!node.online) { if (!node.online) {
@@ -3040,7 +3173,6 @@ window.addEventListener('DOMContentLoaded', () => {
alert(`Storage limit cannot exceed node maximum (${diskMb2.toLocaleString()} MB).`); alert(`Storage limit cannot exceed node maximum (${diskMb2.toLocaleString()} MB).`);
return; return;
} }
}
const portVal = parseStrictPortValue(serverPortEl?.value); const portVal = parseStrictPortValue(serverPortEl?.value);
if (!portVal) { if (!portVal) {
@@ -3048,13 +3180,7 @@ window.addEventListener('DOMContentLoaded', () => {
return; return;
} }
if (selectedNodeId && selectedNodeId !== 'local') { if (node.ports) {
const node = (nodes || []).find(x =>
(x.uuid === selectedNodeId) ||
(x.id === selectedNodeId) ||
(x.name === selectedNodeId)
);
if (node && node.ports) {
const alloc = node.ports; const alloc = node.ports;
let allowed = true; let allowed = true;
if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) { if (alloc.mode === 'range' && alloc.start > 0 && alloc.count > 0) {
@@ -3070,7 +3196,6 @@ window.addEventListener('DOMContentLoaded', () => {
return; return;
} }
} }
}
if (!(await verifySelectedNodePortAvailable(portVal))) { if (!(await verifySelectedNodePortAvailable(portVal))) {
return; return;
@@ -3088,7 +3213,11 @@ window.addEventListener('DOMContentLoaded', () => {
nodeId: selectedNodeId, nodeId: selectedNodeId,
hostPort: portVal hostPort: portVal
}; };
if (selectedStartupCommand && selectedStartupCommandMode !== 'adpanel-startup') { const selectedDiskId = resourceDiskEl ? String(resourceDiskEl.value || '').trim() : '';
if (selectedDiskId && selectedDiskId !== 'primary') {
payload.diskId = selectedDiskId;
}
if (selectedStartupCommand && selectedStartupCommandMode !== 'adpanel-startup' && selectedStartupCommandMode !== 'image-default') {
const payloadCommandError = validateRuntimeProcessCommandInput(selectedStartupCommand); const payloadCommandError = validateRuntimeProcessCommandInput(selectedStartupCommand);
if (!payloadCommandError) { if (!payloadCommandError) {
payload.command = selectedStartupCommand; payload.command = selectedStartupCommand;
+9 -1
View File
@@ -94,9 +94,17 @@
} else { } else {
usedGb = data.disk / 1024; limitGb = 0; pct = 0; usedGb = data.disk / 1024; limitGb = 0; pct = 0;
} }
resDiskLabel.textContent = limitGb > 0 // adpanel:backup-storage - combined storage (server files + backups);
// show the breakdown when backups occupy part of the quota.
const serverMb = (typeof data.disk === 'object') ? data.disk.serverMb : null;
const backupsMb = (typeof data.disk === 'object') ? data.disk.backupsMb : null;
let diskText = limitGb > 0
? `${formatBytes(usedGb * 1073741824)} / ${formatBytes(limitGb * 1073741824)} (${Math.round(pct)}%)` ? `${formatBytes(usedGb * 1073741824)} / ${formatBytes(limitGb * 1073741824)} (${Math.round(pct)}%)`
: `${formatBytes(usedGb * 1073741824)} / Unlimited`; : `${formatBytes(usedGb * 1073741824)} / Unlimited`;
if (Number.isFinite(backupsMb) && backupsMb > 0 && Number.isFinite(serverMb)) {
diskText += ` — files ${formatBytes(serverMb * 1048576)} + backups ${formatBytes(backupsMb * 1048576)}`;
}
resDiskLabel.textContent = diskText;
resDiskBar.style.width = `${pct}%`; resDiskBar.style.width = `${pct}%`;
} else { } else {
resDiskLabel.textContent = '—'; resDiskLabel.textContent = '—';
+2906 -502
View File
File diff suppressed because it is too large. Load diff
+632
View File
@@ -0,0 +1,632 @@
(function () {
"use strict";
const STORAGE_KEY = "adpanel:ssh-terminal-window:v1";
const DEFAULT_WIDTH = 960;
const DEFAULT_HEIGHT = 640;
const MIN_WIDTH = 360;
const MIN_HEIGHT = 260;
const MINIMIZED_WIDTH = 380;
const MINIMIZED_HEIGHT = 38;
const MODAL_SELECTOR = [
".modal-overlay",
".activity-modal",
".info-modal",
".scheduler-modal",
".planner-modal",
".ai-help-modal",
".clear-console-modal",
".notfound-modal",
".activity-modal-overlay",
].join(",");
const MOTION_QUERY = window.matchMedia
? window.matchMedia("(prefers-reduced-motion: reduce), (update: slow)")
: { matches: false };
let win = null;
let frame = null;
let launcher = null;
let interaction = null;
let raf = 0;
let opening = null;
let motionId = 0;
let modalObserver = null;
let launcherVisibilityRaf = 0;
let geometry = { x: 24, y: 24, w: DEFAULT_WIDTH, h: DEFAULT_HEIGHT };
function readState() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return {};
const data = JSON.parse(raw);
return data && typeof data === "object" ? data : {};
} catch {
return {};
}
}
function writeState(patch) {
try {
const next = Object.assign({}, readState(), patch, { updatedAt: Date.now() });
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch { }
}
function viewport() {
return {
w: Math.max(320, window.innerWidth || document.documentElement.clientWidth || 1280),
h: Math.max(240, window.innerHeight || document.documentElement.clientHeight || 720),
};
}
function clampSize(w, h) {
const vp = viewport();
return {
w: Math.max(Math.min(MIN_WIDTH, vp.w - 16), Math.min(Number.isFinite(w) ? w : DEFAULT_WIDTH, vp.w - 16)),
h: Math.max(Math.min(MIN_HEIGHT, vp.h - 16), Math.min(Number.isFinite(h) ? h : DEFAULT_HEIGHT, vp.h - 16)),
};
}
function clampGeometry(x, y, w, h, minimized) {
const vp = viewport();
const size = clampSize(w, h);
const viewW = minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : size.w;
const viewH = minimized ? Math.min(MINIMIZED_HEIGHT, vp.h - 16) : size.h;
return {
x: Math.max(8, Math.min(Number.isFinite(x) ? x : 24, Math.max(8, vp.w - viewW - 8))),
y: Math.max(8, Math.min(Number.isFinite(y) ? y : 24, Math.max(8, vp.h - viewH - 8))),
w: size.w,
h: size.h,
};
}
function getGeometryForState(state) {
const minimized = !!state.minimized;
const size = clampSize(Number(state.w), Number(state.h));
if (Number.isFinite(state.x) && Number.isFinite(state.y)) {
return clampGeometry(Number(state.x), Number(state.y), size.w, size.h, minimized);
}
const vp = viewport();
const viewW = minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : size.w;
const viewH = minimized ? MINIMIZED_HEIGHT : size.h;
return clampGeometry(Math.round((vp.w - viewW) / 2), Math.round((vp.h - viewH) / 2), size.w, size.h, minimized);
}
function applyGeometry(next) {
if (!win) return;
geometry = {
x: Math.round(next.x),
y: Math.round(next.y),
w: Math.round(next.w),
h: Math.round(next.h),
};
win.style.setProperty("--adp-ssh-x", `${geometry.x}px`);
win.style.setProperty("--adp-ssh-y", `${geometry.y}px`);
win.style.setProperty("--adp-ssh-w", `${geometry.w}px`);
win.style.setProperty("--adp-ssh-h", `${geometry.h}px`);
}
function writeWindowState(patch) {
writeState(Object.assign({
x: geometry.x,
y: geometry.y,
w: geometry.w,
h: geometry.h,
}, patch));
}
function resizeCursor(handle) {
if (handle === "n" || handle === "s") return "ns-resize";
if (handle === "e" || handle === "w") return "ew-resize";
if (handle === "ne" || handle === "sw") return "nesw-resize";
return "nwse-resize";
}
function setInteractionCursor(cursor) {
document.documentElement.style.cursor = cursor;
document.body.style.cursor = cursor;
if (win) win.style.cursor = cursor;
}
function clearInteractionCursor() {
document.documentElement.style.cursor = "";
document.body.style.cursor = "";
if (win) win.style.cursor = "";
}
function clearMotionClasses(node) {
if (!node) return;
node.classList.remove("is-liquid-motion", "is-motion-open", "is-motion-minimize", "is-motion-restore", "is-motion-close", "is-motion-lite");
}
function cancelWindowMotion(node = win) {
motionId += 1;
if (node && node.getAnimations) {
node.getAnimations().forEach((animation) => {
try { animation.cancel(); } catch { }
});
}
clearMotionClasses(node);
}
function withoutWindowTransition(node, fn) {
if (!node) return;
const previous = node.style.transition;
node.style.transition = "none";
fn();
void node.offsetWidth;
node.style.transition = previous;
}
function shouldUseLiteMotion() {
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
return !!(
MOTION_QUERY.matches ||
(navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 2) ||
(navigator.deviceMemory && navigator.deviceMemory <= 2) ||
(connection && connection.saveData)
);
}
function visualRectForGeometry(next, minimized) {
const vp = viewport();
return {
left: next.x,
top: next.y,
width: minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : next.w,
height: minimized ? Math.min(MINIMIZED_HEIGHT, vp.h - 16) : next.h,
};
}
function rectTransform(rect, layoutRect) {
const sx = rect.width / Math.max(1, layoutRect.width);
const sy = rect.height / Math.max(1, layoutRect.height);
return `translate3d(${rect.left}px, ${rect.top}px, 0) scale(${sx}, ${sy})`;
}
function morphRect(from, to, progress, sx, sy) {
return {
left: from.left + (to.left - from.left) * progress,
top: from.top + (to.top - from.top) * progress,
width: to.width * sx,
height: to.height * sy,
};
}
function motionKeyframes(kind, fromRect, toRect, layoutRect) {
const start = rectTransform(fromRect, layoutRect);
const end = rectTransform(toRect, layoutRect);
if (kind === "minimize") {
return [
{ opacity: 1, transform: start, offset: 0 },
{ opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 0.72, 1.14, 0.68), layoutRect), offset: 0.58 },
{ opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 0.94, 0.96, 1.12), layoutRect), offset: 0.82 },
{ opacity: 1, transform: end, offset: 1 },
];
}
if (kind === "restore" || kind === "open") {
return [
{ opacity: kind === "open" ? 0 : 1, transform: start, offset: 0 },
{ opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 1, 1.028, 0.982), layoutRect), offset: 0.54 },
{ opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 1, 0.992, 1.006), layoutRect), offset: 0.78 },
{ opacity: 1, transform: end, offset: 1 },
];
}
return [
{ opacity: 1, transform: start, offset: 0 },
{ opacity: 0.86, transform: rectTransform(morphRect(fromRect, toRect, 1, 1.018, 0.9), layoutRect), offset: 0.45 },
{ opacity: 0, transform: end, offset: 1 },
];
}
function playWindowMotion(kind, fromRect, toRect, node = win) {
if (!node) return Promise.resolve();
cancelWindowMotion(node);
const currentMotion = motionId;
const lite = shouldUseLiteMotion();
const layoutRect = node.getBoundingClientRect();
const finalRect = toRect || layoutRect;
const initialRect = fromRect || {
left: finalRect.left + finalRect.width * 0.04,
top: finalRect.top + finalRect.height * 0.035,
width: finalRect.width * 0.92,
height: finalRect.height * 0.92,
};
const duration = lite
? 140
: kind === "restore" || kind === "open"
? 520
: kind === "minimize"
? 460
: 260;
node.classList.add("is-liquid-motion", `is-motion-${kind}`);
node.classList.toggle("is-motion-lite", lite);
const cleanup = (animation) => {
if (currentMotion !== motionId) return;
if (animation) {
try { animation.cancel(); } catch { }
}
clearMotionClasses(node);
};
if (!node.animate) {
return new Promise((resolve) => {
setTimeout(() => {
cleanup();
resolve();
}, duration);
});
}
const easing = kind === "close"
? "cubic-bezier(0.4, 0, 1, 1)"
: "cubic-bezier(0.16, 1, 0.3, 1)";
const animation = node.animate(motionKeyframes(kind, initialRect, finalRect, layoutRect), {
duration,
easing,
fill: "both",
});
return animation.finished.catch(() => { }).then(() => cleanup(animation));
}
function ensureWindow() {
if (win) return win;
win = document.createElement("section");
win.id = "adpSshTerminalWindow";
win.className = "adp-ssh-terminal-window";
win.setAttribute("role", "dialog");
win.setAttribute("aria-label", "SSH Terminal");
win.innerHTML = `
<div class="adp-ssh-terminal-titlebar" data-adp-ssh-drag>
<div class="adp-ssh-terminal-title">
<i class="fa-solid fa-terminal" aria-hidden="true"></i>
<span>SSH Terminal</span>
</div>
<div class="adp-ssh-terminal-grip" aria-hidden="true"></div>
<div class="adp-ssh-terminal-controls">
<button class="adp-ssh-terminal-control" type="button" data-adp-ssh-minimize title="Minimize terminal" aria-label="Minimize terminal">
<i class="fa-solid fa-minus" aria-hidden="true"></i>
</button>
<button class="adp-ssh-terminal-control" type="button" data-adp-ssh-close title="Close terminal" aria-label="Close terminal">
<i class="fa-solid fa-xmark" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="adp-ssh-terminal-frame-wrap">
<iframe class="adp-ssh-terminal-frame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer"></iframe>
</div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-n" data-adp-ssh-resize="n"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-e" data-adp-ssh-resize="e"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-s" data-adp-ssh-resize="s"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-w" data-adp-ssh-resize="w"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-ne" data-adp-ssh-resize="ne"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-nw" data-adp-ssh-resize="nw"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-se" data-adp-ssh-resize="se"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-sw" data-adp-ssh-resize="sw"></div>
`;
document.body.appendChild(win);
updateLauncherVisibility();
frame = win.querySelector(".adp-ssh-terminal-frame");
const state = readState();
const nextGeometry = getGeometryForState(state);
applyGeometry(nextGeometry);
win.classList.toggle("is-minimized", !!state.minimized);
win.querySelector("[data-adp-ssh-close]")?.addEventListener("click", closeTerminal);
win.querySelector("[data-adp-ssh-minimize]")?.addEventListener("click", toggleMinimized);
win.querySelector("[data-adp-ssh-drag]")?.addEventListener("pointerdown", startDrag);
win.querySelectorAll("[data-adp-ssh-resize]").forEach((handle) => {
handle.addEventListener("pointerdown", startResize);
});
win.querySelector("[data-adp-ssh-drag]")?.addEventListener("dblclick", (event) => {
if (event.target.closest("button")) return;
toggleMinimized();
});
requestAnimationFrame(() => {
if (!win) return;
win.classList.add("is-ready");
playWindowMotion("open");
});
return win;
}
async function fetchLaunchUrl() {
const res = await fetch("/api/ssh-terminal/session", { credentials: "include" });
const data = await res.json().catch(() => ({}));
if (!res.ok || !data || !data.launchUrl) {
throw new Error((data && data.error) || "Unable to open terminal");
}
return data.launchUrl;
}
async function openTerminal(options = {}) {
if (opening) return opening;
opening = (async () => {
const node = ensureWindow();
const state = readState();
const nextGeometry = getGeometryForState(state);
applyGeometry(nextGeometry);
node.classList.toggle("is-minimized", !!state.minimized);
writeWindowState({ open: true, minimized: !!state.minimized });
updateLauncherVisibility();
if (frame && (!frame.getAttribute("src") || frame.getAttribute("src") === "about:blank")) {
frame.src = await fetchLaunchUrl();
}
return node;
})();
try {
return await opening;
} catch (err) {
if (!options.silent) alert(err && err.message ? err.message : "Failed to open SSH terminal.");
throw err;
} finally {
opening = null;
}
}
function toggleMinimized() {
if (!win) return;
if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
const node = win;
const from = node.getBoundingClientRect();
const minimized = !win.classList.contains("is-minimized");
const next = clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized);
if (minimized) {
const to = visualRectForGeometry(next, true);
writeState({ open: true, minimized: true, x: next.x, y: next.y, w: next.w, h: next.h, updatedAt: Date.now() });
playWindowMotion("minimize", from, to, node).then(() => {
if (win !== node) return;
withoutWindowTransition(node, () => {
node.classList.add("is-minimized");
applyGeometry(next);
});
});
return;
}
withoutWindowTransition(node, () => {
node.classList.remove("is-minimized");
applyGeometry(next);
});
const to = node.getBoundingClientRect();
writeWindowState({ open: true, minimized: false });
playWindowMotion("restore", from, to, node);
}
function closeTerminal() {
if (win && win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
if (frame && frame.contentWindow) {
try {
frame.contentWindow.postMessage({ type: "adpanel-ssh-terminal-close" }, window.location.origin);
} catch { }
}
try {
localStorage.setItem("adpanel:ssh-terminal-live:v1", "0");
} catch { }
writeState({ open: false, minimized: false });
const old = win;
const from = old ? old.getBoundingClientRect() : null;
const to = from ? {
left: from.left + from.width * 0.04,
top: from.top + from.height * 0.08,
width: from.width * 0.9,
height: from.height * 0.76,
} : null;
win = null;
frame = null;
updateLauncherVisibility();
if (old) {
playWindowMotion("close", from, to, old).then(() => {
old.classList.remove("is-ready");
const iframe = old.querySelector("iframe");
if (iframe) iframe.src = "about:blank";
old.remove();
});
}
}
function startDrag(event) {
if (!win || event.button !== 0 || event.target.closest("button")) return;
if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
interaction = {
type: "drag",
pointerId: event.pointerId,
offsetX: event.clientX - geometry.x,
offsetY: event.clientY - geometry.y,
x: geometry.x,
y: geometry.y,
w: geometry.w,
h: geometry.h,
};
win.classList.add("is-interacting", "is-dragging");
setInteractionCursor("grabbing");
try { event.currentTarget.setPointerCapture(event.pointerId); } catch { }
event.preventDefault();
}
function startResize(event) {
if (!win || event.button !== 0 || win.classList.contains("is-minimized")) return;
if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
const handle = event.currentTarget.getAttribute("data-adp-ssh-resize") || "";
interaction = {
type: "resize",
pointerId: event.pointerId,
handle,
startX: event.clientX,
startY: event.clientY,
x: geometry.x,
y: geometry.y,
w: geometry.w,
h: geometry.h,
next: Object.assign({}, geometry),
};
win.classList.add("is-interacting", "is-resizing");
setInteractionCursor(resizeCursor(handle));
try { event.currentTarget.setPointerCapture(event.pointerId); } catch { }
event.preventDefault();
event.stopPropagation();
}
function resizeGeometry(start, dx, dy, handle) {
const vp = viewport();
let left = start.x;
let top = start.y;
let right = start.x + start.w;
let bottom = start.y + start.h;
if (handle.includes("e")) right += dx;
if (handle.includes("s")) bottom += dy;
if (handle.includes("w")) left += dx;
if (handle.includes("n")) top += dy;
if (handle.includes("w")) {
left = Math.max(8, Math.min(left, right - Math.min(MIN_WIDTH, vp.w - 16)));
} else {
right = Math.min(vp.w - 8, Math.max(right, left + Math.min(MIN_WIDTH, vp.w - 16)));
}
if (handle.includes("n")) {
top = Math.max(8, Math.min(top, bottom - Math.min(MIN_HEIGHT, vp.h - 16)));
} else {
bottom = Math.min(vp.h - 8, Math.max(bottom, top + Math.min(MIN_HEIGHT, vp.h - 16)));
}
return clampGeometry(left, top, right - left, bottom - top, false);
}
function moveInteraction(event) {
if (!interaction || !win || event.pointerId !== interaction.pointerId) return;
const minimized = win.classList.contains("is-minimized");
const next = interaction.type === "resize"
? resizeGeometry(interaction, event.clientX - interaction.startX, event.clientY - interaction.startY, interaction.handle)
: clampGeometry(event.clientX - interaction.offsetX, event.clientY - interaction.offsetY, interaction.w, interaction.h, minimized);
interaction.next = next;
if (!raf) {
raf = requestAnimationFrame(() => {
raf = 0;
if (interaction && interaction.next) applyGeometry(interaction.next);
});
}
}
function endInteraction(event) {
if (!interaction || !win || event.pointerId !== interaction.pointerId) return;
const minimized = win.classList.contains("is-minimized");
const next = interaction.next || clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized);
applyGeometry(next);
writeWindowState({ open: true, minimized });
win.classList.remove("is-interacting", "is-dragging", "is-resizing");
clearInteractionCursor();
interaction = null;
}
function attachLaunchers() {
ensureLauncher();
document.addEventListener("click", (event) => {
const trigger = event.target.closest("[data-open-ssh-terminal], #openSshTerminalBtn");
if (!trigger) return;
event.preventDefault();
if ("disabled" in trigger) trigger.disabled = true;
openTerminal().finally(() => {
if ("disabled" in trigger) trigger.disabled = false;
});
});
const state = readState();
if (state.open) {
openTerminal({ silent: true }).catch(() => { });
}
}
function ensureLauncher() {
if (launcher || document.querySelector("[data-open-ssh-terminal], #openSshTerminalBtn")) return;
launcher = document.createElement("button");
launcher.type = "button";
launcher.className = "adp-ssh-terminal-launcher";
launcher.setAttribute("data-open-ssh-terminal", "true");
launcher.setAttribute("title", "Open SSH Terminal");
launcher.setAttribute("aria-label", "Open SSH Terminal");
launcher.innerHTML = '<i class="fa-solid fa-terminal" aria-hidden="true"></i>';
document.body.appendChild(launcher);
updateLauncherVisibility();
}
function updateLauncherVisibility() {
if (!launcher) return;
const open = !!win || !!readState().open;
launcher.classList.toggle("is-hidden", open || hasVisibleModal());
}
function isVisibleModal(node) {
if (!node || node === win || node === launcher) return false;
if (node.getAttribute("aria-hidden") === "true") return false;
if (node.classList.contains("show") || node.getAttribute("aria-hidden") === "false") return true;
const styles = window.getComputedStyle(node);
if (styles.display === "none" || styles.visibility === "hidden" || styles.opacity === "0") return false;
return node.offsetWidth > 0 && node.offsetHeight > 0;
}
function hasVisibleModal() {
return Array.from(document.querySelectorAll(MODAL_SELECTOR)).some(isVisibleModal);
}
function scheduleLauncherVisibility() {
if (launcherVisibilityRaf) return;
launcherVisibilityRaf = requestAnimationFrame(() => {
launcherVisibilityRaf = 0;
updateLauncherVisibility();
});
}
function observeModalVisibility() {
if (modalObserver || !document.body) return;
modalObserver = new MutationObserver(scheduleLauncherVisibility);
modalObserver.observe(document.body, {
attributes: true,
attributeFilter: ["class", "style", "aria-hidden"],
childList: true,
subtree: true,
});
}
window.addEventListener("pointermove", moveInteraction, { passive: true });
window.addEventListener("pointerup", endInteraction, { passive: true });
window.addEventListener("pointercancel", endInteraction, { passive: true });
window.addEventListener("resize", () => {
if (!win) return;
const minimized = win.classList.contains("is-minimized");
const next = clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized);
applyGeometry(next);
writeWindowState({ open: true, minimized });
});
window.ADPanelSshTerminal = {
open: openTerminal,
close: closeTerminal,
toggleMinimized,
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => {
attachLaunchers();
observeModalVisibility();
}, { once: true });
} else {
attachLaunchers();
observeModalVisibility();
}
})();
+325
View File
@@ -0,0 +1,325 @@
/* Admin /status monitoring client.
*
* - Opens the existing socket.io connection, joins the admin-only "monitor"
* room, and renders live bars (CPU/RAM/Storage/Network/RPS) once per second
* while the page is open.
* - Renders a fixed one-month calendar; clicking a day fetches that day's
* per-minute history via REST and draws it into the graph. Default view is
* today.
* - Everything here is read-only and admin-gated server-side.
*/
(function () {
"use strict";
var SOCKET = null;
var watching = false;
// ---- helpers -----------------------------------------------------------
function $(id) { return document.getElementById(id); }
function clampPct(n) {
n = Number(n);
if (!isFinite(n) || n < 0) return 0;
if (n > 100) return 100;
return n;
}
function fmtBytesPerSec(bps) {
bps = Number(bps) || 0;
var units = ["B/s", "KB/s", "MB/s", "GB/s"];
var i = 0;
while (bps >= 1024 && i < units.length - 1) { bps /= 1024; i++; }
return (bps < 10 ? bps.toFixed(1) : Math.round(bps)) + " " + units[i];
}
function fmtUptime(ms) {
var s = Math.floor((Number(ms) || 0) / 1000);
var d = Math.floor(s / 86400); s -= d * 86400;
var h = Math.floor(s / 3600); s -= h * 3600;
var m = Math.floor(s / 60); s -= m * 60;
var parts = [];
if (d) parts.push(d + "d");
if (h || d) parts.push(h + "h");
parts.push(m + "m");
parts.push(s + "s");
return parts.join(" ");
}
// ---- bar rendering -----------------------------------------------------
function setBar(key, percent, valueText) {
var fill = document.querySelector('[data-bar-fill="' + key + '"]');
var pctEl = document.querySelector('[data-bar-pct="' + key + '"]');
var valEl = document.querySelector('[data-bar-value="' + key + '"]');
var p = clampPct(percent);
// Update circular ring progress
if (fill) {
var circumference = 2 * Math.PI * 15.9155;
var offset = circumference - (p / 100) * circumference;
fill.style.strokeDasharray = p + ', 100';
}
if (pctEl) pctEl.textContent = p.toFixed(1) + "%";
if (valEl && valueText != null) valEl.textContent = valueText;
}
// Network bars are scaled relative to a rolling observed peak so the bar is
// meaningful even without a hard cap.
var netPeak = { rx: 1024 * 256, tx: 1024 * 256 };
function netPercent(dir, bps) {
bps = Number(bps) || 0;
if (bps > netPeak[dir]) netPeak[dir] = bps;
return (bps / netPeak[dir]) * 100;
}
function applySample(s) {
if (!s) return;
setBar("cpu", s.cpu, (Number(s.cpu) || 0).toFixed(1) + "% of " + (s.cores || 1) + " cores");
setBar("mem", s.memPercent, bytesPair(s.memUsed, s.memTotal));
setBar("disk", s.diskPercent != null ? s.diskPercent : 0,
s.diskUsed != null ? bytesPair(s.diskUsed, s.diskTotal) : "n/a");
if (s.netRx != null) setBar("netrx", netPercent("rx", s.netRx), fmtBytesPerSec(s.netRx));
if (s.netTx != null) setBar("nettx", netPercent("tx", s.netTx), fmtBytesPerSec(s.netTx));
var rpsEl = $("metricRps");
if (rpsEl) rpsEl.textContent = (Number(s.rps) || 0).toFixed(1);
var upEl = $("metricUptime");
if (upEl && s.uptimeMs != null) upEl.textContent = fmtUptime(s.uptimeMs);
if (s.services) applyServices(s.services);
pushLive(s);
}
function bytesPair(used, total) {
return fmtBytes(used) + " / " + fmtBytes(total);
}
function fmtBytes(b) {
b = Number(b) || 0;
var units = ["B", "KB", "MB", "GB", "TB"];
var i = 0;
while (b >= 1024 && i < units.length - 1) { b /= 1024; i++; }
return (b < 10 ? b.toFixed(1) : Math.round(b)) + " " + units[i];
}
// ---- services ----------------------------------------------------------
function dot(ok) { return ok ? "ok" : "bad"; }
function applyServices(sv) {
var db = $("svcDatabase");
if (db) {
db.dataset.state = dot(sv.database && sv.database.ok);
var lat = sv.database && sv.database.latencyMs != null ? sv.database.latencyMs + "ms" : "offline";
var dbv = $("svcDatabaseVal"); if (dbv) dbv.textContent = lat;
}
setSvcText("svcNodes", sv.nodes ? (sv.nodes.online + "/" + sv.nodes.total + " online") : "n/a",
sv.nodes && sv.nodes.total > 0 && sv.nodes.online === sv.nodes.total);
setSvcText("svcContainers", sv.containers ? (sv.containers.running + " running, " + sv.containers.stopped + " stopped") : "n/a", true);
setSvcText("svcSsh", (sv.sshSessions || 0) + " active", true);
setSvcText("svcSockets", (sv.activeSockets || 0) + " connected", true);
var ver = $("svcVersion");
if (ver && sv.panelVersion) ver.textContent = sv.panelVersion;
}
function setSvcText(id, text, ok) {
var el = $(id);
if (!el) return;
el.textContent = text;
var row = el.closest("[data-svc-row]");
if (row) row.dataset.state = ok ? "ok" : "warn";
}
// ---- live sparkline buffer (current day, client-side) ------------------
var liveBuffer = [];
function pushLive(s) {
liveBuffer.push({ ts: s.ts, cpu: s.cpu, mem: s.memPercent });
if (liveBuffer.length > 600) liveBuffer.shift();
}
// ---- history graph -----------------------------------------------------
var graphMode = "today"; // or a YYYY-MM-DD string
function drawGraph(points, label) {
var canvas = $("metricsGraph");
if (!canvas) return;
var ctx = canvas.getContext("2d");
var w = canvas.width = canvas.clientWidth * (window.devicePixelRatio || 1);
var h = canvas.height = canvas.clientHeight * (window.devicePixelRatio || 1);
ctx.clearRect(0, 0, w, h);
var lbl = $("graphLabel");
if (lbl) lbl.textContent = label || "";
if (!points || !points.length) {
ctx.fillStyle = "rgba(255,255,255,0.35)";
ctx.font = (14 * (window.devicePixelRatio || 1)) + "px system-ui";
ctx.textAlign = "center";
ctx.fillText("No data recorded for this day yet", w / 2, h / 2);
return;
}
var pad = 8 * (window.devicePixelRatio || 1);
function line(series, color) {
ctx.beginPath();
for (var i = 0; i < points.length; i++) {
var x = pad + (i / (points.length - 1 || 1)) * (w - pad * 2);
var v = clampPct(points[i][series]);
var y = h - pad - (v / 100) * (h - pad * 2);
if (i === 0) ctx.moveTo(x, y); else ctx.lineTo(x, y);
}
ctx.strokeStyle = color;
ctx.lineWidth = 2 * (window.devicePixelRatio || 1);
ctx.lineJoin = "round";
ctx.stroke();
}
// gridlines
ctx.strokeStyle = "rgba(255,255,255,0.06)";
ctx.lineWidth = 1;
for (var g = 0; g <= 4; g++) {
var gy = pad + (g / 4) * (h - pad * 2);
ctx.beginPath(); ctx.moveTo(pad, gy); ctx.lineTo(w - pad, gy); ctx.stroke();
}
line("cpu", "#0EA5E9");
line("mem", "#8B5CF6");
}
function loadDay(dayStr) {
fetch("/api/status/metrics/day?day=" + encodeURIComponent(dayStr), { credentials: "include" })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (data) {
if (!data || !data.ok) { drawGraph([], dayStr); return; }
drawGraph(data.points, formatDayLabel(dayStr));
})
.catch(function () { drawGraph([], dayStr); });
}
function formatDayLabel(dayStr) {
try {
var d = new Date(dayStr + "T00:00:00Z");
return d.toLocaleDateString(undefined, { day: "numeric", month: "long", year: "numeric", timeZone: "UTC" });
} catch (_) { return dayStr; }
}
// ---- calendar (fixed one month) ----------------------------------------
function buildCalendar(summaryDays) {
var grid = $("calendarGrid");
if (!grid) return;
grid.innerHTML = "";
var now = new Date();
var year = now.getUTCFullYear();
var month = now.getUTCMonth();
var first = new Date(Date.UTC(year, month, 1));
var daysInMonth = new Date(Date.UTC(year, month + 1, 0)).getUTCDate();
var startWeekday = first.getUTCDay(); // 0=Sun
var monthLabel = $("calendarMonth");
if (monthLabel) {
monthLabel.textContent = first.toLocaleDateString(undefined, { month: "long", year: "numeric", timeZone: "UTC" });
}
var summaryByDay = {};
(summaryDays || []).forEach(function (d) {
var key = new Date(d.ts).toISOString().slice(0, 10);
summaryByDay[key] = d;
});
var weekdays = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
weekdays.forEach(function (wd) {
var head = document.createElement("div");
head.className = "cal-weekday";
head.textContent = wd;
grid.appendChild(head);
});
for (var i = 0; i < startWeekday; i++) {
var blank = document.createElement("div");
blank.className = "cal-cell cal-cell--blank";
grid.appendChild(blank);
}
var todayKey = now.toISOString().slice(0, 10);
for (var day = 1; day <= daysInMonth; day++) {
(function (day) {
var dateStr = year + "-" + String(month + 1).padStart(2, "0") + "-" + String(day).padStart(2, "0");
var cell = document.createElement("button");
cell.type = "button";
cell.className = "cal-cell";
cell.dataset.day = dateStr;
if (dateStr === todayKey) cell.classList.add("cal-cell--today");
var num = document.createElement("span");
num.className = "cal-cell__num";
num.textContent = day;
cell.appendChild(num);
cell.addEventListener("click", function () {
document.querySelectorAll(".cal-cell--active").forEach(function (c) { c.classList.remove("cal-cell--active"); });
cell.classList.add("cal-cell--active");
graphMode = dateStr;
loadDay(dateStr);
});
grid.appendChild(cell);
})(day);
}
}
function loadSummaryAndCalendar() {
fetch("/api/status/metrics/summary", { credentials: "include" })
.then(function (r) { return r.ok ? r.json() : null; })
.then(function (data) {
buildCalendar(data && data.ok ? data.days : []);
// default: today's graph + mark today active
var todayKey = new Date().toISOString().slice(0, 10);
var todayCell = document.querySelector('.cal-cell[data-day="' + todayKey + '"]');
if (todayCell) todayCell.classList.add("cal-cell--active");
loadDay(todayKey);
})
.catch(function () { buildCalendar([]); });
}
// ---- socket wiring -----------------------------------------------------
function connectSocket() {
if (typeof io !== "function") return;
SOCKET = window._monitorSocket || io({ withCredentials: true });
window._monitorSocket = SOCKET;
SOCKET.on("connect", subscribe);
SOCKET.on("monitor:snapshot", function (snap) { applySample(snap); });
SOCKET.on("monitor:sample", function (s) { applySample(s); });
SOCKET.on("monitor:error", function (e) {
console.warn("[monitor]", e && e.error);
});
if (SOCKET.connected) subscribe();
}
function subscribe() {
if (watching) return;
watching = true;
SOCKET.emit("monitor:subscribe");
}
function unsubscribe() {
if (!watching || !SOCKET) return;
watching = false;
SOCKET.emit("monitor:unsubscribe");
}
// Pause intensive sampling when the tab is hidden (keeps cost near zero).
document.addEventListener("visibilitychange", function () {
if (document.hidden) unsubscribe();
else if (SOCKET) { watching = false; subscribe(); }
});
window.addEventListener("beforeunload", unsubscribe);
function init() {
connectSocket();
loadSummaryAndCalendar();
window.addEventListener("resize", function () {
if (graphMode === "today") loadDay(new Date().toISOString().slice(0, 10));
else loadDay(graphMode);
});
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
} else {
init();
}
})();
+147 -67
View File
@@ -17,6 +17,20 @@
--menu-top: 100rem; --menu-top: 100rem;
--menu-left: -5rem; --menu-left: -5rem;
--watermark-offset-x: 3.5rem; --watermark-offset-x: 3.5rem;
--login-card-width: min(450px, calc(100vw - 48px));
--login-form-width: min(380px, calc(100vw - 48px));
--login-card-height: 470px;
--login-card-height-2fa: 540px;
--login-form-top: calc(50% + 20px);
--login-form-top-2fa: calc(50% - 4px);
--login-icon-top: calc(50% - 190px);
--login-icon-top-2fa: calc(50% - 218px);
--login-title-top: calc(50% - 104px);
--login-title-top-2fa: calc(50% - 130px);
--login-desc-top: calc(50% - 66px);
--login-desc-top-2fa: calc(50% - 92px);
--login-subline-top: calc(50% - 46px);
--login-subline-top-2fa: calc(50% - 72px);
} }
html, html,
@@ -45,21 +59,23 @@ body {
} }
} }
form { .login-form {
position: absolute; position: absolute;
top: var(--login-form-top);
left: 50%;
display: flex; display: flex;
flex-direction: column; flex-direction: column;
user-select: none; user-select: none;
gap: 10px; gap: 12px;
width: 300px; width: var(--login-form-width);
margin-top: 300px; margin: 0;
transform: translateX(-50%);
z-index: 100; z-index: 100;
transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1);
} }
@media (max-width: 768px) { body.login-has-2fa .login-form {
form { top: var(--login-form-top-2fa);
margin-top: 270px;
}
} }
.input-icon { .input-icon {
@@ -78,8 +94,30 @@ form {
position: relative; position: relative;
display: flex; display: flex;
align-items: center; align-items: center;
width: 380px; width: 100%;
margin-left: -40px; margin-left: 0;
}
.login-two-factor-field {
max-height: 48px;
opacity: 1;
overflow: hidden;
transform: translateY(0);
transition:
max-height 360ms cubic-bezier(0.2, 0.8, 0.2, 1),
opacity 220ms ease,
transform 360ms cubic-bezier(0.2, 0.8, 0.2, 1),
margin 360ms cubic-bezier(0.2, 0.8, 0.2, 1);
will-change: max-height, opacity, transform;
}
.login-two-factor-field[aria-hidden="true"] {
max-height: 0;
opacity: 0;
margin-top: -6px;
margin-bottom: -6px;
pointer-events: none;
transform: translateY(-8px);
} }
.input-holder:hover .input-icon { .input-holder:hover .input-icon {
@@ -144,21 +182,15 @@ button {
.get-started { .get-started {
position: relative; position: relative;
border-radius: 12px; border-radius: 12px;
/* Smoother curve */
height: 48px; height: 48px;
/* Slightly taller for touch target size */ width: 100%;
width: 380px;
user-select: none; user-select: none;
margin-top: 50px; margin-top: 4px;
margin-left: -40px; margin-left: 0;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
/* Apple font */
font-size: 16px; font-size: 16px;
/* slightly larger */ letter-spacing: 0;
letter-spacing: -0.01em;
/* Tighter tracking */
font-weight: 600; font-weight: 600;
/* Bolder */
color: #ffffff; color: #ffffff;
background: linear-gradient(to bottom, #363636, #1a1a1a, #000000); background: linear-gradient(to bottom, #363636, #1a1a1a, #000000);
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5); box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5);
@@ -168,7 +200,7 @@ button {
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 0; gap: 0;
transition: transform 0.6s cubic-bezier(0.25, 1, 0.5, 1), background 0.6s ease, box-shadow 0.6s ease; transition: transform 0.6s cubic-bezier(0.25, 1, 0.5, 1), background 0.6s ease, box-shadow 0.6s ease, margin-top 360ms cubic-bezier(0.2, 0.8, 0.2, 1);
} }
.get-started__logo { .get-started__logo {
@@ -182,7 +214,7 @@ button {
@media (max-width: 768px) { @media (max-width: 768px) {
.get-started { .get-started {
margin-top: 30px; margin-top: 4px;
} }
} }
@@ -206,16 +238,25 @@ button {
.menu { .menu {
position: absolute; position: absolute;
width: 390px; top: 50%;
height: 480px; left: 50%;
box-sizing: border-box;
width: var(--login-card-width);
height: var(--login-card-height);
border-radius: 30px; border-radius: 30px;
padding: 30px; padding: 30px;
margin-top: 60px; margin: 0;
isolation: isolate; isolation: isolate;
box-shadow: 0px 6px var(--outer-shadow-blur) rgba(0, 0, 0, 0.2); box-shadow: 0px 6px var(--outer-shadow-blur) rgba(0, 0, 0, 0.2);
background-color: rgba(var(--tint-color), var(--tint-opacity)); background-color: rgba(var(--tint-color), var(--tint-opacity));
border: 1px solid rgba(255, 255, 255, 0.25); border: 1px solid rgba(255, 255, 255, 0.25);
pointer-events: none; pointer-events: none;
transform: translate(-50%, -50%);
transition: height 360ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
body.login-has-2fa .menu {
height: var(--login-card-height-2fa);
} }
.menu::before { .menu::before {
@@ -242,24 +283,17 @@ button {
z-index: 1; z-index: 1;
} }
@media (max-width: 768px) {
.menu {
font-size: 24px;
padding: 20px;
margin-top: 20px;
}
}
.forgot-password { .forgot-password {
position: absolute; position: relative;
align-self: flex-end;
cursor: pointer; cursor: pointer;
color: #f5f5f7; color: #f5f5f7;
/* Matching pure white sub-tone */ /* Matching pure white sub-tone */
user-select: none; user-select: none;
margin-top: 150px; margin: -2px 0 0;
margin-left: 230px;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 14px; font-size: 14px;
line-height: 16px;
font-weight: 500; font-weight: 500;
white-space: nowrap; white-space: nowrap;
opacity: 0.65; opacity: 0.65;
@@ -285,62 +319,68 @@ button {
} }
.sign-up { .sign-up {
position: relative; position: absolute;
top: var(--login-title-top);
left: 50%;
color: #f5f5f7 !important; color: #f5f5f7 !important;
user-select: none; user-select: none;
top: 140px;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Display", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 24px; font-size: 24px;
font-weight: 600; font-weight: 600;
letter-spacing: -0.015em; letter-spacing: 0;
z-index: 1; z-index: 1;
text-shadow: 0 2px 8px rgba(0, 0, 0, 0.4); text-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
transform: translateX(-50%);
white-space: nowrap;
transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1);
} }
@media (max-width: 768px) { body.login-has-2fa .sign-up {
.sign-up { top: var(--login-title-top-2fa);
top: 100px;
}
} }
.sign-up-desc { .sign-up-desc {
position: relative; position: absolute;
top: var(--login-desc-top);
left: 50%;
color: #a1a1a6; color: #a1a1a6;
user-select: none; user-select: none;
top: 207px;
text-align: center; text-align: center;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 15px; font-size: 15px;
font-weight: 500; font-weight: 500;
letter-spacing: -0.012em; letter-spacing: 0;
opacity: 1; opacity: 1;
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
transform: translateX(-50%);
white-space: nowrap;
transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1);
} }
@media (max-width: 768px) { body.login-has-2fa .sign-up-desc {
.sign-up-desc { top: var(--login-desc-top-2fa);
top: 170px;
}
} }
.sign-up-sublines { .sign-up-sublines {
position: relative; position: absolute;
top: var(--login-subline-top);
left: 50%;
color: #86868b; color: #86868b;
user-select: none; user-select: none;
top: 245px;
text-align: center; text-align: center;
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif; font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
font-size: 14px; font-size: 14px;
font-weight: 500; font-weight: 500;
letter-spacing: -0.012em; letter-spacing: 0;
opacity: 1; opacity: 1;
text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3); text-shadow: 0 1px 4px rgba(0, 0, 0, 0.3);
transform: translateX(-50%);
white-space: nowrap;
transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1);
} }
@media (max-width: 758px) { body.login-has-2fa .sign-up-sublines {
.sign-up-sublines { top: var(--login-subline-top-2fa);
top: 210px;
}
} }
@@ -371,27 +411,66 @@ button {
.circle-icon { .circle-icon {
position: absolute; position: absolute;
top: calc(var(--login-icon-top) - var(--login-form-top));
left: 50%;
display: flex;
align-items: center;
justify-content: center;
background-color: white; background-color: white;
padding: 20px; padding: 0;
border-radius: 15px; border-radius: 15px;
height: 12px; height: 54px;
width: 9px; width: 54px;
box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5); box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.5);
margin-top: -210px; margin: 0;
margin-left: 120px;
border: 1px solid #c4c4c4; border: 1px solid #c4c4c4;
box-sizing: border-box;
z-index: 101;
transform: translateX(-50%);
transition: top 360ms cubic-bezier(0.2, 0.8, 0.2, 1);
}
body.login-has-2fa .circle-icon {
top: calc(var(--login-icon-top-2fa) - var(--login-form-top-2fa));
} }
.circle-icon__glyph { .circle-icon__glyph {
color: #000; color: #000;
font-size: 25px; font-size: 25px;
margin-top: -50px; margin: 0;
margin-left: -10px;
} }
@media (max-width: 768px) { @media (max-width: 768px) {
.circle-icon { :root {
margin-top: -220px; --login-card-width: min(420px, calc(100vw - 32px));
--login-form-width: min(360px, calc(100vw - 56px));
--login-card-height: 450px;
--login-card-height-2fa: 516px;
--login-form-top: calc(50% + 18px);
--login-form-top-2fa: calc(50% - 4px);
--login-icon-top: calc(50% - 182px);
--login-icon-top-2fa: calc(50% - 208px);
--login-title-top: calc(50% - 98px);
--login-title-top-2fa: calc(50% - 124px);
--login-desc-top: calc(50% - 60px);
--login-desc-top-2fa: calc(50% - 88px);
--login-subline-top: calc(50% - 40px);
--login-subline-top-2fa: calc(50% - 69px);
}
.login-form {
width: var(--login-form-width);
}
.menu {
font-size: 24px;
padding: 20px;
}
.sign-up-desc,
.sign-up-sublines {
width: calc(100vw - 56px);
white-space: normal;
} }
} }
@@ -567,7 +646,8 @@ button {
} }
.captcha-modal__widget #recaptchaWidget[hidden], .captcha-modal__widget #recaptchaWidget[hidden],
.captcha-modal__widget #cf-turnstile[hidden] { .captcha-modal__widget #cf-turnstile[hidden],
.captcha-modal__widget #hcaptchaWidget[hidden] {
display: none; display: none;
} }
+938 -46
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -69,7 +69,8 @@ body {
.top-actions { .top-actions {
display: flex; display: flex;
gap: 8px; gap: 8px;
align-items: center align-items: center;
margin-left: auto
} }
.icon-btn { .icon-btn {
+3 -3
View File
@@ -21,7 +21,7 @@
{ {
"id": "default-3", "id": "default-3",
"title": "ADPanel Github", "title": "ADPanel Github",
"link": "https://github.com/antonndev/ADPanel-Enterprise", "link": "https://github.com/antonndev/ADPanel",
"icon": "fa-duotone fa-regular fa-panel-ews", "icon": "fa-duotone fa-regular fa-panel-ews",
"animation": "scale", "animation": "scale",
"newTab": true, "newTab": true,
@@ -41,12 +41,12 @@
{ {
"id": "qa-1769251431563", "id": "qa-1769251431563",
"title": "ADPanel Site", "title": "ADPanel Site",
"link": "https://github.com/antonndev/ADPanel-Enterprise", "link": "https://ad-panel.com",
"icon": "fa-solid fa-globe", "icon": "fa-solid fa-globe",
"animation": "scale", "animation": "scale",
"newTab": true, "newTab": true,
"scaleValue": 1.01 "scaleValue": 1.01
} }
], ],
"updatedAt": 1773427337191 "updatedAt": 1780755825878
} }
+95
View File
@@ -0,0 +1,95 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
)
// TestReinstallPreservesDiskIdOnSecondDisk is a regression test for the bug where
// reinstalling a server that lives on a secondary disk dropped the __diskId from
// its rebuilt meta, causing the server to silently fall back to the primary disk
// on the next cold cache / restart and orphan its real files on the secondary
// disk. The reinstall handler rebuilds meta from scratch, so it must carry the
// disk assignment forward exactly like create persists it.
func TestReinstallPreservesDiskIdOnSecondDisk(t *testing.T) {
a, _ := newTestAgent(t)
mount := t.TempDir()
d := registerTestDisk(t, a, mount, 50)
a.setServerDiskMapping("beta", d.ID)
serverDir := a.serverDir("beta")
if err := os.MkdirAll(serverDir, 0o750); err != nil {
t.Fatalf("mkdir srv: %v", err)
}
// Pre-reinstall meta carries the secondary-disk assignment, as create writes it.
oldMeta := map[string]any{
"type": "custom",
"template": "custom",
"__diskId": d.ID,
"createdAt": float64(123),
}
if err := a.saveMeta(serverDir, oldMeta); err != nil {
t.Fatalf("saveMeta old: %v", err)
}
// Simulate the reinstall meta rebuild: a fresh meta map that must inherit
// __diskId from the old meta (mirrors handleReinstallServer).
rebuilt := map[string]any{
"type": "custom",
"template": "custom",
"hostPort": 8080,
}
if diskID, ok := oldMeta["__diskId"].(string); ok && strings.TrimSpace(diskID) != "" {
rebuilt["__diskId"] = strings.TrimSpace(diskID)
}
if err := a.saveMeta(serverDir, rebuilt); err != nil {
t.Fatalf("saveMeta rebuilt: %v", err)
}
// After a cold cache, the server must still resolve to the secondary disk.
a.invalidateServerDiskCache("beta")
if got := a.diskForServer("beta"); got.ID != d.ID {
t.Fatalf("server mis-routed after reinstall: got disk %q want %q", got.ID, d.ID)
}
if got := a.serverDir("beta"); got != serverDir {
t.Fatalf("serverDir after reinstall: got %q want %q", got, serverDir)
}
// Confirm the persisted meta on disk still records the disk assignment.
persisted := a.loadMeta(serverDir)
if id, _ := persisted["__diskId"].(string); id != d.ID {
t.Fatalf("__diskId not persisted after reinstall: got %q want %q", id, d.ID)
}
}
// TestReinstallPrimaryServerOmitsDiskId verifies the common single-disk case is
// unchanged: a primary-disk server with no __diskId stays on the primary disk
// after the reinstall meta rebuild, and we do not inject a spurious assignment.
func TestReinstallPrimaryServerOmitsDiskId(t *testing.T) {
a, vol := newTestAgent(t)
serverDir := filepath.Join(vol, "alpha")
if err := os.MkdirAll(serverDir, 0o750); err != nil {
t.Fatalf("mkdir srv: %v", err)
}
oldMeta := map[string]any{"type": "custom", "template": "custom"}
rebuilt := map[string]any{"type": "custom", "template": "custom", "hostPort": 8080}
if diskID, ok := oldMeta["__diskId"].(string); ok && strings.TrimSpace(diskID) != "" {
rebuilt["__diskId"] = strings.TrimSpace(diskID)
}
if _, ok := rebuilt["__diskId"]; ok {
t.Fatalf("primary-disk reinstall must not inject __diskId")
}
if err := a.saveMeta(serverDir, rebuilt); err != nil {
t.Fatalf("saveMeta: %v", err)
}
a.invalidateServerDiskCache("alpha")
if got := a.diskForServer("alpha"); !(got.Primary || got.ID == primaryDiskID) {
t.Fatalf("primary-disk server mis-routed after reinstall to %q", got.ID)
}
}
Executable
BIN
View File
Binary file not shown.
+181 -14
View File
@@ -11,16 +11,30 @@
"ports": [ "ports": [
25565 25565
], ],
"portProtocols": {
"25565": [
"tcp"
]
},
"volumes": [ "volumes": [
"{BOT_DIR}:/data" "{BOT_DIR}:/data"
], ],
"workdir": "/data", "workdir": "/data",
"env": {}, "env": {},
"command": "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui", "command": "java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui",
"adpanelStartup": "",
"startupDisplay": "",
"install": null,
"restart": "unless-stopped", "restart": "unless-stopped",
"runAsRoot": false,
"console": { "console": {
"type": "stdin" "type": "stdin",
} "targetProcesses": [
"java",
"bedrock_server"
]
},
"javaVersion": "21"
} }
}, },
{ {
@@ -35,6 +49,7 @@
"ports": [ "ports": [
3000 3000
], ],
"portProtocols": {},
"volumes": [ "volumes": [
"{BOT_DIR}:/app" "{BOT_DIR}:/app"
], ],
@@ -43,16 +58,20 @@
"NODE_ENV": "production" "NODE_ENV": "production"
}, },
"command": "node /app/index.js", "command": "node /app/index.js",
"adpanelStartup": "",
"startupDisplay": "",
"install": null,
"restart": "unless-stopped", "restart": "unless-stopped",
"runAsRoot": false,
"console": { "console": {
"type": "stdin" "type": "stdin"
} }
} }
}, },
{ {
"id": "csgo", "id": "cs2",
"name": "Counter-Strike 2", "name": "Counter-Strike 2",
"description": "Counter-Strike 2 dedicated server installed with an ADPanel SteamCMD installer", "description": "Counter-Strike 2 dedicated server template using the ADPanel SteamCMD installer. It installs app 730, persists the server in /home/container and starts the server with safe structured startup variables.",
"defaultPort": 27015, "defaultPort": 27015,
"templateImage": "https://cdn.cloudflare.steamstatic.com/steam/apps/730/header.jpg", "templateImage": "https://cdn.cloudflare.steamstatic.com/steam/apps/730/header.jpg",
"docker": { "docker": {
@@ -63,6 +82,18 @@
27020, 27020,
27005 27005
], ],
"portProtocols": {
"27005": [
"udp"
],
"27015": [
"tcp",
"udp"
],
"27020": [
"udp"
]
},
"volumes": [ "volumes": [
"{BOT_DIR}:/home/container" "{BOT_DIR}:/home/container"
], ],
@@ -86,26 +117,43 @@
"STEAM_AUTH": "", "STEAM_AUTH": "",
"EXTRA_FLAGS": "" "EXTRA_FLAGS": ""
}, },
"adpanelStartup": "LD_LIBRARY_PATH=\"$HOME/game/bin/linuxsteamrt64:$LD_LIBRARY_PATH\" ./game/bin/linuxsteamrt64/cs2 -dedicated $( [ \"$VAC_ENABLED\" == \"1\" ] || printf %s ' -insecure' ) -ip 0.0.0.0 -port {{SERVER_PORT}} -tv_port {{TV_PORT}} -maxplayers {{MAX_PLAYERS}} $( [ \"$RCON_ENABLED\" == \"0\" ] || printf %s ' -usercon' ) +game_mode {{GAME_MODE}} +game_type {{GAME_TYPE}} +map {{SRCDS_MAP}} +hostname \"{{SERVER_NAME}}\" +sv_password \"{{SERVER_PASSWORD}}\" +rcon_password \"{{RCON_PASSWORD}}\" +sv_setsteamaccount {{STEAM_GSLT}}", "command": "",
"adpanelStartup": "cd game && ./cs2.sh -dedicated $( [ \"$VAC_ENABLED\" = \"1\" ] || printf %s ' -insecure' ) -ip 0.0.0.0 -port {{SERVER_PORT}} -tv_port {{TV_PORT}} -maxplayers {{MAX_PLAYERS}} $( [ \"$RCON_ENABLED\" = \"0\" ] || printf %s ' -usercon' ) +game_mode {{GAME_MODE}} +game_type {{GAME_TYPE}} +map {{SRCDS_MAP}} +hostname \"{{SERVER_NAME}}\" +sv_password \"{{SERVER_PASSWORD}}\" +rcon_password \"{{RCON_PASSWORD}}\" $( [ -z \"{{STEAM_GSLT}}\" ] || printf %s ' +sv_setsteamaccount {{STEAM_GSLT}}' )",
"startupDisplay": "",
"install": { "install": {
"image": "ghcr.io/pterodactyl/installers:debian", "image": "ghcr.io/pterodactyl/installers:debian",
"entrypoint": "bash", "script": "#!/bin/bash\nset -Eeuo pipefail\napp_id=\"${SRCDS_APPID:-730}\"\nsteam_user=\"${STEAM_USER:-anonymous}\"\nsteam_pass=\"${STEAM_PASS:-}\"\nsteam_auth=\"${STEAM_AUTH:-}\"\nmkdir -p /mnt/server/steamcmd /mnt/server/steamapps\ninstall_steamcmd() {\n rm -f /tmp/steamcmd.tar.gz\n curl --retry 5 --retry-delay 2 --connect-timeout 20 -fsSL -o /tmp/steamcmd.tar.gz https://steamcdn-a.akamaihd.net/client/installer/steamcmd_linux.tar.gz\n tar -xzf /tmp/steamcmd.tar.gz -C /mnt/server/steamcmd\n}\nif [ ! -x /mnt/server/steamcmd/steamcmd.sh ] || [ ! -x /mnt/server/steamcmd/linux32/steamcmd ]; then\n rm -rf /mnt/server/steamcmd\n mkdir -p /mnt/server/steamcmd\n install_steamcmd\nfi\ncd /mnt/server/steamcmd\nlogin_args=(+login \"$steam_user\")\nif [ \"$steam_user\" != \"anonymous\" ]; then\n login_args=(+login \"$steam_user\" \"$steam_pass\")\n [ -z \"$steam_auth\" ] || login_args+=(\"$steam_auth\")\nfi\nfor attempt in 1 2 3 4; do\n if HOME=/mnt/server ./steamcmd.sh +force_install_dir /mnt/server \"${login_args[@]}\" +app_update \"$app_id\" ${EXTRA_FLAGS:-} validate +quit; then\n break\n fi\n status=$?\n if [ \"$attempt\" -eq 4 ]; then\n exit \"$status\"\n fi\n rm -rf /mnt/server/steamcmd/package /mnt/server/steamcmd/linux32/steamcmd\n install_steamcmd\n sleep $((attempt * 15))\ndone\nmkdir -p /mnt/server/.steam/sdk32 /mnt/server/.steam/sdk64\ncp -f /mnt/server/steamcmd/linux32/steamclient.so /mnt/server/.steam/sdk32/steamclient.so || true\ncp -f /mnt/server/steamcmd/linux64/steamclient.so /mnt/server/.steam/sdk64/steamclient.so || true\nif [ ! -x /mnt/server/game/bin/linuxsteamrt64/cs2 ]; then\n echo \"CS2 executable missing after SteamCMD install.\"\n exit 30\nfi\nchmod -R a+rwX /mnt/server\necho \"Installation completed.\"",
"mountPath": "/mnt/server", "mountPath": "/mnt/server",
"runtimePath": "/home/container", "runtimePath": "/home/container",
"timeoutSeconds": 7200, "timeoutSeconds": 3600,
"minimumStorageMb": 40000, "minimumStorageMb": 70000
"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", "restart": "unless-stopped",
"runAsRoot": false,
"console": { "console": {
"type": "stdin" "type": "stdin",
"targetProcesses": [
"cs2",
"srcds_linux"
]
} }
},
"documentation": [
"https://hub.docker.com/r/joedwards32/cs2",
"https://developer.valvesoftware.com/wiki/Counter-Strike_2/Dedicated_Servers",
"https://steamcommunity.com/dev/managegameservers"
],
"requirements": {
"minimumRamMb": 2048,
"recommendedRamMb": 4096,
"minimumStorageMb": 70000,
"requiresSteamGslt": true
} }
}, },
{ {
"id": "fivem", "id": "fivem",
"name": "FiveM", "name": "FiveM",
"description": "Run your FiveM servers with this template", "description": "FiveM GTA V roleplay server template using ich777/fivemserver. The container downloads artifacts automatically, persists server files, and exposes the game, auxiliary and web console ports.",
"defaultPort": 30120, "defaultPort": 30120,
"templateImage": "https://logos-world.net/wp-content/uploads/2021/03/FiveM-Symbol.png", "templateImage": "https://logos-world.net/wp-content/uploads/2021/03/FiveM-Symbol.png",
"docker": { "docker": {
@@ -116,12 +164,25 @@
30110, 30110,
8080 8080
], ],
"portProtocols": {
"8080": [
"tcp"
],
"30110": [
"tcp",
"udp"
],
"30120": [
"tcp",
"udp"
]
},
"volumes": [ "volumes": [
"{BOT_DIR}:/serverdata/serverfiles" "{BOT_DIR}:/serverdata/serverfiles"
], ],
"workdir": "/serverdata/serverfiles", "workdir": "/serverdata/serverfiles",
"env": { "env": {
"DATA_DIR": "/serverdata", "DATA_DIR": "/serverdata/serverfiles",
"SERVER_DIR": "/serverdata/serverfiles", "SERVER_DIR": "/serverdata/serverfiles",
"GAME_CONFIG": "server.cfg", "GAME_CONFIG": "server.cfg",
"SERVER_KEY": "change-me", "SERVER_KEY": "change-me",
@@ -130,12 +191,41 @@
"ENABLE_WEBCONSOLE": "true", "ENABLE_WEBCONSOLE": "true",
"UID": "99", "UID": "99",
"GID": "100", "GID": "100",
"START_VARS": "" "START_VARS": "",
"HOME": "/serverdata/serverfiles",
"DATA_PERM": "777"
},
"command": "",
"adpanelStartup": "",
"startupDisplay": "",
"install": {
"image": "ghcr.io/pterodactyl/installers:debian",
"script": "#!/bin/sh\nset -eu\ncfg=/mnt/server/server.cfg\nserver_port=\"${SERVER_PORT:-${PORT:-30120}}\"\nmkdir -p /mnt/server/resources\nif [ ! -s \"$cfg\" ]; then\n cat > \"$cfg\" <<EOF\nendpoint_add_tcp \"0.0.0.0:${server_port}\"\nendpoint_add_udp \"0.0.0.0:${server_port}\"\nstart mapmanager\nstart chat\nstart spawnmanager\nstart sessionmanager\nstart fivem\nstart hardcap\nstart rconlog\nstart scoreboard\nstart playernames\nsv_scriptHookAllowed 1\nsets tags \"default\"\nsv_endpointprivacy true\nsv_maxclients 32\nEOF\nelse\n if grep -q '^endpoint_add_tcp ' \"$cfg\"; then\n sed -i \"s|^endpoint_add_tcp .*|endpoint_add_tcp \\\"0.0.0.0:${server_port}\\\"|\" \"$cfg\"\n else\n sed -i \"1i endpoint_add_tcp \\\"0.0.0.0:${server_port}\\\"\" \"$cfg\"\n fi\n if grep -q '^endpoint_add_udp ' \"$cfg\"; then\n sed -i \"s|^endpoint_add_udp .*|endpoint_add_udp \\\"0.0.0.0:${server_port}\\\"|\" \"$cfg\"\n else\n sed -i \"1i endpoint_add_udp \\\"0.0.0.0:${server_port}\\\"\" \"$cfg\"\n fi\nfi\nchown -R 99:100 /mnt/server 2>/dev/null || true\nchmod -R a+rwX /mnt/server",
"mountPath": "/mnt/server",
"runtimePath": "/serverdata/serverfiles",
"timeoutSeconds": 600,
"minimumStorageMb": 8192
}, },
"restart": "unless-stopped", "restart": "unless-stopped",
"runAsRoot": true,
"console": { "console": {
"type": "stdin" "type": "stdin",
"targetProcesses": [
"FXServer",
"fxserver"
]
} }
},
"documentation": [
"https://hub.docker.com/r/ich777/fivemserver",
"https://runtime.fivem.net/artifacts/fivem/build_proot_linux/master/",
"https://keymaster.fivem.net/"
],
"requirements": {
"minimumRamMb": 2048,
"recommendedRamMb": 4096,
"minimumStorageMb": 8192,
"requiresServerKey": true
} }
}, },
{ {
@@ -150,6 +240,7 @@
"ports": [ "ports": [
8000 8000
], ],
"portProtocols": {},
"volumes": [ "volumes": [
"{BOT_DIR}:/app" "{BOT_DIR}:/app"
], ],
@@ -158,10 +249,86 @@
"PYTHONUNBUFFERED": "1" "PYTHONUNBUFFERED": "1"
}, },
"command": "python /app/main.py", "command": "python /app/main.py",
"adpanelStartup": "",
"startupDisplay": "",
"install": null,
"restart": "unless-stopped", "restart": "unless-stopped",
"runAsRoot": false,
"console": { "console": {
"type": "stdin" "type": "stdin"
} }
} }
},
{
"id": "ragemp",
"name": "RAGE:MP",
"description": "RAGE Multiplayer server template for GTA V multiplayer projects. It uses bambutz/ragemp, persists /ragemp, and exposes the UDP game port plus the TCP HTTP port.",
"defaultPort": 22005,
"templateImage": "https://cdn.jsdelivr.net/gh/antonndev/ADCDn/ragemp-logo.avif",
"docker": {
"image": "bambutz/ragemp",
"tag": "latest",
"ports": [
22005,
22006
],
"portProtocols": {
"22005": [
"udp"
],
"22006": [
"tcp"
]
},
"volumes": [
"{BOT_DIR}:/ragemp"
],
"workdir": "/ragemp",
"env": {
"RAGEMP_ANNOUNCE": "false",
"RAGEMP_BIND": "0.0.0.0",
"RAGEMP_GAMEMODE": "freeroam",
"RAGEMP_MAXPLAYERS": "500",
"RAGEMP_NAME": "ADPanel RAGE:MP Server",
"RAGEMP_PORT": "22005",
"RAGEMP_LANGUAGE": "en",
"RAGEMP_VOICE_CHAT": "false",
"RAGEMP_CSHARP": "false",
"DOTNET_SYSTEM_GLOBALIZATION_INVARIANT": "1",
"COMPlus_GlobalizationInvariant": "1",
"PATH": "/ragemp/dotnet/runtime:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
"LD_LIBRARY_PATH": "/ragemp/dotnet/runtime:/lib/x86_64-linux-gnu:/usr/lib/x86_64-linux-gnu",
"TZ": "Etc/UTC"
},
"command": "",
"adpanelStartup": "",
"startupDisplay": "",
"install": {
"image": "ghcr.io/pterodactyl/installers:debian",
"script": "#!/bin/sh\nset -eu\nmkdir -p /mnt/server/resources /mnt/server/packages /mnt/server/plugins /mnt/server/maps /mnt/server/dotnet/resources /mnt/server/dotnet/runtime\nif [ ! -f /mnt/server/dotnet/runtime/dotnet ]; then\ncat > /mnt/server/dotnet/runtime/dotnet <<'EOF'\n#!/bin/sh\nexit 0\nEOF\nfi\nif [ ! -f /mnt/server/dotnet/runtime/libssl.so.1.1 ] || [ ! -f /mnt/server/dotnet/runtime/libcrypto.so.1.1 ]; then\n curl -fsSL -o /tmp/libssl1.1.deb http://security.debian.org/debian-security/pool/updates/main/o/openssl/libssl1.1_1.1.1w-0+deb11u5_amd64.deb\n rm -rf /tmp/libssl1.1\n mkdir -p /tmp/libssl1.1\n dpkg-deb -x /tmp/libssl1.1.deb /tmp/libssl1.1\n cp /tmp/libssl1.1/usr/lib/x86_64-linux-gnu/libssl.so.1.1 /mnt/server/dotnet/runtime/libssl.so.1.1\n cp /tmp/libssl1.1/usr/lib/x86_64-linux-gnu/libcrypto.so.1.1 /mnt/server/dotnet/runtime/libcrypto.so.1.1\nfi\ncat > /tmp/adpanel-ragemp-acl.xml <<'EOF'\n<?xml version=\"1.0\"?>\n<acl xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n <group name=\"Everyone\">\n <acl name=\"Default\" />\n <object name=\"user.*\" />\n <object name=\"resource.*\" />\n </group>\n <acl name=\"Default\" />\n</acl>\nEOF\nfor target in /mnt/server/acl.xml /mnt/server/dotnet/acl.xml /mnt/server/dotnet/runtime/acl.xml /mnt/server/resources/acl.xml; do\n if [ ! -f \"$target\" ]; then\n cp /tmp/adpanel-ragemp-acl.xml \"$target\"\n fi\ndone\nchmod +x /mnt/server/dotnet/runtime/dotnet\nchmod -R 777 /mnt/server",
"mountPath": "/mnt/server",
"runtimePath": "/ragemp",
"timeoutSeconds": 1800,
"minimumStorageMb": 2048
},
"restart": "unless-stopped",
"runAsRoot": false,
"console": {
"type": "stdin",
"targetProcesses": [
"ragemp-server",
"ragemp"
]
}
},
"documentation": [
"https://hub.docker.com/r/bambutz/ragemp",
"https://github.com/BamButz/docker-ragemp"
],
"requirements": {
"minimumRamMb": 1024,
"recommendedRamMb": 2048,
"minimumStorageMb": 2048
}
} }
] ]
+233
View File
@@ -0,0 +1,233 @@
package main
import (
"archive/tar"
"bytes"
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"testing"
)
// buildTransferTar produces a tarball in the exact shape handleExportServer
// emits: server files at the root, backups under ".adpanel_backups/", and the
// server meta under ".adpanel_meta/<name>.json". The meta deliberately carries a
// SOURCE-node __diskId to simulate a server that lived on the source's secondary
// disk, which must be stripped by the destination on import.
func buildTransferTar(t *testing.T, name string, sourceMeta map[string]any) []byte {
t.Helper()
var buf bytes.Buffer
tw := tar.NewWriter(&buf)
writeFile := func(tarName string, data []byte) {
hdr := &tar.Header{Name: tarName, Mode: 0o644, Size: int64(len(data)), Typeflag: tar.TypeReg}
if err := tw.WriteHeader(hdr); err != nil {
t.Fatalf("write header %s: %v", tarName, err)
}
if _, err := tw.Write(data); err != nil {
t.Fatalf("write body %s: %v", tarName, err)
}
}
// Server payload file.
writeFile("server.properties", []byte("level-name=world\n"))
// A backup artifact.
writeFile(".adpanel_backups/backup-1.tar.gz", []byte("fake-backup-bytes"))
// Source meta with a stale disk identity.
metaBytes, err := json.Marshal(sourceMeta)
if err != nil {
t.Fatalf("marshal source meta: %v", err)
}
writeFile(".adpanel_meta/"+sanitizeName(name)+".json", metaBytes)
if err := tw.Close(); err != nil {
t.Fatalf("close tar: %v", err)
}
return buf.Bytes()
}
func doImportTar(t *testing.T, a *Agent, name, diskID string, body []byte) (*httptest.ResponseRecorder, map[string]any) {
t.Helper()
url := "/v1/servers/" + name + "/import-tar"
if diskID != "" {
url += "?diskId=" + diskID
}
req := httptest.NewRequest(http.MethodPost, url, bytes.NewReader(body))
rr := httptest.NewRecorder()
a.handleImportTar(rr, req, name)
var parsed map[string]any
_ = json.Unmarshal(rr.Body.Bytes(), &parsed)
return rr, parsed
}
// TestImportTarToDestinationPrimaryStripsSourceDiskId covers the user's first
// scenario: a server is transferred to another node and lands on that node's
// PRIMARY disk. The source's __diskId must be discarded so the server resolves to
// the destination's default volumes/backups roots, not a phantom disk.
func TestImportTarToDestinationPrimaryStripsSourceDiskId(t *testing.T) {
a, vol := newTestAgent(t)
name := "alpha"
// Source meta pretends the server lived on a secondary disk that does NOT
// exist on this destination node.
sourceMeta := map[string]any{
"type": "custom",
"template": "custom",
"__diskId": "disk-source-secondary",
"resources": map[string]any{
"ramMb": float64(2048),
},
}
tarBytes := buildTransferTar(t, name, sourceMeta)
rr, resp := doImportTar(t, a, name, "", tarBytes)
if rr.Code != 200 {
t.Fatalf("import-tar status: got %d body=%s", rr.Code, rr.Body.String())
}
if ok, _ := resp["ok"].(bool); !ok {
t.Fatalf("import-tar not ok: %v", resp)
}
// Files must live on the primary disk.
wantServerDir := filepath.Join(vol, name)
if _, err := os.Stat(filepath.Join(wantServerDir, "server.properties")); err != nil {
t.Fatalf("server file not on primary disk: %v", err)
}
if _, err := os.Stat(filepath.Join(a.backupsDir(), name, "backup-1.tar.gz")); err != nil {
t.Fatalf("backup file not on primary backups root: %v", err)
}
// Meta must have the stale __diskId stripped and NOT re-added for primary.
a.invalidateServerDiskCache(name)
persisted := a.loadMeta(wantServerDir)
if _, present := persisted["__diskId"]; present {
t.Fatalf("__diskId must be absent for a primary-disk import, got %v", persisted["__diskId"])
}
// Non-routing meta must be preserved.
if persisted["template"] != "custom" {
t.Fatalf("template meta not preserved: %v", persisted["template"])
}
// Routing must resolve to the primary disk across a cold cache.
if got := a.diskForServer(name); !(got.Primary || got.ID == primaryDiskID) {
t.Fatalf("server mis-routed after import: got disk %q", got.ID)
}
if got := a.serverDir(name); got != wantServerDir {
t.Fatalf("serverDir after import: got %q want %q", got, wantServerDir)
}
}
// TestImportTarToDestinationSecondaryStampsCorrectDiskId covers the user's second
// scenario: a server (regardless of which disk it lived on at the source) is
// placed on a SECONDARY disk of the destination node. The destination must stamp
// ITS OWN disk id so the panel/node know the server is at
// "<mountPath>/adpanel/volumes/<name>" with backups at
// "<mountPath>/adpanel/backups/<name>".
func TestImportTarToDestinationSecondaryStampsCorrectDiskId(t *testing.T) {
a, _ := newTestAgent(t)
mount := t.TempDir()
dest := registerTestDisk(t, a, mount, 50)
name := "beta"
sourceMeta := map[string]any{
"type": "custom",
"template": "custom",
// A different, source-only disk id that must be replaced.
"__diskId": "disk-source-foreign",
}
tarBytes := buildTransferTar(t, name, sourceMeta)
rr, resp := doImportTar(t, a, name, dest.ID, tarBytes)
if rr.Code != 200 {
t.Fatalf("import-tar status: got %d body=%s", rr.Code, rr.Body.String())
}
if resp["diskId"] != dest.ID {
t.Fatalf("import-tar reported diskId %v want %q", resp["diskId"], dest.ID)
}
// Files must live under the destination secondary disk's layout.
wantServerDir := filepath.Join(a.diskLayoutVolumes(mount), name)
if _, err := os.Stat(filepath.Join(wantServerDir, "server.properties")); err != nil {
t.Fatalf("server file not on secondary disk volumes root: %v", err)
}
wantBackupDir := filepath.Join(a.diskLayoutBackups(mount), name)
if _, err := os.Stat(filepath.Join(wantBackupDir, "backup-1.tar.gz")); err != nil {
t.Fatalf("backup file not on secondary disk backups root: %v", err)
}
// Meta must record the DESTINATION disk id, never the source's.
persisted := a.loadMeta(wantServerDir)
if id, _ := persisted["__diskId"].(string); id != dest.ID {
t.Fatalf("__diskId after import: got %q want %q (must not keep source id)", id, dest.ID)
}
// Routing must resolve to the destination secondary disk across a cold cache.
a.invalidateServerDiskCache(name)
if got := a.diskForServer(name); got.ID != dest.ID {
t.Fatalf("server mis-routed after import: got disk %q want %q", got.ID, dest.ID)
}
if got := a.serverDir(name); got != wantServerDir {
t.Fatalf("serverDir after import: got %q want %q", got, wantServerDir)
}
if got := a.serverBackupsDir(name); got != wantBackupDir {
t.Fatalf("serverBackupsDir after import: got %q want %q", got, wantBackupDir)
}
}
// TestImportTarRejectsUnknownDiskId ensures a transfer that targets a disk this
// node does not own fails fast instead of silently extracting to the wrong place.
func TestImportTarRejectsUnknownDiskId(t *testing.T) {
a, _ := newTestAgent(t)
name := "gamma"
tarBytes := buildTransferTar(t, name, map[string]any{"type": "custom"})
rr, resp := doImportTar(t, a, name, "disk-does-not-exist", tarBytes)
if rr.Code != 400 {
t.Fatalf("expected 400 for unknown diskId, got %d body=%s", rr.Code, rr.Body.String())
}
if ok, _ := resp["ok"].(bool); ok {
t.Fatalf("expected ok=false for unknown diskId, got %v", resp)
}
}
// TestImportTarReimportClearsStaleSecondaryRouting guards a re-transfer: a server
// previously routed to a secondary disk that is then re-imported onto the primary
// disk must not retain the old secondary __diskId.
func TestImportTarReimportClearsStaleSecondaryRouting(t *testing.T) {
a, vol := newTestAgent(t)
mount := t.TempDir()
dest := registerTestDisk(t, a, mount, 50)
name := "delta"
// First import onto the secondary disk.
first := buildTransferTar(t, name, map[string]any{"type": "custom", "__diskId": "disk-source"})
if rr, _ := doImportTar(t, a, name, dest.ID, first); rr.Code != 200 {
t.Fatalf("first import failed: %d %s", rr.Code, rr.Body.String())
}
if got := a.diskForServer(name); got.ID != dest.ID {
t.Fatalf("after first import expected secondary disk, got %q", got.ID)
}
// Re-import onto the primary disk; routing/meta must follow the new target.
second := buildTransferTar(t, name, map[string]any{"type": "custom", "__diskId": dest.ID})
if rr, _ := doImportTar(t, a, name, "", second); rr.Code != 200 {
t.Fatalf("second import failed: %d %s", rr.Code, rr.Body.String())
}
wantServerDir := filepath.Join(vol, name)
a.invalidateServerDiskCache(name)
if got := a.serverDir(name); got != wantServerDir {
t.Fatalf("serverDir after re-import to primary: got %q want %q", got, wantServerDir)
}
persisted := a.loadMeta(wantServerDir)
if _, present := persisted["__diskId"]; present {
t.Fatalf("__diskId must be cleared on re-import to primary, got %v", persisted["__diskId"])
}
// The secondary-disk copy must no longer be the routing target.
if got := a.diskForServer(name); !(got.Primary || got.ID == primaryDiskID) {
t.Fatalf("re-import did not re-route to primary, got %q", got.ID)
}
}
+1 -3
View File
@@ -1654,9 +1654,6 @@ function createDashboardAssistantToolRunner(deps) {
} }
let sanitizedDocker = sanitizeDockerTemplatePayload(template.docker); let sanitizedDocker = sanitizeDockerTemplatePayload(template.docker);
if (sanitizedDocker && Array.isArray(sanitizedDocker.ports) && sanitizedDocker.ports.length > 1) {
sanitizedDocker.ports = [sanitizedDocker.ports[0]];
}
const payload = { const payload = {
name, name,
@@ -1717,6 +1714,7 @@ function createDashboardAssistantToolRunner(deps) {
volumes: sanitizedDocker.volumes, volumes: sanitizedDocker.volumes,
env: sanitizedDocker.env, env: sanitizedDocker.env,
ports: sanitizedDocker.ports, ports: sanitizedDocker.ports,
portProtocols: sanitizedDocker.portProtocols,
}; };
} }
+501
View File
@@ -0,0 +1,501 @@
"use strict";
/**
* Panel metrics collector for the admin-only /status monitoring page.
*
* Design goals (best-practice, ultra-low overhead):
* - Collect host + panel-process resource usage (CPU, RAM, storage) cheaply
* using only Node core modules (os, fs) plus a single `pm2 jlist` poll for
* aggregate Node/PM2 network counters. No heavy native deps.
* - Live data lives in RAM. We only run the intensive 1s sampling loop while at
* least one admin is actually watching the page (driven by socket room size).
* When nobody watches, the loop stops -> zero ongoing cost.
* - Persistence is RRD-like: one row per minute in `panel_metrics`. A monthly
* cleanup keeps the table at a fixed, small size (~31 days). Writes happen
* once per minute (averaged), never per second.
* - All reads are wrapped so a transient failure never throws into the loop.
*
* This module is intentionally framework-agnostic: index.js wires it to the
* existing socket.io server, admin auth, and MySQL pool.
*/
const os = require("os");
const fsp = require("fs/promises");
const { execFile } = require("child_process");
// ---------------------------------------------------------------------------
// Tunables (overridable via env, sane defaults for cheap VPS).
// ---------------------------------------------------------------------------
const LIVE_SAMPLE_MS = clampInt(process.env.PANEL_METRICS_LIVE_MS, 1000, 250, 10000);
const PERSIST_INTERVAL_MS = clampInt(process.env.PANEL_METRICS_PERSIST_MS, 60_000, 10_000, 600_000);
const RETENTION_DAYS = clampInt(process.env.PANEL_METRICS_RETENTION_DAYS, 31, 7, 366);
const PM2_POLL_MS = clampInt(process.env.PANEL_METRICS_PM2_MS, 5000, 2000, 60_000);
const CLEANUP_INTERVAL_MS = 6 * 60 * 60 * 1000; // run retention sweep 4x/day
function clampInt(value, def, min, max) {
const n = parseInt(value, 10);
if (!Number.isFinite(n)) return def;
return Math.min(Math.max(n, min), max);
}
function nowMs() {
return Date.now();
}
// ---------------------------------------------------------------------------
// CPU sampling: delta of os.cpus() times between two reads -> busy percentage.
// Cheap: a single os.cpus() call (reads /proc/stat once on Linux).
// ---------------------------------------------------------------------------
function cpuTotals() {
const cpus = os.cpus() || [];
let idle = 0;
let total = 0;
for (const c of cpus) {
const t = c.times;
idle += t.idle;
total += t.user + t.nice + t.sys + t.idle + t.irq;
}
return { idle, total, cores: cpus.length || 1 };
}
// ---------------------------------------------------------------------------
// Storage: usage of the filesystem holding the panel working directory.
// Uses statfs when available (Node >= 18.15), else falls back to null.
// ---------------------------------------------------------------------------
async function readStorage() {
try {
if (typeof fsp.statfs === "function") {
const s = await fsp.statfs(process.cwd());
const total = s.blocks * s.bsize;
const free = s.bfree * s.bsize;
const used = total - free;
if (total > 0) {
return { usedBytes: used, totalBytes: total, percent: round1((used / total) * 100) };
}
}
} catch (_) { /* ignore */ }
return { usedBytes: null, totalBytes: null, percent: null };
}
function round1(n) {
return Math.round(n * 10) / 10;
}
// ---------------------------------------------------------------------------
// PM2 network counters. `pm2 jlist` exposes per-process monit + env; PM2 does
// not natively expose net bytes, so we read aggregate NIC counters from
// /proc/net/dev (sum of all non-loopback interfaces) and derive a per-second
// rate from deltas. This reflects the whole Node/PM2 host traffic, which is the
// closest reliable "panel network" signal without per-socket accounting.
// ---------------------------------------------------------------------------
async function readNetCounters() {
try {
const raw = await fsp.readFile("/proc/net/dev", "utf8");
let rx = 0;
let tx = 0;
const lines = raw.split("\n");
for (const line of lines) {
const idx = line.indexOf(":");
if (idx === -1) continue;
const iface = line.slice(0, idx).trim();
if (!iface || iface === "lo") continue;
const parts = line.slice(idx + 1).trim().split(/\s+/);
if (parts.length < 9) continue;
rx += Number(parts[0]) || 0; // bytes received
tx += Number(parts[8]) || 0; // bytes transmitted
}
return { rxBytes: rx, txBytes: tx };
} catch (_) {
return { rxBytes: null, txBytes: null };
}
}
function pm2List() {
return new Promise((resolve) => {
try {
execFile("pm2", ["jlist"], { timeout: 4000, maxBuffer: 4 * 1024 * 1024 }, (err, stdout) => {
if (err || !stdout) return resolve(null);
try {
resolve(JSON.parse(stdout));
} catch (_) {
resolve(null);
}
});
} catch (_) {
resolve(null);
}
});
}
// ---------------------------------------------------------------------------
// Collector
// ---------------------------------------------------------------------------
class PanelMetricsCollector {
constructor(options = {}) {
this.db = options.db || null; // { query }
this.io = options.io || null; // socket.io server
this.room = options.room || "monitor";
this.startTime = options.startTime || nowMs();
this.panelVersion = options.panelVersion || null;
this.getServiceStatus = typeof options.getServiceStatus === "function"
? options.getServiceStatus
: async () => ({});
// Live state
this._prevCpu = cpuTotals();
this._prevNet = null;
this._prevNetAt = 0;
this._reqCounter = 0; // incremented by middleware
this._prevReqCount = 0;
this._prevReqAt = nowMs();
this._pm2Cache = { at: 0, data: null };
this._svcCache = { at: 0, data: null };
this._svcTtlMs = clampInt(process.env.PANEL_METRICS_SVC_MS, 5000, 2000, 60_000);
// Minute-accumulator for persistence (average over the window)
this._acc = this._freshAcc();
// Timers
this._liveTimer = null;
this._persistTimer = null;
this._cleanupTimer = null;
this._lastSample = null;
}
_freshAcc() {
return {
count: 0,
cpu: 0,
memUsed: 0,
memTotal: 0,
diskUsed: 0,
diskTotal: 0,
netRx: 0,
netTx: 0,
rps: 0,
};
}
/**
* The request counter (`_reqCounter`) is incremented directly by a tiny
* Express middleware in index.js (one integer add per request, no allocation).
* The collector only reads/diffs it; it never touches the hot request path
* beyond that single increment.
*/
start() {
// Persistence + cleanup always run (cheap, once per minute / few hours).
if (!this._persistTimer) {
this._persistTimer = setInterval(() => this._persist().catch(() => {}), PERSIST_INTERVAL_MS);
this._persistTimer.unref?.();
}
if (!this._cleanupTimer) {
// Run once shortly after boot, then on interval.
setTimeout(() => this._cleanup().catch(() => {}), 30_000).unref?.();
this._cleanupTimer = setInterval(() => this._cleanup().catch(() => {}), CLEANUP_INTERVAL_MS);
this._cleanupTimer.unref?.();
}
// Drive the live loop from room occupancy.
this._refreshLiveLoop();
}
stop() {
for (const t of [this._liveTimer, this._persistTimer, this._cleanupTimer]) {
if (t) clearInterval(t);
}
this._liveTimer = this._persistTimer = this._cleanupTimer = null;
}
/** Called by index.js whenever a client joins/leaves the monitor room. */
onRoomChange() {
this._refreshLiveLoop();
}
_watcherCount() {
try {
const room = this.io?.sockets?.adapter?.rooms?.get(this.room);
return room ? room.size : 0;
} catch (_) {
return 0;
}
}
_refreshLiveLoop() {
const watching = this._watcherCount() > 0;
if (watching && !this._liveTimer) {
// Prime baselines so the first emitted sample is sane.
this._prevCpu = cpuTotals();
this._liveTimer = setInterval(() => this._tick().catch(() => {}), LIVE_SAMPLE_MS);
this._liveTimer.unref?.();
// Emit one immediately.
this._tick().catch(() => {});
} else if (!watching && this._liveTimer) {
clearInterval(this._liveTimer);
this._liveTimer = null;
}
}
async _readPm2() {
const now = nowMs();
if (this._pm2Cache.data && (now - this._pm2Cache.at) < PM2_POLL_MS) {
return this._pm2Cache.data;
}
const list = await pm2List();
let memBytes = 0;
let cpuPercent = 0;
let found = false;
if (Array.isArray(list)) {
for (const proc of list) {
const monit = proc?.monit || {};
if (typeof monit.memory === "number") memBytes += monit.memory;
if (typeof monit.cpu === "number") cpuPercent += monit.cpu;
found = true;
}
}
const data = found ? { memBytes, cpuPercent: round1(cpuPercent) } : null;
this._pm2Cache = { at: now, data };
return data;
}
/** Build one live sample (cheap). */
async _collect() {
const now = nowMs();
// CPU (host) via delta
const cur = cpuTotals();
let cpuPercent = 0;
const idleDiff = cur.idle - this._prevCpu.idle;
const totalDiff = cur.total - this._prevCpu.total;
if (totalDiff > 0) {
cpuPercent = round1((1 - idleDiff / totalDiff) * 100);
if (cpuPercent < 0) cpuPercent = 0;
if (cpuPercent > 100) cpuPercent = 100;
}
this._prevCpu = cur;
// Memory (host)
const memTotal = os.totalmem();
const memFree = os.freemem();
const memUsed = memTotal - memFree;
// Storage
const storage = await readStorage();
// Network rate (bytes/sec) from /proc/net/dev deltas
const net = await readNetCounters();
let rxRate = null;
let txRate = null;
if (net.rxBytes != null && this._prevNet && this._prevNetAt) {
const dt = (now - this._prevNetAt) / 1000;
if (dt > 0) {
rxRate = Math.max(0, Math.round((net.rxBytes - this._prevNet.rxBytes) / dt));
txRate = Math.max(0, Math.round((net.txBytes - this._prevNet.txBytes) / dt));
}
}
if (net.rxBytes != null) {
this._prevNet = net;
this._prevNetAt = now;
}
// RPS from request counter delta
const dtReq = (now - this._prevReqAt) / 1000;
let rps = 0;
if (dtReq > 0) {
rps = round1((this._reqCounter - this._prevReqCount) / dtReq);
if (rps < 0) rps = 0;
}
this._prevReqCount = this._reqCounter;
this._prevReqAt = now;
// PM2 process aggregate (cached)
const pm2 = await this._readPm2();
const sample = {
ts: now,
cpu: cpuPercent,
cores: cur.cores,
memUsed,
memTotal,
memPercent: memTotal > 0 ? round1((memUsed / memTotal) * 100) : 0,
diskUsed: storage.usedBytes,
diskTotal: storage.totalBytes,
diskPercent: storage.percent,
netRx: rxRate,
netTx: txRate,
rps,
pm2MemBytes: pm2 ? pm2.memBytes : null,
pm2Cpu: pm2 ? pm2.cpuPercent : null,
uptimeMs: now - this.startTime,
};
// Feed the minute accumulator (averages).
const a = this._acc;
a.count++;
a.cpu += sample.cpu;
a.memUsed += sample.memUsed;
a.memTotal += sample.memTotal;
if (sample.diskUsed != null) a.diskUsed += sample.diskUsed;
if (sample.diskTotal != null) a.diskTotal += sample.diskTotal;
if (sample.netRx != null) a.netRx += sample.netRx;
if (sample.netTx != null) a.netTx += sample.netTx;
a.rps += sample.rps;
this._lastSample = sample;
return sample;
}
async _services() {
const now = nowMs();
if (this._svcCache.data && (now - this._svcCache.at) < this._svcTtlMs) {
return this._svcCache.data;
}
let data = {};
try {
data = await this.getServiceStatus();
} catch (_) {
data = {};
}
this._svcCache = { at: now, data };
return data;
}
async _tick() {
const sample = await this._collect();
if (!this.io) return;
const services = await this._services();
this.io.to(this.room).emit("monitor:sample", { ...sample, services });
}
/** Persist one averaged row per minute. */
async _persist() {
if (!this.db || typeof this.db.query !== "function") return;
const a = this._acc;
this._acc = this._freshAcc();
let row;
if (a.count > 0) {
row = {
cpu: round1(a.cpu / a.count),
memPercent: a.memTotal > 0 ? round1((a.memUsed / a.memTotal) * 100) : 0,
diskPercent: a.diskTotal > 0 ? round1((a.diskUsed / a.diskTotal) * 100) : 0,
netRx: Math.round(a.netRx / a.count),
netTx: Math.round(a.netTx / a.count),
rps: round1(a.rps / a.count),
};
} else {
// No live watchers this window: take one cheap point-in-time read so the
// history graph stays continuous without running the 1s loop.
const s = await this._collect();
// Reset accumulator again (the collect above pushed into it).
this._acc = this._freshAcc();
row = {
cpu: s.cpu,
memPercent: s.memPercent,
diskPercent: s.diskPercent ?? 0,
netRx: s.netRx ?? 0,
netTx: s.netTx ?? 0,
rps: s.rps,
};
}
try {
const d = new Date();
// Bucket to the minute (UTC) for a stable RRD-style key.
const bucket = Math.floor(d.getTime() / 60000) * 60000;
await this.db.query(
`INSERT INTO panel_metrics
(bucket_ts, cpu_percent, mem_percent, disk_percent, net_rx_bps, net_tx_bps, rps)
VALUES (?, ?, ?, ?, ?, ?, ?)
ON DUPLICATE KEY UPDATE
cpu_percent = VALUES(cpu_percent),
mem_percent = VALUES(mem_percent),
disk_percent = VALUES(disk_percent),
net_rx_bps = VALUES(net_rx_bps),
net_tx_bps = VALUES(net_tx_bps),
rps = VALUES(rps)`,
[bucket, row.cpu, row.memPercent, row.diskPercent, row.netRx, row.netTx, row.rps]
);
} catch (err) {
// Never let persistence crash the loop.
if (!String(err && err.message).includes("panel_metrics")) {
// table missing or transient; stay silent in prod, log once otherwise.
}
}
}
/** Retention sweep: drop anything older than RETENTION_DAYS. */
async _cleanup() {
if (!this.db || typeof this.db.query !== "function") return;
try {
const cutoff = nowMs() - RETENTION_DAYS * 24 * 60 * 60 * 1000;
await this.db.query("DELETE FROM panel_metrics WHERE bucket_ts < ?", [cutoff]);
} catch (_) { /* ignore */ }
}
/** Admin REST: fetch history rows for a given UTC day (YYYY-MM-DD). */
async getHistoryForDay(dayStr) {
if (!this.db || typeof this.db.query !== "function") return [];
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(String(dayStr || ""));
if (!m) return [];
const start = Date.UTC(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 0, 0, 0);
const end = start + 24 * 60 * 60 * 1000;
const rows = await this.db.query(
`SELECT bucket_ts, cpu_percent, mem_percent, disk_percent, net_rx_bps, net_tx_bps, rps
FROM panel_metrics
WHERE bucket_ts >= ? AND bucket_ts < ?
ORDER BY bucket_ts ASC`,
[start, end]
);
return (rows || []).map((r) => ({
ts: Number(r.bucket_ts),
cpu: Number(r.cpu_percent),
mem: Number(r.mem_percent),
disk: Number(r.disk_percent),
netRx: Number(r.net_rx_bps),
netTx: Number(r.net_tx_bps),
rps: Number(r.rps),
}));
}
/** Admin REST: daily averages across the retained window (for the calendar). */
async getDailySummary() {
if (!this.db || typeof this.db.query !== "function") return [];
const cutoff = nowMs() - RETENTION_DAYS * 24 * 60 * 60 * 1000;
const rows = await this.db.query(
`SELECT
FLOOR(bucket_ts / 86400000) AS day_idx,
AVG(cpu_percent) AS cpu,
AVG(mem_percent) AS mem,
AVG(disk_percent) AS disk,
AVG(net_rx_bps) AS net_rx,
AVG(net_tx_bps) AS net_tx,
AVG(rps) AS rps,
COUNT(*) AS samples
FROM panel_metrics
WHERE bucket_ts >= ?
GROUP BY day_idx
ORDER BY day_idx ASC`,
[cutoff]
);
return (rows || []).map((r) => ({
ts: Number(r.day_idx) * 86400000,
cpu: round1(Number(r.cpu)),
mem: round1(Number(r.mem)),
disk: round1(Number(r.disk)),
netRx: Math.round(Number(r.net_rx)),
netTx: Math.round(Number(r.net_tx)),
rps: round1(Number(r.rps)),
samples: Number(r.samples),
}));
}
/** Current snapshot for the initial REST hydrate when a watcher opens. */
async getSnapshot() {
const sample = this._lastSample || (await this._collect());
const services = await this._services();
return { ...sample, services, panelVersion: this.panelVersion, startTime: this.startTime };
}
}
module.exports = { PanelMetricsCollector };
+206 -35
View File
@@ -2,6 +2,152 @@
const { getTechnicalServerName } = require("./server-name"); const { getTechnicalServerName } = require("./server-name");
function isRemoteMissingResponse(response) {
const status = Number(response?.status || 0);
if (status === 404 || status === 410) return true;
const raw = String(response?.json?.error || response?.json?.detail || response?.json?.message || "").toLowerCase();
return raw.includes("not found") || raw.includes("not exist") || raw.includes("no such server") || raw.includes("no such container");
}
async function remoteServerExists(deps, baseUrl, headers, technicalName, timeoutMs = 8000) {
const response = await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}`,
"GET",
headers,
null,
timeoutMs
);
if (response.status === 200 && response.json && (response.json.ok === true || response.json.name || response.json.status)) {
return true;
}
if (isRemoteMissingResponse(response)) return false;
return null;
}
function deleteStatusShowsActiveGone(response) {
const body = response?.json || {};
return response?.status === 200 &&
body.deleteStatus === true &&
(body.deleted === true || (
body.containerExists === false &&
body.serverDirExists === false &&
body.metaExists === false &&
body.backupsDirExists === false
));
}
async function waitForRemoteDeleteConfirmation(deps, baseUrl, headers, technicalName, timeoutMs = 3_000) {
const deadline = Date.now() + timeoutMs;
while (Date.now() < deadline) {
const timeout = Math.min(1200, Math.max(500, deadline - Date.now()));
const status = await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/delete-status`,
"GET",
headers,
null,
timeout
).catch(() => null);
if (deleteStatusShowsActiveGone(status)) return true;
const exists = await remoteServerExists(deps, baseUrl, headers, technicalName, timeout).catch(() => null);
if (exists === false) return true;
await new Promise((resolve) => setTimeout(resolve, 250));
}
return false;
}
async function requestRemoteDeleteAndConfirm(deps, { name, technicalName, baseUrl, headers, timeoutMs = 3_000 }) {
try {
await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 3_000);
} catch {
}
const response = await deps.httpRequestJson(
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}?async=true&force=true&brutal=true`,
"DELETE",
headers,
null,
6_000
);
if (isRemoteMissingResponse(response)) return { accepted: true, confirmed: true };
if (!((response.status === 200 || response.status === 202) && response.json && response.json.ok) && response.status !== 0) {
const message = response.json && (response.json.error || response.json.detail || response.json.message)
? (response.json.error || response.json.detail || response.json.message)
: `remote delete failed (${response.status})`;
console.warn(`[delete] Remote delete request for ${name} did not complete cleanly: ${message}`);
return { accepted: false, confirmed: false };
}
const confirmed = await waitForRemoteDeleteConfirmation(deps, baseUrl, headers, technicalName, timeoutMs);
return { accepted: true, confirmed };
}
function withTimeout(promise, ms, label = "timeout") {
let timer;
return Promise.race([
Promise.resolve(promise),
new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(label)), ms);
}),
]).finally(() => clearTimeout(timer));
}
function queueRemoteDelete(deps, { name, technicalName, baseUrl, headers }) {
setImmediate(async () => {
try {
try {
await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 3_000);
console.log(`[delete] Force-stopped server ${name}`);
} catch (error) {
console.log(`[delete] Could not force-stop server ${name} (may already be stopped): ${error.message}`);
}
const response = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}?async=true&force=true&brutal=true`, "DELETE", headers, null, 8_000);
if ((response.status === 200 || response.status === 202) && response.json && response.json.ok) {
console.log(`[delete] Remote delete queued for ${name} on node.`);
return;
}
if (isRemoteMissingResponse(response)) {
console.log(`[delete] Remote server ${name} is already gone.`);
return;
}
if (response.status === 0) {
const exists = await remoteServerExists(deps, baseUrl, headers, technicalName, 8_000);
if (exists === false) {
console.log(`[delete] Remote delete for ${name} timed out, but follow-up check confirms it is gone.`);
return;
}
}
const message = response.json && (response.json.error || response.json.detail)
? (response.json.error || response.json.detail)
: `remote delete failed (${response.status})`;
console.warn(`[delete] Background remote delete for ${name} did not complete cleanly: ${message}`);
} catch (error) {
console.warn(`[delete] Background remote delete failed for ${name}: ${error?.message || error}`);
}
});
}
function deleteNameCandidates(entry, requestedName, technicalName) {
const values = [
technicalName,
entry?.bot,
entry?.legacyId,
entry?.legacy_id,
entry?.name,
entry?.id,
requestedName,
];
const out = [];
const seen = new Set();
for (const value of values) {
const clean = String(value || "").trim();
if (!clean || seen.has(clean)) continue;
seen.add(clean);
out.push(clean);
}
return out;
}
async function deleteServerByName(deps, rawName) { async function deleteServerByName(deps, rawName) {
if (!deps || typeof deps !== "object") { if (!deps || typeof deps !== "object") {
throw new Error("Server delete dependencies are required."); throw new Error("Server delete dependencies are required.");
@@ -45,49 +191,74 @@ async function deleteServerByName(deps, rawName) {
const headers = deps.nodeAuthHeadersFor(node, true); const headers = deps.nodeAuthHeadersFor(node, true);
try { if (typeof deps.markServerDeletingStatus === "function") {
await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/kill`, "POST", headers, null, 30_000); await withTimeout(deps.markServerDeletingStatus(name), 5000, "mark-delete-status-timeout").catch((error) => {
console.log(`[delete] Force-stopped server ${name}`); console.warn(`[delete] Could not mark ${name} as deleting: ${error?.message || error}`);
} catch (error) { });
console.log(`[delete] Could not force-stop server ${name} (may already be stopped): ${error.message}`);
} }
try { let deleteAccepted = false;
const backupsRes = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/backups`, "GET", headers, null, 10_000); let confirmedDeleted = false;
if (backupsRes.status === 200 && backupsRes.json?.backups) { let attemptedName = technicalName;
for (const backup of backupsRes.json.backups) { for (const candidate of deleteNameCandidates(entry, name, technicalName)) {
if (!backup?.id) continue; attemptedName = candidate;
await deps.httpRequestJson( const outcome = await requestRemoteDeleteAndConfirm(deps, {
`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}/backups/${encodeURIComponent(backup.id)}`, name,
"DELETE", technicalName: candidate,
baseUrl,
headers, headers,
null, timeoutMs: 3_000,
30_000 }).catch((error) => {
); console.warn(`[delete] Could not confirm remote delete for ${name} using ${candidate}: ${error?.message || error}`);
console.log(`[delete] Deleted backup ${backup.id} for server ${name}`); return { accepted: false, confirmed: false };
} });
} deleteAccepted = !!outcome.accepted;
} catch (error) { confirmedDeleted = !!outcome.confirmed;
console.log(`[delete] Could not delete backups for ${name}: ${error.message}`); if (confirmedDeleted) break;
} if (deleteAccepted) break;
await deps.deleteServerSchedules(name);
const response = await deps.httpRequestJson(`${baseUrl}/v1/servers/${encodeURIComponent(technicalName)}`, "DELETE", headers, null, 60_000);
if (response.status !== 200 || !(response.json && response.json.ok)) {
const message = response.json && (response.json.error || response.json.detail)
? (response.json.error || response.json.detail)
: `remote delete failed (${response.status})`;
return { ok: false, statusCode: 502, error: message };
} }
if (confirmedDeleted) {
await withTimeout(deps.deleteServerSchedules(name), 5000, "delete-schedules-timeout").catch((error) => {
console.warn(`[delete] Could not clean schedules for ${name}: ${error?.message || error}`);
});
try { try {
await deps.removeAccessForServerName(name); await withTimeout(deps.removeAccessForServerName(name), 5000, "delete-access-timeout");
} catch { } catch (error) {
console.warn(`[delete] Could not remove access rows for ${name}: ${error?.message || error}`);
}
await withTimeout(deps.removeServerIndexEntry(name), 8000, "delete-index-timeout");
return {
ok: true,
remote: true,
deleted: true,
queued: false,
};
} }
await deps.removeServerIndexEntry(name); if (typeof deps.enqueueServerDeleteJob === "function") {
return { ok: true, remote: true }; await deps.enqueueServerDeleteJob({ name, technicalName: attemptedName, node });
if (typeof deps.kickServerDeleteWorker === "function") deps.kickServerDeleteWorker();
} else {
queueRemoteDelete(deps, { name, technicalName: attemptedName, baseUrl, headers });
}
withTimeout(deps.deleteServerSchedules(name), 5000, "delete-schedules-timeout").catch((error) => {
console.warn(`[delete] Could not clean schedules for ${name}: ${error?.message || error}`);
});
if (typeof deps.removeAccessForServerName === "function") {
withTimeout(deps.removeAccessForServerName(name), 5000, "delete-access-timeout").catch((error) => {
console.warn(`[delete] Could not remove access rows for ${name}: ${error?.message || error}`);
});
}
return {
ok: true,
remote: true,
deleting: true,
queued: true,
accepted: deleteAccepted,
};
} }
module.exports = { module.exports = {
+1 -1
View File
@@ -406,7 +406,7 @@ function buildDefaultStartupCommand({ name, templateId, docker, hostPort, resour
const serverName = cleanString(name) || "{SERVER_NAME}"; const serverName = cleanString(name) || "{SERVER_NAME}";
const externalPort = toPositiveNumber(hostPort); const externalPort = toPositiveNumber(hostPort);
const containerPort = getContainerPort(normalizedTemplateId, docker, hostPort); const containerPort = getContainerPort(normalizedTemplateId, docker, hostPort);
const parts = ["docker run -d -t", "--name", serverName, "--restart", cleanString(docker?.restart) || "unless-stopped"]; const parts = ["docker run -d -i -t", "--name", serverName, "--restart", cleanString(docker?.restart) || "unless-stopped"];
parts.push(...buildResourceArgs(resources)); parts.push(...buildResourceArgs(resources));
+67 -6
View File
@@ -1,5 +1,7 @@
"use strict"; "use strict";
const POLLUTION_KEYS = new Set(["__proto__", "constructor", "prototype"]);
function cleanString(value) { function cleanString(value) {
return String(value ?? "").trim(); return String(value ?? "").trim();
} }
@@ -17,6 +19,41 @@ function toFiniteNumber(value) {
return Number.isFinite(numeric) ? numeric : null; return Number.isFinite(numeric) ? numeric : null;
} }
function normalizePortProtocol(value) {
const protocol = cleanString(value).toLowerCase();
return protocol === "tcp" || protocol === "udp" || protocol === "sctp" ? protocol : "";
}
function sanitizePortProtocolPayload(portProtocols, ports = []) {
if (!portProtocols || typeof portProtocols !== "object" || Array.isArray(portProtocols)) return null;
const allowedPorts = new Set(
(Array.isArray(ports) ? ports : [])
.map((entry) => toFiniteNumber(entry))
.filter((entry) => Number.isInteger(entry) && entry > 0)
.map((entry) => String(entry))
);
const out = {};
for (const [rawPort, rawProtocols] of Object.entries(portProtocols)) {
const port = toFiniteNumber(rawPort);
if (!Number.isInteger(port) || port < 1 || port > 65535) continue;
const portKey = String(port);
if (allowedPorts.size && !allowedPorts.has(portKey)) continue;
const source = Array.isArray(rawProtocols) ? rawProtocols : [rawProtocols];
const protocols = [];
const seen = new Set();
for (const entry of source) {
const protocol = normalizePortProtocol(entry);
if (!protocol || seen.has(protocol)) continue;
seen.add(protocol);
protocols.push(protocol);
}
if (protocols.length) out[portKey] = protocols;
}
return Object.keys(out).length ? out : null;
}
function cleanAbsoluteContainerPath(value, fallback = "") { function cleanAbsoluteContainerPath(value, fallback = "") {
let raw = cleanString(value).replace(/\0/g, "").replace(/\\/g, "/"); let raw = cleanString(value).replace(/\0/g, "").replace(/\\/g, "/");
if (!raw) return fallback; if (!raw) return fallback;
@@ -31,6 +68,7 @@ function sanitizeEnvPayload(env) {
const out = {}; const out = {};
for (const [key, value] of Object.entries(env)) { for (const [key, value] of Object.entries(env)) {
const envKey = cleanString(key); const envKey = cleanString(key);
if (POLLUTION_KEYS.has(envKey)) continue;
if (!envKey) continue; if (!envKey) continue;
out[envKey] = String(value ?? ""); out[envKey] = String(value ?? "");
} }
@@ -44,7 +82,6 @@ function sanitizeDockerInstallPayload(install) {
if (!script) return null; if (!script) return null;
const image = cleanString(install.image || install.container) || "ghcr.io/pterodactyl/installers:debian"; const image = cleanString(install.image || install.container) || "ghcr.io/pterodactyl/installers:debian";
const entrypoint = cleanString(install.entrypoint) || "bash";
const mountPath = cleanAbsoluteContainerPath( const mountPath = cleanAbsoluteContainerPath(
install.mountPath || install.containerPath || install.container_path || install.serverPath, install.mountPath || install.containerPath || install.container_path || install.serverPath,
"/mnt/server" "/mnt/server"
@@ -54,24 +91,26 @@ function sanitizeDockerInstallPayload(install) {
"/home/container" "/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 minimumStorageRaw = toFiniteNumber(install.minimumStorageMb || install.minimum_storage_mb);
const minimumStorageMb = minimumStorageRaw && minimumStorageRaw > 0 const minimumStorageMb = minimumStorageRaw && minimumStorageRaw > 0
? Math.max(1, Math.min(Math.trunc(minimumStorageRaw), 1024 * 1024)) ? Math.max(1, Math.min(Math.trunc(minimumStorageRaw), 1024 * 1024))
: 0; : 0;
const timeoutRaw = toFiniteNumber(install.timeoutSeconds || install.timeout_seconds);
const timeoutSeconds = timeoutRaw && timeoutRaw > 0
? Math.max(60, Math.min(Math.trunc(timeoutRaw), 7200))
: 1800;
const payload = { const payload = {
image, image,
script, script,
entrypoint,
mountPath, mountPath,
runtimePath, runtimePath,
timeoutSeconds, timeoutSeconds,
}; };
if (minimumStorageMb > 0) payload.minimumStorageMb = minimumStorageMb; if (minimumStorageMb > 0) payload.minimumStorageMb = minimumStorageMb;
if (install.allowEmpty === true || install.allowEmptyResult === true) {
payload.allowEmpty = true;
}
const env = sanitizeEnvPayload(install.env); const env = sanitizeEnvPayload(install.env);
if (env) payload.env = env; if (env) payload.env = env;
@@ -104,6 +143,10 @@ function sanitizeDockerTemplatePayload(docker) {
const restartPolicy = cleanString(docker.restartPolicy); const restartPolicy = cleanString(docker.restartPolicy);
if (restartPolicy) payload.restartPolicy = restartPolicy; if (restartPolicy) payload.restartPolicy = restartPolicy;
if (docker.runAsRoot === true || docker.run_as_root === true) {
payload.runAsRoot = true;
}
const ports = Array.isArray(docker.ports) const ports = Array.isArray(docker.ports)
? docker.ports ? docker.ports
.map((entry) => { .map((entry) => {
@@ -114,6 +157,12 @@ function sanitizeDockerTemplatePayload(docker) {
: []; : [];
if (ports.length) payload.ports = ports; if (ports.length) payload.ports = ports;
const portProtocols = sanitizePortProtocolPayload(
docker.portProtocols || docker.port_protocols || docker.protocols,
ports
);
if (portProtocols) payload.portProtocols = portProtocols;
const volumes = Array.isArray(docker.volumes) const volumes = Array.isArray(docker.volumes)
? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean) ? docker.volumes.map((entry) => cleanString(entry)).filter(Boolean)
: []; : [];
@@ -132,6 +181,17 @@ function sanitizeDockerTemplatePayload(docker) {
); );
if (adpanelStartup) payload.adpanelStartup = adpanelStartup; if (adpanelStartup) payload.adpanelStartup = adpanelStartup;
const startupDisplay = cleanScript(
docker.startupDisplay ||
docker.startup_display ||
docker.startupPreview ||
docker.startup_preview ||
docker.imageDefaultStartup ||
docker.image_default_startup,
32768
);
if (startupDisplay) payload.startupDisplay = startupDisplay;
const install = sanitizeDockerInstallPayload(docker.install || docker.installation); const install = sanitizeDockerInstallPayload(docker.install || docker.installation);
if (install) payload.install = install; if (install) payload.install = install;
@@ -146,4 +206,5 @@ module.exports = {
sanitizeDockerTemplatePayload, sanitizeDockerTemplatePayload,
sanitizeDockerInstallPayload, sanitizeDockerInstallPayload,
sanitizeEnvPayload, sanitizeEnvPayload,
sanitizePortProtocolPayload,
}; };
+134 -71
View File
@@ -9,54 +9,57 @@
<% const assetVersion = typeof themeVersion !== 'undefined' ? themeVersion : '1'; %> <% const assetVersion = typeof themeVersion !== 'undefined' ? themeVersion : '1'; %>
<link rel="stylesheet" href="/style.css?v=<%= assetVersion %>"> <link rel="stylesheet" href="/style.css?v=<%= assetVersion %>">
<link rel="stylesheet" href="/css/ssh-terminal-window.css?v=20260509-floating-terminal-5">
<link id="favicon" rel="icon" type="image/webp" href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>" /> <link id="favicon" rel="icon" type="image/webp" href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>" />
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin>
<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 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 rel="stylesheet" href="/css-ext/all.css" /> <link rel="stylesheet" href="/css-ext/all.css" />
<link rel="preconnect" href="https://cdn.jsdelivr.net"> <link rel="preconnect" href="https://cdn.jsdelivr.net">
<link rel="dns-prefetch" href="https://cdn.jsdelivr.net"> <link rel="dns-prefetch" href="https://cdn.jsdelivr.net">
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/socket.io/socket.io.js"></script> <script nonce="<%= cspNonce %>" data-cfasync="false" src="/socket.io/socket.io.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ansi_up@5.1.0/ansi_up.min.js"></script> src="https://cdn.jsdelivr.net/npm/ansi_up@5.1.0/ansi_up.min.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/ace.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/ace.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/theme-one_dark.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/theme-one_dark.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-javascript.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-javascript.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-json.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-json.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-yaml.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-yaml.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-python.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-python.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-sh.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-sh.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-ini.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-ini.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-html.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-html.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-css.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-css.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-java.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-java.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-text.js"></script> src="https://cdn.jsdelivr.net/npm/ace-builds@1.36.5/src-min-noconflict/mode-text.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false"> <script nonce="<%= cspNonce %>" data-cfasync="false">
window.__ADPANEL_BOOTSTRAP__ = Object.freeze({ window.__ADPANEL_BOOTSTRAP__ = Object.freeze({
currentUser: { currentUser: {
email: <%- JSON.stringify((user && user.email) || "") %>, email: <%- JSON.stringify((user && user.email) || "").replace(/</g, "\\u003c") %>,
preferences: <%- JSON.stringify((user && user.preferences) || {}) %> preferences: <%- JSON.stringify((user && user.preferences) || {}).replace(/</g, "\\u003c") %>
} }
}); });
</script> </script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/bot.js?v=<%= assetVersion %>" defer></script> <script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260509-floating-terminal-5" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/bot.js?v=<%= assetVersion %>-console-eventsource-live-reset-20260528" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" <script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs/loader.min.js"></script> src="https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs/loader.min.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false"> <script nonce="<%= cspNonce %>" data-cfasync="false">
(function () { (function () {
@@ -217,12 +220,11 @@
</style> </style>
<style nonce="<%= cspNonce %>"> <style nonce="<%= cspNonce %>">
.sidebar-shell { .sidebar-shell {
transition: transition: width 0.25s cubic-bezier(0.4, 0, 0.2, 1);
width 0.42s cubic-bezier(0.22, 1, 0.36, 1), will-change: width;
opacity 0.2s ease, transform: translateZ(0);
background-color 0.42s cubic-bezier(0.22, 1, 0.36, 1), backface-visibility: hidden;
box-shadow 0.42s cubic-bezier(0.22, 1, 0.36, 1) !important; -webkit-font-smoothing: subpixel-antialiased;
will-change: width, background-color, box-shadow;
} }
.sidebar-shell.open:hover { .sidebar-shell.open:hover {
@@ -230,29 +232,25 @@
0 18px 44px rgba(0, 0, 0, 0.34), 0 18px 44px rgba(0, 0, 0, 0.34),
inset 0 1px 0 rgba(255, 255, 255, 0.08); inset 0 1px 0 rgba(255, 255, 255, 0.08);
background-color: rgba(255, 255, 255, 0.062); background-color: rgba(255, 255, 255, 0.062);
transition: box-shadow 0.2s ease, background-color 0.2s ease;
} }
.sidebar-shell.open .sidebar-item, .sidebar-shell .sidebar-item,
.sidebar-shell.open .profile-card { .sidebar-shell .profile-card {
transition: transition: background 0.15s ease;
background 0.2s ease,
transform 0.2s ease,
color 0.2s ease,
padding 0.38s cubic-bezier(0.22, 1, 0.36, 1);
} }
.sidebar-shell.open .sidebar-item .label, .sidebar-shell .sidebar-item .label,
.sidebar-shell.open .profile-meta { .sidebar-shell .profile-meta {
transition: transition: opacity 0.2s cubic-bezier(0.4, 0, 0.2, 1);
max-width 0.36s cubic-bezier(0.22, 1, 0.36, 1), will-change: opacity;
opacity 0.26s ease, transform: translateZ(0);
transform 0.36s cubic-bezier(0.22, 1, 0.36, 1); backface-visibility: hidden;
transition-delay: 0s;
} }
.sidebar-shell.open:hover .sidebar-item .label, .sidebar-shell.open:hover .sidebar-item .label,
.sidebar-shell.open:hover .profile-meta { .sidebar-shell.open:hover .profile-meta {
transition-delay: 0.08s; transition-delay: 0.05s;
} }
.sidebar-shell.open:not(:hover) .sidebar-item .label, .sidebar-shell.open:not(:hover) .sidebar-item .label,
@@ -400,29 +398,27 @@
<div class="topbar"> <div class="topbar">
<div class="brands"></div> <div class="brands"></div>
<div class="top-actions"> <div class="top-actions" style="margin-left: auto; margin-right: -700px;">
<button class="icon-btn" id="filesBtn" data-action="open-files"><i class="fa-solid fa-folder-open"></i> <button class="icon-btn top-action-visible" id="filesBtn" data-action="open-files"><i class="fa-solid fa-folder-open"></i>
Files</button> Files</button>
<button class="icon-btn" id="backupsBtn" data-action="open-backups"><i class="fa-solid fa-box-archive"></i> <button class="icon-btn top-action-visible" id="activityBtn" data-action="open-activity"><i
Backups</button>
<button class="icon-btn" id="storeBtn" data-action="open-store"><i class="fa-solid fa-store"></i> Store</button>
<button class="icon-btn" id="activityBtn" data-action="open-activity"><i
class="fa-solid fa-clock-rotate-left"></i> Activity</button> class="fa-solid fa-clock-rotate-left"></i> Activity</button>
<button class="icon-btn" id="schedulerBtn" data-action="open-scheduler"><i <button class="icon-btn top-action-visible" id="moreBtn" data-action="toggle-more"><i class="fa-solid fa-ellipsis"></i>
More</button>
<button class="icon-btn top-action-hidden" id="backupsBtn" data-action="open-backups"><i class="fa-solid fa-box-archive"></i>
Backups</button>
<button class="icon-btn top-action-hidden" id="storeBtn" data-action="open-store"><i class="fa-solid fa-store"></i> Store</button>
<button class="icon-btn top-action-hidden" id="schedulerBtn" data-action="open-scheduler"><i
class="fa-solid fa-calendar-days"></i> Scheduler</button> class="fa-solid fa-calendar-days"></i> Scheduler</button>
<button class="icon-btn" id="aiHelpBtn" data-action="open-ai-help"> <button class="icon-btn top-action-hidden" id="aiHelpBtn" data-action="open-ai-help">
<img src="https://cdn.jsdelivr.net/gh/antonndev/ADCDn/adpanel-dark.webp" alt="ADPanel Agent" width="20px" <img src="https://cdn.jsdelivr.net/gh/antonndev/ADCDn/adpanel-dark.webp" alt="ADPanel Agent" width="20px"
height="21px" /> ADPanel Agent</button> height="21px" /> ADPanel Agent</button>
<button class="icon-btn" id="infoBtn" data-action="open-info"><i class="fa-solid fa-circle-info"></i> <button class="icon-btn top-action-hidden" id="infoBtn" data-action="open-info"><i class="fa-solid fa-circle-info"></i>
Information</button> Information</button>
<button class="icon-btn" id="runBtn" data-action="run" title="Run selected"><i class="fa-solid fa-play"></i> <button class="icon-btn top-action-hidden" id="subdomainsBtn" data-action="open-subdomains"><i class="fa-solid fa-globe"></i>
Run</button>
<button class="icon-btn" id="subdomainsBtn" data-action="open-subdomains"><i class="fa-solid fa-globe"></i>
Subdomains</button> Subdomains</button>
<button class="icon-btn" id="stopBtn" data-action="stop" title="Stop process"><i class="fa-solid fa-stop"></i> <button class="icon-btn top-action-hidden reinstall-topbar-btn" id="reinstallBtn" data-action="open-reinstall"
Stop</button>
<button class="icon-btn reinstall-topbar-btn" id="reinstallBtn" data-action="open-reinstall"
title="Reinstall server"><i class="fa-solid fa-rotate"></i> title="Reinstall server"><i class="fa-solid fa-rotate"></i>
Reinstall</button> Reinstall</button>
</div> </div>
@@ -437,7 +433,7 @@
style="display:flex;align-items:center; gap:10px; position:absolute; top:-60px; left:-40px;"> style="display:flex;align-items:center; gap:10px; position:absolute; top:-60px; left:-40px;">
<a href="/"><img src="https://i.imgur.com/k5agjYf.png" width="50" height="30"></a> <a href="/"><img src="https://i.imgur.com/k5agjYf.png" width="50" height="30"></a>
<a href="/" <a href="/"
style="position: absolute;font-size:30px;font-weight:bold;color:white;text-decoration:none; margin-top: -5px; margin-left: 55px;">Panel</a> style="position: absolute;font-size:30px;font-weight:bold;color:white;text-decoration:none; margin-top: -7px; margin-left: 53px;">Panel<sup style="font-size: 8px; font-weight: 700; margin-left: 1px; vertical-align: super; position: relative; top: -8px;">TM</sup></a>
</div> </div>
<div class="window-header"> <div class="window-header">
<div style="display:flex;align-items:center;gap:8px"> <div style="display:flex;align-items:center;gap:8px">
@@ -466,8 +462,9 @@
<pre id="console" aria-live="polite"></pre> <pre id="console" aria-live="polite"></pre>
<div class="cmd-row" id="cmdRow" style="margin-top: 4px;"> <div class="cmd-row" id="cmdRow" style="margin-top: 4px; position: relative;">
<input id="cmdInput" class="command" type="text" placeholder="Type a command and press Enter" /> <span class="cmd-arrows" aria-hidden="true"><i class="fa-solid fa-chevron-right"></i><i class="fa-solid fa-chevron-right" style="margin-left: -2px;"></i></span>
<input id="cmdInput" class="command" type="text" placeholder="Type a command and press Enter" style="background: #0b0f19; color: #d4d4d4; padding-left: 40px;" />
<button class="icon-btn" id="sendBtn" type="button" data-action="send" title="Send">Send</button> <button class="icon-btn" id="sendBtn" type="button" data-action="send" title="Send">Send</button>
<button class="icon-btn" id="clearBtn" type="button" data-action="clear" title="Clear">Clear</button> <button class="icon-btn" id="clearBtn" type="button" data-action="clear" title="Clear">Clear</button>
</div> </div>
@@ -774,6 +771,7 @@
<div id="bigEditor"> <div id="bigEditor">
<div id="codeShell" class="code-shell" style="display:none"> <div id="codeShell" class="code-shell" style="display:none">
<div class="code-shell-editor">
<div id="monacoContainer" style="width:100%;height:100%;"></div> <div id="monacoContainer" style="width:100%;height:100%;"></div>
<div id="aceContainer" style="width:100%;height:100%;display:none;"></div> <div id="aceContainer" style="width:100%;height:100%;display:none;"></div>
@@ -786,6 +784,32 @@
</div> </div>
</div> </div>
<button id="miniFmToggle" class="mini-fm-toggle" type="button"
title="Toggle file manager" aria-label="Toggle file manager" aria-expanded="true">
<i class="fa-solid fa-chevron-right"></i>
</button>
<aside id="miniFm" class="mini-fm" aria-label="File manager">
<div class="mini-fm-header">
<div class="mini-fm-header-main">
<div class="mini-fm-header-icon"><i class="fa-solid fa-folder-tree"></i></div>
<div class="mini-fm-header-text">
<div class="mini-fm-title">Files</div>
<div id="miniFmBreadcrumbs" class="mini-fm-breadcrumbs"></div>
</div>
</div>
<div class="mini-fm-header-actions">
<label class="mini-fm-icon-btn" id="miniFmUploadLabel" for="miniFmUpload"
title="Upload file" aria-label="Upload file"><i class="fa-solid fa-upload"></i></label>
<input id="miniFmUpload" type="file" multiple style="display:none" />
<button class="mini-fm-icon-btn" id="miniFmRefresh" type="button"
title="Refresh" aria-label="Refresh"><i class="fa-solid fa-rotate"></i></button>
</div>
</div>
<ul id="miniFmEntries" class="mini-fm-entries" role="list"></ul>
</aside>
</div>
<textarea id="textArea" style="display:none" spellcheck="false"></textarea> <textarea id="textArea" style="display:none" spellcheck="false"></textarea>
@@ -805,7 +829,10 @@
<div id="storeModal" class="modal-overlay" aria-hidden="true"> <div id="storeModal" class="modal-overlay" aria-hidden="true">
<div class="modal" role="dialog" aria-modal="true" aria-labelledby="storeModalTitle"> <div class="modal" role="dialog" aria-modal="true" aria-labelledby="storeModalTitle" style="position:relative;">
<div class="ptero-flash-bar" id="storeFlashBar">
<div class="ptero-flash-fill" id="storeFlashFill"></div>
</div>
<div class="store-header"> <div class="store-header">
<div class="store-header-main"> <div class="store-header-main">
<div> <div>
@@ -1515,51 +1542,57 @@
<div class="resource-stats-body"> <div class="resource-stats-body">
<div class="resource-stat-row"> <div class="resource-stat-row">
<div class="resource-stat-icon memory-icon"><i class="fa-solid fa-memory"></i></div> <div class="resource-stat-icon memory-icon"><i class="fa-solid fa-memory"></i></div>
<div class="resource-stat-info"> <div class="resource-stat-content">
<div class="resource-stat-label-line">
<div class="resource-stat-label">Memory</div> <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-bar">
<div class="resource-stat-fill memory-fill" id="resMemoryBar" style="width:0%"></div> <div class="resource-stat-fill memory-fill" id="resMemoryBar" style="width:0%"></div>
</div> </div>
</div> </div>
<div class="resource-stat-value" id="resMemoryLabel">Loading...</div>
</div>
</div>
<div class="resource-stat-row"> <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-icon disk-icon"><i class="fa-solid fa-hard-drive"></i></div>
<div class="resource-stat-info"> <div class="resource-stat-content">
<div class="resource-stat-label-line">
<div class="resource-stat-label">Storage</div> <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-bar">
<div class="resource-stat-fill disk-fill" id="resDiskBar" style="width:0%"></div> <div class="resource-stat-fill disk-fill" id="resDiskBar" style="width:0%"></div>
</div> </div>
</div> </div>
<div class="resource-stat-value" id="resDiskLabel">Loading...</div>
</div>
</div>
<div class="resource-stat-row"> <div class="resource-stat-row">
<div class="resource-stat-icon cpu-icon"><i class="fa-solid fa-microchip"></i></div> <div class="resource-stat-icon cpu-icon"><i class="fa-solid fa-microchip"></i></div>
<div class="resource-stat-info"> <div class="resource-stat-content">
<div class="resource-stat-label-line">
<div class="resource-stat-label">CPU</div> <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-bar">
<div class="resource-stat-fill cpu-fill" id="resCpuBar" style="width:0%"></div> <div class="resource-stat-fill cpu-fill" id="resCpuBar" style="width:0%"></div>
</div> </div>
</div> </div>
<div class="resource-stat-value" id="resCpuLabel">Loading...</div>
</div>
</div>
<div class="resource-stat-row"> <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-icon network-inbound-icon"><i class="fa-solid fa-arrow-down"></i></div>
<div class="resource-stat-info"> <div class="resource-stat-content">
<div class="resource-stat-label">Network Inbound</div> <div class="resource-stat-label">Network Inbound</div>
<div class="resource-stat-value" id="resNetworkInboundLabel">Loading...</div> <div class="resource-stat-value" id="resNetworkInboundLabel">Loading...</div>
</div> </div>
</div> </div>
<div class="resource-stat-row"> <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-icon network-outbound-icon"><i class="fa-solid fa-arrow-up"></i></div>
<div class="resource-stat-info"> <div class="resource-stat-content">
<div class="resource-stat-label">Network Outbound</div> <div class="resource-stat-label">Network Outbound</div>
<div class="resource-stat-value" id="resNetworkOutboundLabel">Loading...</div> <div class="resource-stat-value" id="resNetworkOutboundLabel">Loading...</div>
</div> </div>
</div> </div>
<div class="resource-stat-row"> <div class="resource-stat-row">
<div class="resource-stat-icon uptime-icon"><i class="fa-solid fa-clock"></i></div> <div class="resource-stat-icon uptime-icon"><i class="fa-solid fa-clock"></i></div>
<div class="resource-stat-info"> <div class="resource-stat-content">
<div class="resource-stat-label">Uptime</div> <div class="resource-stat-label">Uptime</div>
<div class="resource-stat-value" id="resUptimeLabel">Loading...</div> <div class="resource-stat-value" id="resUptimeLabel">Loading...</div>
</div> </div>
@@ -2091,3 +2124,33 @@
</body> </body>
</html> </html>
<script nonce="<%= cspNonce %>">
document.addEventListener('DOMContentLoaded', function() {
const moreBtn = document.getElementById('moreBtn');
const topActions = document.querySelector('.top-actions');
if (moreBtn && topActions) {
moreBtn.addEventListener('click', function(e) {
e.preventDefault();
topActions.classList.add('expanded');
});
}
});
</script>
<!-- Store toast & confirm -->
<div id="storeToast" class="store-toast" aria-live="polite" aria-atomic="true"></div>
<div id="storeConfirmOverlay" class="store-confirm-overlay" aria-hidden="true">
<div class="store-confirm-box" role="dialog" aria-modal="true">
<div class="store-confirm-icon"><i class="fa-solid fa-triangle-exclamation"></i></div>
<div class="store-confirm-msg" id="storeConfirmMsg"></div>
<div class="store-confirm-actions">
<button class="backup-create-cancel" id="storeConfirmCancel" type="button">Cancel</button>
<button class="backup-create-confirm" id="storeConfirmOk" type="button">
<i class="fa-solid fa-check"></i>
<span>Continue</span>
</button>
</div>
</div>
</div>
+1 -2
View File
@@ -66,9 +66,8 @@
<p> <p>
[Dashboard] Due to security reasons you can only reset your password [Dashboard] Due to security reasons you can only reset your password
directly from the terminal using the command 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. <strong>bash initialize.sh</strong> from the ADPanel directory or asking an admin to reset it for the specific user from Accounts settings category.
</p> </p>
<p>This panel version doesn't support change password feature directly from normal user UI.</p>
</html> </html>
</body> </body>
+488 -680
View File
File diff suppressed because it is too large. Load diff
+236 -43
View File
@@ -1,13 +1,17 @@
<% const loginBackgroundType=(branding && branding.loginBackgroundType) ? branding.loginBackgroundType : 'video' ; const <% const loginBackgroundType=(branding && branding.loginBackgroundType) ? branding.loginBackgroundType : 'video' ; const
loginBackgroundUrl='/auth-assets/background' ; const protectedLoginWatermarkUrl='/auth-assets/watermark' ; const loginBackgroundUrl='/auth-assets/background' ; const protectedLoginWatermarkUrl='/auth-assets/watermark' ; const
loginBackgroundMimeType=(branding && branding.loginBackgroundMimeType) ? branding.loginBackgroundMimeType loginBackgroundMimeType=(branding && branding.loginBackgroundMimeType) ? branding.loginBackgroundMimeType
: 'video/webm' ; %> : 'video/webm' ; const loginRequiresTwoFactor=typeof requiresTwoFactor !== 'undefined' && !!requiresTwoFactor; const
loginEmailValue=typeof loginEmail !== 'undefined' ? String(loginEmail || '') : ''; const
loginExternalCaptchaAvailable=typeof externalCaptchaAvailable !== 'undefined' ? !!externalCaptchaAvailable : !!useExternalCaptcha; const
loginCaptchaChallengeActive=!!useExternalCaptcha || !!showLocalCaptcha; %>
<!DOCTYPE html> <!DOCTYPE html>
<html lang="ro"> <html lang="ro">
<head> <head>
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<title>Login - <%= (branding && branding.appName) ? branding.appName : 'Panel' %></title> <title>Login - <%= (branding && branding.appName) ? branding.appName : 'Panel' %></title>
<link rel="preconnect" href="https://cdnjs.cloudflare.com" crossorigin>
<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 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" <link id="favicon" rel="icon" type="image/webp" sizes="16x16"
href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>" /> href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>" />
@@ -75,7 +79,7 @@
</script> </script>
</head> </head>
<body class="<%= loginBackgroundType === 'image' && loginBackgroundUrl ? 'login-body--image' : '' %>"> <body class="<%= [loginBackgroundType === 'image' && loginBackgroundUrl ? 'login-body--image' : '', loginRequiresTwoFactor ? 'login-has-2fa' : ''].filter(Boolean).join(' ') %>">
<div id="toastHost" class="toast-host" aria-live="polite" aria-atomic="true"></div> <div id="toastHost" class="toast-host" aria-live="polite" aria-atomic="true"></div>
<script nonce="<%= cspNonce %>"> <script nonce="<%= cspNonce %>">
@@ -116,22 +120,24 @@
</video> </video>
<% } %> <% } %>
<form method="POST" action="/login" class="login-form"> <form method="POST" action="/login" class="login-form" data-requires-two-factor="<%= loginRequiresTwoFactor ? 'true' : 'false' %>">
<input type="text" name="company" tabindex="-1" autocomplete="off" aria-hidden="true" hidden> <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="botProof" id="botProofInput" value="<%= botProofSeed || '' %>" autocomplete="off">
<input type="hidden" name="_csrf" value="<%= csrfToken %>" autocomplete="off"> <input type="hidden" name="_csrf" value="<%= csrfToken %>" autocomplete="off">
<div class="input-holder"> <div class="input-holder">
<i class="input-icon fa-solid fa-envelope" aria-hidden="true"></i> <i class="input-icon fa-solid fa-envelope" aria-hidden="true"></i>
<input class="login-input" type="email" name="email" placeholder="Email" required /> <input class="login-input" type="email" name="email" placeholder="Email" value="<%= loginEmailValue %>" required />
</div> </div>
<div class="input-holder"> <div class="input-holder">
<i class="input-icon fa-solid fa-lock" aria-hidden="true"></i> <i class="input-icon fa-solid fa-lock" aria-hidden="true"></i>
<input class="login-input" type="password" name="password" placeholder="Password" required /> <input class="login-input" type="password" name="password" placeholder="Password" required />
</div> </div>
<div class="input-holder"> <div class="input-holder login-two-factor-field" id="loginTwoFactorField" aria-hidden="<%= loginRequiresTwoFactor ? 'false' : 'true' %>">
<i class="input-icon fa-solid fa-fingerprint" aria-hidden="true"></i> <i class="input-icon fa-solid fa-fingerprint" aria-hidden="true"></i>
<input class="login-input" type="text" name="code" placeholder="2FA Code" required /> <input class="login-input" type="text" name="code" id="loginTwoFactorCode" placeholder="2FA Code" maxlength="6"
inputmode="numeric" autocomplete="one-time-code" <%= loginRequiresTwoFactor ? 'required' : 'disabled' %> />
</div> </div>
<a class="forgot-password" href="/forgot-password">Forgot password?</a>
<input type="hidden" name="captchaToken" id="captchaTokenInput" value="" /> <input type="hidden" name="captchaToken" id="captchaTokenInput" value="" />
<button type="submit" class="get-started"> <button type="submit" class="get-started">
@@ -139,16 +145,15 @@
<img class="get-started__logo" src="/auth-assets/logo" alt="D Logo" draggable="false" /> <img class="get-started__logo" src="/auth-assets/logo" alt="D Logo" draggable="false" />
<span>Panel</span> <span>Panel</span>
</button> </button>
<a class="forgot-password" href="/forgot-password">Forgot password?</a>
<div class="circle-icon"> <div class="circle-icon">
<i class="fa-solid fa-arrow-right-to-bracket circle-icon__glyph"></i> <i class="fa-solid fa-arrow-right-to-bracket circle-icon__glyph"></i>
</div> </div>
</form> </form>
<div id="captchaModal" class="captcha-modal<%= (useExternalCaptcha || showLocalCaptcha) ? ' show' : '' %>" <div id="captchaModal" class="captcha-modal<%= loginCaptchaChallengeActive ? ' show' : '' %>"
data-provider="<%= (externalCaptchaProvider || 'recaptcha').toLowerCase() %>" data-provider="<%= (externalCaptchaProvider || 'recaptcha').toLowerCase() %>"
data-challenge="<%= (useExternalCaptcha || showLocalCaptcha) ? '1' : '0' %>" data-challenge="<%= loginCaptchaChallengeActive ? '1' : '0' %>"
aria-hidden="<%= (useExternalCaptcha || showLocalCaptcha) ? 'false' : 'true' %>"> aria-hidden="<%= loginCaptchaChallengeActive ? 'false' : 'true' %>">
<div class="captcha-modal__backdrop"></div> <div class="captcha-modal__backdrop"></div>
<div class="captcha-modal__card"> <div class="captcha-modal__card">
<div class="captcha-modal__title"> <div class="captcha-modal__title">
@@ -158,6 +163,7 @@
<div class="captcha-modal__widget"> <div class="captcha-modal__widget">
<div id="recaptchaWidget" hidden></div> <div id="recaptchaWidget" hidden></div>
<div id="cf-turnstile" hidden></div> <div id="cf-turnstile" hidden></div>
<div id="hcaptchaWidget" hidden></div>
</div> </div>
<% if (showLocalCaptcha && captchaQuestion) { %> <% if (showLocalCaptcha && captchaQuestion) { %>
<div id="localCaptchaUI" class="local-captcha" data-token="<%= captchaQuestion.token %>" <div id="localCaptchaUI" class="local-captcha" data-token="<%= captchaQuestion.token %>"
@@ -206,13 +212,13 @@
<script nonce="<%= cspNonce %>"> <script nonce="<%= cspNonce %>">
(() => { (() => {
const cfg = { const cfg = {
enabled: <%- useExternalCaptcha ? "true" : "false" %>, enabled: <%- loginExternalCaptchaAvailable ? "true" : "false" %>,
required: <%- externalCaptchaAutoStart ? "true" : "false" %>, required: <%- externalCaptchaAutoStart ? "true" : "false" %>,
provider: <%- JSON.stringify((externalCaptchaProvider || "recaptcha").toLowerCase()) %>, provider: <%- JSON.stringify((externalCaptchaProvider || "recaptcha").toLowerCase()) %>,
siteKey: <%- JSON.stringify(externalCaptchaSiteKey || "") %>, siteKey: <%- JSON.stringify(externalCaptchaSiteKey || "") %>,
hasError: <%- error ? "true" : "false" %>, hasError: <%- error ? "true" : "false" %>,
showLocal: <%- showLocalCaptcha ? "true" : "false" %>, showLocal: <%- showLocalCaptcha ? "true" : "false" %>,
challengeActive: <%- (useExternalCaptcha || showLocalCaptcha) ? "true" : "false" %>, challengeActive: <%- loginCaptchaChallengeActive ? "true" : "false" %>,
}; };
const form = document.querySelector("form"); const form = document.querySelector("form");
@@ -220,11 +226,13 @@
const tokenInput = document.getElementById("captchaTokenInput"); const tokenInput = document.getElementById("captchaTokenInput");
const recaptchaHost = document.getElementById("recaptchaWidget"); const recaptchaHost = document.getElementById("recaptchaWidget");
const turnstileHost = document.getElementById("cf-turnstile"); const turnstileHost = document.getElementById("cf-turnstile");
const hcaptchaHost = document.getElementById("hcaptchaWidget");
const statusEl = modal ? modal.querySelector(".captcha-modal__desc") : null; const statusEl = modal ? modal.querySelector(".captcha-modal__desc") : null;
const defaultStatusText = statusEl ? statusEl.textContent : ""; const defaultStatusText = statusEl ? statusEl.textContent : "";
let recaptchaId = null; let recaptchaId = null;
let turnstileId = null; let turnstileId = null;
let hcaptchaId = null;
let started = false; let started = false;
let timeoutHandle = null; let timeoutHandle = null;
@@ -237,6 +245,10 @@
const enableForm = () => { const enableForm = () => {
if (!form) return; if (!form) return;
form.querySelectorAll("input, button").forEach(el => { el.disabled = false; }); form.querySelectorAll("input, button").forEach(el => { el.disabled = false; });
const loginTwoFactorInput = document.getElementById("loginTwoFactorCode");
if (loginTwoFactorInput && form.dataset.requiresTwoFactor !== "true") {
loginTwoFactorInput.disabled = true;
}
form.classList.remove("login-form--blocked"); form.classList.remove("login-form--blocked");
}; };
@@ -249,6 +261,7 @@
if (modal) { if (modal) {
modal.classList.remove("show"); modal.classList.remove("show");
modal.dataset.challenge = "0"; modal.dataset.challenge = "0";
modal.setAttribute("aria-hidden", "true");
} }
enableForm(); enableForm();
if (timeoutHandle) { if (timeoutHandle) {
@@ -267,26 +280,68 @@
} }
}; };
const resetCaptchaWidget = () => {
tokenInput.value = "";
try {
if (recaptchaId !== null && window.grecaptcha && typeof window.grecaptcha.reset === "function") {
window.grecaptcha.reset(recaptchaId);
}
} catch { }
try {
if (turnstileId !== null && window.turnstile && typeof window.turnstile.reset === "function") {
window.turnstile.reset(turnstileId);
}
} catch { }
try {
if (hcaptchaId !== null && window.hcaptcha && typeof window.hcaptcha.reset === "function") {
window.hcaptcha.reset(hcaptchaId);
}
} catch { }
};
async function verifyCaptchaToken(token) {
tokenInput.value = token || "";
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
if (statusEl) statusEl.textContent = "Finalizing sign in...";
try {
const resp = await fetch("/api/captcha/verify", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ token }),
credentials: "same-origin",
});
const data = await resp.json().catch(() => ({}));
if (resp.ok && data.ok) {
if (data.redirect) {
window.location.href = data.redirect;
return;
}
hideModal();
return;
}
resetCaptchaWidget();
if (data.redirect) {
window.location.href = data.redirect;
return;
}
if (statusEl) statusEl.textContent = data.error || "Captcha verification failed. Try again.";
} catch {
resetCaptchaWidget();
if (statusEl) statusEl.textContent = "Network error. Try again.";
}
}
function renderRecaptcha() { function renderRecaptcha() {
if (!cfg.enabled || recaptchaId !== null) return recaptchaId; if (!cfg.enabled || recaptchaId !== null) return recaptchaId;
if (!window.grecaptcha || typeof window.grecaptcha.render !== "function") return null; if (!window.grecaptcha || typeof window.grecaptcha.render !== "function") return null;
if (turnstileHost) turnstileHost.hidden = true; if (turnstileHost) turnstileHost.hidden = true;
if (hcaptchaHost) hcaptchaHost.hidden = true;
if (recaptchaHost) recaptchaHost.hidden = false; if (recaptchaHost) recaptchaHost.hidden = false;
recaptchaId = window.grecaptcha.render("recaptchaWidget", { recaptchaId = window.grecaptcha.render("recaptchaWidget", {
sitekey: cfg.siteKey, sitekey: cfg.siteKey,
size: "normal", size: "normal",
theme: "dark", theme: "dark",
callback: (token) => { callback: verifyCaptchaToken,
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 = ""; }, "expired-callback": () => { tokenInput.value = ""; },
"error-callback": () => { tokenInput.value = ""; }, "error-callback": () => { tokenInput.value = ""; },
}); });
@@ -305,22 +360,13 @@
if (!cfg.enabled || turnstileId !== null) return turnstileId; if (!cfg.enabled || turnstileId !== null) return turnstileId;
if (!window.turnstile || typeof window.turnstile.render !== "function") return null; if (!window.turnstile || typeof window.turnstile.render !== "function") return null;
if (recaptchaHost) recaptchaHost.hidden = true; if (recaptchaHost) recaptchaHost.hidden = true;
if (hcaptchaHost) hcaptchaHost.hidden = true;
if (turnstileHost) turnstileHost.hidden = false; if (turnstileHost) turnstileHost.hidden = false;
turnstileId = window.turnstile.render("#cf-turnstile", { turnstileId = window.turnstile.render("#cf-turnstile", {
sitekey: cfg.siteKey, sitekey: cfg.siteKey,
size: "normal", size: "normal",
theme: "dark", theme: "dark",
callback: (token) => { callback: verifyCaptchaToken,
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 = ""; }, "expired-callback": () => { tokenInput.value = ""; },
"error-callback": () => { tokenInput.value = ""; }, "error-callback": () => { tokenInput.value = ""; },
}); });
@@ -335,13 +381,44 @@
if (attempt < 50) setTimeout(() => ensureTurnstile(attempt + 1), 200); if (attempt < 50) setTimeout(() => ensureTurnstile(attempt + 1), 200);
} }
function renderHcaptcha() {
if (!cfg.enabled || hcaptchaId !== null) return hcaptchaId;
if (!window.hcaptcha || typeof window.hcaptcha.render !== "function") return null;
if (recaptchaHost) recaptchaHost.hidden = true;
if (turnstileHost) turnstileHost.hidden = true;
if (hcaptchaHost) hcaptchaHost.hidden = false;
hcaptchaId = window.hcaptcha.render("hcaptchaWidget", {
sitekey: cfg.siteKey,
size: "normal",
theme: "dark",
callback: verifyCaptchaToken,
"expired-callback": () => { tokenInput.value = ""; },
"error-callback": () => { tokenInput.value = ""; },
});
if (timeoutHandle) { clearTimeout(timeoutHandle); timeoutHandle = null; }
resetStatus();
return hcaptchaId;
}
function ensureHcaptcha(attempt = 0) {
if (hcaptchaId === null) renderHcaptcha();
if (hcaptchaId !== null) return;
if (attempt < 50) setTimeout(() => ensureHcaptcha(attempt + 1), 200);
}
function startCaptchaFlow() { function startCaptchaFlow() {
started = true; started = true;
if (modal) {
modal.dataset.challenge = "1";
modal.setAttribute("aria-hidden", "false");
}
showModal(); showModal();
resetStatus(); resetStatus();
if (timeoutHandle) clearTimeout(timeoutHandle); if (timeoutHandle) clearTimeout(timeoutHandle);
timeoutHandle = setTimeout(markTimeout, 30000); timeoutHandle = setTimeout(markTimeout, 30000);
if (!cfg.enabled) return;
if (["cloudflare", "turnstile", "cf"].includes(cfg.provider)) return ensureTurnstile(); if (["cloudflare", "turnstile", "cf"].includes(cfg.provider)) return ensureTurnstile();
if (["hcaptcha", "h"].includes(cfg.provider)) return ensureHcaptcha();
return ensureRecaptcha(); return ensureRecaptcha();
} }
@@ -353,11 +430,6 @@
if (cfg.enabled && !tokenInput.value) startCaptchaFlow(); if (cfg.enabled && !tokenInput.value) startCaptchaFlow();
return false; return false;
} }
if (cfg.enabled && !tokenInput.value) {
e.preventDefault();
startCaptchaFlow();
return false;
}
}, true); }, true);
} }
@@ -378,14 +450,131 @@
ensureTurnstile(); ensureTurnstile();
}; };
window.__adCaptchaResolved = hideModal; window.initHcaptcha = function initHcaptcha() {
if (!cfg.enabled) return;
ensureHcaptcha();
};
window.__adCaptchaResolved = (data) => {
if (data && data.redirect) {
window.location.href = data.redirect;
return;
}
hideModal();
};
window.__adStartCaptchaFlow = startCaptchaFlow;
})(); })();
</script> </script>
<% if (useExternalCaptcha) { %> <script nonce="<%= cspNonce %>">
(() => {
const form = document.querySelector("form.login-form");
if (!form || !window.fetch) return;
const twoFactorField = document.getElementById("loginTwoFactorField");
const twoFactorInput = document.getElementById("loginTwoFactorCode");
const csrfInput = form.querySelector('input[name="_csrf"]');
const submitBtn = form.querySelector('button[type="submit"]');
const toastHost = document.getElementById("toastHost");
function showLoginToast(text, duration = 4200) {
if (!toastHost || !text) return;
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;
toastHost.appendChild(toast);
requestAnimationFrame(() => toast.classList.add("toast-show"));
setTimeout(() => toast.classList.add("toast-hide"), Math.max(0, duration - 320));
setTimeout(() => toast.remove(), duration + 450);
}
function setTwoFactorRequired(required) {
form.dataset.requiresTwoFactor = required ? "true" : "false";
document.body?.classList.toggle("login-has-2fa", !!required);
if (twoFactorField) {
twoFactorField.setAttribute("aria-hidden", required ? "false" : "true");
}
if (twoFactorInput) {
twoFactorInput.required = !!required;
twoFactorInput.disabled = !required;
if (!required) twoFactorInput.value = "";
}
}
setTwoFactorRequired(form.dataset.requiresTwoFactor === "true");
twoFactorInput?.addEventListener("input", () => {
twoFactorInput.value = twoFactorInput.value.replace(/\D/g, "").slice(0, 6);
});
form.addEventListener("submit", async (e) => {
if (e.defaultPrevented) return;
e.preventDefault();
if (submitBtn) submitBtn.disabled = true;
let keepSubmitDisabled = false;
try {
const body = new URLSearchParams(new FormData(form));
const res = await fetch(form.action || "/login", {
method: "POST",
headers: {
"Accept": "application/json",
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
"X-Requested-With": "XMLHttpRequest",
},
credentials: "same-origin",
body,
});
const data = await res.json().catch(() => ({}));
if (data.csrfToken && csrfInput) csrfInput.value = data.csrfToken;
if (data.requires2FA) {
setTwoFactorRequired(true);
showLoginToast(data.error || "Enter your 2FA code to continue.");
setTimeout(() => twoFactorInput?.focus(), 40);
return;
}
if (data.captchaRequired) {
keepSubmitDisabled = true;
if (data.useExternalCaptcha && typeof window.__adStartCaptchaFlow === "function") {
window.__adStartCaptchaFlow();
} else {
window.location.reload();
}
return;
}
if (res.ok && data.ok) {
window.location.href = data.redirect || "/";
return;
}
if (res.status === 403 && !data.error) {
window.location.reload();
return;
}
showLoginToast(data.error || "Invalid credentials");
} catch (err) {
showLoginToast("Network error. Try again.");
} finally {
if (submitBtn && !keepSubmitDisabled) submitBtn.disabled = false;
}
});
})();
</script>
<% if (loginExternalCaptchaAvailable) { %>
<% if (["cloudflare","turnstile","cf"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %> <% if (["cloudflare","turnstile","cf"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %>
<script nonce="<%= cspNonce %>" <script nonce="<%= cspNonce %>"
src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=initTurnstile&render=explicit" async src="https://challenges.cloudflare.com/turnstile/v0/api.js?onload=initTurnstile&render=explicit" async
defer></script> defer></script>
<% } else if (["hcaptcha","h"].includes((externalCaptchaProvider || "" ).toLowerCase())) { %>
<script nonce="<%= cspNonce %>"
src="https://js.hcaptcha.com/1/api.js?onload=initHcaptcha&render=explicit" async
defer></script>
<% } else { %> <% } else { %>
<script nonce="<%= cspNonce %>" <script nonce="<%= cspNonce %>"
src="https://www.google.com/recaptcha/api.js?onload=initRecaptcha&render=explicit" async src="https://www.google.com/recaptcha/api.js?onload=initRecaptcha&render=explicit" async
@@ -446,7 +635,7 @@
.then(function (data) { .then(function (data) {
if (data.ok && data.done) { if (data.ok && data.done) {
setLocalStatus("Verified!", "success"); setLocalStatus("Verified!", "success");
if (typeof window.__adCaptchaResolved === "function") window.__adCaptchaResolved(); if (typeof window.__adCaptchaResolved === "function") window.__adCaptchaResolved(data);
return; return;
} }
if (data.ok && !data.done && data.question) { if (data.ok && !data.done && data.question) {
@@ -456,6 +645,10 @@
submitBtn.disabled = false; submitBtn.disabled = false;
return; return;
} }
if (!data.ok && data.redirect) {
window.location.href = data.redirect;
return;
}
setLocalStatus(data.error === "expired" ? "Expired. Reloading..." : "Incorrect selection. Reloading...", "error"); setLocalStatus(data.error === "expired" ? "Expired. Reloading..." : "Incorrect selection. Reloading...", "error");
setTimeout(function () { window.location.reload(); }, 1800); setTimeout(function () { window.location.reload(); }, 1800);
}) })
@@ -533,7 +726,7 @@
<script nonce="<%= cspNonce %>"> <script nonce="<%= cspNonce %>">
(function () { (function () {
var challengeActive = <%- (showLocalCaptcha || (useExternalCaptcha && externalCaptchaAutoStart)) ? "true" : "false" %>; var challengeActive = <%- loginCaptchaChallengeActive ? "true" : "false" %>;
if (!challengeActive) return; if (!challengeActive) return;
var modal = document.getElementById("captchaModal"); var modal = document.getElementById("captchaModal");
+229 -130
View File
@@ -11,22 +11,21 @@
</style> </style>
<script nonce="<%= cspNonce %>"> <script nonce="<%= cspNonce %>">
window.__ADPANEL_DASHBOARD_BACKGROUND__ = <%- JSON.stringify(dashboardBackground || null).replace(/</g, '\\u003c') %>;
(function(){ (function(){
try{ try{
var bg=localStorage.getItem('dashboardBg'); var data=window.__ADPANEL_DASHBOARD_BACKGROUND__;
if(bg){ if(data&&data.type==='color'&&data.value){
var data=JSON.parse(bg);
if(data.type==='color'&&data.value){
document.documentElement.style.setProperty('--bg-main',data.value); document.documentElement.style.setProperty('--bg-main',data.value);
}else if(data.type==='image'&&data.value){ }else if(data&&(data.type==='image'||data.type==='upload'||data.type==='url')&&data.value){
document.documentElement.style.setProperty('--bg-main','url('+data.value+')'); document.documentElement.style.setProperty('--bg-main','url('+data.value+')');
} }
}
}catch(e){} }catch(e){}
})(); })();
</script> </script>
<link rel="stylesheet" href="settings.css?v=20"> <link rel="stylesheet" href="settings.css?v=20260601-server-gray2">
<link rel="stylesheet" href="/css/ssh-terminal-window.css?v=20260509-floating-terminal-5">
<title><%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> Settings</title> <title><%= (branding && branding.appName) ? branding.appName : 'ADPanel' %> Settings</title>
<link id="favicon" rel="icon" type="image/webp" sizes="16x16" <link id="favicon" rel="icon" type="image/webp" sizes="16x16"
href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>"> href="<%= (branding && branding.faviconUrl) ? branding.faviconUrl : '/auth-assets/favicon' %>">
@@ -61,8 +60,14 @@
})(); })();
</script> </script>
<script nonce="<%= cspNonce %>">
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/settings.js?v=26" defer></script> window.__ADPANEL_CURRENT_USER__ = {
has2FA: <%- JSON.stringify(!!(user && String(user.secret || '').trim())) %>,
revokeSecurity: <%- JSON.stringify(destructiveActionSecurity || null) %>
};
</script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260509-floating-terminal-5" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/settings.js?v=20260601-server-gray2" defer></script>
<script nonce="<%= cspNonce %>"> <script nonce="<%= cspNonce %>">
(function(){ (function(){
function enableLink(id){var l=document.getElementById(id);if(l)l.media='all';} function enableLink(id){var l=document.getElementById(id);if(l)l.media='all';}
@@ -104,7 +109,9 @@
<% } %> <% } %>
<button data-panel="databases"><i class="fa-solid fa-database"></i> Databases</button> <button data-panel="databases"><i class="fa-solid fa-database"></i> Databases</button>
<button data-panel="nodes"><i class="fa-solid fa-diagram-project"></i> Nodes</button> <button data-panel="nodes"><i class="fa-solid fa-diagram-project"></i> Nodes</button>
<% if (user && user.admin) { %>
<button data-panel="templates"><i class="fa-solid fa-file"></i> Templates</button> <button data-panel="templates"><i class="fa-solid fa-file"></i> Templates</button>
<% } %>
<button data-panel="servers"><i class="fa-solid fa-server"></i> Servers</button> <button data-panel="servers"><i class="fa-solid fa-server"></i> Servers</button>
<button data-panel="webhooks"><i class="fa-brands fa-discord"></i> Webhooks</button> <button data-panel="webhooks"><i class="fa-brands fa-discord"></i> Webhooks</button>
<% if (user && user.admin) { %> <% if (user && user.admin) { %>
@@ -181,7 +188,7 @@
<div class="thumbs" id="thumbs"></div> <div class="thumbs" id="thumbs"></div>
</div> </div>
<div class="note">Note: background set here will be applied to the dashboard and main style <div class="note">Note: Background set here will be applied to the whole dashboard.
files.</div> files.</div>
</div> </div>
</div> </div>
@@ -362,7 +369,7 @@
<div class="change-pass-header"> <div class="change-pass-header">
<div> <div>
<div class="change-pass-title">Change password</div> <div class="change-pass-title">Change password</div>
<small class="change-pass-subtitle">Requires current password & 2FA.</small> <small class="change-pass-subtitle">Requires your current password.</small>
</div> </div>
<div class="change-pass-icon"><i class="fa-solid fa-key"></i></div> <div class="change-pass-icon"><i class="fa-solid fa-key"></i></div>
</div> </div>
@@ -510,10 +517,10 @@
<div class="sessions-panel-header"> <div class="sessions-panel-header">
<div> <div>
<div class="sessions-panel-title">Sessions</div> <div class="sessions-panel-title">Sessions</div>
<div class="sessions-panel-subtitle">Manage all ADPanel Sessions.</div> <div class="sessions-panel-subtitle">Manage ADPanel sessions and saved browser logins.</div>
</div> </div>
<div class="security-sessions-header-meta"> <div class="security-sessions-header-meta">
<span class="security-inline-chip" id="sessionsCountBadge">0 active</span> <span class="security-inline-chip" id="sessionsCountBadge">0 logins</span>
</div> </div>
</div> </div>
@@ -525,7 +532,7 @@
placeholder="Search by Email" autocomplete="off" spellcheck="false"> placeholder="Search by Email" autocomplete="off" spellcheck="false">
</div> </div>
<div id="sessionsSummary" class="security-summary sessions-summary"> <div id="sessionsSummary" class="security-summary sessions-summary">
Loading active browser sessions... Loading browser sessions...
</div> </div>
</div> </div>
@@ -534,7 +541,7 @@
<div id="sessionsList" class="sessions-list"> <div id="sessionsList" class="sessions-list">
<div class="sessions-empty-state"> <div class="sessions-empty-state">
<i class="fa-solid fa-spinner fa-spin"></i> <i class="fa-solid fa-spinner fa-spin"></i>
<span>Loading active sessions...</span> <span>Loading browser sessions...</span>
</div> </div>
</div> </div>
@@ -752,6 +759,7 @@
<div id="nodesPagination" class="nodes-pagination"></div> <div id="nodesPagination" class="nodes-pagination"></div>
</div> </div>
<% if (user && user.admin) { %>
<div id="templates" class="panel-section"> <div id="templates" class="panel-section">
<div class="servers-header templates-header"> <div class="servers-header templates-header">
<div> <div>
@@ -764,12 +772,14 @@
<input type="text" id="templatesSearchInput" placeholder="Search templates…" spellcheck="false" autocomplete="off" /> <input type="text" id="templatesSearchInput" placeholder="Search templates…" spellcheck="false" autocomplete="off" />
</div> </div>
<button class="btn" id="openCreateTemplate"><i class="fa-solid fa-plus"></i> Create</button> <button class="btn" id="openCreateTemplate"><i class="fa-solid fa-plus"></i> Create</button>
<button class="btn template-store-open-btn" id="openTemplateStore"><i class="fa-solid fa-store"></i> Store</button>
</div> </div>
</div> </div>
<div id="templatesFeedback" class="muted templates-feedback"></div> <div id="templatesFeedback" class="muted templates-feedback"></div>
<div id="templatesList" class="templates-grid templates-list"></div> <div id="templatesList" class="templates-grid templates-list"></div>
<div id="templatesPagination" class="nodes-pagination"></div> <div id="templatesPagination" class="nodes-pagination"></div>
</div> </div>
<% } %>
<div id="servers" class="panel-section"> <div id="servers" class="panel-section">
<div class="servers-header"> <div class="servers-header">
@@ -956,6 +966,7 @@
</div> </div>
</div> </div>
<% if (user && user.admin) { %>
<div id="serverTemplateOverlay" class="modal-overlay enterprise-modal-overlay" aria-hidden="true"> <div id="serverTemplateOverlay" class="modal-overlay enterprise-modal-overlay" aria-hidden="true">
<div class="enterprise-modal server-template-enterprise-modal" id="serverTemplateModal"> <div class="enterprise-modal server-template-enterprise-modal" id="serverTemplateModal">
<div class="enterprise-modal-header"> <div class="enterprise-modal-header">
@@ -1038,51 +1049,16 @@
</div> </div>
<div class="node-form-field" style="margin-top: 12px;"> <div class="node-form-field" style="margin-top: 12px;">
<label class="node-form-label">Startup command <span class="node-form-hint">(optional)</span></label> <label class="node-form-label">Startup command <span class="node-form-hint">(optional)</span></label>
<textarea id="ct_startup_command" class="node-form-textarea" aria-describedby="ct_startupCommandHelp" placeholder="e.g. node /app/index.js"></textarea> <textarea id="ct_startup_command" class="node-form-textarea" aria-describedby="ct_startupCommandHelp" placeholder="e.g. node /app/index.js --port {{SERVER_PORT}}"></textarea>
<small id="ct_startupCommandHelp" class="startup-cmd-help">Leave empty to use the image's Docker ENTRYPOINT/CMD. Direct image entry scripts like <code>bash entry.sh</code> are allowed; shell wrappers like <code>bash -lc</code> and Docker CLI commands are blocked.</small>
</div>
<div class="node-form-field" style="margin-top: 12px;">
<label class="node-form-label">Workdir <span class="node-form-hint">(optional)</span></label>
<input id="ct_workdir" type="text" class="node-form-input" placeholder="e.g. /app" />
</div> </div>
<div class="node-form-field" style="margin-top: 12px;"> <div class="node-form-field" style="margin-top: 12px;">
<label class="node-form-label">Environment JSON <span class="node-form-hint">(optional)</span></label> <label class="node-form-label">Environment JSON <span class="node-form-hint">(optional)</span></label>
<textarea id="ct_env_json" class="node-form-textarea" placeholder='{"SERVER_NAME":"My server"}'></textarea> <textarea id="ct_env_json" class="node-form-textarea" placeholder='{"SERVER_NAME":"My server"}'></textarea>
</div> </div>
<div class="node-form-field" style="margin-top: 12px;">
<label class="node-form-label">ADPanel STARTUP <span class="node-form-hint">(optional)</span></label>
<textarea id="ct_adpanel_startup" class="node-form-textarea" placeholder='Example: ./game/bin/linuxsteamrt64/cs2 -dedicated -port {{SERVER_PORT}}'></textarea>
</div>
</div> </div>
<div class="node-form-section"> <div class="node-form-section">
<div class="node-form-section-title"><i class="fa-solid fa-download"></i> Installer</div> <div class="node-form-section-title"><i class="fa-solid fa-download"></i> Installer</div>
<div class="node-form-grid">
<div class="node-form-field">
<label class="node-form-label">Installer image <span class="node-form-hint">(optional)</span></label>
<input id="ct_install_image" type="text" class="node-form-input" placeholder="ghcr.io/pterodactyl/installers:debian" />
</div>
<div class="node-form-field">
<label class="node-form-label">Entrypoint</label>
<input id="ct_install_entrypoint" type="text" class="node-form-input" placeholder="bash" />
</div>
</div>
<div class="node-form-grid" style="margin-top: 12px;">
<div class="node-form-field">
<label class="node-form-label">Install mount path</label>
<input id="ct_install_mount" type="text" class="node-form-input" placeholder="/mnt/server" />
</div>
<div class="node-form-field">
<label class="node-form-label">Runtime mount path</label>
<input id="ct_install_runtime" type="text" class="node-form-input" placeholder="/home/container" />
</div>
</div>
<div class="node-form-grid" style="margin-top: 12px;">
<div class="node-form-field">
<label class="node-form-label">Install timeout</label>
<input id="ct_install_timeout" type="number" min="60" max="7200" class="node-form-input" placeholder="1800" />
</div>
</div>
<div class="node-form-field" style="margin-top: 12px;"> <div class="node-form-field" style="margin-top: 12px;">
<label class="node-form-label">Install script <span class="node-form-hint">(optional)</span></label> <label class="node-form-label">Install script <span class="node-form-hint">(optional)</span></label>
<textarea id="ct_install_script" class="node-form-textarea" placeholder="Commands that install files into /mnt/server"></textarea> <textarea id="ct_install_script" class="node-form-textarea" placeholder="Commands that install files into /mnt/server"></textarea>
@@ -1098,6 +1074,35 @@
</div> </div>
</div> </div>
<details class="node-form-section template-advanced-settings" id="ct_advanced_settings">
<summary class="template-advanced-summary">
<span class="node-form-section-title"><i class="fa-solid fa-sliders"></i> Advanced Settings</span>
<i class="fa-solid fa-chevron-down template-advanced-chevron"></i>
</summary>
<div class="template-advanced-content">
<div class="node-form-field">
<label class="node-form-label">Workdir <span class="node-form-hint">(optional)</span></label>
<input id="ct_workdir" type="text" class="node-form-input" placeholder="e.g. /app" />
</div>
<div class="node-form-grid" style="margin-top: 12px;">
<div class="node-form-field">
<label class="node-form-label">Installer image <span class="node-form-hint">(optional)</span></label>
<input id="ct_install_image" type="text" class="node-form-input" placeholder="e.g. debian:latest, ubuntu:22.04" />
</div>
<div class="node-form-field">
<label class="node-form-label">Install mount path</label>
<input id="ct_install_mount" type="text" class="node-form-input" placeholder="/mnt/server" />
</div>
</div>
<div class="node-form-grid" style="margin-top: 12px;">
<div class="node-form-field">
<label class="node-form-label">Runtime mount path</label>
<input id="ct_install_runtime" type="text" class="node-form-input" placeholder="/home/container" />
</div>
</div>
</div>
</details>
<div id="createTemplateFeedback" class="node-feedback"></div> <div id="createTemplateFeedback" class="node-feedback"></div>
</div> </div>
@@ -1111,6 +1116,38 @@
</div> </div>
</div> </div>
<div id="templateStoreOverlay" class="modal-overlay enterprise-modal-overlay" aria-hidden="true" inert>
<div class="enterprise-modal template-store-modal" id="templateStoreModal">
<div class="template-store-header">
<div class="template-store-brand">
<img src="https://cdn.jsdelivr.net/gh/antonndev/ADCDn/ADStore.webp" alt="AD Store" width="72" height="72">
</div>
<div class="template-store-toolbar">
<div class="template-store-tabs" role="tablist" aria-label="Template categories">
<button class="template-store-tab active" type="button" data-store-category="games">Games</button>
<button class="template-store-tab" type="button" data-store-category="communication">Communication</button>
<button class="template-store-tab" type="button" data-store-category="development">Development</button>
<button class="template-store-tab" type="button" data-store-category="hosting">Hosting</button>
<button class="template-store-tab" type="button" data-store-category="media">Media</button>
</div>
<div class="template-store-search">
<i class="fa-solid fa-magnifying-glass"></i>
<input type="search" id="templateStoreSearch" placeholder="Search store..." spellcheck="false" autocomplete="off">
</div>
</div>
<button class="enterprise-modal-close" id="templateStoreClose" aria-label="Close">
<i class="fa-solid fa-xmark"></i>
</button>
</div>
<div class="template-store-body">
<div id="templateStoreFeedback" class="template-store-feedback" aria-live="polite"></div>
<div id="templateStoreGrid" class="template-store-grid"></div>
</div>
</div>
</div>
<% } %>
<div id="modalOverlay" class="modal-overlay enterprise-modal-overlay" aria-hidden="true"> <div id="modalOverlay" class="modal-overlay enterprise-modal-overlay" aria-hidden="true">
<div class="enterprise-modal password-modal" id="changeModal"> <div class="enterprise-modal password-modal" id="changeModal">
<div class="enterprise-modal-header"> <div class="enterprise-modal-header">
@@ -1209,6 +1246,14 @@
</button> </button>
</div> </div>
</div> </div>
<div class="password-field">
<label class="password-label" id="adminChangePasswordCredentialLabel">2FA Code</label>
<div class="password-input-wrap">
<input type="text" id="adminChangePasswordCredential" placeholder="000000" autocomplete="one-time-code"
maxlength="6" inputmode="numeric" pattern="[0-9]*">
</div>
<small id="adminChangePasswordCredentialHint" style="color:var(--muted);font-size:12px;margin-top:4px;display:block;">Enter the code from your authenticator app.</small>
</div>
</div> </div>
<div id="adminChangePasswordFeedback" class="node-feedback" style="display:none;"></div> <div id="adminChangePasswordFeedback" class="node-feedback" style="display:none;"></div>
<div class="enterprise-modal-footer"> <div class="enterprise-modal-footer">
@@ -1273,8 +1318,8 @@
style="width: 130px; height: 90px;"> style="width: 130px; height: 90px;">
</div> </div>
<div class="enterprise-modal-titles"> <div class="enterprise-modal-titles">
<h3 class="enterprise-modal-title">Setup 2FA</h3> <h3 class="enterprise-modal-title">Reset 2FA</h3>
<p class="enterprise-modal-subtitle" id="qrResetUserEmail">Scan with your authenticator app.</p> <p class="enterprise-modal-subtitle" id="qrResetUserEmail">Reset two-factor authentication.</p>
</div> </div>
<button class="enterprise-modal-close" id="qrResetModalClose" aria-label="Close"> <button class="enterprise-modal-close" id="qrResetModalClose" aria-label="Close">
<i class="fa-solid fa-xmark"></i> <i class="fa-solid fa-xmark"></i>
@@ -1282,40 +1327,48 @@
</div> </div>
<div class="enterprise-modal-body" style="padding: 24px; text-align: center;"> <div class="enterprise-modal-body" style="padding: 24px; text-align: center;">
<div id="qrResetLoading" style="padding: 40px;"> <div id="qrResetConfirm">
<div style="background: rgba(245, 158, 11, 0.1); border-radius: 8px; padding: 12px; margin-bottom: 16px; text-align: left;">
<i class="fa-solid fa-triangle-exclamation" style="color: #f59e0b; margin-right: 8px;"></i>
<span style="font-size: 13px; color: rgba(255,255,255,0.8);">This removes the user's two-factor
authentication. They will be asked to set up a new authenticator from their account settings after
their next login. For security, you (the admin) are never shown the user's 2FA secret.</span>
</div>
<div style="margin-bottom: 8px; text-align: left;">
<label for="qrResetCredential" id="qrResetCredentialLabel"
style="display:block; font-size: 13px; color: var(--muted); margin-bottom: 6px;">Current Password</label>
<input type="password" id="qrResetCredential" class="node-form-input" autocomplete="current-password"
placeholder="Current password" style="width: 100%;">
<p id="qrResetCredentialHint" style="font-size: 12px; color: var(--muted); margin-top: 6px;">Enter your
current password to confirm this action.</p>
</div>
<div id="qrResetConfirmError"
style="display: none; color: #f44747; font-size: 13px; text-align: left; margin-top: 8px;"></div>
</div>
<div id="qrResetLoading" style="display: none; padding: 40px;">
<i class="fa-solid fa-spinner fa-spin" style="font-size: 32px; color: var(--muted);"></i> <i class="fa-solid fa-spinner fa-spin" style="font-size: 32px; color: var(--muted);"></i>
<p style="margin-top: 12px; color: var(--muted);">Generating new QR code...</p> <p style="margin-top: 12px; color: var(--muted);">Resetting 2FA...</p>
</div> </div>
<div id="qrResetContent" style="display: none;"> <div id="qrResetContent" style="display: none;">
<div <div style="background: rgba(52, 211, 153, 0.1); border-radius: 8px; padding: 16px;">
style="background: white; padding: 16px; border-radius: 12px; display: inline-block; margin-bottom: 16px;"> <i class="fa-solid fa-circle-check" style="color: #34d399; font-size: 24px;"></i>
<img id="qrResetImage" src="" alt="QR Code" style="width: 200px; height: 200px;"> <p style="margin-top: 10px; font-size: 14px; color: rgba(255,255,255,0.85);">2FA has been reset. The user
</div> must set up 2FA again from their account settings after their next login.</p>
<div style="margin-bottom: 16px;">
<p style="color: var(--muted); font-size: 13px; margin-bottom: 8px;">Or enter this secret manually:</p>
<div
style="background: rgba(0,0,0,0.2); padding: 12px 16px; border-radius: 8px; font-family: 'SF Mono', Monaco, monospace; font-size: 14px; letter-spacing: 2px; word-break: break-all;"
id="qrResetSecretText">
</div>
</div>
<div style="background: rgba(245, 158, 11, 0.1); border-radius: 8px; padding: 12px; margin-bottom: 16px;">
<i class="fa-solid fa-triangle-exclamation" style="color: #f59e0b; margin-right: 8px;"></i>
<span style="font-size: 13px; color: rgba(255,255,255,0.8);">The user must scan this QR code with their
authenticator app.</span>
</div> </div>
</div> </div>
<div id="qrResetError" style="display: none; color: #f44747; padding: 20px;"> <div id="qrResetError" style="display: none; color: #f44747; padding: 20px;">
<i class="fa-solid fa-circle-exclamation" style="font-size: 24px;"></i> <i class="fa-solid fa-circle-exclamation" style="font-size: 24px;"></i>
<p style="margin-top: 8px;" id="qrResetErrorText">Failed to generate QR code</p> <p style="margin-top: 8px;" id="qrResetErrorText">Failed to reset 2FA</p>
</div> </div>
</div> </div>
<div class="enterprise-modal-footer"> <div class="enterprise-modal-footer">
<button class="enterprise-btn-primary" id="qrResetDoneBtn"><i class="fa-solid fa-check"></i> Done</button> <button class="enterprise-btn-primary" id="qrResetDoneBtn"><i class="fa-solid fa-shield-halved"></i> Reset 2FA</button>
</div> </div>
</div> </div>
</div> </div>
@@ -1408,7 +1461,7 @@
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label" for="createUserPassword">Password</label> <label class="node-form-label" for="createUserPassword">Password</label>
<div class="create-user-password-wrap"> <div class="create-user-password-wrap">
<input type="password" id="createUserPassword" class="node-form-input" placeholder="12-72 characters" <input type="password" id="createUserPassword" class="node-form-input" placeholder="8-72 characters"
autocomplete="new-password" maxlength="72"> autocomplete="new-password" maxlength="72">
<button type="button" class="password-toggle create-user-password-toggle" data-target="createUserPassword" aria-label="Show password"> <button type="button" class="password-toggle create-user-password-toggle" data-target="createUserPassword" aria-label="Show password">
<i class="fa-solid fa-eye"></i> <i class="fa-solid fa-eye"></i>
@@ -1428,6 +1481,21 @@
</div> </div>
</div> </div>
<div class="node-form-section">
<label class="node-form-label" for="createUserEnableTwoFactor">Two-Factor Authentication</label>
<label class="create-user-2fa-option" for="createUserEnableTwoFactor">
<span class="create-user-2fa-option-main">
<span class="create-user-2fa-option-icon"><i class="fa-solid fa-shield-halved"></i></span>
<span class="create-user-2fa-option-copy">
<strong>Enable 2FA setup</strong>
<small>Generate a QR code and recovery codes for this account.</small>
</span>
</span>
<input type="checkbox" id="createUserEnableTwoFactor">
<span class="create-user-2fa-switch" aria-hidden="true"></span>
</label>
</div>
<div class="node-form-section create-user-admin-stepup" id="createUserAdminStepUp" style="display: none;"> <div class="node-form-section create-user-admin-stepup" id="createUserAdminStepUp" style="display: none;">
<div class="node-form-section-title"><i class="fa-solid fa-shield-halved"></i> Admin Approval</div> <div class="node-form-section-title"><i class="fa-solid fa-shield-halved"></i> Admin Approval</div>
<div class="node-form-grid"> <div class="node-form-grid">
@@ -1441,7 +1509,7 @@
</button> </button>
</div> </div>
</div> </div>
<div class="node-form-field"> <div class="node-form-field" id="createAdminTwoFactorField">
<label class="node-form-label" for="createAdminTwoFactor">2FA Code</label> <label class="node-form-label" for="createAdminTwoFactor">2FA Code</label>
<input type="text" id="createAdminTwoFactor" class="node-form-input create-user-2fa-input" <input type="text" id="createAdminTwoFactor" class="node-form-input create-user-2fa-input"
placeholder="000000" autocomplete="one-time-code" maxlength="6" inputmode="numeric" pattern="[0-9]*"> placeholder="000000" autocomplete="one-time-code" maxlength="6" inputmode="numeric" pattern="[0-9]*">
@@ -1479,24 +1547,24 @@
</div> </div>
<div class="enterprise-modal-body" style="padding: 24px; text-align: center;"> <div class="enterprise-modal-body" style="padding: 24px; text-align: center;">
<div style="background: rgba(245, 158, 11, 0.1); border-radius: 8px; padding: 12px; margin-bottom: 16px;"> <div id="credentialsOneTimeNotice" style="background: rgba(245, 158, 11, 0.1); border-radius: 8px; padding: 12px; margin-bottom: 16px;">
<i class="fa-solid fa-triangle-exclamation" style="color: #f59e0b; margin-right: 8px;"></i> <i class="fa-solid fa-triangle-exclamation" style="color: #f59e0b; margin-right: 8px;"></i>
<span style="font-size: 13px; color: rgba(255,255,255,0.8);">Give these credentials to the user. They can only <span id="credentialsOneTimeNoticeText" style="font-size: 13px; color: rgba(255,255,255,0.8);">Give these credentials to the user. They can only
be shown ONCE!</span> be shown ONCE!</span>
</div> </div>
<div style="background: white; padding: 16px; border-radius: 12px; display: inline-block; margin-bottom: 16px;"> <div id="credentialsQRCodeBlock" style="background: white; padding: 16px; border-radius: 12px; display: inline-block; margin-bottom: 16px;">
<img id="credentialsQRCode" src="" alt="QR Code" style="width: 160px; height: 160px;"> <img id="credentialsQRCode" src="" alt="QR Code" style="width: 160px; height: 160px;">
</div> </div>
<div style="margin-bottom: 16px;"> <div id="credentialsSecretBlock" style="margin-bottom: 16px;">
<p style="color: var(--muted); font-size: 13px; margin-bottom: 8px;">2FA Secret:</p> <p style="color: var(--muted); font-size: 13px; margin-bottom: 8px;">2FA Secret:</p>
<div id="credentialsSecret" <div id="credentialsSecret"
style="background: rgba(0,0,0,0.2); padding: 12px 16px; border-radius: 8px; font-family: 'SF Mono', Monaco, monospace; font-size: 14px; letter-spacing: 2px; word-break: break-all;"> style="background: rgba(0,0,0,0.2); padding: 12px 16px; border-radius: 8px; font-family: 'SF Mono', Monaco, monospace; font-size: 14px; letter-spacing: 2px; word-break: break-all;">
</div> </div>
</div> </div>
<div style="margin-bottom: 16px;"> <div id="credentialsRecoveryBlock" style="margin-bottom: 16px;">
<p style="color: var(--muted); font-size: 13px; margin-bottom: 8px;">Recovery Codes:</p> <p style="color: var(--muted); font-size: 13px; margin-bottom: 8px;">Recovery Codes:</p>
<div id="credentialsRecoveryCodes" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px;"> <div id="credentialsRecoveryCodes" style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 8px;">
</div> </div>
@@ -1882,10 +1950,6 @@
<label class="node-form-label">Daemon Port</label> <label class="node-form-label">Daemon Port</label>
<input id="cn_daemon_port" type="number" class="node-form-input" min="1" max="65535" step="1" placeholder="8080" value="8080" /> <input id="cn_daemon_port" type="number" class="node-form-input" min="1" max="65535" step="1" placeholder="8080" value="8080" />
</div> </div>
<div class="node-form-field">
<label class="node-form-label">SFTP Port</label>
<input id="cn_sftp_port" type="number" class="node-form-input" min="1" max="65535" step="1" placeholder="2022" value="2022" />
</div>
</div> </div>
</div> </div>
@@ -2109,6 +2173,16 @@
</div> </div>
</div> </div>
<div class="node-form-section">
<div class="node-form-section-title"><i class="fa-solid fa-shield-halved"></i> Security Verification</div>
<div class="node-form-field">
<label class="node-form-label" id="maintenanceCredentialLabel">2FA Code</label>
<input type="text" id="maintenanceCredentialInput" class="node-form-input" placeholder="000000"
autocomplete="one-time-code" maxlength="6" inputmode="numeric" pattern="[0-9]*">
<span class="node-form-hint" id="maintenanceCredentialHint">Enter the code from your authenticator app.</span>
</div>
</div>
<div id="maintenanceModalFeedback" class="node-feedback"></div> <div id="maintenanceModalFeedback" class="node-feedback"></div>
</div> </div>
@@ -2144,11 +2218,12 @@
</div> </div>
<div class="password-field"> <div class="password-field">
<label class="password-label">2FA Code</label> <label class="password-label" id="sessionRevokeCredentialLabel">2FA Code</label>
<div class="password-input-wrap"> <div class="password-input-wrap">
<input type="text" id="sessionRevokeTwoFactorInput" placeholder="000000" autocomplete="one-time-code" <input type="text" id="sessionRevokeTwoFactorInput" placeholder="000000" autocomplete="one-time-code"
maxlength="6" inputmode="numeric" pattern="[0-9]*"> maxlength="6" inputmode="numeric" pattern="[0-9]*">
</div> </div>
<small id="sessionRevokeCredentialHint" style="color:var(--muted);font-size:12px;margin-top:4px;display:block;">Enter the code from your authenticator app.</small>
</div> </div>
</div> </div>
@@ -2313,11 +2388,28 @@
<label class="node-form-label">Daemon Port</label> <label class="node-form-label">Daemon Port</label>
<input id="nm_daemon_port" type="number" class="node-form-input" min="1" max="65535" step="1" /> <input id="nm_daemon_port" type="number" class="node-form-input" min="1" max="65535" step="1" />
</div> </div>
<div class="node-form-field">
<label class="node-form-label">SFTP Port</label>
<input id="nm_sftp_port" type="number" class="node-form-input" min="1" max="65535" step="1" />
</div> </div>
</div> </div>
<div class="node-form-section" id="nm_disks_section">
<div class="node-form-section-title"><i class="fa-solid fa-hard-drive"></i> Additional Disks</div>
<p class="node-linking-desc" style="margin-top:-4px;">Mount extra storage volumes for this node. The
primary disk <code>/var/lib/node</code> is always available and cannot be removed.</p>
<div id="nm_disks_list" class="node-disks-list"></div>
<div id="nm_disks_feedback" class="node-feedback"></div>
<div class="node-disks-add" style="display:flex; gap:10px; align-items:flex-end; flex-wrap:wrap; margin-top:10px;">
<div class="node-form-field" style="flex:1 1 220px; min-width:200px;">
<label class="node-form-label" for="nm_disk_mount">Mount Path</label>
<input id="nm_disk_mount" type="text" class="node-form-input" placeholder="/mnt/disk1" autocomplete="off" />
</div>
<div class="node-form-field" style="flex:0 0 130px;">
<label class="node-form-label" for="nm_disk_limit">Limit (GB)</label>
<input id="nm_disk_limit" type="number" class="node-form-input" min="1" step="1" placeholder="e.g. 100" />
</div>
<button type="button" class="enterprise-btn-secondary" id="nm_disk_add" style="flex:0 0 auto;">
<i class="fa-solid fa-plus"></i> Add Disk
</button>
</div>
</div> </div>
<div id="nm_saveFeedback" class="node-feedback"></div> <div id="nm_saveFeedback" class="node-feedback"></div>
@@ -2344,7 +2436,7 @@
<div class="node-linking-header"> <div class="node-linking-header">
<div class="node-linking-info"> <div class="node-linking-info">
<div class="node-form-section-title"><i class="fa-solid fa-terminal"></i> Setup Command</div> <div class="node-form-section-title"><i class="fa-solid fa-terminal"></i> Setup Command</div>
<p class="node-linking-desc">One-time command to configure the node</p> <p class="node-linking-desc">One-time command to install and configure the node</p>
</div> </div>
<button class="enterprise-btn-secondary node-generate-btn" id="nm_showCmd"><i <button class="enterprise-btn-secondary node-generate-btn" id="nm_showCmd"><i
class="fa-solid fa-wand-magic-sparkles"></i> Generate</button> class="fa-solid fa-wand-magic-sparkles"></i> Generate</button>
@@ -2366,6 +2458,12 @@
<h4 class="node-danger-title">Delete this node</h4> <h4 class="node-danger-title">Delete this node</h4>
<p class="node-danger-desc">This action is permanent and cannot be undone. The node must have <strong>no <p class="node-danger-desc">This action is permanent and cannot be undone. The node must have <strong>no
servers</strong> assigned before deletion.</p> servers</strong> assigned before deletion.</p>
<div class="node-delete-security-field">
<label class="node-form-label" id="nm_deleteCredentialLabel">2FA Code</label>
<input type="text" id="nm_deleteCredential" class="node-form-input" placeholder="000000"
autocomplete="one-time-code" maxlength="6" inputmode="numeric" pattern="[0-9]*">
<span class="node-form-hint" id="nm_deleteCredentialHint">Enter the code from your authenticator app.</span>
</div>
</div> </div>
<button class="node-danger-btn" id="nm_delete"><i class="fa-solid fa-trash"></i> Delete Node</button> <button class="node-danger-btn" id="nm_delete"><i class="fa-solid fa-trash"></i> Delete Node</button>
<div id="nm_deleteFeedback" class="node-feedback node-danger-feedback"></div> <div id="nm_deleteFeedback" class="node-feedback node-danger-feedback"></div>
@@ -2413,11 +2511,12 @@
<input id="res_serverName" type="text" class="node-form-input" maxlength="120" placeholder="My Server" /> <input id="res_serverName" type="text" class="node-form-input" maxlength="120" placeholder="My Server" />
</div> </div>
<div class="node-form-field resource-rename-action"> <div class="node-form-field resource-rename-action">
<label class="node-form-label">Apply Rename</label> <label class="node-form-label">
Apply Rename
</label>
<button type="button" id="res_renameServer" class="enterprise-btn-secondary resource-rename-btn"> <button type="button" id="res_renameServer" class="enterprise-btn-secondary resource-rename-btn">
<i class="fa-solid fa-pen"></i> Rename <i class="fa-solid fa-pen"></i> Rename
</button> </button>
<small class="resource-hint">Renames safely across panel, cache, and schedules.</small>
</div> </div>
</div> </div>
</div> </div>
@@ -2429,31 +2528,28 @@
</div> </div>
<div class="node-form-grid"> <div class="node-form-grid">
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">RAM</label> <label class="node-form-label">RAM <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">Memory limit. Typical: 1024–4096 MB.</span></span></label>
<div class="resource-input-wrapper"> <div class="resource-input-wrapper">
<input id="res_ramMb" type="number" class="node-form-input" placeholder="2048" min="128" step="128" /> <input id="res_ramMb" type="number" class="node-form-input" placeholder="2048" min="128" step="128" />
<span class="resource-input-suffix">MB</span> <span class="resource-input-suffix">MB</span>
</div> </div>
<small class="resource-hint">Memory limit. Typical: 1024–4096 MB.</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">CPU Cores</label> <label class="node-form-label">CPU Cores <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">Decimal supported (e.g. 1.5).</span></span></label>
<div class="resource-input-wrapper"> <div class="resource-input-wrapper">
<input id="res_cpuCores" type="number" class="node-form-input" placeholder="2" min="0.5" step="0.5" /> <input id="res_cpuCores" type="number" class="node-form-input" placeholder="2" min="0.5" step="0.5" />
<span class="resource-input-suffix">cores</span> <span class="resource-input-suffix">cores</span>
</div> </div>
<small class="resource-hint">Decimal supported (e.g. 1.5).</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">Storage</label> <label class="node-form-label">Storage <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">Max disk space for server files.</span></span></label>
<div class="resource-input-wrapper"> <div class="resource-input-wrapper">
<input id="res_storageMb" type="number" class="node-form-input" placeholder="500" min="1" step="1" /> <input id="res_storageMb" type="number" class="node-form-input" placeholder="500" min="1" step="1" />
<span class="resource-input-suffix">MB</span> <span class="resource-input-suffix">MB</span>
</div> </div>
<small class="resource-hint">Max disk space for server files.</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">Swap</label> <label class="node-form-label">Swap <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">-1 = disabled, 0 = unlimited.</span></span></label>
<select id="res_swapMb" class="node-form-input resource-select"> <select id="res_swapMb" class="node-form-input resource-select">
<option value="-1">Disabled</option> <option value="-1">Disabled</option>
<option value="0">Unlimited</option> <option value="0">Unlimited</option>
@@ -2462,7 +2558,6 @@
<option value="1024">1024 MB</option> <option value="1024">1024 MB</option>
<option value="2048">2048 MB</option> <option value="2048">2048 MB</option>
</select> </select>
<small class="resource-hint">-1 = disabled, 0 = unlimited.</small>
</div> </div>
</div> </div>
</div> </div>
@@ -2474,40 +2569,34 @@
</div> </div>
<div class="node-form-grid"> <div class="node-form-grid">
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">Max Backups</label> <label class="node-form-label">Max Backups <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">0 = unlimited.</span></span></label>
<div class="resource-input-wrapper"> <div class="resource-input-wrapper">
<input id="res_backupsMax" type="number" class="node-form-input" placeholder="5" min="0" step="1" /> <input id="res_backupsMax" type="number" class="node-form-input" placeholder="5" min="0" step="1" />
<span class="resource-input-suffix">backups</span> <span class="resource-input-suffix">backups</span>
</div> </div>
<small class="resource-hint">0 = unlimited.</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">Max Schedules</label> <label class="node-form-label">Max Schedules <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">0 = unlimited.</span></span></label>
<div class="resource-input-wrapper"> <div class="resource-input-wrapper">
<input id="res_maxSchedules" type="number" class="node-form-input" placeholder="10" min="0" step="1" /> <input id="res_maxSchedules" type="number" class="node-form-input" placeholder="10" min="0" step="1" />
<span class="resource-input-suffix">schedules</span> <span class="resource-input-suffix">schedules</span>
</div> </div>
<small class="resource-hint">0 = unlimited.</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">I/O Priority</label> <label class="node-form-label">I/O Priority <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">Disk I/O weight (10–1000).</span></span></label>
<input id="res_ioWeight" type="number" class="node-form-input" placeholder="500" min="10" max="1000" step="10" /> <input id="res_ioWeight" type="number" class="node-form-input" placeholder="500" min="10" max="1000" step="10" />
<small class="resource-hint">Disk I/O weight (10–1000).</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">CPU Priority</label> <label class="node-form-label">CPU Priority <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">CPU weight (1–1000).</span></span></label>
<input id="res_cpuWeight" type="number" class="node-form-input" placeholder="500" min="1" max="1000" step="10" /> <input id="res_cpuWeight" type="number" class="node-form-input" placeholder="500" min="1" max="1000" step="10" />
<small class="resource-hint">CPU weight (1–1000).</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">Process Limit</label> <label class="node-form-label">Process Limit <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">Max processes (64–4096).</span></span></label>
<input id="res_pidsLimit" type="number" class="node-form-input" placeholder="512" min="64" max="4096" step="64" /> <input id="res_pidsLimit" type="number" class="node-form-input" placeholder="512" min="64" max="4096" step="64" />
<small class="resource-hint">Max processes (64–4096).</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">File Limit</label> <label class="node-form-label">File Limit <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">Max open files (1024–1048576).</span></span></label>
<input id="res_fileLimit" type="number" class="node-form-input" placeholder="65535" min="1024" max="1048576" step="1024" /> <input id="res_fileLimit" type="number" class="node-form-input" placeholder="65535" min="1024" max="1048576" step="1024" />
<small class="resource-hint">Max open files (1024–1048576).</small>
</div> </div>
</div> </div>
<div class="resource-usage-row" id="res_usageRow"> <div class="resource-usage-row" id="res_usageRow">
@@ -2531,28 +2620,25 @@
</div> </div>
<div class="node-form-grid"> <div class="node-form-grid">
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">Inbound</label> <label class="node-form-label">Inbound <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">Packets received. Leave empty to disable.</span></span></label>
<div class="resource-input-wrapper"> <div class="resource-input-wrapper">
<input id="res_networkInboundLimitMb" type="number" class="node-form-input" placeholder="10240" min="1" step="1" /> <input id="res_networkInboundLimitMb" type="number" class="node-form-input" placeholder="10240" min="1" step="1" />
<span class="resource-input-suffix">MB</span> <span class="resource-input-suffix">MB</span>
</div> </div>
<small class="resource-hint">Packets received. Leave empty to disable.</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">Outbound</label> <label class="node-form-label">Outbound <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">Packets sent. Leave empty to disable.</span></span></label>
<div class="resource-input-wrapper"> <div class="resource-input-wrapper">
<input id="res_networkOutboundLimitMb" type="number" class="node-form-input" placeholder="10240" min="1" step="1" /> <input id="res_networkOutboundLimitMb" type="number" class="node-form-input" placeholder="10240" min="1" step="1" />
<span class="resource-input-suffix">MB</span> <span class="resource-input-suffix">MB</span>
</div> </div>
<small class="resource-hint">Packets sent. Leave empty to disable.</small>
</div> </div>
<div class="node-form-field"> <div class="node-form-field">
<label class="node-form-label">Reset After</label> <label class="node-form-label">Reset After <span class="resource-tooltip"><i class="fa-solid fa-circle-question"></i><span class="resource-tooltip-card">When limits reset. Default: 1440 min.</span></span></label>
<div class="resource-input-wrapper"> <div class="resource-input-wrapper">
<input id="res_networkResetMinutes" type="number" class="node-form-input" placeholder="1440" min="1" step="1" /> <input id="res_networkResetMinutes" type="number" class="node-form-input" placeholder="1440" min="1" step="1" />
<span class="resource-input-suffix">min</span> <span class="resource-input-suffix">min</span>
</div> </div>
<small class="resource-hint">When limits reset. Default: 1440 min.</small>
</div> </div>
</div> </div>
</div> </div>
@@ -2585,12 +2671,11 @@
<label class="node-form-label">Current</label> <label class="node-form-label">Current</label>
<div class="startup-cmd-display" id="res_startupDisplay"> <div class="startup-cmd-display" id="res_startupDisplay">
<div class="startup-cmd-display-header"> <div class="startup-cmd-display-header">
<div class="startup-cmd-display-label"><i class="fa-solid fa-terminal"></i> Running command</div> <pre class="startup-cmd-code" id="res_startupPreview"><code>No startup command configured</code></pre>
<button type="button" class="startup-cmd-copy-btn" id="res_copyStartupCmd" title="Copy"> <button type="button" class="startup-cmd-copy-btn" id="res_copyStartupCmd" title="Copy">
<i class="fa-solid fa-copy"></i> <i class="fa-solid fa-copy"></i>
</button> </button>
</div> </div>
<pre class="startup-cmd-code" id="res_startupPreview"><code>No startup command configured</code></pre>
</div> </div>
</div> </div>
<div class="node-form-field" style="margin-top: 16px;"> <div class="node-form-field" style="margin-top: 16px;">
@@ -2599,14 +2684,7 @@
<div class="startup-cmd-editor-gutter"><span class="startup-cmd-prompt">$</span></div> <div class="startup-cmd-editor-gutter"><span class="startup-cmd-prompt">$</span></div>
<textarea id="res_startupCommand" class="node-form-textarea startup-cmd-textarea" rows="4" spellcheck="false" placeholder="java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui"></textarea> <textarea id="res_startupCommand" class="node-form-textarea startup-cmd-textarea" rows="4" spellcheck="false" placeholder="java -Xms128M -Xmx{RAM_MB}M -jar /data/server.jar nogui"></textarea>
</div> </div>
<div class="startup-cmd-variables">
<span class="startup-cmd-var-label">Available variables:</span>
<code class="startup-cmd-var">{PORT}</code>
<code class="startup-cmd-var">{DATA_DIR}</code>
<code class="startup-cmd-var">{START_FILE}</code>
<code class="startup-cmd-var">{RAM_MB}</code>
<code class="startup-cmd-var">{CPU_CORES}</code>
</div>
<small id="res_startupCommandHelp" class="startup-cmd-help"></small> <small id="res_startupCommandHelp" class="startup-cmd-help"></small>
</div> </div>
<div class="node-form-field minecraft-java-field" id="res_javaVersionField" hidden> <div class="node-form-field minecraft-java-field" id="res_javaVersionField" hidden>
@@ -2615,7 +2693,7 @@
<i class="fa-brands fa-java"></i> <i class="fa-brands fa-java"></i>
<select id="res_javaVersion" class="node-form-input resource-select minecraft-java-select" aria-label="Minecraft Java version"></select> <select id="res_javaVersion" class="node-form-input resource-select minecraft-java-select" aria-label="Minecraft Java version"></select>
</div> </div>
<small class="resource-hint" id="res_javaVersionHint">Runs this Minecraft server with the selected Eclipse Temurin JRE image.</small> <small class="resource-hint" id="res_javaVersionHint"></small>
</div> </div>
</div> </div>
@@ -2682,7 +2760,6 @@
<i class="fa-solid fa-plus"></i> Add Rule <i class="fa-solid fa-plus"></i> Add Rule
</button> </button>
</div> </div>
<small class="resource-hint">Internal port must be allocated. Public port from node range.</small>
</div> </div>
</div> </div>
@@ -3483,6 +3560,17 @@
style="width: 100%; height: 48px; padding: 0 16px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.08); background: rgba(0,0,0,0.2); color: rgba(255,255,255,0.95); font-size: 14px; outline: none;"> style="width: 100%; height: 48px; padding: 0 16px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.08); background: rgba(0,0,0,0.2); color: rgba(255,255,255,0.95); font-size: 14px; outline: none;">
</div> </div>
<div style="margin-bottom: 16px;">
<label id="webhookCredentialLabel"
style="display: block; font-size: 13px; font-weight: 600; color: rgba(255,255,255,0.7); margin-bottom: 8px;">
2FA Code
</label>
<input type="text" id="webhookCredentialInput" placeholder="000000" autocomplete="one-time-code"
maxlength="6" inputmode="numeric" pattern="[0-9]*"
style="width: 100%; height: 48px; padding: 0 16px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.08); background: rgba(0,0,0,0.2); color: rgba(255,255,255,0.95); font-size: 14px; outline: none;">
<small id="webhookCredentialHint" style="display:block;margin-top:6px;font-size:12px;color:var(--muted);">Enter the code from your authenticator app.</small>
</div>
<div style="background: rgba(59, 130, 246, 0.1); border-radius: 8px; padding: 12px; margin-top: 12px;"> <div style="background: rgba(59, 130, 246, 0.1); border-radius: 8px; padding: 12px; margin-top: 12px;">
<i class="fa-solid fa-circle-info" style="color: #3b82f6; margin-right: 8px;"></i> <i class="fa-solid fa-circle-info" style="color: #3b82f6; margin-right: 8px;"></i>
<span style="font-size: 13px; color: rgba(255,255,255,0.8);">Paste a Discord webhook URL. Go to your Discord <span style="font-size: 13px; color: rgba(255,255,255,0.8);">Paste a Discord webhook URL. Go to your Discord
@@ -3522,6 +3610,17 @@
<span style="font-size: 13px; color: rgba(255,255,255,0.8);" id="webhookDeleteText">Are you sure you want to <span style="font-size: 13px; color: rgba(255,255,255,0.8);" id="webhookDeleteText">Are you sure you want to
remove this webhook?</span> remove this webhook?</span>
</div> </div>
<div style="margin-top: 16px;">
<label id="webhookDeleteCredentialLabel"
style="display: block; font-size: 13px; font-weight: 600; color: rgba(255,255,255,0.7); margin-bottom: 8px;">
2FA Code
</label>
<input type="text" id="webhookDeleteCredentialInput" placeholder="000000" autocomplete="one-time-code"
maxlength="6" inputmode="numeric" pattern="[0-9]*"
style="width: 100%; height: 48px; padding: 0 16px; border-radius: 12px; border: 1px solid rgba(255,255,255,0.08); background: rgba(0,0,0,0.2); color: rgba(255,255,255,0.95); font-size: 14px; outline: none;">
<small id="webhookDeleteCredentialHint" style="display:block;margin-top:6px;font-size:12px;color:var(--muted);">Enter the code from your authenticator app.</small>
</div>
<div id="webhookDeleteError" style="display: none; color: #f44747; font-size: 13px; margin-top: 12px;"></div>
</div> </div>
<div class="enterprise-modal-footer"> <div class="enterprise-modal-footer">
+1270
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -0,0 +1,16 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<title>ADPanel | Suspended server</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
html,body{width:100%;height:100%;overflow:hidden;touch-action:none}
body{background:#000}
body::before{content:'';position:fixed;top:0;left:0;width:100%;height:100%;background:url('https://cdn.jsdelivr.net/gh/antonndev/ADCDn/suspended.avif') no-repeat center/cover;pointer-events:none;user-select:none;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none}
</style>
<script>document.addEventListener('wheel',e=>e.ctrlKey&&e.preventDefault(),{passive:false});document.addEventListener('keydown',e=>(e.ctrlKey&&(e.key==='+'||e.key==='-'||e.key==='0'))&&e.preventDefault())</script>
</head>
<body></body>
</html>