Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+590 -50
View File
@@ -45,6 +45,18 @@ type wsMessage struct {
Cols int `json:"cols,omitempty"`
Rows int `json:"rows,omitempty"`
Error string `json:"error,omitempty"`
// Code, Fingerprint and KnownFingerprints are only set on the structured
// host-key divergence refusal (Code "host-key-divergence"); every other
// message leaves them empty. The client renders that refusal as an
// explicit accept-after-warning prompt instead of a dead-end error line.
Code string `json:"code,omitempty"`
Fingerprint string `json:"fingerprint,omitempty"`
KnownFingerprints []string `json:"knownFingerprints,omitempty"`
// AcceptDivergentKey is only set by the client's explicit accept retry
// after the divergence warning: it flips tofuHostKeyCallback into the
// allowDivergentFirstUse path for that single connect. It never affects
// the pinned-mismatch refusal.
AcceptDivergentKey bool `json:"acceptDivergentKey,omitempty"`
}
type sshTarget struct {
@@ -91,19 +103,22 @@ const sshSetupTimeout = 30 * time.Second
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
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
// lastActive is refreshed by both keystrokes (writeInput) and remote
// output chunks (addOutput); the idle reapers close a session only after
// it has produced neither for terminalIdleTimeout.
lastActive time.Time
lastDetach time.Time
}
@@ -388,16 +403,105 @@ func removeTerminalSession(ts *terminalSession) {
terminalSessions.Unlock()
}
// terminalMaxSessionsPerUser bounds how many live terminal sessions (SSH
// clients) one owner may hold at once. Every other attacker-influenced
// collection in this service is capped (replay buffer, known-hosts store,
// token cache); sessions were the one unbounded collection — each connect
// mints a terminalSession plus an SSH client, and a scripted client holding a
// valid 20-minute token could pin unbounded goroutines/sockets on this host.
// The idle timeout and detach grace bound DURATION, not count. Tunable via
// SSH_TERM_MAX_SESSIONS_PER_USER; invalid or out-of-range values fall back to
// the default rather than disabling the cap.
const defaultTerminalMaxSessionsPerUser = 4
const maxTerminalSessionsPerUserLimit = 128
func terminalMaxSessionsPerUser() int {
raw := strings.TrimSpace(os.Getenv("SSH_TERM_MAX_SESSIONS_PER_USER"))
if raw == "" {
return defaultTerminalMaxSessionsPerUser
}
limit, err := strconv.Atoi(raw)
if err != nil || limit <= 0 {
return defaultTerminalMaxSessionsPerUser
}
if limit > maxTerminalSessionsPerUserLimit {
return maxTerminalSessionsPerUserLimit
}
return limit
}
// Per-owner slot accounting for the session cap. Reservations are atomic
// under the mutex, so parallel WS handshakes cannot race past the limit the
// way a read-then-create against terminalSessions.items would. A slot is held
// from just before openSSHSession (the dial is exactly the resource being
// capped) until the session's closeWithMessage teardown, and released by the
// dial-failure path — exactly one release per reservation. Owner keys are
// trimmed so a uid with stray whitespace cannot split one owner into two
// accounting buckets (mirrors the panel's normalized uid keys); an owner that
// is empty after trimming is unattributable and fails closed.
var terminalSessionSlots = struct {
sync.Mutex
counts map[string]int
}{counts: make(map[string]int)}
func reserveTerminalSessionSlot(owner string, limit int) bool {
key := strings.TrimSpace(owner)
if key == "" || limit <= 0 {
return false
}
terminalSessionSlots.Lock()
defer terminalSessionSlots.Unlock()
if terminalSessionSlots.counts[key] >= limit {
return false
}
terminalSessionSlots.counts[key]++
return true
}
// Non-reserving peek for the fail-fast check: rejecting at-cap connects
// before the reachability probe saves a 6s target dial, and a stale yes here
// is harmless because the authoritative reserve below still gates the dial.
func terminalSessionSlotAvailable(owner string, limit int) bool {
key := strings.TrimSpace(owner)
if key == "" || limit <= 0 {
return false
}
terminalSessionSlots.Lock()
defer terminalSessionSlots.Unlock()
return terminalSessionSlots.counts[key] < limit
}
func releaseTerminalSessionSlot(owner string) {
key := strings.TrimSpace(owner)
if key == "" {
return
}
terminalSessionSlots.Lock()
defer terminalSessionSlots.Unlock()
if terminalSessionSlots.counts[key] <= 1 {
delete(terminalSessionSlots.counts, key)
return
}
terminalSessionSlots.counts[key]--
}
// Terminal-facing rejection text for the per-owner session cap: states the
// limit and the two legitimate ways past it (close another window, or let the
// 20-minute idle expiry reclaim stale sessions).
func terminalSessionCapMessage(limit int) string {
return fmt.Sprintf("too many concurrent terminal sessions (limit %d) - close another terminal window or wait for idle sessions to expire", limit)
}
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(),
owner: owner,
id: id,
client: client,
session: session,
stdin: stdin,
done: make(chan struct{}),
subs: make(map[chan wsMessage]struct{}),
lastActive: time.Now(),
}
pump := func(reader io.Reader) {
@@ -443,22 +547,46 @@ func (ts *terminalSession) addOutput(data string) {
ts.mu.Unlock()
return
}
// Remote output counts as activity: a scrolling tail -f or long build
// must not be reaped by the idle timeout while it is visibly streaming.
ts.lastActive = time.Now()
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))
// Fan out to every live viewer while still holding ts.mu. The sends are
// non-blocking, so the critical section stays short; every
// subscriber-channel send in the program happens here (callers are the
// two pump goroutines and closeWithMessage's final notice — all funnel
// through this method), and attachTerminalSession only ever RECEIVES on
// a subscriber channel, so all sends are serialized by ts.mu.
//
// Invariant: a channel is closed only on this full-buffer path, under
// the same lock that guards the map, and it is deleted from ts.subs
// before (and atomically with) being closed — so a channel present in
// ts.subs is never closed, a closed channel is never in ts.subs, and a
// send-on-closed-channel panic is impossible. unsubscribe() only
// deletes; it never closes.
//
// A viewer whose 256-slot buffer is FULL has fallen behind the producer
// and can never catch up on the live stream. Dropping the chunk (the
// old behavior) silently corrupted its terminal: terminal output is a
// byte stream with no per-chunk framing, so any lost chunk garbles
// everything after it. Instead the viewer is force-detached — removed
// and closed here, without this chunk — so its attach loop sees the
// closed channel, tells the client to resync, and the viewer re-attaches
// and rebuilds its screen from ts.replay, which kept every byte.
for ch := range ts.subs {
subs = append(subs, ch)
}
ts.mu.Unlock()
for _, ch := range subs {
select {
case ch <- msg:
default:
// Buffer full: force-detach this viewer so it resyncs from the
// replay buffer instead of silently losing output chunks.
delete(ts.subs, ch)
close(ch)
}
}
ts.mu.Unlock()
}
func (ts *terminalSession) subscribe() (chan wsMessage, string, bool) {
@@ -492,10 +620,10 @@ func cleanupIdleTerminalSessions() {
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
idleActive := now.Sub(ts.lastActive) >= terminalIdleTimeout
closed := ts.closed
ts.mu.Unlock()
if !closed && (idleDetached || idleInput) {
if !closed && (idleDetached || idleActive) {
stale = append(stale, ts)
}
}
@@ -527,6 +655,12 @@ func (ts *terminalSession) closeWithMessage(message string) {
_ = ts.client.Close()
}
removeTerminalSession(ts)
// Paired with the reserveTerminalSessionSlot in handleWS: every
// created session closes exactly once through here (idle expiry,
// detach grace, last-viewer disconnect, replaced-by-new-connection,
// or its own SSH session ending), so the per-owner slot accounting
// cannot leak.
releaseTerminalSessionSlot(ts.owner)
close(ts.done)
})
}
@@ -540,7 +674,7 @@ func (ts *terminalSession) writeInput(data string) error {
ts.mu.Unlock()
return errors.New("terminal session closed")
}
ts.lastInput = time.Now()
ts.lastActive = time.Now()
stdin := ts.stdin
ts.mu.Unlock()
if stdin == nil {
@@ -613,7 +747,7 @@ func attachTerminalSession(ctx context.Context, conn *websocket.Conn, ts *termin
return
case <-ticker.C:
ts.mu.Lock()
expired := time.Since(ts.lastInput) >= terminalIdleTimeout
expired := time.Since(ts.lastActive) >= terminalIdleTimeout
ts.mu.Unlock()
if expired {
ts.closeWithMessage("\r\n[adpanel] session expired after 20 minutes of inactivity\r\n")
@@ -634,10 +768,36 @@ func attachTerminalSession(ctx context.Context, conn *websocket.Conn, ts *termin
case "resize":
ts.resize(msg.Cols, msg.Rows)
case "disconnect":
ts.closeWithMessage("")
// An explicit disconnect tears the session down only when the
// sender is the LAST attached viewer. The panel restores the
// same session id into every new tab, so several connections
// legitimately share one session, and a close in one tab must
// not destroy it under the others — that left every other
// viewer's terminal frozen mid-use. With other viewers still
// attached, this connection simply detaches (the deferred
// unsubscribe) and the session keeps running for them; the
// last viewer's disconnect keeps the immediate teardown.
ts.mu.Lock()
lastViewer := len(ts.subs) <= 1
ts.mu.Unlock()
if lastViewer {
ts.closeWithMessage("")
}
return
}
case msg, ok := <-outCh:
if !ok {
// addOutput force-detached this viewer (its buffer filled, so
// it could no longer keep up with the live stream): the
// channel was closed after its buffered messages, so reaching
// ok=false means this viewer missed live output and must
// rebuild from the replay buffer. Best-effort resync notice
// (the client closes quietly and re-attaches to the same
// session), then return — the deferred unsubscribe runs and
// the websocket closes.
_ = write(wsMessage{Type: "resync"})
return
}
case msg := <-outCh:
if !write(msg) {
return
}
@@ -653,6 +813,15 @@ func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
// The issuing panel always embeds a uid (its upgrade gate refuses
// uid-less tokens), so an empty owner can only arrive on a mis-issued
// token: per-owner session accounting would be unattributable — refuse
// rather than run such connects outside the cap.
if strings.TrimSpace(payload.UserID) == "" {
log.Printf("[ssh-term] ws token reject: missing uid")
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
conn, err := websocket.Accept(w, r, &websocket.AcceptOptions{CompressionMode: websocket.CompressionDisabled})
if err != nil {
@@ -682,6 +851,17 @@ func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) {
return
}
// Connect/probe flows create real SSH sessions; the attach path above
// only re-attaches a viewer and must stay ungated. Fail fast at cap
// before the reachability probe so a rejected connect neither waits out
// the probe's dial nor burns a connection attempt against the target;
// the authoritative reservation below still gates the actual dial.
if limit := terminalMaxSessionsPerUser(); !terminalSessionSlotAvailable(payload.UserID, limit) {
log.Printf("[ssh-term] connect rejected: per-owner terminal session cap reached (limit %d)", limit)
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: terminalSessionCapMessage(limit)})
return
}
connectMsg := first
if first.Type == "probe" {
target, err := parseSSHCommand(first.Command)
@@ -746,9 +926,33 @@ func handleWS(cfg appConfig, w http.ResponseWriter, r *http.Request) {
sessionID = fmt.Sprintf("session-%d", time.Now().UnixNano())
}
client, session, stdin, stdout, stderr, err := openSSHSession(target, strings.TrimSpace(connectMsg.Password), knownHostsPath(cfg.PanelRoot), payload.UserID, connectMsg.Cols, connectMsg.Rows)
// Authoritative cap gate: reserve a per-owner slot before dialing. The
// reservation is atomic, so parallel handshakes cannot race past the
// limit between a check and the session creation; the slot is released
// here on dial failure and by the session's closeWithMessage teardown on
// success (exactly one release per reservation).
limit := terminalMaxSessionsPerUser()
if !reserveTerminalSessionSlot(payload.UserID, limit) {
log.Printf("[ssh-term] connect rejected: per-owner terminal session cap reached (limit %d)", limit)
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: terminalSessionCapMessage(limit)})
return
}
client, session, stdin, stdout, stderr, err := openSSHSession(target, strings.TrimSpace(connectMsg.Password), knownHostsPath(cfg.PanelRoot), payload.UserID, connectMsg.Cols, connectMsg.Rows, connectMsg.AcceptDivergentKey)
if err != nil {
_ = wsjson.Write(ctx, conn, wsMessage{Type: "error", Error: "ssh connection failed: " + explainSSHConnectError(err)})
releaseTerminalSessionSlot(payload.UserID)
errMsg := wsMessage{Type: "error", Error: "ssh connection failed: " + explainSSHConnectError(err)}
// A typed divergence refusal becomes the structured notice the client
// renders as an explicit accept-after-warning prompt: the presented
// fingerprint and the previously-seen ones let the user compare them
// out-of-band. Every other failure keeps the plain error message.
var dke *hostKeyDivergenceError
if errors.As(err, &dke) {
errMsg.Code = "host-key-divergence"
errMsg.Fingerprint = dke.presented
errMsg.KnownFingerprints = dke.known
}
_ = wsjson.Write(ctx, conn, errMsg)
return
}
@@ -779,7 +983,7 @@ func explainSSHConnectError(err error) string {
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 (the change takes effect on the next connection attempt - no restart needed)"
}
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"
return "this host presented a different key to another user - refusing to connect (possible interception). Compare the presented fingerprint against the server's real fingerprint out-of-band; if the new key is legitimate, confirm to accept it when prompted"
}
if strings.Contains(lower, "host key store unavailable") {
return "cannot verify the server's host key (key store unavailable) - refusing to connect"
@@ -792,14 +996,18 @@ func explainSSHConnectError(err error) string {
// Cloud metadata endpoints must never be dialable as ssh targets: a panel
// host inside a cloud VPC would otherwise let a terminal user connect to
// services that exist only at those link-local addresses (instance credential
// endpoints and similar). This literal-host blocklist is only the cheap
// first gate — M6: any hostname that RESOLVES to a metadata address used to
// slip past it, so the authoritative gate is address-based (see
// isForbiddenMetadataIP + guardedSSHDialer below).
// services that exist only at those addresses (instance credential
// endpoints and similar): the 169.254.0.0/16 link-local block, Alibaba
// Cloud's ECS metadata endpoint 100.100.100.200 and Azure's Wireserver /
// guest-agent virtual IP 168.63.129.16. This literal-host blocklist is only
// the cheap first gate — M6: any hostname that RESOLVES to a metadata
// address used to slip past it, so the authoritative gate is address-based
// (see isForbiddenMetadataIP + guardedSSHDialer below).
var forbiddenSSHHosts = map[string]struct{}{
"169.254.169.254": {},
"169.254.169.253": {},
"100.100.100.200": {},
"168.63.129.16": {},
"fd00:ec2::254": {},
"metadata": {},
"metadata.internal": {},
@@ -811,15 +1019,29 @@ var forbiddenSSHHosts = map[string]struct{}{
// or the resolved-address metadata check.
var errSSHTargetNotAllowed = errors.New("ssh target is not allowed")
// alibabaMetadataIP is Alibaba Cloud's ECS instance metadata endpoint
// (100.100.100.200) and azureWireserverIP is Azure's Wireserver/guest-agent
// virtual IP (168.63.129.16). Both are single /32s outside the link-local
// block, so isForbiddenMetadataIP matches them explicitly alongside the
// 169.254.0.0/16 and fd00:ec2::/32 ranges.
var (
alibabaMetadataIP = net.IPv4(100, 100, 100, 200).To4()
azureWireserverIP = net.IPv4(168, 63, 129, 16).To4()
)
// isForbiddenMetadataIP reports whether ip points at a cloud instance
// metadata service — or any other link-local service in 169.254.0.0/16 (AWS,
// GCP, Azure, OpenStack all place metadata endpoints there), or AWS's IPv6
// metadata range fd00:ec2::/32.
// GCP, Azure, OpenStack all place metadata endpoints there), Alibaba Cloud's
// ECS metadata endpoint 100.100.100.200, Azure's Wireserver/guest-agent
// virtual IP 168.63.129.16, or AWS's IPv6 metadata range fd00:ec2::/32.
func isForbiddenMetadataIP(ip net.IP) bool {
if ip == nil {
return false
}
if ip4 := ip.To4(); ip4 != nil {
if ip4.Equal(alibabaMetadataIP) || ip4.Equal(azureWireserverIP) {
return true
}
return ip4[0] == 169 && ip4[1] == 254
}
if ip16 := ip.To16(); ip16 != nil {
@@ -1550,6 +1772,22 @@ func saveKnownHosts(path string, st knownHostsStore) (int, error) {
// 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.
// hostKeyDivergenceError reports a cross-user first-use divergence. It is a
// distinct type so the ws handler can turn the refusal into a structured,
// machine-readable notice the client renders as an explicit accept-after-
// warning prompt, instead of a dead-end error line. Error() text is
// unchanged from the historical refusal text.
type hostKeyDivergenceError struct {
host string
presented string
known []string
}
func (e *hostKeyDivergenceError) Error() string {
return fmt.Sprintf("host key divergence for %s: this host previously presented a different key to another user (got %s) - possible interception; explicit confirmation required", e.host, e.presented)
}
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))
@@ -1592,7 +1830,18 @@ func tofuHostKeyCallback(storePath, userID string, allowDivergentFirstUse bool)
// 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)
// The typed error lets handleWS upgrade this refusal to the
// structured "host-key-divergence" notice the client renders as an
// accept-after-warning prompt (the flag is only ever set there).
return &hostKeyDivergenceError{host: host, presented: fp, known: append([]string(nil), seen...)}
}
// Explicit-accept audit trail: the connecting user saw the divergence
// warning and chose to trust this key. Log the decision (fingerprints
// only — never credentials) before pinning so the acceptance is
// attributable.
if allowDivergentFirstUse && len(seen) > 0 && !seenThis {
log.Printf("[ssh-term] user %s explicitly accepted divergent host key for %s (presented %s; previously seen: %s)", userID, host, fp, strings.Join(seen, ", "))
}
// Pin for this user and record in the global advisory set. The
@@ -1621,7 +1870,7 @@ func tofuHostKeyCallback(storePath, userID string, allowDivergentFirstUse bool)
}
}
func openSSHSession(target sshTarget, password, knownHostsStore, userID string, cols, rows int) (*ssh.Client, *ssh.Session, io.WriteCloser, io.Reader, io.Reader, error) {
func openSSHSession(target sshTarget, password, knownHostsStore, userID string, cols, rows int, allowDivergentFirstUse bool) (*ssh.Client, *ssh.Session, io.WriteCloser, io.Reader, io.Reader, error) {
if cols <= 0 {
cols = 100
}
@@ -1641,9 +1890,12 @@ func openSSHSession(target sshTarget, password, knownHostsStore, userID string,
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),
// Divergent first-use is refused by default; the client's explicit
// accept-after-warning flow passes allowDivergentFirstUse=true only on
// the retry that follows a user's informed confirmation of the
// structured "host-key-divergence" notice (see handleWS). The flag
// never affects the pinned-mismatch refusal, which stays absolute.
HostKeyCallback: tofuHostKeyCallback(knownHostsStore, userID, allowDivergentFirstUse),
Timeout: 15 * time.Second,
}
@@ -2204,6 +2456,32 @@ const indexHTML = `<!doctype html>
let pendingCommand = '';
let connectInFlight = false;
let wsAttemptIndex = 0;
// Host-key divergence confirm state: the server's structured
// "host-key-divergence" refusal parks the connect here and the user
// must explicitly accept (accept/yes) or cancel. pendingDivergence
// holds the command and the password of the refused attempt so the
// one-shot accept retry can resend the connect — the password lives
// only in page JS memory (exactly as it already does for the whole
// connect flow), is never rendered or logged, and is overwritten in
// clearPendingDivergence() on every terminal transition.
let pendingDivergence = null;
let divergenceConfirmBuffer = '';
// The password of the most recent connect attempt (set by
// sendConnectWithPassword) so the divergence notice can stash it into
// pendingDivergence when the refusal arrives.
let lastConnectPassword = '';
// Resync state: when a viewer cannot keep up with the live stream the
// server force-detaches it (closed subscriber channel + a one-shot
// 'resync' notice) and the viewer rebuilds its screen by re-attaching
// to the SAME session, which replays the server-side buffer.
// resyncAttempts counts consecutive auto-resyncs that never reach a
// successful 'connected' (reset there) so a persistently failing
// reconnect degrades to the plain session-closed path instead of
// looping forever.
let resyncAttempts = 0;
const RESYNC_MAX_ATTEMPTS = 3;
let resyncTimer = null;
let resyncInProgress = false;
let screen = '';
// ── VT100 viewport ──────────────────────────────────────────────────────
// termCols / termRows: dimensiunea fizică a terminalului (actualizată la resize)
@@ -2643,6 +2921,8 @@ const indexHTML = `<!doctype html>
active = 'Password: ' + '*'.repeat(passwordBuffer.length) + '<span class="cursor"> </span>';
} else if (inputMode === 'connecting') {
active = '[adpanel] connecting... <span class="cursor"> </span><span class="conn-hint">(Ctrl+C to cancel)</span>';
} else if (inputMode === 'divergence-confirm') {
active = 'Accept new host key? type accept/yes or cancel: ' + escapeHtml(divergenceConfirmBuffer) + '<span class="cursor"> </span>';
}
terminal.innerHTML = inputMode === 'connected'
@@ -2683,6 +2963,9 @@ const indexHTML = `<!doctype html>
passwordBuffer = '';
pendingCommand = '';
connectInFlight = false;
// Every reset is a terminal transition: the stashed divergence
// confirm (and the password inside it) must not survive it.
clearPendingDivergence();
// 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
@@ -2697,6 +2980,102 @@ const indexHTML = `<!doctype html>
render();
}
// Wipes the divergence confirm state. The stashed password field is
// overwritten (not just dropped with the object) so no credential
// lingers in page memory beyond the confirm step it was needed for.
function clearPendingDivergence() {
if (pendingDivergence) pendingDivergence.password = '';
pendingDivergence = null;
divergenceConfirmBuffer = '';
}
// The server refused the connect with the structured host-key
// divergence notice: render the explicit accept-after-warning block
// and park the flow in divergence-confirm mode. The password of the
// refused attempt is stashed for the ONE-SHOT accept retry; it is
// never written to the screen or any log.
function handleDivergenceNotice(msg) {
// A user cancel (Ctrl+C in connecting) or a panel-driven close that
// raced the server's refusal wins: a stale refusal frame can still
// be delivered after closeSocketQuietly(), and parking a cancelled
// flow back into the confirm step would clobber whatever the user
// started next.
if (intentionalDisconnect) return;
const presented = String(msg.fingerprint || 'unknown');
const known = Array.isArray(msg.knownFingerprints) ? msg.knownFingerprints.map(String) : [];
let block = '\n=============================================\n'
+ 'HOST KEY DIVERGENCE WARNING\n'
+ '=============================================\n'
+ String(msg.error || 'This host presented a different key to another user.') + '\n'
+ 'Presented key fingerprint: ' + presented + '\n';
if (known.length) {
block += 'Previously seen fingerprint(s) for this host:\n';
for (const fp of known) block += ' - ' + fp + '\n';
}
block += 'This can mean an interception attempt, OR a legitimately\n'
+ 'different server answering at the same hostname:port\n'
+ '(NAT/bastion, a reinstalled or replaced server).\n'
+ 'Verify the presented fingerprint against the server\'s real\n'
+ 'fingerprint out-of-band before trusting it.\n'
+ 'Type "accept" to trust this key and connect, or anything else to cancel:\n';
writeScreen(block);
pendingDivergence = { command: pendingCommand, password: lastConnectPassword, accepted: false };
divergenceConfirmBuffer = '';
inputMode = 'divergence-confirm';
render();
closeSocketQuietly();
connected = false;
connectInFlight = false;
}
// One-shot accept retry: the user typed accept/yes. Reopen a FRESH
// websocket (the server closed the old one after the refusal) and send
// the connect directly as the FIRST message — the client-side probe is
// skipped because the server re-probes the target on the connect path
// anyway. acceptDivergentKey:true is what lets the server-side TOFU
// callback pin the presented key after the explicit confirmation.
function retryDivergentConnect() {
const pending = pendingDivergence;
if (!pending || !pending.command || !pending.password) {
clearPendingDivergence();
resetCommandMode();
return;
}
pending.accepted = true;
intentionalDisconnect = false;
connected = false;
connectInFlight = true;
inputMode = 'connecting';
render();
wsAttemptIndex = 0;
connectSocketWithFallback(pending.command, false, true);
}
// The connect message of the accept retry, sent from the fresh
// socket's onopen with the SAME command/sessionId/cols/rows and the
// stashed password as the refused attempt, plus acceptDivergentKey.
function sendDivergentConnect() {
const pending = pendingDivergence;
if (!pending || !pending.command || !pending.password) {
// The confirm state vanished between the accept and the socket
// opening (should not happen). Refuse rather than send a
// half-specified connect.
closeSocketQuietly();
writeScreen('[adpanel] confirmation state expired - run the ssh command again\n');
resetCommandMode();
return;
}
const sz = estimateSize();
send('connect', {
sessionId: TERMINAL_SESSION_ID,
command: pending.command,
password: pending.password,
cols: sz.cols,
rows: sz.rows,
acceptDivergentKey: true,
});
}
function resetHistoryNavigation() {
commandHistoryIndex = -1;
commandHistoryDraft = '';
@@ -2789,7 +3168,11 @@ const indexHTML = `<!doctype html>
return urls;
}
function connectSocketWithFallback(command, attachOnly = false) {
// directConnect is only true for the host-key divergence accept retry:
// onopen sends the connect (with acceptDivergentKey) directly as the
// FIRST message instead of the usual probe. Every existing flow
// (probe, attach, resync) passes the default false and is unchanged.
function connectSocketWithFallback(command, attachOnly = false, directConnect = false) {
const candidates = wsURLs();
if (wsAttemptIndex >= candidates.length) {
// All candidates were rejected before any byte was proxied — an
@@ -2845,6 +3228,8 @@ const indexHTML = `<!doctype html>
socket.onopen = () => {
if (attachOnly) {
send('attach', { sessionId: TERMINAL_SESSION_ID });
} else if (directConnect) {
sendDivergentConnect();
} else {
send('probe', { command: pendingCommand, sessionId: TERMINAL_SESSION_ID });
}
@@ -2856,6 +3241,19 @@ const indexHTML = `<!doctype html>
if (!msg || !msg.type) return;
if (msg.type === 'error') {
if (msg.code === 'host-key-divergence') {
if (pendingDivergence && pendingDivergence.accepted) {
// The ONE-SHOT accept retry failed with another
// divergence (should not happen once pinning
// succeeded; would indicate a host-key store write
// failure). No loop: fall through to the generic
// error path below and drop the confirm state.
clearPendingDivergence();
} else {
handleDivergenceNotice(msg);
return;
}
}
if (attachOnly && String(msg.error || '').toLowerCase().includes('terminal session not found')) {
// The server answered, so the token is valid — this page
// needs no self-heal; restore the one-shot refresh
@@ -2887,6 +3285,10 @@ const indexHTML = `<!doctype html>
connected = true;
intentionalDisconnect = false;
setTerminalLive(true);
// A successful connection (including the divergence accept
// retry) ends the confirm step: drop the stashed state and
// its password.
clearPendingDivergence();
// A successful connection resets the one-shot refresh budget
// so a later token expiry can self-heal again. Both the
// in-memory flags and the fragment copies are cleared; a
@@ -2895,6 +3297,10 @@ const indexHTML = `<!doctype html>
BOOT_PARAMS.rt = false;
BOOT_PARAMS.fresh = false;
writeBootParams({ rt: false, fresh: false });
// A successful connection refills the auto-resync budget:
// only CONSECUTIVE resyncs that never reach this point
// count against the cap.
resyncAttempts = 0;
connectInFlight = false;
inputMode = 'connected';
// Inițializează viewport-ul cu dimensiunea curentă a terminalului
@@ -2904,18 +3310,43 @@ const indexHTML = `<!doctype html>
return;
}
if (msg.type === 'resync') {
// This viewer fell behind and the server closed its live
// stream so it can resync from the replay buffer.
handleResync();
return;
}
if (msg.type === 'output' && typeof msg.data === 'string') {
writeScreen(msg.data);
}
};
socket.onclose = (ev) => {
// The deliberate quiet close of a resync owns the reconnect
// (resync timer); onclose's fallback handling must not also
// fire for it.
if (resyncInProgress) {
socket = null;
return;
}
// Dacă am anulat intenționat (Ctrl+C în connecting), ignorăm onclose
if (intentionalDisconnect && !connected) {
socket = null;
return;
}
// The divergence-confirm prompt owns the flow: the server
// already closed this socket right after writing the
// structured refusal, and the message handler did the cleanup
// (connectInFlight=false). The generic close fallback below
// must not resetCommandMode() out of the divergence-confirm
// state — that would wipe the pending accept/cancel decision.
if (inputMode === 'divergence-confirm') {
socket = null;
return;
}
if (!connected && connectInFlight) {
wsAttemptIndex += 1;
if (wsAttemptIndex < candidates.length) {
@@ -2926,7 +3357,10 @@ const indexHTML = `<!doctype html>
// exhaustion guard at the top of connectSocketWithFallback
// (token self-heal, final messages). Re-calling
// unconditionally is what makes that guard reachable.
connectSocketWithFallback(command, attachOnly);
// directConnect survives too, so a divergence accept retry
// that loses its tunnel keeps resending the confirmed
// connect (never a probe that would drop the accept flag).
connectSocketWithFallback(command, attachOnly, directConnect);
return;
}
@@ -2974,6 +3408,56 @@ const indexHTML = `<!doctype html>
socket = null;
}
// The server closed this viewer's live stream ('resync' notice)
// because it could not keep up; instead of a garbled screen with
// dropped chunks, re-attach to the SAME session and rebuild the
// screen from the server's replay buffer. This goes through the
// attach machinery directly rather than startAttach():
// startAttach's boot-fragment guard (!BOOT_PARAMS.sid ||
// BOOT_PARAMS.fresh) would also block a viewer that fresh-connected
// with an ephemeral session id (no #sid fragment), yet such a viewer
// is still legitimately bound to TERMINAL_SESSION_ID — and that is
// exactly the id its fresh connect registered the session under, so
// attach-with-TERMINAL_SESSION_ID works for BOTH the fresh-connect
// and the attach flows. startAttach's normal behavior is unchanged.
function handleResync() {
if (intentionalDisconnect || connectInFlight || resyncInProgress || resyncTimer !== null) return;
if (resyncAttempts >= RESYNC_MAX_ATTEMPTS) {
// Too many consecutive resyncs without a successful reconnect:
// stop retrying and fall back to the ordinary session-closed
// handling for a connection that dropped while connected.
connected = false;
connectInFlight = false;
resyncInProgress = false;
setTerminalLive(false);
writeScreen('\n[adpanel] session closed\n');
resetCommandMode();
return;
}
resyncAttempts += 1;
// The quiet close below must not run through onclose's fallback
// handling — the timer owns the reconnect.
resyncInProgress = true;
connected = false;
setTerminalLive(false);
closeSocketQuietly();
inputMode = 'connecting';
render();
writeScreen('\n[adpanel] reconnecting to resync output...\n');
resyncTimer = setTimeout(() => {
resyncTimer = null;
resyncInProgress = false;
// A user cancel (Ctrl+C) or any real connect started while we
// waited wins over the automatic resync.
if (intentionalDisconnect || connectInFlight) return;
wsAttemptIndex = 0;
pendingCommand = '';
passwordBuffer = '';
connectInFlight = true;
connectSocketWithFallback('', true);
}, 1000);
}
function startProbe(command) {
if (connectInFlight) return;
connectInFlight = true;
@@ -2981,6 +3465,10 @@ const indexHTML = `<!doctype html>
wsAttemptIndex = 0;
pendingCommand = command;
passwordBuffer = '';
// A new command starts a fresh flow: any leftover divergence
// confirm state (and its stashed password) is dropped.
clearPendingDivergence();
lastConnectPassword = '';
inputMode = 'connecting';
render();
@@ -3015,6 +3503,11 @@ const indexHTML = `<!doctype html>
resetCommandMode();
return;
}
// Remember the password of this connect attempt so the structured
// host-key divergence refusal (if the server sends one) can stash
// it into pendingDivergence for the explicit accept retry. It
// stays in page JS memory only — never rendered, never logged.
lastConnectPassword = String(password || '');
connectInFlight = true;
inputMode = 'connecting';
@@ -3093,6 +3586,40 @@ const indexHTML = `<!doctype html>
return;
}
if (inputMode === 'divergence-confirm') {
if (e.key === 'Enter') {
e.preventDefault();
const answer = divergenceConfirmBuffer.trim();
divergenceConfirmBuffer = '';
if (/^(accept|yes)$/i.test(answer)) {
// Explicit, informed acceptance: exactly one retry.
retryDivergentConnect();
} else {
writeScreen('cancelled - the host key was not accepted\n');
resetCommandMode();
}
return;
}
if (e.ctrlKey && (e.key === 'c' || e.key === 'C')) {
e.preventDefault();
writeScreen('^C\n');
resetCommandMode();
return;
}
if (e.key === 'Backspace') {
e.preventDefault();
if (divergenceConfirmBuffer.length) divergenceConfirmBuffer = divergenceConfirmBuffer.slice(0, -1);
render();
return;
}
if (isPrintableKey(e)) {
e.preventDefault();
divergenceConfirmBuffer += e.key;
render();
}
return;
}
if (inputMode === 'password') {
if (e.key === 'Enter') {
e.preventDefault();
@@ -3235,6 +3762,11 @@ const indexHTML = `<!doctype html>
e.preventDefault();
if (inputMode === 'connected') {
if (/\r|\n/.test(text)) {
const lineCount = text.split(/\r|\n/).filter((line) => line.length > 0).length;
const message = 'This paste contains ' + lineCount + ' lines. Pasting will run each line immediately in the remote shell. Paste anyway?';
if (!window.confirm(message)) return;
}
send('input', { data: text.replace(/\n/g, '\r') });
return;
}
@@ -3244,6 +3776,14 @@ const indexHTML = `<!doctype html>
const inlineText = text.replace(/[\r\n]+/g, '');
if (!inlineText) return;
if (inputMode === 'divergence-confirm') {
// Pasted text goes inline into the confirm buffer; newlines
// are stripped so a paste can never smuggle an accept/Enter.
divergenceConfirmBuffer += inlineText;
render();
return;
}
if (inputMode === 'password') {
passwordBuffer += inlineText;
render();