5 Commits

5 changed files with 177 additions and 41 deletions
+30 -2
View File
@@ -4,6 +4,7 @@ SSH web client — Flask backend: auth, MariaDB, encrypted identities, WebSocket
from __future__ import annotations from __future__ import annotations
import os import os
import socket
if os.getenv("GEVENT_MONKEY_PATCH", "").lower() in ("1", "true", "yes"): if os.getenv("GEVENT_MONKEY_PATCH", "").lower() in ("1", "true", "yes"):
from gevent import monkey from gevent import monkey
@@ -883,7 +884,13 @@ def _connect_with_jump_chain(host_id: int) -> tuple[paramiko.SSHClient, paramiko
raise RuntimeError("failed to build jump chain") raise RuntimeError("failed to build jump chain")
def is_audit_log_enabled() -> bool:
return os.getenv("ENABLE_AUDIT_LOG", "true").lower() in ("1", "true", "yes")
def _insert_connection_audit(host_row: dict[str, Any]) -> int | None: def _insert_connection_audit(host_row: dict[str, Any]) -> int | None:
if not is_audit_log_enabled():
return None
try: try:
with db_cursor() as (_, cur): with db_cursor() as (_, cur):
cur.execute( cur.execute(
@@ -964,9 +971,10 @@ def api_logout():
@app.route("/api/me", methods=["GET"]) @app.route("/api/me", methods=["GET"])
def api_me(): def api_me():
version = app.config.get("VERSION", "unknown") version = app.config.get("VERSION", "unknown")
audit_enabled = is_audit_log_enabled()
if session.get("logged_in"): if session.get("logged_in"):
return jsonify({"logged_in": True, "app_version": version}) return jsonify({"logged_in": True, "app_version": version, "audit_log_enabled": audit_enabled})
return jsonify({"logged_in": False, "app_version": version}) return jsonify({"logged_in": False, "app_version": version, "audit_log_enabled": audit_enabled})
@app.route("/api/identities", methods=["GET"]) @app.route("/api/identities", methods=["GET"])
@@ -1404,6 +1412,26 @@ def list_hosts():
return jsonify({"items": rows}) return jsonify({"items": rows})
@app.route("/api/hosts/<int:hid>/ping", methods=["GET"])
@require_auth("read:hosts")
def ping_host(hid: int):
with db_cursor() as (_, cur):
cur.execute("SELECT hostname, port FROM ssh_hosts WHERE id = %s", (hid,))
row = cur.fetchone()
if not row:
return jsonify({"error": "not found"}), 404
up = False
try:
with socket.create_connection((row["hostname"], row["port"]), timeout=2.0):
up = True
except Exception:
pass
return jsonify({"up": up})
@app.route("/api/tags", methods=["GET"]) @app.route("/api/tags", methods=["GET"])
@require_auth("read:hosts") @require_auth("read:hosts")
def list_tags(): def list_tags():
+5
View File
@@ -25,6 +25,7 @@ interface TabItem {
const loggedIn = ref(false); const loggedIn = ref(false);
const checking = ref(true); const checking = ref(true);
const appVersion = ref("unknown"); const appVersion = ref("unknown");
const auditLogEnabled = ref(true);
const identities = ref<IdentityRow[]>([]); const identities = ref<IdentityRow[]>([]);
const allHosts = ref<HostRow[]>([]); const allHosts = ref<HostRow[]>([]);
const allFolders = ref<FolderRow[]>([]); const allFolders = ref<FolderRow[]>([]);
@@ -347,6 +348,9 @@ onMounted(async () => {
if (m.app_version) { if (m.app_version) {
appVersion.value = m.app_version; appVersion.value = m.app_version;
} }
if (m.audit_log_enabled !== undefined) {
auditLogEnabled.value = m.audit_log_enabled;
}
if (loggedIn.value) await refreshData(); if (loggedIn.value) await refreshData();
} catch { } catch {
loggedIn.value = false; loggedIn.value = false;
@@ -918,6 +922,7 @@ async function deleteIdentityRow(id: number) {
API keys API keys
</button> </button>
<button <button
v-if="auditLogEnabled"
type="button" type="button"
class="hidden rounded-lg px-3 py-1.5 text-xs text-slate-400 hover:bg-slate-800 hover:text-white md:inline-flex" class="hidden rounded-lg px-3 py-1.5 text-xs text-slate-400 hover:bg-slate-800 hover:text-white md:inline-flex"
@click="openAuditLog" @click="openAuditLog"
+37 -7
View File
@@ -21,7 +21,7 @@ function browseParams(folderId: number | null, q: string): string {
} }
export const api = { export const api = {
async me(): Promise<{ logged_in: boolean; app_version?: string }> { async me(): Promise<{ logged_in: boolean; app_version?: string; audit_log_enabled?: boolean }> {
const res = await fetch("/api/me", { credentials: "include" }); const res = await fetch("/api/me", { credentials: "include" });
return handle(res); return handle(res);
}, },
@@ -65,6 +65,11 @@ export const api = {
return d.items; return d.items;
}, },
async pingHost(id: number): Promise<{ up: boolean }> {
const res = await fetch(`/api/hosts/${id}/ping`, { credentials: "include" });
return handle<{ up: boolean }>(res);
},
async listTags(): Promise<string[]> { async listTags(): Promise<string[]> {
const res = await fetch("/api/tags", { credentials: "include" }); const res = await fetch("/api/tags", { credentials: "include" });
const d = await handle<{ items: string[] }>(res); const d = await handle<{ items: string[] }>(res);
@@ -318,16 +323,41 @@ export const api = {
await handle(res); await handle(res);
}, },
async sftpUpload(connId: string, path: string, file: File): Promise<void> { async sftpUpload(
connId: string,
path: string,
file: File,
onProgress?: (loaded: number, total: number) => void
): Promise<void> {
const fd = new FormData(); const fd = new FormData();
fd.set("path", path); fd.set("path", path);
fd.set("file", file); fd.set("file", file);
const res = await fetch(`/api/sftp/${connId}/upload`, { return new Promise((resolve, reject) => {
method: "POST", const xhr = new XMLHttpRequest();
credentials: "include", xhr.open("POST", `/api/sftp/${connId}/upload`);
body: fd, xhr.withCredentials = true;
if (onProgress) {
xhr.upload.onprogress = (e) => {
if (e.lengthComputable) {
onProgress(e.loaded, e.total);
}
};
}
xhr.onload = () => {
if (xhr.status === 401) return reject(new Error("unauthorized"));
let data: any = {};
try {
data = JSON.parse(xhr.responseText);
} catch (e) {}
if (xhr.status >= 200 && xhr.status < 300) {
resolve();
} else {
reject(new Error(data.error || xhr.statusText));
}
};
xhr.onerror = () => reject(new Error("Network Error"));
xhr.send(fd);
}); });
await handle(res);
}, },
sftpDownloadUrl(connId: string, path: string): string { sftpDownloadUrl(connId: string, path: string): string {
+20 -2
View File
@@ -11,6 +11,7 @@ const err = ref("");
const busy = ref(false); const busy = ref(false);
const renameTarget = ref<SftpEntry | null>(null); const renameTarget = ref<SftpEntry | null>(null);
const newName = ref(""); const newName = ref("");
const uploadProgress = ref<number | null>(null);
function isDir(m: number): boolean { function isDir(m: number): boolean {
return (m & 0o170000) === 0o040000; return (m & 0o170000) === 0o040000;
@@ -66,11 +67,16 @@ async function onUpload(ev: Event) {
input.value = ""; input.value = "";
if (!file) return; if (!file) return;
err.value = ""; err.value = "";
uploadProgress.value = 0;
try { try {
await api.sftpUpload(props.connId, path.value, file); await api.sftpUpload(props.connId, path.value, file, (loaded, total) => {
uploadProgress.value = Math.round((loaded / total) * 100);
});
await load(); await load();
} catch (e) { } catch (e) {
err.value = e instanceof Error ? e.message : "Upload failed"; err.value = e instanceof Error ? e.message : "Upload failed";
} finally {
uploadProgress.value = null;
} }
} }
@@ -186,7 +192,19 @@ function fmtSize(n: number): string {
</div> </div>
<div class="min-h-0 flex-1 overflow-auto p-2"> <div class="min-h-0 flex-1 overflow-auto p-2">
<p v-if="err" class="mb-2 text-xs text-red-400">{{ err }}</p> <p v-if="err" class="mb-2 text-xs text-red-400">{{ err }}</p>
<p v-if="busy" class="text-xs text-slate-500">Loading</p> <div v-if="uploadProgress !== null" class="mb-2 space-y-1">
<div class="flex justify-between text-[10px] text-slate-400">
<span>Uploading...</span>
<span>{{ uploadProgress }}%</span>
</div>
<div class="h-1.5 w-full overflow-hidden rounded-full bg-slate-800">
<div
class="h-full bg-accent transition-all duration-200"
:style="{ width: uploadProgress + '%' }"
></div>
</div>
</div>
<p v-else-if="busy" class="text-xs text-slate-500">Loading</p>
<ul v-else class="space-y-0.5"> <ul v-else class="space-y-0.5">
<li <li
v-for="e in entries" v-for="e in entries"
+85 -30
View File
@@ -6,6 +6,7 @@ import {
watch, watch,
nextTick, nextTick,
} from "vue"; } from "vue";
import { api } from "@/api";
import { Terminal } from "@xterm/xterm"; import { Terminal } from "@xterm/xterm";
import { FitAddon } from "@xterm/addon-fit"; import { FitAddon } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css"; import "@xterm/xterm/css/xterm.css";
@@ -32,12 +33,14 @@ defineExpose({
const termEl = ref<HTMLElement | null>(null); const termEl = ref<HTMLElement | null>(null);
const status = ref("Connecting…"); const status = ref("Connecting…");
const connId = ref<string | null>(null); const connId = ref<string | null>(null);
const serverBackOnline = ref(false);
let ws: WebSocket | null = null; let ws: WebSocket | null = null;
let term: Terminal | null = null; let term: Terminal | null = null;
let fit: FitAddon | null = null; let fit: FitAddon | null = null;
let ro: ResizeObserver | null = null; let ro: ResizeObserver | null = null;
let visibilityHandler: (() => void) | null = null; let visibilityHandler: (() => void) | null = null;
let pingInterval: number | null = null;
function wsUrl(hostId: number): string { function wsUrl(hostId: number): string {
const proto = location.protocol === "https:" ? "wss:" : "ws:"; const proto = location.protocol === "https:" ? "wss:" : "ws:";
@@ -85,6 +88,71 @@ function isControlMessage(raw: string): boolean {
return false; return false;
} }
function connectWs() {
serverBackOnline.value = false;
if (pingInterval) {
clearInterval(pingInterval);
pingInterval = null;
}
if (ws) {
ws.close();
}
ws = new WebSocket(wsUrl(props.hostId));
ws.binaryType = "arraybuffer";
ws.onopen = () => {
status.value = "Handshaking…";
sendResize();
};
ws.onmessage = (ev) => {
if (!term) return;
if (typeof ev.data === "string") {
if (isControlMessage(ev.data)) return;
term.write(ev.data);
return;
}
const u8 = new Uint8Array(ev.data as ArrayBuffer);
term.write(new TextDecoder().decode(u8));
};
ws.onerror = () => {
status.value = "WebSocket error";
};
ws.onclose = () => {
if (!connId.value) {
status.value = "Disconnected";
} else {
status.value = "Session ended";
}
pingInterval = window.setInterval(async () => {
try {
const { up } = await api.pingHost(props.hostId);
if (up) {
if (pingInterval) {
clearInterval(pingInterval);
pingInterval = null;
}
serverBackOnline.value = true;
}
} catch (err) {
// ignore
}
}, 5000);
};
}
function reconnect() {
term?.clear();
term?.focus();
connId.value = null;
status.value = "Connecting…";
connectWs();
}
onMounted(async () => { onMounted(async () => {
await nextTick(); await nextTick();
if (!termEl.value) return; if (!termEl.value) return;
@@ -121,36 +189,7 @@ onMounted(async () => {
ro = new ResizeObserver(() => fitAndResize()); ro = new ResizeObserver(() => fitAndResize());
ro.observe(termEl.value); ro.observe(termEl.value);
ws = new WebSocket(wsUrl(props.hostId)); connectWs();
ws.binaryType = "arraybuffer";
ws.onopen = () => {
status.value = "Handshaking…";
sendResize();
};
ws.onmessage = (ev) => {
if (!term) return;
if (typeof ev.data === "string") {
if (isControlMessage(ev.data)) return;
term.write(ev.data);
return;
}
const u8 = new Uint8Array(ev.data as ArrayBuffer);
term.write(new TextDecoder().decode(u8));
};
ws.onerror = () => {
status.value = "WebSocket error";
};
ws.onclose = () => {
if (!connId.value) {
status.value = "Disconnected";
} else {
status.value = "Session ended";
}
};
visibilityHandler = () => { visibilityHandler = () => {
if (document.visibilityState === "visible") { if (document.visibilityState === "visible") {
@@ -162,6 +201,10 @@ onMounted(async () => {
}); });
onUnmounted(() => { onUnmounted(() => {
if (pingInterval) {
clearInterval(pingInterval);
pingInterval = null;
}
if (visibilityHandler) { if (visibilityHandler) {
document.removeEventListener("visibilitychange", visibilityHandler); document.removeEventListener("visibilitychange", visibilityHandler);
visibilityHandler = null; visibilityHandler = null;
@@ -197,6 +240,18 @@ watch(
> >
{{ status }} {{ status }}
</div> </div>
<div
v-if="serverBackOnline"
class="absolute bottom-4 right-4 z-20 flex items-center gap-3 rounded bg-slate-800 px-4 py-3 text-sm shadow-lg border border-slate-700"
>
<span class="text-slate-200">Server is back online</span>
<button
@click="reconnect"
class="rounded bg-emerald-600 px-3 py-1.5 font-medium text-white hover:bg-emerald-500 transition-colors"
>
Reconnect
</button>
</div>
<div <div
ref="termEl" ref="termEl"
class="h-full min-h-[320px] rounded-lg border border-slate-800 bg-[#0d1117] p-1" class="h-full min-h-[320px] rounded-lg border border-slate-800 bg-[#0d1117] p-1"