Files
Kelx/cmd/sshterm/main.go
T
2026-06-10 17:04:11 +00:00

2288 lines
62 KiB
Go

package main
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"html"
"io"
"log"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
"golang.org/x/crypto/ssh"
"nhooyr.io/websocket"
"nhooyr.io/websocket/wsjson"
)
type tokenPayload struct {
Version int `json:"v"`
UserID string `json:"uid"`
IP string `json:"ip"`
ExpMS int64 `json:"exp"`
}
type wsMessage struct {
Type string `json:"type"`
SessionID string `json:"sessionId,omitempty"`
Command string `json:"command,omitempty"`
Password string `json:"password,omitempty"`
Data string `json:"data,omitempty"`
Cols int `json:"cols,omitempty"`
Rows int `json:"rows,omitempty"`
Error string `json:"error,omitempty"`
}
type sshTarget struct {
User string
Host string
Port int
}
type appConfig struct {
BindAddr string
Secret []byte
PanelRoot string
ReadTimout time.Duration
UseTLS bool
TLSCert string
TLSKey string
WSFallback string
WSOrigin string
}
const terminalResumeGrace = 15 * time.Minute
const terminalIdleTimeout = 20 * time.Minute
const terminalReplayLimit = 128 * 1024
type terminalSession struct {
owner string
id string
client *ssh.Client
session *ssh.Session
stdin io.WriteCloser
done chan struct{}
closeOnce sync.Once
mu sync.Mutex
subs map[chan wsMessage]struct{}
replay []byte
closed bool
waitErr error
lastInput time.Time
lastDetach time.Time
}
var terminalSessions = struct {
sync.Mutex
items map[string]*terminalSession
}{items: make(map[string]*terminalSession)}
func main() {
cwd, _ := os.Getwd()
panelRoot := strings.TrimSpace(os.Getenv("SSH_TERM_PANEL_ROOT"))
if panelRoot == "" {
panelRoot = cwd
}
_ = loadDotEnv(filepath.Join(panelRoot, ".env"))
bind := strings.TrimSpace(os.Getenv("SSH_TERM_BIND"))
if bind == "" {
port := strings.TrimSpace(os.Getenv("SSH_TERM_PORT"))
if port == "" {
port = "9393"
}
bind = "0.0.0.0:" + port
}
secretText := strings.TrimSpace(os.Getenv("SSH_TERM_TOKEN_SECRET"))
if secretText == "" {
sessionSecret := strings.TrimSpace(os.Getenv("SESSION_SECRET"))
if sessionSecret != "" {
h := hmac.New(sha256.New, []byte(sessionSecret))
_, _ = h.Write([]byte("adpanel-ssh-term-token-key-v1"))
secretText = fmt.Sprintf("%x", h.Sum(nil))
}
}
if len(secretText) < 16 {
log.Fatal("missing SSH_TERM_TOKEN_SECRET or SESSION_SECRET (must be >= 16 chars)")
}
cfg := appConfig{
BindAddr: bind,
Secret: []byte(secretText),
PanelRoot: panelRoot,
ReadTimout: 20 * time.Second,
UseTLS: parseBoolEnv("ENABLE_HTTPS"),
TLSCert: strings.TrimSpace(os.Getenv("SSL_CERT_PATH")),
TLSKey: strings.TrimSpace(os.Getenv("SSL_KEY_PATH")),
WSFallback: buildWSFallbackURL(bind, strings.TrimSpace(os.Getenv("SSH_TERM_PUBLIC_URL")), strings.TrimSpace(os.Getenv("SSH_TERM_WS_PUBLIC_URL"))),
}
cfg.WSOrigin = websocketOrigin(cfg.WSFallback)
if cfg.UseTLS && (cfg.TLSCert == "" || cfg.TLSKey == "") {
cfg.UseTLS = false
}
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
handleIndex(cfg, w, r)
})
mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
handleWS(cfg, w, r)
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Cache-Control", "no-store")
_, _ = w.Write([]byte("ok"))
})
srv := &http.Server{
Addr: cfg.BindAddr,
Handler: mux,
ReadHeaderTimeout: 5 * time.Second,
IdleTimeout: 60 * time.Second,
WriteTimeout: 0,
}
if cfg.UseTLS {
log.Printf("[ssh-term] listening on https://%s", cfg.BindAddr)
if err := srv.ListenAndServeTLS(cfg.TLSCert, cfg.TLSKey); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server failed: %v", err)
}
return
}
log.Printf("[ssh-term] listening on http://%s", cfg.BindAddr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("server failed: %v", err)
}
}
func parseBoolEnv(key string) bool {
v := strings.ToLower(strings.TrimSpace(os.Getenv(key)))
return v == "1" || v == "true" || v == "yes" || v == "on"
}
func handleIndex(cfg appConfig, w http.ResponseWriter, r *http.Request) {
token := strings.TrimSpace(r.URL.Query().Get("token"))
payload, err := verifyToken(cfg.Secret, token, requestIP(r))
if err != nil {
log.Printf("[ssh-term] index token reject: %v", err)
http.Error(w, "invalid or expired terminal token", http.StatusUnauthorized)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Referrer-Policy", "no-referrer")
cspConnect := "connect-src " + websocketConnectSrc(cfg.WSOrigin) + ";"
w.Header().Set("Content-Security-Policy", "default-src 'self'; style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; "+cspConnect+" img-src 'self' data:;")
page := strings.ReplaceAll(indexHTML, "__TOKEN__", html.EscapeString(token))
page = strings.ReplaceAll(page, "__USER__", html.EscapeString(payload.UserID))
page = strings.ReplaceAll(page, "__WS_FALLBACK__", html.EscapeString(cfg.WSFallback))
_, _ = w.Write([]byte(page))
}
func buildWSFallbackURL(bindAddr string, publicURL string, wsPublicURL string) string {
if raw := strings.TrimSpace(wsPublicURL); raw != "" {
if u, ok := normalizeWSURL(raw); ok {
return u
}
}
if raw := strings.TrimSpace(publicURL); raw != "" {
value := raw
if !strings.HasPrefix(strings.ToLower(value), "http://") && !strings.HasPrefix(strings.ToLower(value), "https://") {
value = "http://" + value
}
if u, err := url.Parse(value); err == nil {
wsProto := "ws"
if strings.EqualFold(u.Scheme, "https") {
wsProto = "wss"
}
host := u.Host
if host != "" {
return wsProto + "://" + host + "/ws"
}
}
}
_ = bindAddr
return ""
}
func normalizeWSURL(raw string) (string, bool) {
value := strings.TrimSpace(raw)
if value == "" {
return "", false
}
if !strings.HasPrefix(strings.ToLower(value), "ws://") && !strings.HasPrefix(strings.ToLower(value), "wss://") {
value = "ws://" + value
}
u, err := url.Parse(value)
if err != nil || u == nil || u.Host == "" {
return "", false
}
pathPart := u.Path
if strings.TrimSpace(pathPart) == "" {
pathPart = "/ws"
}
u.Path = pathPart
u.RawQuery = ""
u.Fragment = ""
return u.String(), true
}
func websocketOrigin(wsURL string) string {
u, err := url.Parse(strings.TrimSpace(wsURL))
if err != nil || u == nil || u.Host == "" {
return ""
}
if u.Scheme != "ws" && u.Scheme != "wss" {
return ""
}
return u.Scheme + "://" + u.Host
}
func websocketConnectSrc(wsOrigin string) string {
base := []string{"'self'"}
u, err := url.Parse(strings.TrimSpace(wsOrigin))
if err != nil || u == nil || u.Host == "" {
return strings.Join(base, " ")
}
base = append(base, "ws://"+u.Host, "wss://"+u.Host)
seen := make(map[string]struct{}, len(base))
uniq := make([]string, 0, len(base))
for _, item := range base {
if _, ok := seen[item]; ok {
continue
}
seen[item] = struct{}{}
uniq = append(uniq, item)
}
return strings.Join(uniq, " ")
}
func normalizeTerminalSessionID(raw string) string {
id := strings.TrimSpace(raw)
if len(id) < 8 || len(id) > 128 {
return ""
}
for _, r := range id {
if (r >= 'a' && r <= 'z') || (r >= 'A' && r <= 'Z') || (r >= '0' && r <= '9') || r == '-' || r == '_' || r == '.' || r == ':' {
continue
}
return ""
}
return id
}
func terminalSessionKey(owner string, id string) string {
return owner + "\x00" + id
}
func getTerminalSession(owner string, id string) *terminalSession {
id = normalizeTerminalSessionID(id)
if owner == "" || id == "" {
return nil
}
terminalSessions.Lock()
ts := terminalSessions.items[terminalSessionKey(owner, id)]
terminalSessions.Unlock()
if ts == nil {
return nil
}
ts.mu.Lock()
closed := ts.closed
ts.mu.Unlock()
if closed {
return nil
}
return ts
}
func registerTerminalSession(ts *terminalSession) {
if ts == nil || ts.owner == "" || ts.id == "" {
return
}
key := terminalSessionKey(ts.owner, ts.id)
terminalSessions.Lock()
if old := terminalSessions.items[key]; old != nil && old != ts {
go old.closeWithMessage("\r\n[adpanel] terminal replaced by a new connection\r\n")
}
terminalSessions.items[key] = ts
terminalSessions.Unlock()
}
func removeTerminalSession(ts *terminalSession) {
if ts == nil || ts.owner == "" || ts.id == "" {
return
}
key := terminalSessionKey(ts.owner, ts.id)
terminalSessions.Lock()
if terminalSessions.items[key] == ts {
delete(terminalSessions.items, key)
}
terminalSessions.Unlock()
}
func newTerminalSession(owner string, id string, client *ssh.Client, session *ssh.Session, stdin io.WriteCloser, stdout io.Reader, stderr io.Reader) *terminalSession {
ts := &terminalSession{
owner: owner,
id: id,
client: client,
session: session,
stdin: stdin,
done: make(chan struct{}),
subs: make(map[chan wsMessage]struct{}),
lastInput: time.Now(),
}
pump := func(reader io.Reader) {
buf := make([]byte, 4096)
for {
n, rerr := reader.Read(buf)
if n > 0 {
ts.addOutput(string(buf[:n]))
}
if rerr != nil {
if !errors.Is(rerr, io.EOF) {
ts.addOutput("\r\n[adpanel] remote stream closed\r\n")
}
return
}
}
}
go pump(stdout)
go pump(stderr)
go func() {
err := session.Wait()
if err != nil {
ts.mu.Lock()
ts.waitErr = err
ts.mu.Unlock()
ts.closeWithMessage("\r\n[adpanel] ssh session ended: " + sanitizeReason(err) + "\r\n")
return
}
ts.closeWithMessage("\r\n[adpanel] ssh session ended\r\n")
}()
return ts
}
func (ts *terminalSession) addOutput(data string) {
if ts == nil || data == "" {
return
}
msg := wsMessage{Type: "output", Data: data}
ts.mu.Lock()
if ts.closed {
ts.mu.Unlock()
return
}
ts.replay = append(ts.replay, []byte(data)...)
if len(ts.replay) > terminalReplayLimit {
ts.replay = ts.replay[len(ts.replay)-terminalReplayLimit:]
}
subs := make([]chan wsMessage, 0, len(ts.subs))
for ch := range ts.subs {
subs = append(subs, ch)
}
ts.mu.Unlock()
for _, ch := range subs {
select {
case ch <- msg:
default:
}
}
}
func (ts *terminalSession) subscribe() (chan wsMessage, string, bool) {
ch := make(chan wsMessage, 256)
ts.mu.Lock()
defer ts.mu.Unlock()
if ts.closed {
return nil, "", false
}
ts.subs[ch] = struct{}{}
return ch, string(ts.replay), true
}
func (ts *terminalSession) unsubscribe(ch chan wsMessage) {
ts.mu.Lock()
if ch != nil {
delete(ts.subs, ch)
}
noSubs := len(ts.subs) == 0
ts.lastDetach = time.Now()
ts.mu.Unlock()
if noSubs {
time.AfterFunc(terminalResumeGrace, cleanupIdleTerminalSessions)
}
}
func cleanupIdleTerminalSessions() {
now := time.Now()
var stale []*terminalSession
terminalSessions.Lock()
for _, ts := range terminalSessions.items {
ts.mu.Lock()
idleDetached := len(ts.subs) == 0 && !ts.lastDetach.IsZero() && now.Sub(ts.lastDetach) >= terminalResumeGrace
idleInput := now.Sub(ts.lastInput) >= terminalIdleTimeout
closed := ts.closed
ts.mu.Unlock()
if !closed && (idleDetached || idleInput) {
stale = append(stale, ts)
}
}
terminalSessions.Unlock()
for _, ts := range stale {
ts.closeWithMessage("")
}
}
func (ts *terminalSession) closeWithMessage(message string) {
if ts == nil {
return
}
if strings.TrimSpace(message) != "" {
ts.addOutput(message)
}
ts.closeOnce.Do(func() {
ts.mu.Lock()
ts.closed = true
ts.mu.Unlock()
if ts.stdin != nil {
_ = ts.stdin.Close()
}
if ts.session != nil {
_ = ts.session.Close()
}
if ts.client != nil {
_ = ts.client.Close()
}
removeTerminalSession(ts)
close(ts.done)
})
}
func (ts *terminalSession) writeInput(data string) error {
if ts == nil || data == "" {
return nil
}
ts.mu.Lock()
if ts.closed {
ts.mu.Unlock()
return errors.New("terminal session closed")
}
ts.lastInput = time.Now()
stdin := ts.stdin
ts.mu.Unlock()
if stdin == nil {
return errors.New("terminal input unavailable")
}
_, err := io.WriteString(stdin, data)
return err
}
func (ts *terminalSession) resize(cols int, rows int) {
if ts == nil || ts.session == nil {
return
}
if rows <= 0 {
rows = 24
}
if cols <= 0 {
cols = 80
}
_ = ts.session.WindowChange(rows, cols)
}
func attachTerminalSession(ctx context.Context, conn *websocket.Conn, ts *terminalSession) {
outCh, replay, ok := ts.subscribe()
if !ok {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session closed"})
return
}
defer ts.unsubscribe(outCh)
write := func(msg wsMessage) bool {
wctx, cancel := context.WithTimeout(ctx, 10*time.Second)
err := wsjson.Write(wctx, conn, msg)
cancel()
return err == nil
}
if !write(wsMessage{Type: "connected", SessionID: ts.id}) {
return
}
if replay != "" && !write(wsMessage{Type: "output", Data: replay}) {
return
}
inputCh := make(chan wsMessage, 16)
errCh := make(chan error, 1)
go func() {
for {
var msg wsMessage
if err := wsjson.Read(ctx, conn, &msg); err != nil {
errCh <- err
return
}
select {
case inputCh <- msg:
case <-ctx.Done():
return
}
}
}()
ticker := time.NewTicker(30 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ts.done:
return
case <-ticker.C:
ts.mu.Lock()
expired := time.Since(ts.lastInput) >= terminalIdleTimeout
ts.mu.Unlock()
if expired {
ts.closeWithMessage("\r\n[adpanel] session expired after 20 minutes of inactivity\r\n")
return
}
case err := <-errCh:
if errors.Is(err, context.DeadlineExceeded) {
ts.closeWithMessage("\r\n[adpanel] session expired after 20 minutes of inactivity\r\n")
}
return
case msg := <-inputCh:
switch msg.Type {
case "input":
if err := ts.writeInput(msg.Data); err != nil {
ts.closeWithMessage("\r\n[adpanel] terminal input failed: " + sanitizeReason(err) + "\r\n")
return
}
case "resize":
ts.resize(msg.Cols, msg.Rows)
case "disconnect":
ts.closeWithMessage("")
return
}
case msg := <-outCh:
if !write(msg) {
return
}
}
}
}
func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) {
token := strings.TrimSpace(r.URL.Query().Get("token"))
payload, err := verifyToken(cfg.Secret, token, requestIP(r))
if err != nil {
log.Printf("[ssh-term] ws token reject: %v", err)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled})
if err != nil {
return
}
defer conn.Close(websocket.StatusNormalClosure, "bye")
ctx := r.Context()
conn.SetReadLimit(1 << 20)
var first wsMessage
if err := wsjson.Read(ctx, conn, &first); err != nil {
return
}
if first.Type == "attach" {
sessionID := normalizeTerminalSessionID(first.SessionID)
if sessionID == "" {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session id is missing"})
return
}
if existing := getTerminalSession(payload.UserID, sessionID); existing != nil {
attachTerminalSession(ctx, conn, existing)
return
}
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "terminal session not found"})
return
}
connectMsg := first
if first.Type == "probe" {
target, err := parseSSHCommand(first.Command)
if err != nil {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: err.Error()})
return
}
if err := probeSSHReachability(target, 6*time.Second); err != nil {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh target unreachable: " + sanitizeReason(err)})
return
}
if err := wsjson.Write(ctx, conn, wsMessage{Type: "probe-ok"}); err != nil {
return
}
if err := wsjson.Read(ctx, conn, &connectMsg); err != nil {
return
}
if connectMsg.Type != "connect" {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "expected connect message"})
return
}
if strings.TrimSpace(connectMsg.Command) == "" {
connectMsg.Command = first.Command
}
if strings.TrimSpace(connectMsg.SessionID) == "" {
connectMsg.SessionID = first.SessionID
}
}
if connectMsg.Type != "connect" {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "expected connect message"})
return
}
target, err := parseSSHCommand(connectMsg.Command)
if err != nil {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: err.Error()})
return
}
if err := probeSSHReachability(target, 6*time.Second); err != nil {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh target unreachable: " + sanitizeReason(err)})
return
}
if strings.TrimSpace(connectMsg.Password) == "" {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "password is required"})
return
}
sessionID := normalizeTerminalSessionID(connectMsg.SessionID)
if sessionID == "" {
sessionID = fmt.Sprintf("session-%d", time.Now().UnixNano())
}
client, session, stdin, err := openSSHSession(target, strings.TrimSpace(connectMsg.Password), knownHostsPath(cfg.PanelRoot), payload.UserID, connectMsg.Cols, connectMsg.Rows)
if err != nil {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh connection failed: " + explainSSHConnectError(err)})
return
}
stdout, _ := session.StdoutPipe()
stderr, _ := session.StderrPipe()
if err := session.Shell(); err != nil {
_ = client.Close()
_ = session.Close()
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "failed to start remote shell: " + sanitizeReason(err)})
return
}
term := newTerminalSession(payload.UserID, sessionID, client, session, stdin, stdout, stderr)
registerTerminalSession(term)
attachTerminalSession(ctx, conn, term)
}
func sanitizeReason(err error) string {
if err == nil {
return "unknown error"
}
reason := strings.TrimSpace(err.Error())
reason = strings.ReplaceAll(reason, "\n", " ")
if len(reason) > 220 {
reason = reason[:220]
}
if reason == "" {
return "unknown error"
}
return reason
}
func explainSSHConnectError(err error) string {
reason := sanitizeReason(err)
lower := strings.ToLower(reason)
if strings.Contains(lower, "host key mismatch") || strings.Contains(lower, "man-in-the-middle") {
return "host key changed since the last connection - refusing to connect (possible man-in-the-middle). If the server was legitimately reinstalled, an admin must remove its entry from data/ssh_known_hosts.json"
}
if strings.Contains(lower, "host key divergence") || strings.Contains(lower, "possible interception") {
return "this host presented a different key to another user - refusing to connect (possible interception). Verify the server fingerprint out-of-band before trusting it"
}
if strings.Contains(lower, "host key store unavailable") {
return "cannot verify the server's host key (key store unavailable) - refusing to connect"
}
if strings.Contains(lower, "unable to authenticate") || strings.Contains(lower, "no supported methods remain") {
return "remote server rejected password authentication (wrong password or password login is disabled)"
}
return reason
}
func probeSSHReachability(target sshTarget, timeout time.Duration) error {
addr := net.JoinHostPort(target.Host, strconv.Itoa(target.Port))
d := net.Dialer{Timeout: timeout}
conn, err := d.Dial("tcp", addr)
if err != nil {
return err
}
_ = conn.Close()
return nil
}
// knownHostsMu serializes read/modify/write access to the on-disk TOFU store so
// concurrent terminal sessions cannot corrupt it or race on first-use pinning.
var knownHostsMu sync.Mutex
// knownHostsPath returns the path of the TOFU known-hosts store, derived from the
// panel root. Kept alongside other node state so it survives restarts.
func knownHostsPath(panelRoot string) string {
root := strings.TrimSpace(panelRoot)
if root == "" {
root = "."
}
return filepath.Join(root, "data", "ssh_known_hosts.json")
}
// hostKeyFingerprint returns a stable, comparable fingerprint for a host key.
// We use the SHA-256 of the wire-format public key (the same bytes OpenSSH
// fingerprints), base64-encoded, which is collision-resistant and unambiguous.
func hostKeyFingerprint(key ssh.PublicKey) string {
sum := sha256.Sum256(key.Marshal())
return key.Type() + ":SHA256:" + base64.StdEncoding.EncodeToString(sum[:])
}
// knownHostsStore is the on-disk TOFU model.
//
// Pins are keyed PER USER ("uid\x00host:port" -> fingerprint) so one user can
// never pin a host key on behalf of another. This closes the multi-user
// pre-pinning attack: a malicious panel user pinning a trap key only affects
// their OWN store, and a victim still performs their own first-use pinning
// against the real server.
//
// Global holds the union of every fingerprint that has EVER been seen for a
// host:port across all users. It is advisory only: when a user pins a host for
// the first time and the presented key is NOT among the keys other users have
// already seen, we surface a warning (divergence => possible interception),
// but we still pin the user's own observation. This way a victim is never
// silently bound to an attacker's key and gets a visible signal on divergence.
type knownHostsStore struct {
Pins map[string]string `json:"pins"`
Global map[string][]string `json:"global"`
}
func userHostKey(userID, hostport string) string {
return strings.TrimSpace(userID) + "\x00" + strings.ToLower(strings.TrimSpace(hostport))
}
func loadKnownHosts(path string) knownHostsStore {
st := knownHostsStore{Pins: map[string]string{}, Global: map[string][]string{}}
b, err := os.ReadFile(path)
if err != nil || len(b) == 0 {
return st
}
_ = json.Unmarshal(b, &st)
if st.Pins == nil {
st.Pins = map[string]string{}
}
if st.Global == nil {
st.Global = map[string][]string{}
}
return st
}
func saveKnownHosts(path string, st knownHostsStore) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
b, err := json.MarshalIndent(st, "", " ")
if err != nil {
return err
}
tmp := path + ".tmp"
if err := os.WriteFile(tmp, b, 0o600); err != nil {
return err
}
return os.Rename(tmp, path)
}
// tofuHostKeyCallback implements PER-USER Trust-On-First-Use host-key
// verification with a cross-user divergence check.
//
// - The first time a given USER connects to host:port, the presented key is
// pinned for that user and the connection is allowed.
// - Every subsequent connection by the SAME user must present the SAME key,
// otherwise the connection is rejected (classic MITM defense).
// - Pins are namespaced by user, so no panel user can pre-pin a key that
// another user will inherit (defeats the first-come pre-pinning attack).
// - On a user's first use, if other users have previously recorded a
// DIFFERENT key for the same host, that is a divergence signal (possible
// interception). We reject by default and require the connecting user to
// explicitly accept, surfacing the risk instead of silently trusting it.
//
// If the store path is empty/unwritable we fail closed (reject) rather than
// fall back to ignoring the key, so a misconfiguration can never silently
// re-disable verification.
func tofuHostKeyCallback(storePath, userID string, allowDivergentFirstUse bool) ssh.HostKeyCallback {
return func(hostport string, remote net.Addr, key ssh.PublicKey) error {
host := strings.ToLower(strings.TrimSpace(hostport))
if host == "" {
host = strings.ToLower(strings.TrimSpace(remote.String()))
}
fp := hostKeyFingerprint(key)
uhk := userHostKey(userID, host)
knownHostsMu.Lock()
defer knownHostsMu.Unlock()
st := loadKnownHosts(storePath)
if pinned, ok := st.Pins[uhk]; ok {
// This user already pinned a key for this host: must match exactly.
if hmac.Equal([]byte(pinned), []byte(fp)) {
return nil
}
return fmt.Errorf("host key mismatch for %s: possible man-in-the-middle attack (pinned %s, got %s)", host, pinned, fp)
}
// First use for THIS user. Check divergence against what others saw.
seen := st.Global[host]
seenThis := false
for _, s := range seen {
if s == fp {
seenThis = true
break
}
}
if len(seen) > 0 && !seenThis && !allowDivergentFirstUse {
// Another user previously recorded a different key for this host and
// the current key is not among them => the connection may be
// intercepted. Refuse and force an explicit, informed decision.
return fmt.Errorf("host key divergence for %s: this host previously presented a different key to another user (got %s) - possible interception; explicit confirmation required", host, fp)
}
// Pin for this user and record in the global advisory set.
st.Pins[uhk] = fp
if !seenThis {
st.Global[host] = append(seen, fp)
}
if err := saveKnownHosts(storePath, st); err != nil {
return fmt.Errorf("host key store unavailable: %w", err)
}
return nil
}
}
func openSSHSession(target sshTarget, password, knownHostsStore, userID string, cols, rows int) (*ssh.Client, *ssh.Session, io.WriteCloser, error) {
if cols <= 0 {
cols = 100
}
if rows <= 0 {
rows = 30
}
config := &ssh.ClientConfig{
User: target.User,
Auth: []ssh.AuthMethod{
ssh.Password(password),
ssh.KeyboardInteractive(func(_ string, _ string, questions []string, _ []bool) ([]string, error) {
answers := make([]string, len(questions))
for i := range questions {
answers[i] = password
}
return answers, nil
}),
},
// Divergent first-use is refused by default; an explicit accept flow can
// pass allowDivergentFirstUse=true after warning the user.
HostKeyCallback: tofuHostKeyCallback(knownHostsStore, userID, false),
Timeout: 15 * time.Second,
}
addr := net.JoinHostPort(target.Host, strconv.Itoa(target.Port))
client, err := ssh.Dial("tcp", addr, config)
if err != nil {
return nil, nil, nil, err
}
session, err := client.NewSession()
if err != nil {
client.Close()
return nil, nil, nil, err
}
stdin, err := session.StdinPipe()
if err != nil {
session.Close()
client.Close()
return nil, nil, nil, err
}
modes := ssh.TerminalModes{
ssh.ECHO: 1,
ssh.TTY_OP_ISPEED: 14400,
ssh.TTY_OP_OSPEED: 14400,
}
if err := session.RequestPty("xterm-256color", rows, cols, modes); err != nil {
stdin.Close()
session.Close()
client.Close()
return nil, nil, nil, err
}
return client, session, stdin, nil
}
func parseSSHCommand(input string) (sshTarget, error) {
trimmed := strings.TrimSpace(input)
parts := strings.Fields(trimmed)
if len(parts) < 2 || !strings.EqualFold(parts[0], "ssh") {
return sshTarget{}, errors.New("only ssh user@host -p <port> is allowed")
}
args := parts[1:]
dest := ""
cliPort := 0
for i := 0; i < len(args); i++ {
arg := strings.TrimSpace(args[i])
if arg == "" {
continue
}
// Tolerate accidental spacing around '@', e.g. "root@ 1.2.3.4" or "root @1.2.3.4".
if dest != "" {
if strings.HasSuffix(dest, "@") && !strings.HasPrefix(arg, "-") {
dest += arg
continue
}
if strings.HasPrefix(arg, "@") && !strings.Contains(dest, "@") {
dest += arg
continue
}
}
if strings.HasPrefix(arg, "-p") {
portText := ""
if arg == "-p" {
if i+1 >= len(args) {
return sshTarget{}, errors.New("invalid port")
}
i++
portText = strings.TrimSpace(args[i])
} else {
portText = strings.TrimSpace(strings.TrimPrefix(arg, "-p"))
}
n, err := strconv.Atoi(portText)
if err != nil || n < 1 || n > 65535 {
return sshTarget{}, errors.New("invalid port")
}
cliPort = n
continue
}
if strings.HasPrefix(arg, "-") {
return sshTarget{}, errors.New("only -p <port> is accepted")
}
if dest != "" {
return sshTarget{}, errors.New("only one ssh destination is allowed")
}
dest = arg
}
if dest == "" {
return sshTarget{}, errors.New("missing ssh destination")
}
at := strings.Index(dest, "@")
if at <= 0 || at == len(dest)-1 {
return sshTarget{}, errors.New("invalid ssh destination")
}
user := dest[:at]
host, inlinePort, err := splitSSHHostPort(dest[at+1:])
if err != nil {
return sshTarget{}, err
}
if !isSafeSSHUser(user) || !isSafeSSHHost(host) {
return sshTarget{}, errors.New("invalid user or host")
}
port := 22
if inlinePort > 0 {
port = inlinePort
}
if cliPort > 0 {
port = cliPort
}
return sshTarget{User: user, Host: host, Port: port}, nil
}
func splitSSHHostPort(raw string) (string, int, error) {
hostPart := strings.TrimSpace(raw)
if hostPart == "" {
return "", 0, errors.New("invalid ssh destination")
}
if strings.HasPrefix(hostPart, "[") {
closeIdx := strings.Index(hostPart, "]")
if closeIdx <= 1 {
return "", 0, errors.New("invalid user or host")
}
host := hostPart[1:closeIdx]
rest := strings.TrimSpace(hostPart[closeIdx+1:])
if rest == "" {
return host, 0, nil
}
if !strings.HasPrefix(rest, ":") {
return "", 0, errors.New("invalid user or host")
}
portText := strings.TrimSpace(rest[1:])
n, err := strconv.Atoi(portText)
if err != nil || n < 1 || n > 65535 {
return "", 0, errors.New("invalid port")
}
return host, n, nil
}
lastColon := strings.LastIndex(hostPart, ":")
if lastColon > 0 && lastColon < len(hostPart)-1 {
portText := hostPart[lastColon+1:]
if isDecimalDigits(portText) {
host := hostPart[:lastColon]
if strings.Count(host, ":") == 0 {
n, err := strconv.Atoi(portText)
if err != nil || n < 1 || n > 65535 {
return "", 0, errors.New("invalid port")
}
return host, n, nil
}
}
}
return hostPart, 0, nil
}
func isDecimalDigits(input string) bool {
if input == "" {
return false
}
for _, c := range input {
if c < '0' || c > '9' {
return false
}
}
return true
}
func isSafeSSHUser(user string) bool {
if len(user) < 1 || len(user) > 32 {
return false
}
for _, c := range user {
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '_' || c == '-' || c == '.' {
continue
}
return false
}
return true
}
func isSafeSSHHost(host string) bool {
if len(host) < 1 || len(host) > 253 {
return false
}
for _, c := range host {
if (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '.' || c == ':' || c == '-' {
continue
}
return false
}
return true
}
func verifyToken(secret []byte, token string, requestIP string) (tokenPayload, error) {
parts := strings.Split(token, ".")
if len(parts) != 2 {
return tokenPayload{}, errors.New("invalid token format")
}
payloadB64 := parts[0]
sigRaw, err := decodeB64URL(parts[1])
if err != nil {
return tokenPayload{}, errors.New("invalid token signature")
}
mac := hmac.New(sha256.New, secret)
_, _ = mac.Write([]byte(payloadB64))
expected := mac.Sum(nil)
if !hmac.Equal(expected, sigRaw) {
return tokenPayload{}, errors.New("token signature mismatch")
}
payloadRaw, err := decodeB64URL(payloadB64)
if err != nil {
return tokenPayload{}, errors.New("invalid token payload")
}
var payload tokenPayload
if err := json.Unmarshal(payloadRaw, &payload); err != nil {
return tokenPayload{}, errors.New("invalid token json")
}
if payload.ExpMS < time.Now().UnixMilli() {
return tokenPayload{}, errors.New("token expired")
}
return payload, nil
}
func sameIP(a, b string) bool {
na := normalizeIP(a)
nb := normalizeIP(b)
return na != "" && nb != "" && na == nb
}
func normalizeIP(raw string) string {
s := strings.TrimSpace(raw)
if s == "" {
return ""
}
if strings.Contains(s, ",") {
s = strings.TrimSpace(strings.Split(s, ",")[0])
}
host, _, err := net.SplitHostPort(s)
if err == nil {
s = host
}
s = strings.TrimPrefix(s, "::ffff:")
ip := net.ParseIP(s)
if ip == nil {
return ""
}
return ip.String()
}
func requestIP(r *http.Request) string {
if xff := strings.TrimSpace(r.Header.Get("X-Forwarded-For")); xff != "" {
return normalizeIP(xff)
}
if xr := strings.TrimSpace(r.Header.Get("X-Real-IP")); xr != "" {
return normalizeIP(xr)
}
return normalizeIP(r.RemoteAddr)
}
func decodeB64URL(s string) ([]byte, error) {
s = strings.TrimSpace(s)
if s == "" {
return nil, errors.New("empty base64url")
}
if b, err := base64.RawURLEncoding.DecodeString(s); err == nil {
return b, nil
}
if m := len(s) % 4; m != 0 {
s += strings.Repeat("=", 4-m)
}
if b, err := base64.URLEncoding.DecodeString(s); err == nil {
return b, nil
}
std := strings.ReplaceAll(strings.ReplaceAll(s, "-", "+"), "_", "/")
return base64.StdEncoding.DecodeString(std)
}
func loadDotEnv(path string) error {
b, err := os.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(strings.ReplaceAll(string(b), "\r\n", "\n"), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
continue
}
eq := strings.IndexByte(line, '=')
if eq <= 0 {
continue
}
k := strings.TrimSpace(line[:eq])
v := strings.TrimSpace(line[eq+1:])
if len(v) >= 2 {
if (strings.HasPrefix(v, "\"") && strings.HasSuffix(v, "\"")) || (strings.HasPrefix(v, "'") && strings.HasSuffix(v, "'")) {
v = v[1 : len(v)-1]
}
}
if k != "" {
if _, exists := os.LookupEnv(k); exists {
continue
}
_ = os.Setenv(k, v)
}
}
return nil
}
const indexHTML = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>ADPanel SSH Terminal</title>
<style>
* { box-sizing: border-box; }
body {
margin: 0;
width: 100vw;
height: 100vh;
overflow: hidden;
background: #000;
}
#terminal {
width: 100%;
height: 100%;
background: #000;
color: #d1d5db;
font: 14px/1.35 "IBM Plex Mono", Menlo, Monaco, Consolas, monospace;
white-space: pre-wrap;
word-break: break-word;
padding: 12px;
outline: none;
overflow: auto;
-ms-overflow-style: none;
scrollbar-width: none;
caret-color: transparent;
user-select: text;
}
#terminal::-webkit-scrollbar {
display: none;
width: 0;
height: 0;
}
.cursor {
background-color: #d1d5db;
color: #000;
display: inline-block;
animation: blink 1s step-end infinite;
}
@keyframes blink {
0%, 50% {
background-color: #d1d5db;
color: #000;
}
50.01%, 100% {
background-color: transparent;
color: #d1d5db;
}
}
</style>
</head>
<body>
<div id="terminal" tabindex="0" role="application" aria-label="SSH terminal"></div>
<script>
const TOKEN = '__TOKEN__';
const WS_FALLBACK = '__WS_FALLBACK__';
const SESSION_KEY = 'adpanel:ssh-terminal-session-id:v1';
const LIVE_KEY = 'adpanel:ssh-terminal-live:v1';
const terminal = document.getElementById('terminal');
let socket = null;
let connected = false;
let intentionalDisconnect = false;
let inputMode = 'command';
let commandBuffer = '';
let commandCursorPos = 0;
let passwordBuffer = '';
let pendingCommand = '';
let connectInFlight = false;
let wsAttemptIndex = 0;
let screen = '';
// ── VT100 viewport ──────────────────────────────────────────────────────
// termCols / termRows: dimensiunea fizică a terminalului (actualizată la resize)
// viewport: array fix de termRows linii (fiecare linie = string de termCols chars)
// scrollback: liniile care au ieșit din viewport prin scroll-up
// termRow / termCol: poziția cursorului în viewport (0-indexed)
let termCols = 80;
let termRows = 24;
let viewport = [];
let scrollback = [];
let termRow = 0;
let termCol = 0;
function initViewport(cols, rows) {
termCols = Math.max(10, cols || 80);
termRows = Math.max(4, rows || 24);
viewport = [];
for (let i = 0; i < termRows; i++) viewport.push('');
scrollback = [];
termRow = 0;
termCol = 0;
}
function resizeViewport(newCols, newRows) {
newCols = Math.max(10, newCols || 80);
newRows = Math.max(4, newRows || 24);
// Ajustează numărul de linii
while (viewport.length < newRows) {
// Adaugă linii goale jos
viewport.push('');
}
while (viewport.length > newRows) {
// Mută liniile de sus în scrollback
scrollback.push(viewport.shift());
termRow = Math.max(0, termRow - 1);
}
termCols = newCols;
termRows = newRows;
termRow = Math.max(0, Math.min(termRow, termRows - 1));
termCol = Math.max(0, Math.min(termCol, termCols - 1));
}
// Scroll viewport cu o linie în sus (linia de sus merge în scrollback)
function scrollUp() {
scrollback.push(viewport.shift());
viewport.push('');
// Limitează scrollback la 5000 linii
if (scrollback.length > 5000) scrollback.shift();
}
// Scroll viewport cu o linie în jos (linia de jos dispare, sus apare linie goală)
function scrollDown() {
viewport.pop();
viewport.unshift('');
}
const commandHistory = [];
let commandHistoryIndex = -1;
let commandHistoryDraft = '';
const PROMPT = 'root@adpanel:~# ';
const TERMINAL_SESSION_ID = getTerminalSessionId();
function getTerminalSessionId() {
try {
let existing = String(localStorage.getItem(SESSION_KEY) || '').trim();
if (/^[A-Za-z0-9._:-]{8,128}$/.test(existing)) return existing;
const generated = (window.crypto && typeof window.crypto.randomUUID === 'function')
? window.crypto.randomUUID()
: 'session-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
localStorage.setItem(SESSION_KEY, generated);
return generated;
} catch {
return 'session-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2);
}
}
function setTerminalLive(value) {
try {
localStorage.setItem(LIVE_KEY, value ? '1' : '0');
} catch { }
}
function shouldAttachExistingTerminal() {
try {
return localStorage.getItem(LIVE_KEY) === '1';
} catch {
return false;
}
}
function escapeHtml(text) {
return String(text).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
function stripAnsi(s) {
let out = String(s || '');
out = out.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, '');
out = out.replace(/\x1b[P^_].*?\x1b\\/g, '');
out = out.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, '');
out = out.replace(/\x1b[@-_]/g, '');
out = out.replace(/[\x00-\x08\x0b-\x1a\x1c-\x1f\x7f]/g, '');
return out;
}
function syncTerminalLinesFromScreen() {
// La tranziția spre modul connected, inițializăm viewport-ul
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
// Punem conținutul existent din screen în viewport (ultimele termRows linii)
const lines = String(screen || '').split('\n');
const start = Math.max(0, lines.length - termRows);
for (let i = start; i < lines.length; i++) {
viewport[i - start] = lines[i] || '';
}
termRow = Math.min(lines.length - start - 1, termRows - 1);
termCol = viewport[termRow] ? viewport[termRow].length : 0;
}
function syncScreenFromTerminalLines() {
// Nu mai e necesar - viewport e sursa de adevăr
}
function ensureCursorLine() {
if (termRow < 0) termRow = 0;
if (termRow >= termRows) {
// Cursor a depășit ultima linie - scroll up
const overflow = termRow - (termRows - 1);
for (let i = 0; i < overflow; i++) scrollUp();
termRow = termRows - 1;
}
if (termCol < 0) termCol = 0;
}
function clampCursorToLine() {
ensureCursorLine();
// Nu clampăm la lungimea liniei - terminalul poate poziționa cursorul oriunde în cols
}
function writeTerminalChar(ch) {
ensureCursorLine();
const line = viewport[termRow] || '';
const pad = termCol > line.length ? ' '.repeat(termCol - line.length) : '';
viewport[termRow] = line.slice(0, termCol) + pad + ch + line.slice(Math.min(termCol + 1, line.length));
termCol += 1;
// Wrap automat la depășirea coloanei
if (termCol >= termCols) {
termCol = 0;
termRow += 1;
ensureCursorLine();
}
}
function terminalLineFeed() {
termRow += 1;
if (termRow >= termRows) {
scrollUp();
termRow = termRows - 1;
}
}
function terminalBackspace() {
if (termCol > 0) {
termCol -= 1;
} else if (termRow > 0) {
// Wrap înapoi pe linia anterioară
termRow -= 1;
termCol = termCols - 1;
}
}
function terminalTab() {
const spaces = 8 - (termCol % 8);
const newCol = termCol + spaces;
if (newCol < termCols) {
termCol = newCol;
} else {
termCol = termCols - 1;
}
}
function eraseInLine(mode) {
ensureCursorLine();
const line = viewport[termRow] || '';
if (mode === 1) {
// Șterge de la început până la cursor (inclusiv)
viewport[termRow] = ' '.repeat(Math.min(termCol + 1, termCols)) + line.slice(termCol + 1);
} else if (mode === 2) {
// Șterge toată linia
viewport[termRow] = '';
} else {
// Șterge de la cursor până la sfârșit
viewport[termRow] = line.slice(0, termCol);
}
}
function eraseInDisplay(mode) {
ensureCursorLine();
if (mode === 2 || mode === 3) {
// Șterge tot ecranul
for (let i = 0; i < termRows; i++) viewport[i] = '';
termRow = 0;
termCol = 0;
return;
}
if (mode === 1) {
// Șterge de la început până la cursor
for (let i = 0; i < termRow; i++) viewport[i] = '';
viewport[termRow] = ' '.repeat(Math.min(termCol + 1, termCols)) + (viewport[termRow] || '').slice(termCol + 1);
return;
}
// mode === 0: șterge de la cursor până la sfârșit
viewport[termRow] = (viewport[termRow] || '').slice(0, termCol);
for (let i = termRow + 1; i < termRows; i++) viewport[i] = '';
}
function insertBlankChars(count) {
ensureCursorLine();
const line = viewport[termRow] || '';
const col = Math.max(0, Math.min(termCol, line.length));
const n = Math.max(1, count || 1);
viewport[termRow] = (line.slice(0, col) + ' '.repeat(n) + line.slice(col)).slice(0, termCols);
}
function deleteChars(count) {
ensureCursorLine();
const line = viewport[termRow] || '';
const col = Math.max(0, Math.min(termCol, line.length));
const n = Math.max(1, count || 1);
viewport[termRow] = line.slice(0, col) + line.slice(col + n);
}
function eraseChars(count) {
ensureCursorLine();
const line = viewport[termRow] || '';
const col = Math.max(0, Math.min(termCol, line.length));
const n = Math.max(1, count || 1);
if (col >= line.length) return;
const end = Math.min(line.length, col + n);
viewport[termRow] = line.slice(0, col) + ' '.repeat(end - col) + line.slice(end);
}
function insertLines(count) {
ensureCursorLine();
const n = Math.max(1, count || 1);
for (let i = 0; i < n; i++) {
viewport.splice(termRow, 0, '');
if (viewport.length > termRows) viewport.pop();
}
}
function deleteLines(count) {
ensureCursorLine();
const n = Math.max(1, count || 1);
for (let i = 0; i < n; i++) {
viewport.splice(termRow, 1);
viewport.push('');
}
}
function parseCsiParams(raw) {
const clean = String(raw || '').replace(/[?>!]/g, '');
if (!clean) return [0];
return clean.split(';').map((part) => {
const n = parseInt(part, 10);
return Number.isFinite(n) ? n : 0;
});
}
function applyCsi(rawParams, finalChar) {
const params = parseCsiParams(rawParams);
const first = params[0] || 0;
const count = Math.max(1, first || 1);
switch (finalChar) {
case '@':
insertBlankChars(count);
break;
case 'A':
termRow = Math.max(0, termRow - count);
break;
case 'B':
termRow = Math.min(termRows - 1, termRow + count);
break;
case 'C':
termCol = Math.min(termCols - 1, termCol + count);
break;
case 'D':
termCol = Math.max(0, termCol - count);
break;
case 'G':
termCol = Math.max(0, Math.min(termCols - 1, count - 1));
break;
case 'H':
case 'f':
termRow = Math.max(0, Math.min(termRows - 1, (params[0] || 1) - 1));
termCol = Math.max(0, Math.min(termCols - 1, (params[1] || 1) - 1));
break;
case 'J':
eraseInDisplay(first);
break;
case 'K':
eraseInLine(first);
break;
case 'L':
insertLines(count);
break;
case 'M':
deleteLines(count);
break;
case 'P':
deleteChars(count);
break;
case 'S':
// Scroll up
for (let i = 0; i < count; i++) scrollUp();
break;
case 'T':
// Scroll down
for (let i = 0; i < count; i++) scrollDown();
break;
case 'X':
eraseChars(count);
break;
case 'd':
// Cursor vertical absolute
termRow = Math.max(0, Math.min(termRows - 1, first - 1));
break;
default:
break;
}
}
function processTerminalOutput(text) {
const value = String(text || '').replace(/\r\n/g, '\r\n');
for (let i = 0; i < value.length; i++) {
const ch = value[i];
if (ch === '\x1b') {
const next = value[i + 1] || '';
if (next === '[') {
const match = value.slice(i).match(/^\x1b\[([0-?]*)([ -/]*)([@-~])/);
if (match) {
applyCsi(match[1], match[3]);
i += match[0].length - 1;
continue;
}
}
if (next === ']') {
let end = i + 2;
while (end < value.length && value[end] !== '\x07' && !(value[end] === '\x1b' && value[end + 1] === '\\')) end++;
i = value[end] === '\x1b' ? end + 1 : end;
continue;
}
if (next >= '@' && next <= '_') {
i += 1;
continue;
}
continue;
}
if (ch === '\r') {
termCol = 0;
continue;
}
if (ch === '\n') {
terminalLineFeed();
continue;
}
if (ch === '\b') {
terminalBackspace();
continue;
}
if (ch === '\t') {
terminalTab();
continue;
}
const code = ch.charCodeAt(0);
if (code < 32 || code === 127) continue;
writeTerminalChar(ch);
}
}
function renderConnectedScreen() {
// Afișăm scrollback + viewport
const allLines = scrollback.concat(viewport);
return allLines.map((line, index) => {
const viewportIndex = index - scrollback.length;
if (viewportIndex !== termRow) return escapeHtml(line);
const col = Math.max(0, Math.min(termCol, line.length));
const before = escapeHtml(line.slice(0, col));
const cursorChar = col < line.length ? escapeHtml(line[col]) : ' ';
const after = escapeHtml(line.slice(col + 1));
return before + '<span class="cursor">' + cursorChar + '</span>' + after;
}).join('\n');
}
function render() {
let active = '';
if (inputMode === 'command') {
const before = escapeHtml(commandBuffer.slice(0, commandCursorPos));
const cursorChar = commandCursorPos < commandBuffer.length ? escapeHtml(commandBuffer[commandCursorPos]) : ' ';
const after = escapeHtml(commandBuffer.slice(commandCursorPos + 1));
active = escapeHtml(PROMPT) + before + '<span class="cursor">' + cursorChar + '</span>' + after;
} else if (inputMode === 'password') {
active = 'Password: ' + '*'.repeat(passwordBuffer.length) + '<span class="cursor"> </span>';
} else if (inputMode === 'connecting') {
active = '[adpanel] connecting... <span class="cursor"> </span><span style="color:#6b7280;font-size:0.85em">(Ctrl+C to cancel)</span>';
}
terminal.innerHTML = inputMode === 'connected'
? renderConnectedScreen()
: escapeHtml(screen) + active;
terminal.scrollTop = terminal.scrollHeight;
}
function writeScreen(text) {
if (inputMode === 'connected' || connected) {
processTerminalOutput(text);
} else {
screen += stripAnsi(String(text || '')).replace(/\r\n/g, '\n').replace(/\r/g, '');
// Limitează screen la ultimele 500 de linii pentru a preveni DOM-ul enorm
const lines = screen.split('\n');
if (lines.length > 500) {
screen = lines.slice(lines.length - 500).join('\n');
}
}
render();
}
function clearScreen() {
screen = '';
if (inputMode === 'connected' || connected) {
for (let i = 0; i < termRows; i++) viewport[i] = '';
scrollback = [];
termRow = 0;
termCol = 0;
}
render();
}
function resetCommandMode() {
inputMode = 'command';
commandBuffer = '';
commandCursorPos = 0;
passwordBuffer = '';
pendingCommand = '';
connectInFlight = false;
// Dacă am fost conectați, transferăm viewport-ul în screen pentru a păstra output-ul vizibil
if (connected || viewport.some(l => l !== '')) {
// Păstrăm ultimele linii din viewport ca text în screen
const viewportText = scrollback.concat(viewport).join('\n').replace(/\n+$/, '');
if (viewportText.trim()) {
screen = viewportText + '\n';
}
// Resetăm viewport-ul
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
}
render();
}
function resetHistoryNavigation() {
commandHistoryIndex = -1;
commandHistoryDraft = '';
}
function rememberCommand(command) {
const value = String(command || '');
if (!value.trim()) return;
if (commandHistory[commandHistory.length - 1] !== value) {
commandHistory.push(value);
if (commandHistory.length > 200) commandHistory.shift();
}
resetHistoryNavigation();
}
function showPreviousCommand() {
if (!commandHistory.length) return;
if (commandHistoryIndex === -1) {
commandHistoryDraft = commandBuffer;
commandHistoryIndex = commandHistory.length - 1;
} else if (commandHistoryIndex > 0) {
commandHistoryIndex -= 1;
} else {
return; // deja la primul din history, nu face nimic
}
commandBuffer = commandHistory[commandHistoryIndex] || '';
commandCursorPos = commandBuffer.length;
render();
}
function showNextCommand() {
if (commandHistoryIndex === -1) return;
if (commandHistoryIndex < commandHistory.length - 1) {
commandHistoryIndex += 1;
commandBuffer = commandHistory[commandHistoryIndex] || '';
} else {
commandHistoryIndex = -1;
commandBuffer = commandHistoryDraft;
commandHistoryDraft = '';
}
commandCursorPos = commandBuffer.length;
render();
}
function cancelConnecting() {
intentionalDisconnect = true;
closeSocketQuietly();
connected = false;
connectInFlight = false;
setTerminalLive(false);
writeScreen('^C\n');
resetCommandMode();
}
return e.key && e.key.length === 1 && !e.ctrlKey && !e.metaKey;
}
function validCommand(cmd) {
const s = String(cmd || '').trim();
if (!/^ssh\b/i.test(s)) return false;
const normalized = s.replace(/\s*@\s*/g, '@');
return /\S+@\S+/.test(normalized);
}
function showReject() {
writeScreen("Only SSH commands are allowed. Try: ssh root@1.2.3.4 or ssh -p 2222 root@1.2.3.4\n");
resetCommandMode();
}
function wsURL() {
const proto = window.location.protocol === 'https:' ? 'wss' : 'ws';
return proto + '://' + window.location.host + '/ssh-terminal/ws?token=' + encodeURIComponent(TOKEN);
}
function wsURLs() {
const primary = wsURL();
const urls = [primary];
const trimmed = String(WS_FALLBACK || '').trim();
if (trimmed) {
try {
const parsed = new URL(trimmed);
if (window.location.protocol === 'https:' && parsed.protocol === 'ws:') {
parsed.protocol = 'wss:';
}
const fallback = parsed.toString() + '?token=' + encodeURIComponent(TOKEN);
if (fallback !== primary) urls.push(fallback);
} catch { }
}
return urls;
}
function connectSocketWithFallback(command, attachOnly = false) {
const candidates = wsURLs();
if (wsAttemptIndex >= candidates.length) {
if (attachOnly) {
setTerminalLive(false);
screen = '';
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
writeScreen('[adpanel] previous SSH session expired\n');
} else {
writeScreen('\n[adpanel] terminal tunnel failed after retry\n');
}
connectInFlight = false;
resetCommandMode();
return;
}
const url = candidates[wsAttemptIndex];
closeSocketQuietly();
socket = new WebSocket(url);
socket.onopen = () => {
if (attachOnly) {
send('attach', { sessionId: TERMINAL_SESSION_ID });
} else {
send('probe', { command: pendingCommand, sessionId: TERMINAL_SESSION_ID });
}
};
socket.onmessage = (ev) => {
let msg = null;
try { msg = JSON.parse(ev.data); } catch { return; }
if (!msg || !msg.type) return;
if (msg.type === 'error') {
if (attachOnly && String(msg.error || '').toLowerCase().includes('terminal session not found')) {
setTerminalLive(false);
screen = '';
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
writeScreen('[adpanel] previous SSH session expired\n');
} else if (msg.error) {
writeScreen(msg.error + '\n');
}
connected = false;
connectInFlight = false;
closeSocketQuietly();
resetCommandMode();
return;
}
if (msg.type === 'probe-ok') {
connectInFlight = false;
inputMode = 'password';
render();
return;
}
if (msg.type === 'connected') {
connected = true;
intentionalDisconnect = false;
setTerminalLive(true);
connectInFlight = false;
inputMode = 'connected';
// Inițializează viewport-ul cu dimensiunea curentă a terminalului
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
render();
return;
}
if (msg.type === 'output' && typeof msg.data === 'string') {
writeScreen(msg.data);
}
};
socket.onclose = (ev) => {
// Dacă am anulat intenționat (Ctrl+C în connecting), ignorăm onclose
if (intentionalDisconnect && !connected) {
socket = null;
return;
}
if (!connected && connectInFlight) {
wsAttemptIndex += 1;
if (wsAttemptIndex < candidates.length) {
writeScreen('[adpanel] retrying tunnel...\n');
connectSocketWithFallback(command);
return;
}
}
if (connected) {
writeScreen('\n[adpanel] session closed\n');
if (intentionalDisconnect) setTerminalLive(false);
} else if (connectInFlight) {
const code = Number(ev && ev.code) || 0;
const reason = String((ev && ev.reason) || '').trim();
if (reason) {
writeScreen('\n[adpanel] terminal tunnel failed (code ' + String(code) + '): ' + reason + '\n');
} else {
writeScreen('\n[adpanel] terminal tunnel failed (code ' + String(code) + ')\n');
}
} else if (inputMode === 'password') {
writeScreen('\n[adpanel] connection closed before authentication\n');
}
connected = false;
connectInFlight = false;
socket = null;
resetCommandMode();
};
socket.onerror = () => {
if (!connected && !intentionalDisconnect) writeScreen('[adpanel] connection error\n');
};
}
function send(type, payload = {}) {
if (!socket || socket.readyState !== WebSocket.OPEN) return;
socket.send(JSON.stringify(Object.assign({ type }, payload)));
}
function estimateSize() {
const w = Math.max(640, terminal.clientWidth || window.innerWidth || 1200);
const h = Math.max(320, terminal.clientHeight || window.innerHeight || 700);
const cols = Math.max(80, Math.floor((w - 24) / 8.4));
const rows = Math.max(24, Math.floor((h - 24) / 18));
return { cols, rows };
}
function closeSocketQuietly() {
if (!socket) return;
try { socket.close(); } catch { }
socket = null;
}
function startProbe(command) {
if (connectInFlight) return;
connectInFlight = true;
intentionalDisconnect = false;
wsAttemptIndex = 0;
pendingCommand = command;
passwordBuffer = '';
inputMode = 'connecting';
render();
connectSocketWithFallback(command, false);
}
function startAttach() {
if (connectInFlight || connected || !shouldAttachExistingTerminal()) return;
connectInFlight = true;
intentionalDisconnect = false;
wsAttemptIndex = 0;
pendingCommand = '';
passwordBuffer = '';
inputMode = 'connecting';
render();
connectSocketWithFallback('', true);
}
function sendConnectWithPassword(password) {
if (!pendingCommand) {
showReject();
return;
}
if (!socket || socket.readyState !== WebSocket.OPEN) {
writeScreen('[adpanel] terminal tunnel is not ready, retry command\n');
resetCommandMode();
return;
}
connectInFlight = true;
inputMode = 'connecting';
render();
const sz = estimateSize();
send('connect', {
sessionId: TERMINAL_SESSION_ID,
command: pendingCommand,
password,
cols: sz.cols,
rows: sz.rows,
});
}
window.addEventListener('message', (event) => {
if (event.origin !== window.location.origin) return;
if (!event.data || event.data.type !== 'adpanel-ssh-terminal-close') return;
intentionalDisconnect = true;
setTerminalLive(false);
if (socket && socket.readyState === WebSocket.OPEN) {
send('disconnect', { sessionId: TERMINAL_SESSION_ID });
}
closeSocketQuietly();
connected = false;
resetCommandMode();
});
terminal.addEventListener('keydown', (e) => {
if (inputMode === 'connected') {
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
send('input', { data: '\u0003' });
return;
}
if (e.key === 'Enter') {
e.preventDefault();
send('input', { data: '\r' });
return;
}
if (e.key === 'Backspace') {
e.preventDefault();
send('input', { data: '\u007f' });
return;
}
if (e.key === 'Delete') { e.preventDefault(); send('input', { data: '\x1b[3~' }); return; }
if (e.key === 'ArrowLeft') { e.preventDefault(); send('input', { data: '\x1b[D' }); return; }
if (e.key === 'ArrowRight') { e.preventDefault(); send('input', { data: '\x1b[C' }); return; }
if (e.key === 'ArrowUp') { e.preventDefault(); send('input', { data: '\x1b[A' }); return; }
if (e.key === 'ArrowDown') { e.preventDefault(); send('input', { data: '\x1b[B' }); return; }
if (e.key === 'Home') { e.preventDefault(); send('input', { data: '\x1b[H' }); return; }
if (e.key === 'End') { e.preventDefault(); send('input', { data: '\x1b[F' }); return; }
if (e.key === 'Tab') { e.preventDefault(); send('input', { data: '\t' }); return; }
if (isPrintableKey(e)) {
e.preventDefault();
send('input', { data: e.key });
return;
}
return;
}
if (inputMode === 'connecting') {
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
cancelConnecting();
return;
}
e.preventDefault();
return;
}
if (inputMode === 'password') {
if (e.key === 'Enter') {
e.preventDefault();
writeScreen('Password: ' + '*'.repeat(passwordBuffer.length) + '\n');
if (!passwordBuffer) {
showReject();
return;
}
const pwd = passwordBuffer;
passwordBuffer = '';
sendConnectWithPassword(pwd);
return;
}
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
writeScreen('^C\n');
resetCommandMode();
return;
}
if (e.key === 'Backspace') {
e.preventDefault();
if (passwordBuffer.length) passwordBuffer = passwordBuffer.slice(0, -1);
render();
return;
}
if (isPrintableKey(e)) {
e.preventDefault();
passwordBuffer += e.key;
render();
}
return;
}
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
writeScreen('^C\n');
resetCommandMode();
return;
}
if (e.key === 'Enter') {
e.preventDefault();
const cmd = commandBuffer.trim();
rememberCommand(commandBuffer);
writeScreen(PROMPT + commandBuffer + '\n');
if (cmd === 'clear') {
commandBuffer = '';
commandCursorPos = 0;
clearScreen();
return;
}
if (!validCommand(cmd)) {
showReject();
return;
}
commandBuffer = '';
commandCursorPos = 0;
startProbe(cmd);
return;
}
if (e.key === 'Backspace') {
e.preventDefault();
resetHistoryNavigation();
if (commandCursorPos > 0) {
commandBuffer = commandBuffer.slice(0, commandCursorPos - 1) + commandBuffer.slice(commandCursorPos);
commandCursorPos--;
render();
}
return;
}
if (e.key === 'Delete') {
e.preventDefault();
resetHistoryNavigation();
if (commandCursorPos < commandBuffer.length) {
commandBuffer = commandBuffer.slice(0, commandCursorPos) + commandBuffer.slice(commandCursorPos + 1);
render();
}
return;
}
if (e.key === 'ArrowUp') {
e.preventDefault();
showPreviousCommand();
return;
}
if (e.key === 'ArrowDown') {
e.preventDefault();
showNextCommand();
return;
}
if (e.key === 'ArrowLeft') {
e.preventDefault();
if (commandCursorPos > 0) {
commandCursorPos--;
render();
}
return;
}
if (e.key === 'ArrowRight') {
e.preventDefault();
if (commandCursorPos < commandBuffer.length) {
commandCursorPos++;
render();
}
return;
}
if (e.key === 'Home') {
e.preventDefault();
commandCursorPos = 0;
render();
return;
}
if (e.key === 'End') {
e.preventDefault();
commandCursorPos = commandBuffer.length;
render();
return;
}
if (e.key === 'Tab') {
e.preventDefault();
const trimmed = commandBuffer.trim();
if ('ssh'.startsWith(trimmed.toLowerCase()) && !trimmed.includes(' ')) {
resetHistoryNavigation();
commandBuffer = 'ssh ';
commandCursorPos = commandBuffer.length;
render();
}
return;
}
if (isPrintableKey(e)) {
e.preventDefault();
resetHistoryNavigation();
commandBuffer = commandBuffer.slice(0, commandCursorPos) + e.key + commandBuffer.slice(commandCursorPos);
commandCursorPos++;
render();
}
});
terminal.addEventListener('paste', (e) => {
const text = String((e.clipboardData && e.clipboardData.getData('text')) || '').replace(/\r\n/g, '\n');
if (!text) return;
e.preventDefault();
if (inputMode === 'connected') {
send('input', { data: text.replace(/\n/g, '\r') });
return;
}
if (inputMode === 'connecting') return;
const inlineText = text.replace(/[\r\n]+/g, '');
if (!inlineText) return;
if (inputMode === 'password') {
passwordBuffer += inlineText;
render();
return;
}
resetHistoryNavigation();
commandBuffer = commandBuffer.slice(0, commandCursorPos) + inlineText + commandBuffer.slice(commandCursorPos);
commandCursorPos += inlineText.length;
render();
});
terminal.addEventListener('click', () => terminal.focus());
window.addEventListener('resize', () => {
if (!connected) return;
const sz = estimateSize();
resizeViewport(sz.cols, sz.rows);
send('resize', { cols: sz.cols, rows: sz.rows });
});
window.addEventListener('load', () => {
const sz = estimateSize();
initViewport(sz.cols, sz.rows);
render();
terminal.focus();
startAttach();
});
</script>
</body>
</html>`