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:
1 parent
a022f29e34
commit
78193254ad
14 files changed
+21400
-4827
No files matched your search
@@ -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">
|
||||
|
||||
@@ -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();
|
||||
|
||||
if (frame && (!frame.getAttribute("src") || frame.getAttribute("src") === "about:blank")) {
|
||||
frame.src = await fetchLaunchUrl();
|
||||
// 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;
|
||||
})();
|
||||
@@ -372,7 +439,12 @@
|
||||
if (!options.silent) alert(err && err.message ? err.message : "Failed to open SSH terminal.");
|
||||
throw err;
|
||||
} finally {
|
||||
opening = null;
|
||||
// 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");
|
||||
|
||||
Vendored
+736
@@ -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();
|
||||
}
|
||||
})();
|
||||
Reference in new issue
Block a user