Security: fix ws-upgrade crash, per-user TOFU eviction, token log leaks; rebuild sshterm

Panel (index.js, client, views):
- upgrade handler: error guard on every upgraded socket (any path) plus a 3s
  zero-byte orphan reaper; engine.io destroyUpgrade disabled — closes the
  unauthenticated ECONNRESET crash of the whole panel and stops engine.io's
  1s timer from killing slow ssh-terminal handshakes
- /api/ssh-terminal/session: per-session token reuse cache in front of the
  rate limiter — floating-terminal auto-restore no longer burns the 10/min
  mint budget (tokens are re-served only to the same panel session + IP)
- global error middleware redacts credential-bearing query params via
  utils/url-sanitize.js — ssh-terminal ?token= values no longer reach logs
- floating-terminal restore consumes the persisted live flag: after the
  frame reported the SSH session dead, restore drops the stored session id
  and starts a clean connect; script cache busters bumped

sshterm (cmd/sshterm/main.go, rebuilt and deployed):
- TOFU store eviction is per-user and offender-pays (per-user caps: 64 pins
  and 256 contributed advisory hosts; total caps remain as backstops that
  evict the largest contributor first) — one user flooding first-use pins
  to hosts they control can no longer evict another user's pinned key or
  suppress their divergence warning
- the store file is reloaded on mtime/size change: admin edits to
  data/ssh_known_hosts.json now take effect on the next connection without
  a restart; corrupt files keep the last good state, deleted files clear
  the store, other read errors fail closed
- regression tests for flood/eviction/reload/healing + negative controls
- also lands the previously uncommitted IP-binding, trusted-proxy,
  allowed-hosts and metadata-blocking hardening; binary rebuilt through
  initialize.sh --repair-sshterm and verified live at
  /usr/local/bin/adpanel-sshterm (sha256 6bc0363479b91e6c49af9b153c8e552fd4ad8f9a5f787d73bbdc238ce0f7579e)
This commit is contained in:
antonn committed 2026-09-23 17:50:40 +00:00
1 parent a022f29e34
commit 78193254ad
14 files changed
+20391 -3818

No files matched your search

+459
View File
@@ -0,0 +1,459 @@
package main
import (
"encoding/json"
"fmt"
"net"
"os"
"path/filepath"
"strings"
"testing"
)
// loadKnownHostsMust loads the store at path and fails the test when the
// file exists but cannot be parsed.
func loadKnownHostsMust(t *testing.T, path string) knownHostsStore {
t.Helper()
st, err := loadKnownHosts(path)
if err != nil {
t.Fatalf("loadKnownHosts(%q) failed: %v", path, err)
}
return st
}
// newTestStore returns an empty, fully-initialized store for direct
// recordPin / recordGlobalFingerprint unit tests.
func newTestStore() knownHostsStore {
return knownHostsStore{
Pins: map[string]string{},
Global: map[string][]string{},
GlobalContrib: map[string]string{},
}
}
// Core of the eviction attack: a malicious user floods first-use pins for
// hosts they control; eviction must be PER USER (offender pays) so the
// flood only costs the attacker their own oldest pins and can never evict
// another user's pinned key (which would let a MITM key be silently pinned
// on the victim's next connect).
func TestPinFloodDoesNotEvictOtherUsersPins(t *testing.T) {
dir := t.TempDir()
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
victimKey := mkKey(t)
victim := tofuHostKeyCallback(store, "victim", false)
if err := victim("victim.example:22", addr, victimKey); err != nil {
t.Fatalf("victim first-use pin failed: %v", err)
}
attacker := tofuHostKeyCallback(store, "attacker", false)
for i := 0; i < 300; i++ {
if err := attacker(fmt.Sprintf("flood-%d.example:22", i), addr, mkKey(t)); err != nil {
t.Fatalf("attacker flood pin %d failed: %v", i, err)
}
}
// The victim's pin survived the flood: reconnect still verifies exactly.
if err := victim("victim.example:22", addr, victimKey); err != nil {
t.Fatalf("victim pin must survive an attacker's pin flood, got: %v", err)
}
st := loadKnownHostsMust(t, store)
if got := st.Pins[userHostKey("victim", "victim.example:22")]; got != hostKeyFingerprint(victimKey) {
t.Fatalf("victim pin missing from store, got %q", got)
}
// The attacker absorbed the cap themselves.
if n := countUserPins(&st, "attacker"); n != maxKnownHostsPinsPerUser {
t.Fatalf("attacker should be capped at %d own pins, has %d", maxKnownHostsPinsPerUser, n)
}
}
// Same attack against the advisory Global divergence map: flooding hosts
// must only evict the attacker's OWN contributed hosts, so the victim's
// advisory entry survives and divergences on it are still reported.
func TestGlobalFloodDoesNotEvictOtherUsersAdvisoryHosts(t *testing.T) {
dir := t.TempDir()
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
victimKey := mkKey(t)
victim := tofuHostKeyCallback(store, "victim", false)
if err := victim("shared.example:22", addr, victimKey); err != nil {
t.Fatalf("victim first-use pin failed: %v", err)
}
attacker := tofuHostKeyCallback(store, "attacker", false)
for i := 0; i < 300; i++ {
if err := attacker(fmt.Sprintf("gossip-%d.example:22", i), addr, mkKey(t)); err != nil {
t.Fatalf("attacker flood %d failed: %v", i, err)
}
}
st := loadKnownHostsMust(t, store)
if _, ok := st.Global["shared.example:22"]; !ok {
t.Fatal("victim host's advisory entry must survive an attacker's global flood")
}
// The attacker absorbed the per-contributor cap themselves; without that
// cap this assertion fails (the flood would leave 300 attacker hosts in
// the map, all below the 2048 total cap, so nothing else here would catch
// the missing per-user eviction).
if n := countUserGlobalHosts(&st, "attacker"); n != maxGlobalHostsPerUser {
t.Fatalf("attacker should be capped at %d own advisory hosts, has %d", maxGlobalHostsPerUser, n)
}
// The advisory entry is still live: a third user presenting a NEW key on
// the victim's host must still get the divergence warning.
third := tofuHostKeyCallback(store, "third", false)
err := third("shared.example:22", addr, mkKey(t))
if err == nil {
t.Fatal("divergence for the victim host must still be detected after the flood")
} else if !strings.Contains(strings.ToLower(err.Error()), "divergence") {
t.Fatalf("expected divergence error, got: %v", err)
}
}
// A user exceeding the per-user cap ends at exactly the cap, losing their
// OWN oldest entries; no other user's entries are touched. Covers both the
// pin store and the advisory Global map's per-contributor cap.
func TestPerUserCapEvictsOwnOldest(t *testing.T) {
st := newTestStore()
for i := 0; i < maxKnownHostsPinsPerUser+6; i++ {
recordPin(&st, "u1", userHostKey("u1", fmt.Sprintf("h%03d:22", i)), fmt.Sprintf("fp-%d", i))
}
recordPin(&st, "u2", userHostKey("u2", "other:22"), "fp-u2")
if n := countUserPins(&st, "u1"); n != maxKnownHostsPinsPerUser {
t.Fatalf("u1 should hold exactly %d pins, has %d", maxKnownHostsPinsPerUser, n)
}
if _, ok := st.Pins[userHostKey("u1", "h000:22")]; ok {
t.Fatal("u1's own oldest pin should have been evicted")
}
if got := st.Pins[userHostKey("u1", fmt.Sprintf("h%03d:22", maxKnownHostsPinsPerUser+5))]; got != fmt.Sprintf("fp-%d", maxKnownHostsPinsPerUser+5) {
t.Fatalf("u1's newest pin should survive, got %q", got)
}
if got := st.Pins[userHostKey("u2", "other:22")]; got != "fp-u2" {
t.Fatalf("another user's pin must be untouched, got %q", got)
}
recordGlobalFingerprint(&st, "u2host.example:22", "gfp-u2", "u2")
for i := 0; i < maxGlobalHostsPerUser+2; i++ {
recordGlobalFingerprint(&st, fmt.Sprintf("g%03d.example:22", i), fmt.Sprintf("gfp-%d", i), "u1")
}
if n := countUserGlobalHosts(&st, "u1"); n != maxGlobalHostsPerUser {
t.Fatalf("u1 should contribute exactly %d advisory hosts, has %d", maxGlobalHostsPerUser, n)
}
if _, ok := st.Global["g000.example:22"]; ok {
t.Fatal("u1's own oldest contributed host should have been evicted")
}
if _, ok := st.Global[fmt.Sprintf("g%03d.example:22", maxGlobalHostsPerUser+1)]; !ok {
t.Fatal("u1's newest contributed host should survive")
}
if _, ok := st.Global["u2host.example:22"]; !ok {
t.Fatal("another user's advisory host must be untouched")
}
}
// The total caps are backstops: an overflowing insert must evict from the
// LARGEST contributor's entries (offender pays), not from the globally
// oldest entry, and the total must stay at the cap. The setup builds the
// two users up to the cap directly, because recordPin would keep each user
// at maxKnownHostsPinsPerUser long before 2048 entries. The smaller user's
// entries are inserted FIRST, so they are the globally oldest: a globally-
// oldest eviction would hit them, so the assertions below only pass with
// true offender-pays eviction.
func TestOffenderPaysBackstopEviction(t *testing.T) {
st := newTestStore()
for i := 0; i < 10; i++ {
k := userHostKey("u2", fmt.Sprintf("small-%04d:22", i))
st.Pins[k] = "fp-u2"
st.PinsOrder = append(st.PinsOrder, k)
}
for i := 0; i < maxKnownHostsPins-10; i++ {
k := userHostKey("u1", fmt.Sprintf("big-%04d:22", i))
st.Pins[k] = "fp-u1"
st.PinsOrder = append(st.PinsOrder, k)
}
if len(st.Pins) != maxKnownHostsPins {
t.Fatalf("setup: store must be exactly at the cap %d, has %d", maxKnownHostsPins, len(st.Pins))
}
// Overflowing insert BY u2 must cost the largest user (u1).
recordPin(&st, "u2", userHostKey("u2", "overflow:22"), "fp-overflow")
if len(st.Pins) != maxKnownHostsPins {
t.Fatalf("total pins must stay at the cap %d, got %d", maxKnownHostsPins, len(st.Pins))
}
if _, ok := st.Pins[userHostKey("u1", "big-0000:22")]; ok {
t.Fatal("backstop eviction must hit the largest user's OLDEST pin (u1)")
}
if n := countUserPins(&st, "u1"); n != maxKnownHostsPins-11 {
t.Fatalf("u1 should have paid one pin (%d), has %d", maxKnownHostsPins-11, n)
}
if n := countUserPins(&st, "u2"); n != 11 {
t.Fatalf("u2 should have gained a pin (11), has %d", n)
}
if _, ok := st.Pins[userHostKey("u2", "small-0000:22")]; !ok {
t.Fatal("the inserting user's oldest pin must not be evicted by the backstop")
}
// Same offender-pays shape for the advisory Global map.
for i := 0; i < maxKnownHostsGlobalHosts-10; i++ {
h := fmt.Sprintf("gh-big-%04d.example:22", i)
st.Global[h] = []string{"gfp"}
st.GlobalOrder = append(st.GlobalOrder, h)
st.GlobalContrib[h] = "u1"
}
for i := 0; i < 10; i++ {
h := fmt.Sprintf("gh-small-%04d.example:22", i)
st.Global[h] = []string{"gfp"}
st.GlobalOrder = append(st.GlobalOrder, h)
st.GlobalContrib[h] = "u2"
}
recordGlobalFingerprint(&st, "gh-overflow.example:22", "gfp", "u2")
if len(st.Global) != maxKnownHostsGlobalHosts {
t.Fatalf("total advisory hosts must stay at the cap %d, got %d", maxKnownHostsGlobalHosts, len(st.Global))
}
if _, ok := st.Global["gh-big-0000.example:22"]; ok {
t.Fatal("backstop eviction must hit the largest contributor's OLDEST host (u1)")
}
if n := countUserGlobalHosts(&st, "u1"); n != maxKnownHostsGlobalHosts-11 {
t.Fatalf("u1 should have paid one host (%d), has %d", maxKnownHostsGlobalHosts-11, n)
}
if st.GlobalContrib["gh-overflow.example:22"] != "u2" {
t.Fatalf("new host must be attributed to its contributor, got %q", st.GlobalContrib["gh-overflow.example:22"])
}
}
// BUG 6 regression: the resident store must reload when the file changes on
// disk. An admin edit takes effect on the next connection (no restart), a
// corrupt file keeps the last good state (fail closed), and a deleted file
// behaves as an empty store (the next save recreates it).
func TestKnownHostsReloadOnFileChange(t *testing.T) {
dir := t.TempDir()
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
host := "reload.example:22"
key1 := mkKey(t)
key2 := mkKey(t)
key3 := mkKey(t)
key4 := mkKey(t)
cb := tofuHostKeyCallback(store, "userA", false)
if err := cb(host, addr, key1); err != nil {
t.Fatalf("initial pin failed: %v", err)
}
// An admin edits the file out-of-band, removing userA's entry (pin and
// advisory host) — exactly what the mismatch error text instructs.
b, err := os.ReadFile(store)
if err != nil {
t.Fatal(err)
}
var edited knownHostsStore
if err := json.Unmarshal(b, &edited); err != nil {
t.Fatal(err)
}
delete(edited.Pins, userHostKey("userA", host))
delete(edited.Global, host)
delete(edited.GlobalContrib, host)
out, err := json.MarshalIndent(edited, "", " ")
if err != nil {
t.Fatal(err)
}
if err := os.WriteFile(store, out, 0o600); err != nil {
t.Fatal(err)
}
// The next connection must see the edited file WITHOUT a restart: userA
// gets a fresh first-use pin (a stale cache would reject key2 as a
// mismatch against the removed key1 pin).
if err := cb(host, addr, key2); err != nil {
t.Fatalf("next connection must behave as first use after the admin edit, got: %v", err)
}
// A corrupt file must not take the resident (last good) store down: the
// key pinned above still mismatches a different key, fail closed.
if err := os.WriteFile(store, []byte("{not json"), 0o600); err != nil {
t.Fatal(err)
}
err = cb(host, addr, key3)
if err == nil || !strings.Contains(strings.ToLower(err.Error()), "host key mismatch") {
t.Fatalf("corrupt file must keep the last good state (mismatch expected), got: %v", err)
}
// A deleted file means "clear all": the next connection is a first use
// again, and the next save recreates the file.
if err := os.Remove(store); err != nil {
t.Fatal(err)
}
if err := cb(host, addr, key4); err != nil {
t.Fatalf("deleted store must behave as empty (first-use pin), got: %v", err)
}
if _, err := os.Stat(store); err != nil {
t.Fatalf("next save should recreate the store file: %v", err)
}
}
// A store file that exists but cannot be READ (permissions, I/O error, the
// path replaced by a directory) is NOT the same as a missing or empty one:
// loadKnownHosts must report the error so callers keep their last good state
// instead of silently degrading to an empty store, which would drop every
// pin and let the next connection re-pin whatever key it is shown.
func TestLoadKnownHostsUnreadableFileIsAnError(t *testing.T) {
dir := t.TempDir()
// Missing file: a fresh store, not an error.
if _, err := loadKnownHosts(filepath.Join(dir, "missing.json")); err != nil {
t.Fatalf("a missing store file must load as empty, got: %v", err)
}
// Empty file: also a fresh store (v0 behavior).
emptyPath := filepath.Join(dir, "empty.json")
if err := os.WriteFile(emptyPath, nil, 0o600); err != nil {
t.Fatal(err)
}
if _, err := loadKnownHosts(emptyPath); err != nil {
t.Fatalf("an empty store file must load as empty, got: %v", err)
}
// A directory where the file is expected: os.Stat succeeds, the read
// fails with EISDIR (not ENOENT) — a read error, not a fresh store. This
// works even when running the tests as root, unlike a chmod 000.
if err := os.Mkdir(filepath.Join(dir, "dir.json"), 0o700); err != nil {
t.Fatal(err)
}
if _, err := loadKnownHosts(filepath.Join(dir, "dir.json")); err == nil {
t.Fatal("a directory in place of the store file must be a load error, not an empty store")
}
}
// End-to-end version of the above: once the store is resident, replacing the
// file with something unreadable must keep the last good state — the old pin
// stays enforced (a different key must MISMATCH), rather than the store
// degrading to empty and silently pinning the new key.
func TestReloadKeepsLastGoodStateOnUnreadableFile(t *testing.T) {
dir := t.TempDir()
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
addr := &net.TCPAddr{IP: net.IPv4(10, 0, 0, 9), Port: 22}
host := "unreadable.example:22"
key1 := mkKey(t)
key2 := mkKey(t)
cb := tofuHostKeyCallback(store, "userU", false)
if err := cb(host, addr, key1); err != nil {
t.Fatalf("initial pin failed: %v", err)
}
// Replace the store file with a DIRECTORY: the stat in cachedKnownHosts
// succeeds (so the reload triggers) but the read fails. The resident
// store must keep the last good state; the reload of the unreadable file
// must NOT be treated as an empty store.
if err := os.Remove(store); err != nil {
t.Fatal(err)
}
if err := os.Mkdir(store, 0o700); err != nil {
t.Fatal(err)
}
err := cb(host, addr, key2)
if err == nil {
t.Fatal("pinned key must still be enforced when the store file is unreadable")
}
if !strings.Contains(strings.ToLower(err.Error()), "host key mismatch") {
// An empty-store degradation would instead fail later with "host key
// store unavailable" (the save hits the directory) after silently
// accepting the new key's re-pin path.
t.Fatalf("expected the kept last-good pin to mismatch, got: %v", err)
}
}
// A store written over the caps heals itself on load: every user is trimmed
// to their own per-user cap (keeping their newest entries) and the total
// stays within the global cap. A v1 file without globalContrib still loads
// and works (backward compatibility).
func TestTrimHealsOverCapStores(t *testing.T) {
dir := t.TempDir()
store := filepath.Join(dir, "data", "ssh_known_hosts.json")
// 3000 pins spread across 30 users in per-user chunks (100 each).
over := newTestStore()
for u := 0; u < 30; u++ {
uid := fmt.Sprintf("user%02d", u)
for i := 0; i < 100; i++ {
k := userHostKey(uid, fmt.Sprintf("h%03d:22", i))
over.Pins[k] = "fp"
over.PinsOrder = append(over.PinsOrder, k)
}
}
b, err := json.MarshalIndent(over, "", " ")
if err != nil {
t.Fatal(err)
}
if err := os.MkdirAll(filepath.Dir(store), 0o700); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(store, b, 0o600); err != nil {
t.Fatal(err)
}
st, err := loadKnownHosts(store)
if err != nil {
t.Fatalf("over-cap store must still load: %v", err)
}
total := 0
for uid, n := range countPinsPerUser(&st) {
if n > maxKnownHostsPinsPerUser {
t.Fatalf("user %q has %d pins, over the per-user cap %d", uid, n, maxKnownHostsPinsPerUser)
}
total += n
}
if total > maxKnownHostsPins {
t.Fatalf("healed store holds %d pins, over the total cap %d", total, maxKnownHostsPins)
}
if total == 0 {
t.Fatal("healing must not empty the store")
}
if n := countUserPins(&st, "user00"); n != maxKnownHostsPinsPerUser {
t.Fatalf("user00 should be healed to exactly %d pins, has %d", maxKnownHostsPinsPerUser, n)
}
if _, ok := st.Pins[userHostKey("user00", "h000:22")]; ok {
t.Fatal("user00's own oldest pin should have been evicted by healing")
}
if _, ok := st.Pins[userHostKey("user00", "h099:22")]; !ok {
t.Fatal("user00's newest pin should survive healing")
}
// Backward compat: a v1 file (pins/global/orders, NO globalContrib)
// still loads, its pins stay readable, and recording still works on it.
v1 := knownHostsStore{
Pins: map[string]string{userHostKey("legacy", "old.example:22"): "fp-legacy"},
Global: map[string][]string{"old.example:22": {"fp-legacy"}},
PinsOrder: []string{userHostKey("legacy", "old.example:22")},
GlobalOrder: []string{"old.example:22"},
}
v1b, err := json.MarshalIndent(v1, "", " ")
if err != nil {
t.Fatal(err)
}
v1Path := filepath.Join(dir, "data", "v1_known_hosts.json")
if err := os.WriteFile(v1Path, v1b, 0o600); err != nil {
t.Fatal(err)
}
v1st, err := loadKnownHosts(v1Path)
if err != nil {
t.Fatalf("v1 store must load without error: %v", err)
}
if got := v1st.Pins[userHostKey("legacy", "old.example:22")]; got != "fp-legacy" {
t.Fatalf("v1 pin must be readable, got %q", got)
}
if v1st.GlobalContrib == nil {
t.Fatal("loadKnownHosts must initialize GlobalContrib for v1 stores")
}
recordGlobalFingerprint(&v1st, "new.example:22", "gfp-new", "legacy")
if _, ok := v1st.Global["new.example:22"]; !ok {
t.Fatal("recording on a v1-loaded store must work")
}
if v1st.GlobalContrib["new.example:22"] != "legacy" {
t.Fatalf("new host must be attributed to its contributor, got %q", v1st.GlobalContrib["new.example:22"])
}
}
+1069 -81
View File
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -77,7 +77,7 @@ func TestTOFUPrePinningDoesNotPoisonVictim(t *testing.T) {
}
// Critically: the victim is NEVER bound to the attacker's trap key.
st := loadKnownHosts(store)
st, _ := loadKnownHosts(store)
if got := st.Pins[userHostKey("victim", "newsrv:22")]; got == hostKeyFingerprint(trap) {
t.Fatal("victim must NOT inherit the attacker's pinned key")
}
@@ -87,7 +87,7 @@ func TestTOFUPrePinningDoesNotPoisonVictim(t *testing.T) {
if err := victimAccept("newsrv:22", addr, real); err != nil {
t.Fatalf("victim explicit-accept of real key failed: %v", err)
}
st = loadKnownHosts(store)
st, _ = loadKnownHosts(store)
if got := st.Pins[userHostKey("victim", "newsrv:22")]; got != hostKeyFingerprint(real) {
t.Fatalf("victim should be pinned to the REAL key, got %q", got)
}
+17761 -3721
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1161,7 +1161,7 @@
<script nonce="x" data-cfasync="false" src="/socket.io/socket.io.min.js"></script>
<script nonce="x" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260509-floating-terminal-5" defer></script>
<script nonce="x" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260923-ssh-terminal-restore-7" defer></script>
<script nonce="x" data-cfasync="false" src="/js/dashboard.js?v=20260512-dashboard-timeout-1" defer></script>
<div class="christmas-modal" id="christmasModal">
+112 -9
View File
@@ -29,6 +29,8 @@
let interaction = null;
let raf = 0;
let opening = null;
let openEpoch = 0;
let openingEpoch = -1;
let motionId = 0;
let modalObserver = null;
let launcherVisibilityRaf = 0;
@@ -284,6 +286,12 @@
win.className = "adp-ssh-terminal-window";
win.setAttribute("role", "dialog");
win.setAttribute("aria-label", "SSH Terminal");
// sandbox="allow-scripts" gives the terminal page an opaque origin so a
// terminal-page XSS cannot reach panel cookies/storage. The WS origin
// check is handled by the panel's upgrade proxy (it rewrites the Origin
// header upstream). The page receives its session id via the URL
// fragment and uses no storage at all; the sandbox must keep excluding
// allow-same-origin.
win.innerHTML = `
<div class="adp-ssh-terminal-titlebar" data-adp-ssh-drag>
<div class="adp-ssh-terminal-title">
@@ -301,7 +309,7 @@
</div>
</div>
<div class="adp-ssh-terminal-frame-wrap">
<iframe class="adp-ssh-terminal-frame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer"></iframe>
<iframe class="adp-ssh-terminal-frame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer" sandbox="allow-scripts"></iframe>
</div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-n" data-adp-ssh-resize="n"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-e" data-adp-ssh-resize="e"></div>
@@ -350,18 +358,77 @@
}
async function openTerminal(options = {}) {
if (opening) return opening;
// Share a pending open only if no close happened since it started; a
// close bumps the epoch, so the next click starts a fresh open instead
// of attaching to a promise whose window may already be gone.
if (opening && openingEpoch === openEpoch) return opening;
const epoch = openEpoch;
openingEpoch = epoch;
opening = (async () => {
const node = ensureWindow();
const state = readState();
const nextGeometry = getGeometryForState(state);
applyGeometry(nextGeometry);
node.classList.toggle("is-minimized", !!state.minimized);
writeWindowState({ open: true, minimized: !!state.minimized });
// The window is shown immediately, but `open: true` is NOT persisted
// yet: persisting before the launch URL is fetched would leave a ghost
// window that auto-restores on every page load after a transient
// /api/ssh-terminal/session failure (401/403/outage/network blip).
updateLauncherVisibility();
// The panel parent owns the session id — it survives dashboard
// navigations in panel-origin storage the sandboxed frame can never
// touch, and rides into the page as a URL fragment the server never
// sees. A minted id is flagged fresh so the page skips a pointless
// attach attempt; a reused id lets the page re-attach to the
// still-live SSH session.
let sessionId = (typeof state.sessionId === "string" && /^[A-Za-z0-9._:-]{8,128}$/.test(state.sessionId)) ? state.sessionId : "";
let minted = false;
if (!sessionId) {
sessionId = (window.crypto && typeof window.crypto.randomUUID === "function")
? window.crypto.randomUUID()
: "session-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
minted = true;
}
let sidAssigned = false;
try {
if (frame && (!frame.getAttribute("src") || frame.getAttribute("src") === "about:blank")) {
frame.src = await fetchLaunchUrl();
const launchUrl = await fetchLaunchUrl();
if (epoch !== openEpoch || !win || !frame) {
// The user closed the window while the fetch was in flight (or a
// newer open superseded this one); closeTerminal already reset
// the persisted state, so abort quietly instead of erroring on a
// dead frame or clobbering a newer open's frame.src.
return node;
}
frame.src = launchUrl + "#sid=" + encodeURIComponent(sessionId) + (minted ? "&fresh=1" : "");
sidAssigned = true;
}
} catch (err) {
// Roll back to a clean closed state, then rethrow so the outer catch
// still alerts non-silent callers. closeTerminal performs the
// writeState({ open: false, minimized: false }) rollback, posts the
// close signal and removes the node. It does not call openTerminal,
// and `opening` is nulled in the outer finally, so no recursion.
// The epoch check keeps a superseded open's late rejection from
// tearing down a newer open's window.
if (epoch === openEpoch) closeTerminal();
throw err;
}
// Persist only after the launch URL was fetched successfully, so
// `state.open === true` implies the last launch fully succeeded. A
// stale open finishing after a close must not persist `open: true`,
// which would auto-restore a ghost window on the next page load.
if (epoch === openEpoch) {
// Persist the id only if THIS open assigned it to the frame; a
// running frame that kept its src kept its old id, so the stored
// value must be left untouched.
writeWindowState(sidAssigned
? { open: true, minimized: !!node.classList.contains("is-minimized"), sessionId }
: { open: true, minimized: !!node.classList.contains("is-minimized") });
updateLauncherVisibility();
}
return node;
})();
@@ -372,7 +439,12 @@
if (!options.silent) alert(err && err.message ? err.message : "Failed to open SSH terminal.");
throw err;
} finally {
// Only clear the slot if this open is still current; a stale open
// finishing late must never clear a newer pending open.
if (openingEpoch === epoch) {
opening = null;
openingEpoch = -1;
}
}
}
@@ -407,17 +479,28 @@
}
function closeTerminal() {
// Invalidate any in-flight open: after a close, a pending openTerminal
// promise is stale and must neither be reused nor write state/frame.src.
openEpoch += 1;
if (win && win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
if (frame && frame.contentWindow) {
try {
frame.contentWindow.postMessage({ type: "adpanel-ssh-terminal-close" }, window.location.origin);
// The frame is sandbox="allow-scripts" without allow-same-origin, so
// the framed document has an opaque origin and no concrete
// targetOrigin — including window.location.origin — can ever match
// it (a concrete origin would make this message dead code). The
// payload carries no secrets, and the child authenticates the sender
// itself via event.source === window.parent, so "*" is the correct
// target here. The sandbox must keep excluding allow-same-origin so
// a terminal-page XSS cannot reach panel cookies/storage.
frame.contentWindow.postMessage({ type: "adpanel-ssh-terminal-close" }, "*");
} catch { }
}
try {
localStorage.setItem("adpanel:ssh-terminal-live:v1", "0");
} catch { }
writeState({ open: false, minimized: false });
// The child receives the close signal and replies with a 'disconnect'
// message, destroying the server-side session; clearing the id here
// means the next open is a genuinely new terminal session.
writeState({ open: false, minimized: false, live: false, sessionId: "" });
const old = win;
const from = old ? old.getBoundingClientRect() : null;
@@ -546,8 +629,18 @@
});
});
// Invariant: `open: true` is only persisted after a successful launch
// (see openTerminal), so a true state here means the last open fully
// succeeded — restoring it can never resurrect a failed/ghost window.
const state = readState();
if (state.open) {
// The frame reports liveness via postMessage (live on ws connect, false
// when the SSH session ends). Restoring after live === false would
// re-attach to a session the frame already reported dead, so drop the
// stored session id and let the restored page start a clean connect.
if (state.live === false && typeof state.sessionId === "string" && state.sessionId) {
writeState({ sessionId: "" });
}
openTerminal({ silent: true }).catch(() => { });
}
}
@@ -606,6 +699,16 @@
window.addEventListener("pointermove", moveInteraction, { passive: true });
window.addEventListener("pointerup", endInteraction, { passive: true });
window.addEventListener("pointercancel", endInteraction, { passive: true });
window.addEventListener("message", (event) => {
// The terminal frame is sandbox="allow-scripts" (opaque origin): like
// the close signal we send it, the sender cannot be authenticated by
// event.origin — the unforgeable check is event.source against the
// live frame window. The payload carries only a boolean liveness flag.
if (!frame || event.source !== frame.contentWindow) return;
const data = event.data;
if (!data || data.type !== "adpanel-ssh-terminal-live" || typeof data.live !== "boolean") return;
writeState({ live: data.live });
});
window.addEventListener("resize", () => {
if (!win) return;
const minimized = win.classList.contains("is-minimized");
+736
View File
@@ -0,0 +1,736 @@
/* Mirror of ssh-terminal-window.js (no minifier in repo) — keep in sync. */
(function () {
"use strict";
const STORAGE_KEY = "adpanel:ssh-terminal-window:v1";
const DEFAULT_WIDTH = 960;
const DEFAULT_HEIGHT = 640;
const MIN_WIDTH = 360;
const MIN_HEIGHT = 260;
const MINIMIZED_WIDTH = 380;
const MINIMIZED_HEIGHT = 38;
const MODAL_SELECTOR = [
".modal-overlay",
".activity-modal",
".info-modal",
".scheduler-modal",
".planner-modal",
".ai-help-modal",
".clear-console-modal",
".notfound-modal",
".activity-modal-overlay",
].join(",");
const MOTION_QUERY = window.matchMedia
? window.matchMedia("(prefers-reduced-motion: reduce), (update: slow)")
: { matches: false };
let win = null;
let frame = null;
let launcher = null;
let interaction = null;
let raf = 0;
let opening = null;
let openEpoch = 0;
let openingEpoch = -1;
let motionId = 0;
let modalObserver = null;
let launcherVisibilityRaf = 0;
let geometry = { x: 24, y: 24, w: DEFAULT_WIDTH, h: DEFAULT_HEIGHT };
function readState() {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return {};
const data = JSON.parse(raw);
return data && typeof data === "object" ? data : {};
} catch {
return {};
}
}
function writeState(patch) {
try {
const next = Object.assign({}, readState(), patch, { updatedAt: Date.now() });
localStorage.setItem(STORAGE_KEY, JSON.stringify(next));
} catch { }
}
function viewport() {
return {
w: Math.max(320, window.innerWidth || document.documentElement.clientWidth || 1280),
h: Math.max(240, window.innerHeight || document.documentElement.clientHeight || 720),
};
}
function clampSize(w, h) {
const vp = viewport();
return {
w: Math.max(Math.min(MIN_WIDTH, vp.w - 16), Math.min(Number.isFinite(w) ? w : DEFAULT_WIDTH, vp.w - 16)),
h: Math.max(Math.min(MIN_HEIGHT, vp.h - 16), Math.min(Number.isFinite(h) ? h : DEFAULT_HEIGHT, vp.h - 16)),
};
}
function clampGeometry(x, y, w, h, minimized) {
const vp = viewport();
const size = clampSize(w, h);
const viewW = minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : size.w;
const viewH = minimized ? Math.min(MINIMIZED_HEIGHT, vp.h - 16) : size.h;
return {
x: Math.max(8, Math.min(Number.isFinite(x) ? x : 24, Math.max(8, vp.w - viewW - 8))),
y: Math.max(8, Math.min(Number.isFinite(y) ? y : 24, Math.max(8, vp.h - viewH - 8))),
w: size.w,
h: size.h,
};
}
function getGeometryForState(state) {
const minimized = !!state.minimized;
const size = clampSize(Number(state.w), Number(state.h));
if (Number.isFinite(state.x) && Number.isFinite(state.y)) {
return clampGeometry(Number(state.x), Number(state.y), size.w, size.h, minimized);
}
const vp = viewport();
const viewW = minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : size.w;
const viewH = minimized ? MINIMIZED_HEIGHT : size.h;
return clampGeometry(Math.round((vp.w - viewW) / 2), Math.round((vp.h - viewH) / 2), size.w, size.h, minimized);
}
function applyGeometry(next) {
if (!win) return;
geometry = {
x: Math.round(next.x),
y: Math.round(next.y),
w: Math.round(next.w),
h: Math.round(next.h),
};
win.style.setProperty("--adp-ssh-x", `${geometry.x}px`);
win.style.setProperty("--adp-ssh-y", `${geometry.y}px`);
win.style.setProperty("--adp-ssh-w", `${geometry.w}px`);
win.style.setProperty("--adp-ssh-h", `${geometry.h}px`);
}
function writeWindowState(patch) {
writeState(Object.assign({
x: geometry.x,
y: geometry.y,
w: geometry.w,
h: geometry.h,
}, patch));
}
function resizeCursor(handle) {
if (handle === "n" || handle === "s") return "ns-resize";
if (handle === "e" || handle === "w") return "ew-resize";
if (handle === "ne" || handle === "sw") return "nesw-resize";
return "nwse-resize";
}
function setInteractionCursor(cursor) {
document.documentElement.style.cursor = cursor;
document.body.style.cursor = cursor;
if (win) win.style.cursor = cursor;
}
function clearInteractionCursor() {
document.documentElement.style.cursor = "";
document.body.style.cursor = "";
if (win) win.style.cursor = "";
}
function clearMotionClasses(node) {
if (!node) return;
node.classList.remove("is-liquid-motion", "is-motion-open", "is-motion-minimize", "is-motion-restore", "is-motion-close", "is-motion-lite");
}
function cancelWindowMotion(node = win) {
motionId += 1;
if (node && node.getAnimations) {
node.getAnimations().forEach((animation) => {
try { animation.cancel(); } catch { }
});
}
clearMotionClasses(node);
}
function withoutWindowTransition(node, fn) {
if (!node) return;
const previous = node.style.transition;
node.style.transition = "none";
fn();
void node.offsetWidth;
node.style.transition = previous;
}
function shouldUseLiteMotion() {
const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
return !!(
MOTION_QUERY.matches ||
(navigator.hardwareConcurrency && navigator.hardwareConcurrency <= 2) ||
(navigator.deviceMemory && navigator.deviceMemory <= 2) ||
(connection && connection.saveData)
);
}
function visualRectForGeometry(next, minimized) {
const vp = viewport();
return {
left: next.x,
top: next.y,
width: minimized ? Math.min(MINIMIZED_WIDTH, vp.w - 16) : next.w,
height: minimized ? Math.min(MINIMIZED_HEIGHT, vp.h - 16) : next.h,
};
}
function rectTransform(rect, layoutRect) {
const sx = rect.width / Math.max(1, layoutRect.width);
const sy = rect.height / Math.max(1, layoutRect.height);
return `translate3d(${rect.left}px, ${rect.top}px, 0) scale(${sx}, ${sy})`;
}
function morphRect(from, to, progress, sx, sy) {
return {
left: from.left + (to.left - from.left) * progress,
top: from.top + (to.top - from.top) * progress,
width: to.width * sx,
height: to.height * sy,
};
}
function motionKeyframes(kind, fromRect, toRect, layoutRect) {
const start = rectTransform(fromRect, layoutRect);
const end = rectTransform(toRect, layoutRect);
if (kind === "minimize") {
return [
{ opacity: 1, transform: start, offset: 0 },
{ opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 0.72, 1.14, 0.68), layoutRect), offset: 0.58 },
{ opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 0.94, 0.96, 1.12), layoutRect), offset: 0.82 },
{ opacity: 1, transform: end, offset: 1 },
];
}
if (kind === "restore" || kind === "open") {
return [
{ opacity: kind === "open" ? 0 : 1, transform: start, offset: 0 },
{ opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 1, 1.028, 0.982), layoutRect), offset: 0.54 },
{ opacity: 1, transform: rectTransform(morphRect(fromRect, toRect, 1, 0.992, 1.006), layoutRect), offset: 0.78 },
{ opacity: 1, transform: end, offset: 1 },
];
}
return [
{ opacity: 1, transform: start, offset: 0 },
{ opacity: 0.86, transform: rectTransform(morphRect(fromRect, toRect, 1, 1.018, 0.9), layoutRect), offset: 0.45 },
{ opacity: 0, transform: end, offset: 1 },
];
}
function playWindowMotion(kind, fromRect, toRect, node = win) {
if (!node) return Promise.resolve();
cancelWindowMotion(node);
const currentMotion = motionId;
const lite = shouldUseLiteMotion();
const layoutRect = node.getBoundingClientRect();
const finalRect = toRect || layoutRect;
const initialRect = fromRect || {
left: finalRect.left + finalRect.width * 0.04,
top: finalRect.top + finalRect.height * 0.035,
width: finalRect.width * 0.92,
height: finalRect.height * 0.92,
};
const duration = lite
? 140
: kind === "restore" || kind === "open"
? 520
: kind === "minimize"
? 460
: 260;
node.classList.add("is-liquid-motion", `is-motion-${kind}`);
node.classList.toggle("is-motion-lite", lite);
const cleanup = (animation) => {
if (currentMotion !== motionId) return;
if (animation) {
try { animation.cancel(); } catch { }
}
clearMotionClasses(node);
};
if (!node.animate) {
return new Promise((resolve) => {
setTimeout(() => {
cleanup();
resolve();
}, duration);
});
}
const easing = kind === "close"
? "cubic-bezier(0.4, 0, 1, 1)"
: "cubic-bezier(0.16, 1, 0.3, 1)";
const animation = node.animate(motionKeyframes(kind, initialRect, finalRect, layoutRect), {
duration,
easing,
fill: "both",
});
return animation.finished.catch(() => { }).then(() => cleanup(animation));
}
function ensureWindow() {
if (win) return win;
win = document.createElement("section");
win.id = "adpSshTerminalWindow";
win.className = "adp-ssh-terminal-window";
win.setAttribute("role", "dialog");
win.setAttribute("aria-label", "SSH Terminal");
// sandbox="allow-scripts" gives the terminal page an opaque origin so a
// terminal-page XSS cannot reach panel cookies/storage. The WS origin
// check is handled by the panel's upgrade proxy (it rewrites the Origin
// header upstream). The page receives its session id via the URL
// fragment and uses no storage at all; the sandbox must keep excluding
// allow-same-origin.
win.innerHTML = `
<div class="adp-ssh-terminal-titlebar" data-adp-ssh-drag>
<div class="adp-ssh-terminal-title">
<i class="fa-solid fa-terminal" aria-hidden="true"></i>
<span>SSH Terminal</span>
</div>
<div class="adp-ssh-terminal-grip" aria-hidden="true"></div>
<div class="adp-ssh-terminal-controls">
<button class="adp-ssh-terminal-control" type="button" data-adp-ssh-minimize title="Minimize terminal" aria-label="Minimize terminal">
<i class="fa-solid fa-minus" aria-hidden="true"></i>
</button>
<button class="adp-ssh-terminal-control" type="button" data-adp-ssh-close title="Close terminal" aria-label="Close terminal">
<i class="fa-solid fa-xmark" aria-hidden="true"></i>
</button>
</div>
</div>
<div class="adp-ssh-terminal-frame-wrap">
<iframe class="adp-ssh-terminal-frame" title="ADPanel SSH Terminal" loading="eager" referrerpolicy="no-referrer" sandbox="allow-scripts"></iframe>
</div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-n" data-adp-ssh-resize="n"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-e" data-adp-ssh-resize="e"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-s" data-adp-ssh-resize="s"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-w" data-adp-ssh-resize="w"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-ne" data-adp-ssh-resize="ne"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-nw" data-adp-ssh-resize="nw"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-se" data-adp-ssh-resize="se"></div>
<div class="adp-ssh-terminal-resize adp-ssh-terminal-resize-sw" data-adp-ssh-resize="sw"></div>
`;
document.body.appendChild(win);
updateLauncherVisibility();
frame = win.querySelector(".adp-ssh-terminal-frame");
const state = readState();
const nextGeometry = getGeometryForState(state);
applyGeometry(nextGeometry);
win.classList.toggle("is-minimized", !!state.minimized);
win.querySelector("[data-adp-ssh-close]")?.addEventListener("click", closeTerminal);
win.querySelector("[data-adp-ssh-minimize]")?.addEventListener("click", toggleMinimized);
win.querySelector("[data-adp-ssh-drag]")?.addEventListener("pointerdown", startDrag);
win.querySelectorAll("[data-adp-ssh-resize]").forEach((handle) => {
handle.addEventListener("pointerdown", startResize);
});
win.querySelector("[data-adp-ssh-drag]")?.addEventListener("dblclick", (event) => {
if (event.target.closest("button")) return;
toggleMinimized();
});
requestAnimationFrame(() => {
if (!win) return;
win.classList.add("is-ready");
playWindowMotion("open");
});
return win;
}
async function fetchLaunchUrl() {
const res = await fetch("/api/ssh-terminal/session", { credentials: "include" });
const data = await res.json().catch(() => ({}));
if (!res.ok || !data || !data.launchUrl) {
throw new Error((data && data.error) || "Unable to open terminal");
}
return data.launchUrl;
}
async function openTerminal(options = {}) {
// Share a pending open only if no close happened since it started; a
// close bumps the epoch, so the next click starts a fresh open instead
// of attaching to a promise whose window may already be gone.
if (opening && openingEpoch === openEpoch) return opening;
const epoch = openEpoch;
openingEpoch = epoch;
opening = (async () => {
const node = ensureWindow();
const state = readState();
const nextGeometry = getGeometryForState(state);
applyGeometry(nextGeometry);
node.classList.toggle("is-minimized", !!state.minimized);
// The window is shown immediately, but `open: true` is NOT persisted
// yet: persisting before the launch URL is fetched would leave a ghost
// window that auto-restores on every page load after a transient
// /api/ssh-terminal/session failure (401/403/outage/network blip).
updateLauncherVisibility();
// The panel parent owns the session id — it survives dashboard
// navigations in panel-origin storage the sandboxed frame can never
// touch, and rides into the page as a URL fragment the server never
// sees. A minted id is flagged fresh so the page skips a pointless
// attach attempt; a reused id lets the page re-attach to the
// still-live SSH session.
let sessionId = (typeof state.sessionId === "string" && /^[A-Za-z0-9._:-]{8,128}$/.test(state.sessionId)) ? state.sessionId : "";
let minted = false;
if (!sessionId) {
sessionId = (window.crypto && typeof window.crypto.randomUUID === "function")
? window.crypto.randomUUID()
: "session-" + Date.now().toString(36) + "-" + Math.random().toString(36).slice(2);
minted = true;
}
let sidAssigned = false;
try {
if (frame && (!frame.getAttribute("src") || frame.getAttribute("src") === "about:blank")) {
const launchUrl = await fetchLaunchUrl();
if (epoch !== openEpoch || !win || !frame) {
// The user closed the window while the fetch was in flight (or a
// newer open superseded this one); closeTerminal already reset
// the persisted state, so abort quietly instead of erroring on a
// dead frame or clobbering a newer open's frame.src.
return node;
}
frame.src = launchUrl + "#sid=" + encodeURIComponent(sessionId) + (minted ? "&fresh=1" : "");
sidAssigned = true;
}
} catch (err) {
// Roll back to a clean closed state, then rethrow so the outer catch
// still alerts non-silent callers. closeTerminal performs the
// writeState({ open: false, minimized: false }) rollback, posts the
// close signal and removes the node. It does not call openTerminal,
// and `opening` is nulled in the outer finally, so no recursion.
// The epoch check keeps a superseded open's late rejection from
// tearing down a newer open's window.
if (epoch === openEpoch) closeTerminal();
throw err;
}
// Persist only after the launch URL was fetched successfully, so
// `state.open === true` implies the last launch fully succeeded. A
// stale open finishing after a close must not persist `open: true`,
// which would auto-restore a ghost window on the next page load.
if (epoch === openEpoch) {
// Persist the id only if THIS open assigned it to the frame; a
// running frame that kept its src kept its old id, so the stored
// value must be left untouched.
writeWindowState(sidAssigned
? { open: true, minimized: !!node.classList.contains("is-minimized"), sessionId }
: { open: true, minimized: !!node.classList.contains("is-minimized") });
updateLauncherVisibility();
}
return node;
})();
try {
return await opening;
} catch (err) {
if (!options.silent) alert(err && err.message ? err.message : "Failed to open SSH terminal.");
throw err;
} finally {
// Only clear the slot if this open is still current; a stale open
// finishing late must never clear a newer pending open.
if (openingEpoch === epoch) {
opening = null;
openingEpoch = -1;
}
}
}
function toggleMinimized() {
if (!win) return;
if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
const node = win;
const from = node.getBoundingClientRect();
const minimized = !win.classList.contains("is-minimized");
const next = clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized);
if (minimized) {
const to = visualRectForGeometry(next, true);
writeState({ open: true, minimized: true, x: next.x, y: next.y, w: next.w, h: next.h, updatedAt: Date.now() });
playWindowMotion("minimize", from, to, node).then(() => {
if (win !== node) return;
withoutWindowTransition(node, () => {
node.classList.add("is-minimized");
applyGeometry(next);
});
});
return;
}
withoutWindowTransition(node, () => {
node.classList.remove("is-minimized");
applyGeometry(next);
});
const to = node.getBoundingClientRect();
writeWindowState({ open: true, minimized: false });
playWindowMotion("restore", from, to, node);
}
function closeTerminal() {
// Invalidate any in-flight open: after a close, a pending openTerminal
// promise is stale and must neither be reused nor write state/frame.src.
openEpoch += 1;
if (win && win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
if (frame && frame.contentWindow) {
try {
// The frame is sandbox="allow-scripts" without allow-same-origin, so
// the framed document has an opaque origin and no concrete
// targetOrigin — including window.location.origin — can ever match
// it (a concrete origin would make this message dead code). The
// payload carries no secrets, and the child authenticates the sender
// itself via event.source === window.parent, so "*" is the correct
// target here. The sandbox must keep excluding allow-same-origin so
// a terminal-page XSS cannot reach panel cookies/storage.
frame.contentWindow.postMessage({ type: "adpanel-ssh-terminal-close" }, "*");
} catch { }
}
// The child receives the close signal and replies with a 'disconnect'
// message, destroying the server-side session; clearing the id here
// means the next open is a genuinely new terminal session.
writeState({ open: false, minimized: false, live: false, sessionId: "" });
const old = win;
const from = old ? old.getBoundingClientRect() : null;
const to = from ? {
left: from.left + from.width * 0.04,
top: from.top + from.height * 0.08,
width: from.width * 0.9,
height: from.height * 0.76,
} : null;
win = null;
frame = null;
updateLauncherVisibility();
if (old) {
playWindowMotion("close", from, to, old).then(() => {
old.classList.remove("is-ready");
const iframe = old.querySelector("iframe");
if (iframe) iframe.src = "about:blank";
old.remove();
});
}
}
function startDrag(event) {
if (!win || event.button !== 0 || event.target.closest("button")) return;
if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
interaction = {
type: "drag",
pointerId: event.pointerId,
offsetX: event.clientX - geometry.x,
offsetY: event.clientY - geometry.y,
x: geometry.x,
y: geometry.y,
w: geometry.w,
h: geometry.h,
};
win.classList.add("is-interacting", "is-dragging");
setInteractionCursor("grabbing");
try { event.currentTarget.setPointerCapture(event.pointerId); } catch { }
event.preventDefault();
}
function startResize(event) {
if (!win || event.button !== 0 || win.classList.contains("is-minimized")) return;
if (win.classList.contains("is-liquid-motion")) cancelWindowMotion(win);
const handle = event.currentTarget.getAttribute("data-adp-ssh-resize") || "";
interaction = {
type: "resize",
pointerId: event.pointerId,
handle,
startX: event.clientX,
startY: event.clientY,
x: geometry.x,
y: geometry.y,
w: geometry.w,
h: geometry.h,
next: Object.assign({}, geometry),
};
win.classList.add("is-interacting", "is-resizing");
setInteractionCursor(resizeCursor(handle));
try { event.currentTarget.setPointerCapture(event.pointerId); } catch { }
event.preventDefault();
event.stopPropagation();
}
function resizeGeometry(start, dx, dy, handle) {
const vp = viewport();
let left = start.x;
let top = start.y;
let right = start.x + start.w;
let bottom = start.y + start.h;
if (handle.includes("e")) right += dx;
if (handle.includes("s")) bottom += dy;
if (handle.includes("w")) left += dx;
if (handle.includes("n")) top += dy;
if (handle.includes("w")) {
left = Math.max(8, Math.min(left, right - Math.min(MIN_WIDTH, vp.w - 16)));
} else {
right = Math.min(vp.w - 8, Math.max(right, left + Math.min(MIN_WIDTH, vp.w - 16)));
}
if (handle.includes("n")) {
top = Math.max(8, Math.min(top, bottom - Math.min(MIN_HEIGHT, vp.h - 16)));
} else {
bottom = Math.min(vp.h - 8, Math.max(bottom, top + Math.min(MIN_HEIGHT, vp.h - 16)));
}
return clampGeometry(left, top, right - left, bottom - top, false);
}
function moveInteraction(event) {
if (!interaction || !win || event.pointerId !== interaction.pointerId) return;
const minimized = win.classList.contains("is-minimized");
const next = interaction.type === "resize"
? resizeGeometry(interaction, event.clientX - interaction.startX, event.clientY - interaction.startY, interaction.handle)
: clampGeometry(event.clientX - interaction.offsetX, event.clientY - interaction.offsetY, interaction.w, interaction.h, minimized);
interaction.next = next;
if (!raf) {
raf = requestAnimationFrame(() => {
raf = 0;
if (interaction && interaction.next) applyGeometry(interaction.next);
});
}
}
function endInteraction(event) {
if (!interaction || !win || event.pointerId !== interaction.pointerId) return;
const minimized = win.classList.contains("is-minimized");
const next = interaction.next || clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized);
applyGeometry(next);
writeWindowState({ open: true, minimized });
win.classList.remove("is-interacting", "is-dragging", "is-resizing");
clearInteractionCursor();
interaction = null;
}
function attachLaunchers() {
ensureLauncher();
document.addEventListener("click", (event) => {
const trigger = event.target.closest("[data-open-ssh-terminal], #openSshTerminalBtn");
if (!trigger) return;
event.preventDefault();
if ("disabled" in trigger) trigger.disabled = true;
openTerminal().finally(() => {
if ("disabled" in trigger) trigger.disabled = false;
});
});
// Invariant: `open: true` is only persisted after a successful launch
// (see openTerminal), so a true state here means the last open fully
// succeeded — restoring it can never resurrect a failed/ghost window.
const state = readState();
if (state.open) {
// The frame reports liveness via postMessage (live on ws connect, false
// when the SSH session ends). Restoring after live === false would
// re-attach to a session the frame already reported dead, so drop the
// stored session id and let the restored page start a clean connect.
if (state.live === false && typeof state.sessionId === "string" && state.sessionId) {
writeState({ sessionId: "" });
}
openTerminal({ silent: true }).catch(() => { });
}
}
function ensureLauncher() {
if (launcher || document.querySelector("[data-open-ssh-terminal], #openSshTerminalBtn")) return;
launcher = document.createElement("button");
launcher.type = "button";
launcher.className = "adp-ssh-terminal-launcher";
launcher.setAttribute("data-open-ssh-terminal", "true");
launcher.setAttribute("title", "Open SSH Terminal");
launcher.setAttribute("aria-label", "Open SSH Terminal");
launcher.innerHTML = '<i class="fa-solid fa-terminal" aria-hidden="true"></i>';
document.body.appendChild(launcher);
updateLauncherVisibility();
}
function updateLauncherVisibility() {
if (!launcher) return;
const open = !!win || !!readState().open;
launcher.classList.toggle("is-hidden", open || hasVisibleModal());
}
function isVisibleModal(node) {
if (!node || node === win || node === launcher) return false;
if (node.getAttribute("aria-hidden") === "true") return false;
if (node.classList.contains("show") || node.getAttribute("aria-hidden") === "false") return true;
const styles = window.getComputedStyle(node);
if (styles.display === "none" || styles.visibility === "hidden" || styles.opacity === "0") return false;
return node.offsetWidth > 0 && node.offsetHeight > 0;
}
function hasVisibleModal() {
return Array.from(document.querySelectorAll(MODAL_SELECTOR)).some(isVisibleModal);
}
function scheduleLauncherVisibility() {
if (launcherVisibilityRaf) return;
launcherVisibilityRaf = requestAnimationFrame(() => {
launcherVisibilityRaf = 0;
updateLauncherVisibility();
});
}
function observeModalVisibility() {
if (modalObserver || !document.body) return;
modalObserver = new MutationObserver(scheduleLauncherVisibility);
modalObserver.observe(document.body, {
attributes: true,
attributeFilter: ["class", "style", "aria-hidden"],
childList: true,
subtree: true,
});
}
window.addEventListener("pointermove", moveInteraction, { passive: true });
window.addEventListener("pointerup", endInteraction, { passive: true });
window.addEventListener("pointercancel", endInteraction, { passive: true });
window.addEventListener("message", (event) => {
// The terminal frame is sandbox="allow-scripts" (opaque origin): like
// the close signal we send it, the sender cannot be authenticated by
// event.origin — the unforgeable check is event.source against the
// live frame window. The payload carries only a boolean liveness flag.
if (!frame || event.source !== frame.contentWindow) return;
const data = event.data;
if (!data || data.type !== "adpanel-ssh-terminal-live" || typeof data.live !== "boolean") return;
writeState({ live: data.live });
});
window.addEventListener("resize", () => {
if (!win) return;
const minimized = win.classList.contains("is-minimized");
const next = clampGeometry(geometry.x, geometry.y, geometry.w, geometry.h, minimized);
applyGeometry(next);
writeWindowState({ open: true, minimized });
});
window.ADPanelSshTerminal = {
open: openTerminal,
close: closeTerminal,
toggleMinimized,
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => {
attachLaunchers();
observeModalVisibility();
}, { once: true });
} else {
attachLaunchers();
observeModalVisibility();
}
})();
BIN
View File
Binary file not shown.
+103
View File
@@ -0,0 +1,103 @@
"use strict";
// Redacts credential-bearing query parameters before a URL is written to any
// log sink. Query strings are a documented token-exposure channel in this
// panel's threat model: the SSH-terminal ticket travels as
// `/ssh-terminal/?token=...`, is replayable for its full 20-minute TTL, and
// Express's req.originalUrl (used by the global error middleware) includes the
// query string verbatim — so an unredacted URL would put a live credential
// into persistent logs (console, journald, containers) on every store or
// handler error. The sanitizer keeps the path and the query's original order
// and encoding intact, and replaces only the VALUE of any parameter whose name
// decodes to a denylist entry with the literal "[REDACTED]".
//
// Fragments are dropped before parsing: req.originalUrl never carries one, but
// the helper must also be safe if ever handed a client-side URL — credentials
// do live in fragments (this panel's #sid=..., OAuth implicit-flow tokens),
// and a "?token=..." buried after a "#" would otherwise slip past the query
// parsing below into a log line.
//
// "code" is deliberately NOT on the denylist: it is a common benign parameter
// (color=, sort=, country_code=, ...) and redacting it would corrupt ordinary
// log lines without protecting a credential.
const REDACTED = "[REDACTED]";
// Exact lowercase matches against the decoded parameter name.
const SENSITIVE_QUERY_KEYS = Object.freeze(new Set([
"token",
"access_token",
"refresh_token",
"auth",
"authorization",
"key",
"apikey",
"api_key",
"secret",
"password",
"passwd",
"pwd",
"session",
"sessionid",
"session_id",
"sid",
"sig",
"signature",
"jwt",
"otp",
]));
// decodeURIComponent throws on malformed UTF-8 percent-escapes; callers must
// not crash (and must not lose the whole line) over a hostile name.
function decodeName(rawName) {
try {
return decodeURIComponent(rawName);
} catch (_) {
return null;
}
}
function isSensitiveName(rawName) {
const decoded = decodeName(rawName);
if (decoded !== null && SENSITIVE_QUERY_KEYS.has(decoded.toLowerCase())) {
return true;
}
// Fallback: a malformed escape defeats decoding, so also compare the raw
// lowercased name — an attacker should not be able to smuggle a credential
// parameter past the filter by corrupting their own escape sequence.
return SENSITIVE_QUERY_KEYS.has(String(rawName).toLowerCase());
}
function sanitizeUrlForLogging(raw) {
if (typeof raw !== "string" || raw.length === 0) return raw;
// Drop any fragment first: nothing after "#" is ever sent to a server, and
// leaving it in the output could leak a fragment-borne credential verbatim.
const fragmentStart = raw.indexOf("#");
const withoutFragment = fragmentStart === -1 ? raw : raw.slice(0, fragmentStart);
const queryStart = withoutFragment.indexOf("?");
if (queryStart === -1) return withoutFragment;
const base = withoutFragment.slice(0, queryStart);
const query = withoutFragment.slice(queryStart + 1);
const parts = query.split("&");
const sanitized = new Array(parts.length);
for (let i = 0; i < parts.length; i++) {
const part = parts[i];
if (part.length === 0) {
sanitized[i] = part;
continue;
}
// Split on the FIRST "=" only: values may legitimately contain "=".
const eq = part.indexOf("=");
if (eq === -1) {
// Bare valueless flag (e.g. "?token") — redact it whole when sensitive.
sanitized[i] = isSensitiveName(part) ? REDACTED : part;
} else {
const name = part.slice(0, eq);
sanitized[i] = isSensitiveName(name) ? `${name}=${REDACTED}` : part;
}
}
return `${base}?${sanitized.join("&")}`;
}
module.exports = { sanitizeUrlForLogging, SENSITIVE_QUERY_KEYS };
+144
View File
@@ -0,0 +1,144 @@
"use strict";
// Tests for the URL log-sanitizer. Contract under test:
// - credential-bearing query parameters (the ssh-terminal ?token= is the
// concrete case) never survive into a URL destined for persistent logs;
// - everything else — path, parameter order, encoding, non-sensitive
// values — is preserved byte-for-byte;
// - hostile input (non-strings, malformed escapes, "=" inside values) can
// never crash a logging path.
const test = require("node:test");
const assert = require("node:assert");
const { sanitizeUrlForLogging, SENSITIVE_QUERY_KEYS } = require("./url-sanitize");
test("redacts the ssh-terminal token in place", () => {
assert.strictEqual(
sanitizeUrlForLogging("/ssh-terminal/?token=ABC.123.def"),
"/ssh-terminal/?token=[REDACTED]"
);
});
test("redacts only sensitive parameters, preserving order and neighbors", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?a=1&token=s&b=2"),
"/x?a=1&token=[REDACTED]&b=2"
);
});
test("redacts every occurrence of a repeated sensitive parameter", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?token=a&token=b"),
"/x?token=[REDACTED]&token=[REDACTED]"
);
});
test("matching is case-insensitive on the parameter name", () => {
assert.strictEqual(sanitizeUrlForLogging("/x?Token=x"), "/x?Token=[REDACTED]");
assert.strictEqual(sanitizeUrlForLogging("/x?PASSWORD=hunter2"), "/x?PASSWORD=[REDACTED]");
});
test("covers the whole denylist, not just token", () => {
for (const key of SENSITIVE_QUERY_KEYS) {
assert.strictEqual(
sanitizeUrlForLogging(`/x?${key}=v`),
`/x?${key}=[REDACTED]`,
`expected "${key}" to be redacted`
);
}
});
test("a URL with no query string is returned as-is", () => {
assert.strictEqual(sanitizeUrlForLogging("/ssh-terminal/"), "/ssh-terminal/");
assert.strictEqual(sanitizeUrlForLogging("/a/b/c"), "/a/b/c");
});
test("empty and non-string input passes through unchanged", () => {
assert.strictEqual(sanitizeUrlForLogging(""), "");
assert.strictEqual(sanitizeUrlForLogging(123), 123);
assert.strictEqual(sanitizeUrlForLogging(null), null);
assert.strictEqual(sanitizeUrlForLogging(undefined), undefined);
});
test("percent-encoded sensitive names are still recognized", () => {
// %74oken === "token"
assert.strictEqual(sanitizeUrlForLogging("/x?%74oken=x"), "/x?%74oken=[REDACTED]");
});
test("values containing '=' are split on the first '=' only", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?token=abc=def"),
"/x?token=[REDACTED]"
);
// Non-sensitive value with '=' inside passes through untouched.
assert.strictEqual(sanitizeUrlForLogging("/x?a=b=c"), "/x?a=b=c");
});
test("malformed percent-escapes in a name do not throw", () => {
// %C3%28 is an invalid UTF-8 sequence; decodeURIComponent throws on it.
const url = "/x?token%C3%28=x&a=1";
assert.doesNotThrow(() => sanitizeUrlForLogging(url));
assert.strictEqual(sanitizeUrlForLogging(url), "/x?token%C3%28=x&a=1");
// The raw-name fallback can only fire when the raw lowercase name itself is
// a denylist entry — impossible for a "%"-bearing name, since no denylist
// key contains "%". So a malformed escape that defeats decoding passes the
// pair through untouched (which matches what the query parser on the
// server sees: the same undecoded name).
assert.strictEqual(sanitizeUrlForLogging("/x?token%ZZ=x"), "/x?token%ZZ=x");
});
test("benign parameters are never redacted", () => {
assert.strictEqual(sanitizeUrlForLogging("/x?code=abc&state=def"), "/x?code=abc&state=def");
assert.strictEqual(sanitizeUrlForLogging("/x?page=2&sort=country_code"), "/x?page=2&sort=country_code");
});
test("encoding of untouched parts is preserved byte-for-byte", () => {
const url = "/x?a%20b=1%2F2&c=3";
assert.strictEqual(sanitizeUrlForLogging(url), url);
});
test("a bare valueless sensitive flag is redacted whole", () => {
assert.strictEqual(sanitizeUrlForLogging("/x?token"), "/x?[REDACTED]");
assert.strictEqual(sanitizeUrlForLogging("/x?debug&token&b=2"), "/x?debug&[REDACTED]&b=2");
assert.strictEqual(sanitizeUrlForLogging("/x?debug"), "/x?debug");
});
test("mixed-case escapes and letters in a name are still recognized", () => {
// %54 === "T"; decodeURIComponent accepts both hex cases.
assert.strictEqual(sanitizeUrlForLogging("/x?%54oKeN=x"), "/x?%54oKeN=[REDACTED]");
assert.strictEqual(sanitizeUrlForLogging("/x?SeSsIoNiD=x"), "/x?SeSsIoNiD=[REDACTED]");
});
test("a raw '?' inside a value does not hide a later sensitive name", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?next=/y?a=b&token=s"),
"/x?next=/y?a=b&token=[REDACTED]"
);
});
test("an encoded '&' stays inside the value and does not split the pair", () => {
assert.strictEqual(
sanitizeUrlForLogging("/x?token=a%26b&x=1"),
"/x?token=[REDACTED]&x=1"
);
});
test("fragments are dropped, never logged", () => {
// A fragment after a sensitive value is swallowed by the redaction anyway.
assert.strictEqual(sanitizeUrlForLogging("/x?token=s#frag"), "/x?token=[REDACTED]");
// A sensitive name buried after a "#" must not slip past query parsing.
assert.strictEqual(sanitizeUrlForLogging("/x?a=1#b?token=s"), "/x?a=1");
// Client-side URLs put credentials in the fragment (this panel's #sid=...,
// OAuth implicit-flow tokens) — they must not survive into a log line.
assert.strictEqual(sanitizeUrlForLogging("/x#access_token=abc"), "/x");
assert.strictEqual(sanitizeUrlForLogging("/x?a=1#keep"), "/x?a=1");
});
test("regression: a full-length ssh-terminal token leaves no trace in the output", () => {
const secret = "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08";
assert.strictEqual(secret.length, 64);
const out = sanitizeUrlForLogging(`/ssh-terminal/?token=${secret}`);
assert.strictEqual(out, "/ssh-terminal/?token=[REDACTED]");
assert.ok(!out.includes(secret), "sanitized URL must not contain the token value");
});
+1 -1
View File
@@ -56,7 +56,7 @@
}
});
</script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260509-floating-terminal-5" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260923-ssh-terminal-restore-7" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/bot.js?v=<%= assetVersion %>-console-eventsource-live-reset-20260528" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false"
src="https://cdn.jsdelivr.net/npm/monaco-editor@0.55.1/min/vs/loader.min.js" defer></script>
+1 -1
View File
@@ -1209,7 +1209,7 @@
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/socket.io/socket.io.min.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260509-floating-terminal-5" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260923-ssh-terminal-restore-7" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/dashboard.js?v=20260512-dashboard-timeout-1" defer></script>
<div class="christmas-modal" id="christmasModal">
+1 -1
View File
@@ -66,7 +66,7 @@
revokeSecurity: <%- JSON.stringify(destructiveActionSecurity || null) %>
};
</script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260509-floating-terminal-5" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260923-ssh-terminal-restore-7" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/settings.js?v=20260601-server-gray2" defer></script>
<script nonce="<%= cspNonce %>">
(function(){
+1 -1
View File
@@ -1111,7 +1111,7 @@
<% } %>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/socket.io/socket.io.min.js" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260509-floating-terminal-5" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/ssh-terminal-window.js?v=20260923-ssh-terminal-restore-7" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/dashboard.js?v=20260512-dashboard-timeout-1" defer></script>
<script nonce="<%= cspNonce %>" data-cfasync="false" src="/js/status-monitor.js?v=<%= typeof themeVersion !== 'undefined' ? themeVersion : Date.now() %>" defer></script>