Initial commit — Proxmox SPICE Client (Electron)

This commit is contained in:
aria.hacker
2026-07-01 09:23:50 +02:00
commit efb8c7f446
15 changed files with 1223 additions and 0 deletions
+9
View File
@@ -0,0 +1,9 @@
# X11-Display des Hosts
# Linux lokal: DISPLAY=:0
# Über SSH mit X11: DISPLAY=localhost:10.0 (wird automatisch gesetzt)
DISPLAY=:0
# UID des lokalen Benutzers für den PulseAudio-Socket
# Herausfinden mit: id -u
# Wird für den Mount /run/user/<UID>/pulse verwendet
PULSE_UID=1000
+10
View File
@@ -0,0 +1,10 @@
node_modules/
dist/
.DS_Store
*.vv
*.pem
# Laufzeit-Daten (gespeicherte Credentials etc.) — nicht ins Repo
daten/
!daten/.gitkeep
# Lokale Umgebung
.env
+94
View File
@@ -0,0 +1,94 @@
# Build — Proxmox SPICE Client
## Voraussetzungen
```bash
node >= 18
npm >= 9
```
Für Linux-Builds auf Linux-Host, für Windows-Builds entweder Windows oder Wine (cross-build eingeschränkt — lieber nativ bauen).
## Entwicklung
```bash
npm install
npm start
```
## Produktions-Build
### Linux (AppImage + .deb)
```bash
npm run build:linux
# Output: dist/Proxmox SPICE Client-1.0.0.AppImage
# dist/proxmox-spice-client_1.0.0_amd64.deb
```
### Windows (.exe Installer)
```bash
npm run build:win
# Output: dist/Proxmox SPICE Client Setup 1.0.0.exe
```
### Beides auf einmal
```bash
npm run build:linux && npm run build:win
```
## Icons
Dateien in `assets/` müssen vor dem Build vorhanden sein:
| Datei | Größe | Verwendung |
|-------|-------|------------|
| `assets/icon.png` | mind. 512×512 | Linux AppImage + deb |
| `assets/icon.ico` | multi-size | Windows NSIS Installer |
| `assets/icon.icns` | multi-size | macOS (optional) |
**PNG → ICO konvertieren (Linux):**
```bash
sudo apt install imagemagick
convert assets/icon.png -resize 256x256 assets/icon.ico
```
**PNG → ICNS (macOS):**
```bash
# mit electron-icon-maker:
npx electron-icon-maker --input=assets/icon.png --output=assets/
```
## Abhängigkeit: virt-viewer
Der Client startet `remote-viewer` (Teil von virt-viewer). Muss auf dem Zielrechner installiert sein:
- **Linux:** `sudo apt install virt-viewer`
- **Windows:** https://virt-manager.org/download/ → "Windows MSI"
Die App zeigt beim ersten Verbindungsversuch einen Dialog wenn `remote-viewer` nicht gefunden wird.
## Verzeichnisstruktur
```
proxmox-spice-client/
├── src/
│ ├── main.js # Electron-Hauptprozess
│ ├── preload.js # Context-Bridge
│ ├── proxmox.js # Proxmox REST API Client
│ └── renderer/
│ ├── login.html
│ ├── login.js
│ ├── vms.html
│ ├── vms.js
│ └── styles.css
├── assets/
│ ├── icon.png # Quell-Icon (mind. 512×512)
│ ├── icon.ico # Windows
│ └── icon.icns # macOS (optional)
├── daten/ # persistente Einstellungen (Docker-Mount)
├── Dockerfile
├── docker-compose.yml
├── .env.example
├── package.json
└── BUILD.md
```
+53
View File
@@ -0,0 +1,53 @@
FROM node:20-bullseye
# Electron-Laufzeit-Abhängigkeiten + virt-viewer für SPICE
RUN apt-get update && apt-get install -y --no-install-recommends \
# Electron / Chromium
libgtk-3-0 \
libdrm2 \
libgbm1 \
libasound2 \
libatk1.0-0 \
libatk-bridge2.0-0 \
libcairo2 \
libcups2 \
libdbus-1-3 \
libexpat1 \
libfontconfig1 \
libgcc-s1 \
libgdk-pixbuf2.0-0 \
libglib2.0-0 \
libnspr4 \
libnss3 \
libpango-1.0-0 \
libpangocairo-1.0-0 \
libstdc++6 \
libx11-6 \
libx11-xcb1 \
libxcb1 \
libxcomposite1 \
libxcursor1 \
libxdamage1 \
libxext6 \
libxfixes3 \
libxi6 \
libxrandr2 \
libxrender1 \
libxss1 \
libxtst6 \
xdg-utils \
# SPICE-Client
virt-viewer \
&& rm -rf /var/lib/apt/lists/*
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
# Kein Sandbox-Modus nötig im Container (kein setuid-Binary verfügbar)
ENV ELECTRON_DISABLE_SANDBOX=1
CMD ["node_modules/.bin/electron", "--no-sandbox", "."]
+92
View File
@@ -0,0 +1,92 @@
# Proxmox SPICE Client
Electron-basierter Desktop-Client für Proxmox VE — als Alternative zu RDP/noVNC.
Nutzt das SPICE-Protokoll über `virt-viewer` für USB-Redirect, Vollbild und Multi-Monitor-Support.
## Features
- **Auto-Connect** — hat ein Benutzer nur eine SPICE-fähige VM, wird direkt verbunden (kein Menü)
- **VM-Liste** — bei mehreren VMs erscheint ein Auswahl-Menü (nur laufende VMs mit SPICE)
- **Credential-Speicher** — Zugangsdaten optional lokal speichern
- **USB-Redirect** — nativ über `remote-viewer` (kein Plugin nötig)
- **Vollbild / Multi-Monitor** — `Shift+F11` im SPICE-Viewer
- **Proxmox-Benutzer-Konten** — jeder User sieht nur seine zugewiesenen VMs
## Voraussetzungen
### Client-Maschinen
**Linux:**
```bash
sudo apt install virt-viewer
```
**Windows:**
Download: https://virt-manager.org/download/
### Node.js / npm
```bash
node >= 18
npm >= 9
```
## Installation & Start
```bash
git clone https://git.hacker-net.de/aria.hacker/proxmox-spice-client.git
cd proxmox-spice-client
npm install
npm start
```
## Build (AppImage / deb / Windows Installer)
```bash
npm run build:linux # → dist/*.AppImage + *.deb
npm run build:win # → dist/*Setup*.exe
```
Siehe [BUILD.md](BUILD.md) für detaillierte Build-Anleitung inkl. Icon-Konvertierung.
## Docker (X11-Forwarding)
```bash
cp .env.example .env
# DISPLAY und PULSE_UID anpassen
xhost +local:docker
docker compose up --build
```
Persistente Daten (Zugangsdaten) landen im Verzeichnis `./daten/`.
## Konfiguration
| Einstellung | Ort |
|---|---|
| Proxmox-URL | Login-Maske in der App |
| Zugangsdaten | Optional lokal gespeichert (electron-store) |
| Realm | Login-Maske (Standard: `pam`) |
## Architektur
```
src/
├── main.js # Electron-Hauptprozess, IPC, SPICE-Ticket, remote-viewer-Start
├── preload.js # Context-Bridge (sicherer API-Kanal ins Renderer)
├── proxmox.js # Proxmox REST API Client (self-signed SSL OK)
└── renderer/
├── login.html/js # Login mit optionalem Credential-Speicher
├── vms.html/js # VM-Liste, Auto-Connect-Logik
└── styles.css # Dark-UI
```
**Ablauf:**
1. Login mit Proxmox-Credentials (Benutzer + Realm)
2. `GET /cluster/resources?type=vm` — nur zugewiesene VMs
3. Filter: laufend + SPICE-fähig (`qxl*` oder `virtio-vga-gl`)
4. Eine VM → direkt verbinden; mehrere → Liste
5. SPICE-Ticket via `/spiceproxy``.vv`-Datei → `remote-viewer`
## Lizenz
MIT
+27
View File
@@ -0,0 +1,27 @@
services:
vdi-client:
build: .
env_file:
- .env
environment:
- DISPLAY=${DISPLAY:-:0}
- ELECTRON_DISABLE_SANDBOX=1
# PulseAudio-Server (optional, für Audio in der VM)
- PULSE_SERVER=unix:/run/pulse/socket
volumes:
# X11-Display des Hosts einbinden
- /tmp/.X11-unix:/tmp/.X11-unix:rw
# Persistente App-Daten (gespeicherte Zugangsdaten, Einstellungen)
- ./daten:/root/.config/proxmox-spice-client:rw
# PulseAudio-Socket (optional — auskommentieren wenn kein Audio nötig)
- /run/user/${PULSE_UID:-1000}/pulse:/run/pulse:ro
devices:
# GPU-Beschleunigung (optional — auskommentieren wenn nicht vorhanden)
- /dev/dri:/dev/dri
# Host-Netzwerk: remote-viewer muss SPICE-Port auf Proxmox direkt erreichen
network_mode: host
restart: unless-stopped
# Damit USB-Redirect funktioniert braucht remote-viewer Zugriff auf USB
privileged: false
group_add:
- video
+38
View File
@@ -0,0 +1,38 @@
{
"name": "proxmox-spice-client",
"version": "1.0.0",
"description": "VDI SPICE Client für Proxmox",
"main": "src/main.js",
"scripts": {
"start": "electron .",
"build:linux": "electron-builder --linux",
"build:win": "electron-builder --win"
},
"dependencies": {
"electron-store": "^7.0.3"
},
"devDependencies": {
"electron": "^28.0.0",
"electron-builder": "^24.0.0"
},
"build": {
"appId": "de.hackersoft.proxmox-spice-client",
"productName": "Proxmox SPICE Client",
"directories": {
"output": "dist"
},
"linux": {
"target": ["AppImage", "deb"],
"category": "Network",
"icon": "assets/icon.png"
},
"win": {
"target": ["nsis"],
"icon": "assets/icon.ico"
},
"mac": {
"target": ["dmg"],
"icon": "assets/icon.icns"
}
}
}
+166
View File
@@ -0,0 +1,166 @@
const { app, BrowserWindow, ipcMain, dialog } = require('electron');
const path = require('path');
const fs = require('fs');
const os = require('os');
const { spawn } = require('child_process');
const Store = require('electron-store');
const ProxmoxClient = require('./proxmox');
const store = new Store({ name: 'proxmox-spice-client' });
let mainWindow;
let client; // ProxmoxClient instance (persists across login → VM views)
// ---------- Window management ----------
function createWindow(file, width, height, resizable = false) {
if (mainWindow) {
mainWindow.setResizable(true);
mainWindow.setSize(width, height);
mainWindow.setResizable(resizable);
mainWindow.loadFile(path.join(__dirname, 'renderer', file));
return;
}
mainWindow = new BrowserWindow({
width,
height,
resizable,
title: 'Proxmox SPICE Client',
autoHideMenuBar: true,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
contextIsolation: true,
nodeIntegration: false,
},
});
mainWindow.loadFile(path.join(__dirname, 'renderer', file));
mainWindow.on('closed', () => { mainWindow = null; });
}
app.whenReady().then(() => {
createWindow('login.html', 460, 500, false);
app.on('activate', () => {
if (!mainWindow) createWindow('login.html', 460, 500, false);
});
});
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') app.quit();
});
// ---------- IPC: credentials ----------
ipcMain.handle('credentials:load', () => store.get('credentials', null));
ipcMain.handle('credentials:save', (_e, creds) => {
store.set('credentials', creds);
});
ipcMain.handle('credentials:clear', () => {
store.delete('credentials');
});
// ---------- IPC: Proxmox ----------
ipcMain.handle('proxmox:login', async (_e, { host, username, password }) => {
try {
client = new ProxmoxClient(host);
await client.login(username, password);
// Switch to VM list view
createWindow('vms.html', 680, 520, true);
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle('proxmox:getVMs', async () => {
try {
const vms = await client.getSpiceVMs();
return { success: true, vms };
} catch (err) {
return { success: false, error: err.message };
}
});
ipcMain.handle('proxmox:logout', () => {
client = null;
createWindow('login.html', 460, 500, false);
});
ipcMain.handle('proxmox:connect', async (_e, { node, vmid }) => {
try {
const params = await client.getSpiceTicket(node, vmid);
const vvPath = buildVVFile(params, vmid);
launchRemoteViewer(vvPath);
return { success: true };
} catch (err) {
return { success: false, error: err.message };
}
});
// ---------- SPICE helpers ----------
function buildVVFile(params, vmid) {
const lines = ['[virt-viewer]', `type=${params.type || 'spice'}`];
// Proxmox spiceproxy returns 'proxy' as the SPICE host
const host = params.proxy || params.host || client.host.split(':')[0];
lines.push(`host=${host}`);
if (params['tls-port']) lines.push(`tls-port=${params['tls-port']}`);
if (params.port) lines.push(`port=${params.port}`);
if (params.password) lines.push(`password=${params.password}`);
// Write CA cert to temp file if provided
if (params.ca) {
const caPath = path.join(os.tmpdir(), 'proxmox-spice-ca.pem');
fs.writeFileSync(caPath, params.ca);
lines.push(`tls-ca-file=${caPath}`);
}
if (params['host-subject']) lines.push(`host-subject=${params['host-subject']}`);
// UX + USB
lines.push('fullscreen=0');
lines.push('title=%d — SPICE');
lines.push('delete-this-file=1'); // remote-viewer deletes the file after reading (hides password)
lines.push('toggle-fullscreen=shift+f11');
lines.push('release-cursor=shift+f12');
lines.push('secure-attention=ctrl+alt+end');
lines.push('usb-filter=-1,-1,-1,-1,0'); // allow all USB devices
const vvPath = path.join(os.tmpdir(), `spice-${vmid}-${Date.now()}.vv`);
fs.writeFileSync(vvPath, lines.join('\n') + '\n', { mode: 0o600 });
return vvPath;
}
function launchRemoteViewer(vvPath) {
const candidates =
process.platform === 'win32'
? [
'remote-viewer',
path.join('C:', 'Program Files', 'VirtViewer', 'bin', 'remote-viewer.exe'),
path.join('C:', 'Program Files (x86)', 'VirtViewer', 'bin', 'remote-viewer.exe'),
]
: ['remote-viewer', 'virt-viewer'];
let launched = false;
function tryNext(i) {
if (i >= candidates.length) {
dialog.showErrorBox(
'remote-viewer nicht gefunden',
'Bitte installiere virt-viewer:\n\n' +
' Linux: sudo apt install virt-viewer\n' +
' Windows: https://virt-manager.org/download/\n\n' +
'Danach bitte erneut verbinden.'
);
return;
}
const child = spawn(candidates[i], [vvPath], { detached: true, stdio: 'ignore' });
child.on('error', () => tryNext(i + 1));
child.on('spawn', () => { launched = true; });
child.unref();
}
tryNext(0);
}
+15
View File
@@ -0,0 +1,15 @@
const { contextBridge, ipcRenderer } = require('electron');
contextBridge.exposeInMainWorld('api', {
credentials: {
load: () => ipcRenderer.invoke('credentials:load'),
save: (creds) => ipcRenderer.invoke('credentials:save', creds),
clear: () => ipcRenderer.invoke('credentials:clear'),
},
proxmox: {
login: (params) => ipcRenderer.invoke('proxmox:login', params),
getVMs: () => ipcRenderer.invoke('proxmox:getVMs'),
connect: (vm) => ipcRenderer.invoke('proxmox:connect', vm),
logout: () => ipcRenderer.invoke('proxmox:logout'),
},
});
+133
View File
@@ -0,0 +1,133 @@
/**
* Proxmox VE REST API client.
* Uses self-signed cert bypass — standard for most Proxmox installations.
*/
const https = require('https');
const http = require('http');
// Ignore self-signed certs (Proxmox default)
const agent = new https.Agent({ rejectUnauthorized: false });
class ProxmoxClient {
constructor(host) {
// Strip protocol prefix, trailing slash
const clean = host.replace(/^https?:\/\//, '').replace(/\/$/, '');
// Add default port 8006 if none given
this.host = clean.includes(':') ? clean : `${clean}:8006`;
this.baseUrl = `https://${this.host}`;
this.ticket = null;
this.csrf = null;
}
async request(method, path, body = null, skipAuth = false) {
const url = new URL(`${this.baseUrl}/api2/json${path}`);
const headers = { Accept: 'application/json' };
if (this.ticket && !skipAuth) {
headers['Cookie'] = `PVEAuthCookie=${this.ticket}`;
}
if (this.csrf && method !== 'GET') {
headers['CSRFPreventionToken'] = this.csrf;
}
let bodyStr = null;
if (body) {
bodyStr = new URLSearchParams(body).toString();
headers['Content-Type'] = 'application/x-www-form-urlencoded';
headers['Content-Length'] = Buffer.byteLength(bodyStr);
}
return new Promise((resolve, reject) => {
const proto = url.protocol === 'https:' ? https : http;
const opts = { method, headers, agent };
const req = proto.request(url, opts, (res) => {
let raw = '';
res.on('data', (c) => (raw += c));
res.on('end', () => {
if (res.statusCode === 200 || res.statusCode === 201) {
try {
const json = JSON.parse(raw);
resolve(json.data ?? json);
} catch {
resolve({});
}
} else {
let msg = `HTTP ${res.statusCode}`;
try {
const json = JSON.parse(raw);
msg = json.errors
? Object.values(json.errors).join(', ')
: json.message || msg;
} catch {}
reject(new Error(msg));
}
});
});
req.on('error', reject);
if (bodyStr) req.write(bodyStr);
req.end();
});
}
async login(username, password) {
const data = await this.request(
'POST',
'/access/ticket',
{ username, password },
true
);
if (!data?.ticket) {
throw new Error('Anmeldung fehlgeschlagen — Benutzername oder Passwort falsch.');
}
this.ticket = data.ticket;
this.csrf = data.CSRFPreventionToken;
return data;
}
async getSpiceVMs() {
// Proxmox only returns resources the authenticated user has access to
const resources = await this.request('GET', '/cluster/resources?type=vm');
const runningVMs = (resources || []).filter(
(r) => r.type === 'qemu' && r.status === 'running'
);
const spiceVMs = [];
for (const vm of runningVMs) {
try {
const cfg = await this.request(
'GET',
`/nodes/${vm.node}/qemu/${vm.vmid}/config`
);
if (this._isSpiceCapable(cfg)) {
spiceVMs.push({
vmid: vm.vmid,
name: vm.name || `VM ${vm.vmid}`,
node: vm.node,
});
}
} catch {
// No access to this VM's config — skip
}
}
return spiceVMs;
}
_isSpiceCapable(config) {
if (!config) return false;
const vga = (config.vga || '').toLowerCase();
// qxl, qxl2, qxl4 → SPICE
// virtio-vga-gl → SPICE with GL acceleration
return vga.startsWith('qxl') || vga === 'virtio-vga-gl';
}
async getSpiceTicket(node, vmid) {
// proxy = address clients should connect to for SPICE traffic
const proxy = this.host.split(':')[0];
return this.request('POST', `/nodes/${node}/qemu/${vmid}/spiceproxy`, {
proxy,
});
}
}
module.exports = ProxmoxClient;
+42
View File
@@ -0,0 +1,42 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self'">
<title>Proxmox SPICE Client</title>
<link rel="stylesheet" href="styles.css">
</head>
<body class="login-page">
<div class="login-card">
<div class="brand">
<h1>Proxmox SPICE</h1>
<div class="tagline">VDI Client</div>
</div>
<form id="loginForm" autocomplete="on">
<div class="field">
<label for="host">Proxmox Host</label>
<input type="text" id="host" placeholder="pve.example.com" autocomplete="url" spellcheck="false">
</div>
<div class="field">
<label for="username">Benutzer</label>
<input type="text" id="username" placeholder="user@pam" autocomplete="username" spellcheck="false">
</div>
<div class="field">
<label for="password">Passwort</label>
<input type="password" id="password" autocomplete="current-password">
</div>
<div class="checkbox-row">
<input type="checkbox" id="saveCredentials">
<label for="saveCredentials">Zugangsdaten speichern</label>
</div>
<button type="submit" id="loginBtn" class="btn-primary">Anmelden</button>
<div id="error" class="error hidden"></div>
</form>
</div>
<script src="login.js"></script>
</body>
</html>
+69
View File
@@ -0,0 +1,69 @@
/* global api */
const hostEl = document.getElementById('host');
const userEl = document.getElementById('username');
const passEl = document.getElementById('password');
const saveEl = document.getElementById('saveCredentials');
const btnEl = document.getElementById('loginBtn');
const errEl = document.getElementById('error');
// Restore saved credentials on load
(async () => {
const saved = await api.credentials.load();
if (saved) {
hostEl.value = saved.host || '';
userEl.value = saved.username || '';
passEl.value = saved.password || '';
saveEl.checked = true;
}
// Focus first empty required field
if (!hostEl.value) hostEl.focus();
else if (!userEl.value) userEl.focus();
else passEl.focus();
})();
document.getElementById('loginForm').addEventListener('submit', async (e) => {
e.preventDefault();
clearError();
const host = hostEl.value.trim();
const username = userEl.value.trim();
const password = passEl.value;
if (!host || !username || !password) {
showError('Bitte alle Felder ausfüllen.');
return;
}
setLoading(true);
const result = await api.proxmox.login({ host, username, password });
if (!result.success) {
setLoading(false);
showError(result.error || 'Anmeldung fehlgeschlagen.');
return;
}
if (saveEl.checked) {
await api.credentials.save({ host, username, password });
} else {
await api.credentials.clear();
}
// Main process will switch window to vms.html
});
function setLoading(on) {
btnEl.disabled = on;
btnEl.textContent = on ? 'Anmelden…' : 'Anmelden';
}
function showError(msg) {
errEl.textContent = msg;
errEl.classList.remove('hidden');
}
function clearError() {
errEl.classList.add('hidden');
}
+294
View File
@@ -0,0 +1,294 @@
*, *::before, *::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
:root {
--bg-deep: #0f1117;
--bg-card: #16213e;
--bg-input: #0d2040;
--accent: #e94560;
--accent-hov: #c73652;
--border: #1e3a5f;
--text: #dde4f0;
--muted: #7a8aaa;
--green: #4caf6e;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: var(--bg-deep);
color: var(--text);
height: 100vh;
display: flex;
align-items: center;
justify-content: center;
-webkit-font-smoothing: antialiased;
user-select: none;
}
/* ── Login page ──────────────────────────────────────────── */
body.login-page {
align-items: center;
}
.login-card {
width: 380px;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 14px;
padding: 2.2rem 2rem;
box-shadow: 0 24px 60px rgba(0,0,0,0.55);
}
.brand {
text-align: center;
margin-bottom: 2rem;
}
.brand h1 {
font-size: 1.65rem;
font-weight: 700;
color: var(--accent);
letter-spacing: -0.02em;
}
.brand .tagline {
font-size: 0.78rem;
color: var(--muted);
margin-top: 0.2rem;
text-transform: uppercase;
letter-spacing: 0.1em;
}
/* ── Form elements ───────────────────────────────────────── */
.field {
margin-bottom: 1.1rem;
}
.field label {
display: block;
font-size: 0.72rem;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.08em;
margin-bottom: 0.4rem;
}
input[type="text"],
input[type="password"] {
width: 100%;
padding: 0.6rem 0.85rem;
background: var(--bg-input);
border: 1px solid var(--border);
border-radius: 7px;
color: var(--text);
font-size: 0.92rem;
outline: none;
transition: border-color 0.18s;
}
input[type="text"]:focus,
input[type="password"]:focus {
border-color: var(--accent);
}
.checkbox-row {
display: flex;
align-items: center;
gap: 0.5rem;
margin-bottom: 1.4rem;
}
.checkbox-row label {
font-size: 0.82rem;
color: var(--muted);
cursor: pointer;
text-transform: none;
letter-spacing: 0;
}
input[type="checkbox"] {
accent-color: var(--accent);
cursor: pointer;
width: 15px;
height: 15px;
}
/* ── Buttons ─────────────────────────────────────────────── */
.btn-primary {
width: 100%;
padding: 0.72rem;
background: var(--accent);
color: #fff;
border: none;
border-radius: 7px;
font-size: 0.95rem;
font-weight: 600;
cursor: pointer;
transition: background 0.18s;
}
.btn-primary:hover:not(:disabled) { background: var(--accent-hov); }
.btn-primary:disabled { background: #3a3a4a; color: #666; cursor: not-allowed; }
.btn-secondary {
padding: 0.42rem 0.9rem;
background: transparent;
color: var(--muted);
border: 1px solid #2a3a55;
border-radius: 7px;
font-size: 0.8rem;
cursor: pointer;
transition: all 0.18s;
}
.btn-secondary:hover { border-color: var(--accent); color: var(--accent); }
.btn-connect {
padding: 0.44rem 1.1rem;
background: var(--accent);
color: #fff;
border: none;
border-radius: 7px;
font-size: 0.82rem;
font-weight: 600;
cursor: pointer;
transition: background 0.18s;
white-space: nowrap;
flex-shrink: 0;
}
.btn-connect:hover:not(:disabled) { background: var(--accent-hov); }
.btn-connect:disabled { background: #3a3a4a; color: #666; cursor: not-allowed; }
/* ── Error / notice ──────────────────────────────────────── */
.error {
margin-top: 1rem;
padding: 0.65rem 0.85rem;
background: rgba(233,69,96,0.12);
border: 1px solid rgba(233,69,96,0.35);
border-radius: 7px;
color: #f07090;
font-size: 0.82rem;
line-height: 1.45;
}
.notice {
margin-top: 1rem;
padding: 0.65rem 0.85rem;
background: rgba(76,175,110,0.1);
border: 1px solid rgba(76,175,110,0.3);
border-radius: 7px;
color: #80d09a;
font-size: 0.82rem;
}
.hidden { display: none !important; }
/* ── VMs page ────────────────────────────────────────────── */
body.vms-page {
align-items: flex-start;
padding: 2rem 2.5rem;
}
.vms-wrapper {
width: 100%;
max-width: 660px;
margin: 0 auto;
}
.page-header {
display: flex;
align-items: center;
justify-content: space-between;
margin-bottom: 1.4rem;
padding-bottom: 1rem;
border-bottom: 1px solid var(--border);
}
.page-header h2 {
font-size: 1.1rem;
font-weight: 600;
color: var(--text);
}
.header-actions {
display: flex;
gap: 0.5rem;
align-items: center;
}
/* ── VM cards ─────────────────────────────────────────────── */
.vm-list {
display: flex;
flex-direction: column;
gap: 0.6rem;
}
.vm-card {
display: flex;
align-items: center;
justify-content: space-between;
gap: 1rem;
padding: 1rem 1.2rem;
background: var(--bg-card);
border: 1px solid var(--border);
border-radius: 9px;
transition: border-color 0.18s;
}
.vm-card:hover { border-color: #2e5a8a; }
.vm-info { flex: 1; min-width: 0; }
.vm-name {
font-size: 0.97rem;
font-weight: 600;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-bottom: 0.22rem;
}
.vm-meta {
font-size: 0.75rem;
color: var(--muted);
}
.status-dot {
display: inline-block;
width: 7px;
height: 7px;
border-radius: 50%;
background: var(--green);
margin-right: 0.35rem;
vertical-align: middle;
}
/* ── States ───────────────────────────────────────────────── */
.loading-state,
.empty-state {
text-align: center;
padding: 3rem 0;
color: var(--muted);
}
.spinner {
width: 34px;
height: 34px;
border: 3px solid #1e2d40;
border-top-color: var(--accent);
border-radius: 50%;
animation: spin 0.75s linear infinite;
margin: 0 auto 1rem;
}
@keyframes spin { to { transform: rotate(360deg); } }
.empty-state .hint {
font-size: 0.78rem;
margin-top: 0.5rem;
color: #3a4a60;
}
+47
View File
@@ -0,0 +1,47 @@
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-Policy"
content="default-src 'self'; script-src 'self'; style-src 'self'">
<title>Proxmox SPICE Client — VMs</title>
<link rel="stylesheet" href="styles.css">
</head>
<body class="vms-page">
<div class="vms-wrapper">
<div class="page-header">
<h2>Virtuelle Maschinen</h2>
<div class="header-actions">
<button id="refreshBtn" class="btn-secondary" title="Liste aktualisieren">↻ Aktualisieren</button>
<button id="logoutBtn" class="btn-secondary">Abmelden</button>
</div>
</div>
<!-- Loading -->
<div id="loadingState" class="loading-state">
<div class="spinner"></div>
<p>VMs werden geladen…</p>
</div>
<!-- VM cards -->
<div id="vmList" class="vm-list hidden"></div>
<!-- No VMs found -->
<div id="emptyState" class="empty-state hidden">
<p>Keine SPICE-fähigen VMs gefunden.</p>
<p class="hint">Nur laufende VMs mit QXL- oder Virtio-VGA-GL-Display werden angezeigt.</p>
</div>
<!-- Error -->
<div id="error" class="error hidden"></div>
<!-- Connected notice -->
<div id="notice" class="notice hidden"></div>
</div>
<script src="vms.js"></script>
</body>
</html>
+134
View File
@@ -0,0 +1,134 @@
/* global api */
const loadingEl = document.getElementById('loadingState');
const listEl = document.getElementById('vmList');
const emptyEl = document.getElementById('emptyState');
const errorEl = document.getElementById('error');
const noticeEl = document.getElementById('notice');
const refreshBtn = document.getElementById('refreshBtn');
document.getElementById('logoutBtn').addEventListener('click', async () => {
await api.proxmox.logout();
});
refreshBtn.addEventListener('click', () => loadVMs());
// ── Load on mount ─────────────────────────────────────────
async function loadVMs() {
clearMessages();
listEl.classList.add('hidden');
emptyEl.classList.add('hidden');
loadingEl.classList.remove('hidden');
const result = await api.proxmox.getVMs();
loadingEl.classList.add('hidden');
if (!result.success) {
showError(result.error || 'Fehler beim Laden der VMs.');
return;
}
const vms = result.vms;
if (vms.length === 0) {
emptyEl.classList.remove('hidden');
return;
}
// Auto-connect when there is exactly one SPICE VM
if (vms.length === 1) {
showNotice(`Nur eine VM verfügbar — verbinde mit „${vms[0].name}" …`);
await connectVM(vms[0]);
return;
}
renderList(vms);
}
loadVMs();
// ── Render ────────────────────────────────────────────────
function renderList(vms) {
listEl.innerHTML = vms
.map(
(vm) => `
<div class="vm-card" data-vmid="${vm.vmid}">
<div class="vm-info">
<div class="vm-name">${esc(vm.name)}</div>
<div class="vm-meta">
<span class="status-dot"></span>
Läuft &nbsp;·&nbsp; Node: ${esc(vm.node)} &nbsp;·&nbsp; ID: ${vm.vmid}
</div>
</div>
<button
class="btn-connect"
data-vmid="${vm.vmid}"
data-node="${esc(vm.node)}"
data-name="${esc(vm.name)}"
>Verbinden</button>
</div>
`
)
.join('');
listEl.querySelectorAll('.btn-connect').forEach((btn) => {
btn.addEventListener('click', () =>
connectVM({ vmid: btn.dataset.vmid, node: btn.dataset.node, name: btn.dataset.name })
);
});
listEl.classList.remove('hidden');
}
// ── Connect ───────────────────────────────────────────────
async function connectVM(vm) {
clearMessages();
setAllButtons(true, 'Verbinde…');
const result = await api.proxmox.connect(vm);
setAllButtons(false, 'Verbinden');
if (!result.success) {
showError(result.error || 'Verbindung fehlgeschlagen.');
} else {
showNotice(`${vm.name}" — SPICE-Sitzung gestartet.`);
}
}
// ── Helpers ───────────────────────────────────────────────
function setAllButtons(disabled, label) {
listEl.querySelectorAll('.btn-connect').forEach((b) => {
b.disabled = disabled;
b.textContent = label;
});
}
function showError(msg) {
errorEl.textContent = msg;
errorEl.classList.remove('hidden');
}
function showNotice(msg) {
noticeEl.textContent = msg;
noticeEl.classList.remove('hidden');
setTimeout(() => noticeEl.classList.add('hidden'), 5000);
}
function clearMessages() {
errorEl.classList.add('hidden');
noticeEl.classList.add('hidden');
}
function esc(str) {
return String(str)
.replace(/&/g, '&amp;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;')
.replace(/"/g, '&quot;');
}