Compare commits
7 Commits
6539a7f2c4
..
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 9050986364 | |||
| d625c3903d | |||
| c487a4e949 | |||
| b4f31aa0ab | |||
| 0d98e16f29 | |||
| db33658ffa | |||
| a38e3488e4 |
@@ -4,6 +4,7 @@ SSH web client — Flask backend: auth, MariaDB, encrypted identities, WebSocket
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import socket
|
||||
|
||||
if os.getenv("GEVENT_MONKEY_PATCH", "").lower() in ("1", "true", "yes"):
|
||||
from gevent import monkey
|
||||
@@ -164,6 +165,13 @@ def init_db():
|
||||
CONSTRAINT fk_host_tags_tag FOREIGN KEY (tag_id)
|
||||
REFERENCES ssh_tags(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS ssh_snippets (
|
||||
id INT AUTO_INCREMENT PRIMARY KEY,
|
||||
label VARCHAR(255) NOT NULL,
|
||||
command TEXT NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
|
||||
);
|
||||
"""
|
||||
with db_cursor() as (_, cur):
|
||||
for stmt in ddl.split(";"):
|
||||
@@ -876,7 +884,13 @@ def _connect_with_jump_chain(host_id: int) -> tuple[paramiko.SSHClient, paramiko
|
||||
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:
|
||||
if not is_audit_log_enabled():
|
||||
return None
|
||||
try:
|
||||
with db_cursor() as (_, cur):
|
||||
cur.execute(
|
||||
@@ -957,9 +971,10 @@ def api_logout():
|
||||
@app.route("/api/me", methods=["GET"])
|
||||
def api_me():
|
||||
version = app.config.get("VERSION", "unknown")
|
||||
audit_enabled = is_audit_log_enabled()
|
||||
if session.get("logged_in"):
|
||||
return jsonify({"logged_in": True, "app_version": version})
|
||||
return jsonify({"logged_in": False, "app_version": version})
|
||||
return jsonify({"logged_in": True, "app_version": version, "audit_log_enabled": audit_enabled})
|
||||
return jsonify({"logged_in": False, "app_version": version, "audit_log_enabled": audit_enabled})
|
||||
|
||||
|
||||
@app.route("/api/identities", methods=["GET"])
|
||||
@@ -1103,6 +1118,80 @@ def delete_identity(iid: int):
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@app.route("/api/snippets", methods=["GET"])
|
||||
@require_auth("read:hosts")
|
||||
def list_snippets():
|
||||
with db_cursor() as (_, cur):
|
||||
cur.execute("SELECT id, label, command, created_at, updated_at FROM ssh_snippets ORDER BY label ASC")
|
||||
rows = cur.fetchall()
|
||||
return jsonify({"items": rows})
|
||||
|
||||
|
||||
@app.route("/api/snippets", methods=["POST"])
|
||||
@require_auth("write:hosts")
|
||||
def create_snippet():
|
||||
req = request.get_json()
|
||||
if not req:
|
||||
return jsonify({"error": "invalid json"}), 400
|
||||
label = (req.get("label") or "").strip()
|
||||
command = req.get("command") or ""
|
||||
if not label or not command:
|
||||
return jsonify({"error": "label and command required"}), 400
|
||||
with db_cursor() as (_, cur):
|
||||
cur.execute(
|
||||
"INSERT INTO ssh_snippets (label, command) VALUES (%s, %s)",
|
||||
(label, command),
|
||||
)
|
||||
sid = cur.lastrowid
|
||||
return jsonify({"id": sid}), 201
|
||||
|
||||
|
||||
@app.route("/api/snippets/<int:sid>", methods=["PATCH"])
|
||||
@require_auth("write:hosts")
|
||||
def update_snippet(sid: int):
|
||||
req = request.get_json()
|
||||
if not req:
|
||||
return jsonify({"error": "invalid json"}), 400
|
||||
|
||||
updates = []
|
||||
args = []
|
||||
if "label" in req:
|
||||
label = (req["label"] or "").strip()
|
||||
if not label:
|
||||
return jsonify({"error": "label cannot be empty"}), 400
|
||||
updates.append("label = %s")
|
||||
args.append(label)
|
||||
if "command" in req:
|
||||
cmd = req["command"] or ""
|
||||
if not cmd:
|
||||
return jsonify({"error": "command cannot be empty"}), 400
|
||||
updates.append("command = %s")
|
||||
args.append(cmd)
|
||||
|
||||
if not updates:
|
||||
return jsonify({"ok": True})
|
||||
|
||||
args.append(sid)
|
||||
with db_cursor() as (_, cur):
|
||||
cur.execute(
|
||||
f"UPDATE ssh_snippets SET {', '.join(updates)} WHERE id = %s",
|
||||
tuple(args),
|
||||
)
|
||||
if cur.rowcount == 0:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
@app.route("/api/snippets/<int:sid>", methods=["DELETE"])
|
||||
@require_auth("write:hosts")
|
||||
def delete_snippet(sid: int):
|
||||
with db_cursor() as (_, cur):
|
||||
cur.execute("DELETE FROM ssh_snippets WHERE id = %s", (sid,))
|
||||
if cur.rowcount == 0:
|
||||
return jsonify({"error": "not found"}), 404
|
||||
return jsonify({"ok": True})
|
||||
|
||||
|
||||
def _host_select_sql(extra_where: str = "") -> str:
|
||||
return f"""
|
||||
SELECT h.id, h.folder_id, h.label, h.hostname, h.port, h.identity_id, h.jump_host_id,
|
||||
@@ -1323,6 +1412,26 @@ def list_hosts():
|
||||
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"])
|
||||
@require_auth("read:hosts")
|
||||
def list_tags():
|
||||
|
||||
+143
-2
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from "vue";
|
||||
import { Folder, Pencil, Trash2, Radio } from "lucide-vue-next";
|
||||
import { onMounted, onUnmounted, ref } from "vue";
|
||||
import { Folder, Pencil, Trash2, Radio, ChevronDown } from "lucide-vue-next";
|
||||
import {
|
||||
api,
|
||||
type HostRow,
|
||||
@@ -9,10 +9,12 @@ import {
|
||||
type ConnectionAuditRow,
|
||||
type ApiKeyRow,
|
||||
type ApiKeyScopeDef,
|
||||
type SnippetRow,
|
||||
} from "@/api";
|
||||
import LoginForm from "@/components/LoginForm.vue";
|
||||
import TabContent from "@/components/TabContent.vue";
|
||||
import TagInput from "@/components/TagInput.vue";
|
||||
import SnippetForm from "@/components/SnippetForm.vue";
|
||||
|
||||
interface TabItem {
|
||||
id: string;
|
||||
@@ -23,6 +25,7 @@ interface TabItem {
|
||||
const loggedIn = ref(false);
|
||||
const checking = ref(true);
|
||||
const appVersion = ref("unknown");
|
||||
const auditLogEnabled = ref(true);
|
||||
const identities = ref<IdentityRow[]>([]);
|
||||
const allHosts = ref<HostRow[]>([]);
|
||||
const allFolders = ref<FolderRow[]>([]);
|
||||
@@ -53,6 +56,79 @@ function handleBroadcast(data: string, sourceId: string) {
|
||||
}
|
||||
}
|
||||
|
||||
const snippets = ref<SnippetRow[]>([]);
|
||||
const showSnippetsMenu = ref(false);
|
||||
const showSnippetForm = ref(false);
|
||||
const editingSnippet = ref<SnippetRow | null>(null);
|
||||
const snippetsButtonRef = ref<HTMLElement | null>(null);
|
||||
const snippetsMenuRef = ref<HTMLElement | null>(null);
|
||||
|
||||
function closeSnippetsMenu(e: MouseEvent) {
|
||||
if (
|
||||
showSnippetsMenu.value &&
|
||||
!snippetsButtonRef.value?.contains(e.target as Node) &&
|
||||
!snippetsMenuRef.value?.contains(e.target as Node)
|
||||
) {
|
||||
showSnippetsMenu.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
document.addEventListener("click", closeSnippetsMenu);
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener("click", closeSnippetsMenu);
|
||||
});
|
||||
|
||||
async function loadSnippets() {
|
||||
try {
|
||||
snippets.value = await api.listSnippets();
|
||||
} catch (err: any) {
|
||||
loadErr.value = err.message;
|
||||
}
|
||||
}
|
||||
|
||||
function runSnippet(command: string) {
|
||||
showSnippetsMenu.value = false;
|
||||
const targetPanes = broadcastMode.value ? activePanes.value : [activePanes.value[0]];
|
||||
for (const paneId of targetPanes) {
|
||||
if (paneId && tabRefs.value[paneId]) {
|
||||
tabRefs.value[paneId].sendData(command + "\r");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSnippet(data: { label: string; command: string }) {
|
||||
try {
|
||||
if (editingSnippet.value) {
|
||||
await api.updateSnippet(editingSnippet.value.id, data);
|
||||
} else {
|
||||
await api.createSnippet(data);
|
||||
}
|
||||
showSnippetForm.value = false;
|
||||
await loadSnippets();
|
||||
} catch (err: any) {
|
||||
alert(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function deleteSnippet(id: number) {
|
||||
if (!confirm("Are you sure you want to delete this snippet?")) return;
|
||||
try {
|
||||
await api.deleteSnippet(id);
|
||||
await loadSnippets();
|
||||
} catch (err: any) {
|
||||
alert(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
function openEditSnippet(s?: SnippetRow) {
|
||||
showSnippetsMenu.value = false;
|
||||
editingSnippet.value = s || null;
|
||||
showSnippetForm.value = true;
|
||||
}
|
||||
|
||||
function onTabDragStart(id: string) {
|
||||
draggedTabId.value = id;
|
||||
}
|
||||
@@ -255,6 +331,7 @@ async function refreshData() {
|
||||
allHosts.value = await api.listHosts();
|
||||
allFolders.value = await api.listFoldersFlat();
|
||||
allTags.value = await api.listTags();
|
||||
await loadSnippets();
|
||||
if (!hostForm.value.identity_id && identities.value.length) {
|
||||
hostForm.value.identity_id = identities.value[0].id;
|
||||
}
|
||||
@@ -271,6 +348,9 @@ onMounted(async () => {
|
||||
if (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();
|
||||
} catch {
|
||||
loggedIn.value = false;
|
||||
@@ -773,6 +853,59 @@ async function deleteIdentityRow(id: number) {
|
||||
Broadcast
|
||||
</span>
|
||||
</button>
|
||||
<div class="relative hidden md:block">
|
||||
<button
|
||||
ref="snippetsButtonRef"
|
||||
type="button"
|
||||
class="rounded-lg px-3 py-1.5 text-xs text-slate-400 hover:bg-slate-800 hover:text-white inline-flex items-center gap-1"
|
||||
@click="showSnippetsMenu = !showSnippetsMenu"
|
||||
>
|
||||
Snippets
|
||||
<ChevronDown class="h-3 w-3" />
|
||||
</button>
|
||||
<div
|
||||
v-if="showSnippetsMenu"
|
||||
ref="snippetsMenuRef"
|
||||
class="absolute right-0 top-full mt-2 w-64 rounded-xl border border-slate-700 bg-surface shadow-xl z-50 overflow-hidden"
|
||||
>
|
||||
<div class="max-h-64 overflow-y-auto p-1">
|
||||
<div v-if="snippets.length === 0" class="p-3 text-center text-xs text-slate-500">
|
||||
No snippets saved.
|
||||
</div>
|
||||
<div
|
||||
v-for="s in snippets"
|
||||
:key="s.id"
|
||||
class="flex items-center justify-between group rounded-lg px-2 py-1.5 hover:bg-slate-800"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="flex-1 text-left text-sm text-white truncate"
|
||||
@click="runSnippet(s.command)"
|
||||
:title="s.command"
|
||||
>
|
||||
{{ s.label }}
|
||||
</button>
|
||||
<div class="flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
|
||||
<button type="button" class="text-slate-400 hover:text-white p-1" @click="openEditSnippet(s)">
|
||||
<Pencil class="h-3 w-3" />
|
||||
</button>
|
||||
<button type="button" class="text-red-400 hover:text-red-300 p-1" @click="deleteSnippet(s.id)">
|
||||
<Trash2 class="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="border-t border-slate-700 p-1">
|
||||
<button
|
||||
type="button"
|
||||
class="w-full rounded-lg px-2 py-1.5 text-left text-xs text-slate-400 hover:bg-slate-800 hover:text-white"
|
||||
@click="openEditSnippet()"
|
||||
>
|
||||
+ Add new snippet...
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="hidden rounded-lg px-3 py-1.5 text-xs md:inline-flex"
|
||||
@@ -789,6 +922,7 @@ async function deleteIdentityRow(id: number) {
|
||||
API keys
|
||||
</button>
|
||||
<button
|
||||
v-if="auditLogEnabled"
|
||||
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"
|
||||
@click="openAuditLog"
|
||||
@@ -1117,6 +1251,13 @@ async function deleteIdentityRow(id: number) {
|
||||
</main>
|
||||
</div>
|
||||
|
||||
<SnippetForm
|
||||
v-if="showSnippetForm"
|
||||
:snippet="editingSnippet"
|
||||
@save="saveSnippet"
|
||||
@cancel="showSnippetForm = false"
|
||||
/>
|
||||
|
||||
<div
|
||||
v-if="showApiKeys"
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/60 p-4"
|
||||
|
||||
+80
-7
@@ -21,7 +21,7 @@ function browseParams(folderId: number | null, q: string): string {
|
||||
}
|
||||
|
||||
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" });
|
||||
return handle(res);
|
||||
},
|
||||
@@ -65,6 +65,11 @@ export const api = {
|
||||
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[]> {
|
||||
const res = await fetch("/api/tags", { credentials: "include" });
|
||||
const d = await handle<{ items: string[] }>(res);
|
||||
@@ -188,6 +193,43 @@ export const api = {
|
||||
await handle(res);
|
||||
},
|
||||
|
||||
async listSnippets(): Promise<SnippetRow[]> {
|
||||
const res = await fetch("/api/snippets", { credentials: "include" });
|
||||
const d = await handle<{ items: SnippetRow[] }>(res);
|
||||
return d.items;
|
||||
},
|
||||
|
||||
async createSnippet(body: Record<string, unknown>): Promise<{ id: number }> {
|
||||
const res = await fetch("/api/snippets", {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
return handle(res);
|
||||
},
|
||||
|
||||
async updateSnippet(
|
||||
id: number,
|
||||
body: Partial<{ label: string; command: string }>,
|
||||
): Promise<void> {
|
||||
const res = await fetch(`/api/snippets/${id}`, {
|
||||
method: "PATCH",
|
||||
credentials: "include",
|
||||
headers: jsonHeaders,
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
await handle(res);
|
||||
},
|
||||
|
||||
async deleteSnippet(id: number): Promise<void> {
|
||||
const res = await fetch(`/api/snippets/${id}`, {
|
||||
method: "DELETE",
|
||||
credentials: "include",
|
||||
});
|
||||
await handle(res);
|
||||
},
|
||||
|
||||
async listConnectionAudit(limit = 200, daysBack?: number): Promise<ConnectionAuditRow[]> {
|
||||
const q = new URLSearchParams({ limit: String(limit) });
|
||||
if (daysBack !== undefined) {
|
||||
@@ -281,16 +323,41 @@ export const api = {
|
||||
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();
|
||||
fd.set("path", path);
|
||||
fd.set("file", file);
|
||||
const res = await fetch(`/api/sftp/${connId}/upload`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
body: fd,
|
||||
return new Promise((resolve, reject) => {
|
||||
const xhr = new XMLHttpRequest();
|
||||
xhr.open("POST", `/api/sftp/${connId}/upload`);
|
||||
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 {
|
||||
@@ -327,6 +394,12 @@ export interface IdentityRow {
|
||||
auth_type: string;
|
||||
}
|
||||
|
||||
export interface SnippetRow {
|
||||
id: number;
|
||||
label: string;
|
||||
command: string;
|
||||
}
|
||||
|
||||
export interface SftpEntry {
|
||||
filename: string;
|
||||
st_mode: number;
|
||||
|
||||
@@ -11,6 +11,7 @@ const err = ref("");
|
||||
const busy = ref(false);
|
||||
const renameTarget = ref<SftpEntry | null>(null);
|
||||
const newName = ref("");
|
||||
const uploadProgress = ref<number | null>(null);
|
||||
|
||||
function isDir(m: number): boolean {
|
||||
return (m & 0o170000) === 0o040000;
|
||||
@@ -66,11 +67,16 @@ async function onUpload(ev: Event) {
|
||||
input.value = "";
|
||||
if (!file) return;
|
||||
err.value = "";
|
||||
uploadProgress.value = 0;
|
||||
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();
|
||||
} catch (e) {
|
||||
err.value = e instanceof Error ? e.message : "Upload failed";
|
||||
} finally {
|
||||
uploadProgress.value = null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,7 +192,19 @@ function fmtSize(n: number): string {
|
||||
</div>
|
||||
<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="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">
|
||||
<li
|
||||
v-for="e in entries"
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from "vue";
|
||||
import type { SnippetRow } from "@/api";
|
||||
|
||||
const props = defineProps<{
|
||||
snippet?: SnippetRow | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: "save", data: { label: string; command: string }): void;
|
||||
(e: "cancel"): void;
|
||||
}>();
|
||||
|
||||
const label = ref(props.snippet?.label || "");
|
||||
const command = ref(props.snippet?.command || "");
|
||||
|
||||
function submit() {
|
||||
if (!label.value.trim() || !command.value.trim()) return;
|
||||
emit("save", {
|
||||
label: label.value.trim(),
|
||||
command: command.value.trim(),
|
||||
});
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div
|
||||
class="fixed inset-0 z-50 flex items-center justify-center bg-black/50 p-4 backdrop-blur-sm"
|
||||
>
|
||||
<div
|
||||
class="w-full max-w-md rounded-xl border border-slate-700 bg-surface shadow-2xl"
|
||||
>
|
||||
<div class="flex items-center justify-between border-b border-slate-800 p-4">
|
||||
<h2 class="text-lg font-semibold text-white">
|
||||
{{ snippet ? "Edit snippet" : "Add snippet" }}
|
||||
</h2>
|
||||
<button
|
||||
type="button"
|
||||
class="text-slate-400 hover:text-white"
|
||||
@click="emit('cancel')"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
</div>
|
||||
<form class="space-y-4 p-4" @submit.prevent="submit">
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium text-slate-300">
|
||||
Label
|
||||
</label>
|
||||
<input
|
||||
v-model="label"
|
||||
type="text"
|
||||
required
|
||||
class="w-full rounded-lg border border-slate-700 bg-surface-overlay px-3 py-2 text-sm text-white placeholder:text-slate-500 focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
|
||||
placeholder="e.g. Docker logs"
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label class="mb-1 block text-sm font-medium text-slate-300">
|
||||
Command
|
||||
</label>
|
||||
<textarea
|
||||
v-model="command"
|
||||
required
|
||||
rows="3"
|
||||
class="w-full rounded-lg border border-slate-700 bg-surface-overlay px-3 py-2 text-sm font-mono text-white placeholder:text-slate-500 focus:border-accent focus:outline-none focus:ring-1 focus:ring-accent"
|
||||
placeholder="docker compose logs -f"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex justify-end gap-2 pt-2">
|
||||
<button
|
||||
type="button"
|
||||
class="rounded-lg px-4 py-2 text-sm font-medium text-slate-300 hover:text-white"
|
||||
@click="emit('cancel')"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class="rounded-lg bg-accent px-4 py-2 text-sm font-medium text-black hover:bg-[#16966b]"
|
||||
>
|
||||
Save snippet
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
watch,
|
||||
nextTick,
|
||||
} from "vue";
|
||||
import { api } from "@/api";
|
||||
import { Terminal } from "@xterm/xterm";
|
||||
import { FitAddon } from "@xterm/addon-fit";
|
||||
import "@xterm/xterm/css/xterm.css";
|
||||
@@ -32,12 +33,14 @@ defineExpose({
|
||||
const termEl = ref<HTMLElement | null>(null);
|
||||
const status = ref("Connecting…");
|
||||
const connId = ref<string | null>(null);
|
||||
const serverBackOnline = ref(false);
|
||||
|
||||
let ws: WebSocket | null = null;
|
||||
let term: Terminal | null = null;
|
||||
let fit: FitAddon | null = null;
|
||||
let ro: ResizeObserver | null = null;
|
||||
let visibilityHandler: (() => void) | null = null;
|
||||
let pingInterval: number | null = null;
|
||||
|
||||
function wsUrl(hostId: number): string {
|
||||
const proto = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
@@ -85,6 +88,71 @@ function isControlMessage(raw: string): boolean {
|
||||
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 () => {
|
||||
await nextTick();
|
||||
if (!termEl.value) return;
|
||||
@@ -121,36 +189,7 @@ onMounted(async () => {
|
||||
ro = new ResizeObserver(() => fitAndResize());
|
||||
ro.observe(termEl.value);
|
||||
|
||||
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";
|
||||
}
|
||||
};
|
||||
connectWs();
|
||||
|
||||
visibilityHandler = () => {
|
||||
if (document.visibilityState === "visible") {
|
||||
@@ -162,6 +201,10 @@ onMounted(async () => {
|
||||
});
|
||||
|
||||
onUnmounted(() => {
|
||||
if (pingInterval) {
|
||||
clearInterval(pingInterval);
|
||||
pingInterval = null;
|
||||
}
|
||||
if (visibilityHandler) {
|
||||
document.removeEventListener("visibilitychange", visibilityHandler);
|
||||
visibilityHandler = null;
|
||||
@@ -197,6 +240,18 @@ watch(
|
||||
>
|
||||
{{ status }}
|
||||
</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
|
||||
ref="termEl"
|
||||
class="h-full min-h-[320px] rounded-lg border border-slate-800 bg-[#0d1117] p-1"
|
||||
|
||||
Reference in New Issue
Block a user