feat: add xterm.js web terminal frontend
WebSocket-to-SSH proxy on :8080. Browser connects via xterm.js, server bridges to localhost:2222 SSH. Single HTML file, CDN deps. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
161
web/server.go
Normal file
161
web/server.go
Normal file
@@ -0,0 +1,161 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"net/http"
|
||||
"sync"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"golang.org/x/crypto/ssh"
|
||||
)
|
||||
|
||||
//go:embed static
|
||||
var staticFiles embed.FS
|
||||
|
||||
var upgrader = websocket.Upgrader{
|
||||
CheckOrigin: func(r *http.Request) bool { return true },
|
||||
}
|
||||
|
||||
type resizeMsg struct {
|
||||
Type string `json:"type"`
|
||||
Cols int `json:"cols"`
|
||||
Rows int `json:"rows"`
|
||||
}
|
||||
|
||||
// Start launches the HTTP server for the web terminal.
|
||||
func Start(addr string, sshPort int) error {
|
||||
mux := http.NewServeMux()
|
||||
|
||||
// Serve static files from embedded FS
|
||||
mux.Handle("/", http.FileServer(http.FS(staticFiles)))
|
||||
|
||||
// WebSocket endpoint
|
||||
mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
|
||||
handleWS(w, r, sshPort)
|
||||
})
|
||||
|
||||
log.Printf("Starting web terminal on %s", addr)
|
||||
return http.ListenAndServe(addr, mux)
|
||||
}
|
||||
|
||||
func handleWS(w http.ResponseWriter, r *http.Request, sshPort int) {
|
||||
ws, err := upgrader.Upgrade(w, r, nil)
|
||||
if err != nil {
|
||||
log.Printf("WebSocket upgrade error: %v", err)
|
||||
return
|
||||
}
|
||||
defer ws.Close()
|
||||
|
||||
// Connect to local SSH server
|
||||
sshConfig := &ssh.ClientConfig{
|
||||
User: "web-player",
|
||||
Auth: []ssh.AuthMethod{
|
||||
ssh.Password(""),
|
||||
},
|
||||
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
|
||||
}
|
||||
|
||||
sshAddr := fmt.Sprintf("localhost:%d", sshPort)
|
||||
client, err := ssh.Dial("tcp", sshAddr, sshConfig)
|
||||
if err != nil {
|
||||
log.Printf("SSH dial error: %v", err)
|
||||
ws.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("Failed to connect to game server: %v\r\n", err)))
|
||||
return
|
||||
}
|
||||
defer client.Close()
|
||||
|
||||
session, err := client.NewSession()
|
||||
if err != nil {
|
||||
log.Printf("SSH session error: %v", err)
|
||||
return
|
||||
}
|
||||
defer session.Close()
|
||||
|
||||
// Request PTY
|
||||
if err := session.RequestPty("xterm-256color", 24, 80, ssh.TerminalModes{
|
||||
ssh.ECHO: 1,
|
||||
ssh.TTY_OP_ISPEED: 14400,
|
||||
ssh.TTY_OP_OSPEED: 14400,
|
||||
}); err != nil {
|
||||
log.Printf("PTY request error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
stdin, err := session.StdinPipe()
|
||||
if err != nil {
|
||||
log.Printf("stdin pipe error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
stdout, err := session.StdoutPipe()
|
||||
if err != nil {
|
||||
log.Printf("stdout pipe error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
if err := session.Shell(); err != nil {
|
||||
log.Printf("shell error: %v", err)
|
||||
return
|
||||
}
|
||||
|
||||
var once sync.Once
|
||||
done := make(chan struct{})
|
||||
cleanup := func() {
|
||||
once.Do(func() {
|
||||
close(done)
|
||||
})
|
||||
}
|
||||
|
||||
// SSH stdout → WebSocket
|
||||
go func() {
|
||||
defer cleanup()
|
||||
buf := make([]byte, 4096)
|
||||
for {
|
||||
n, err := stdout.Read(buf)
|
||||
if n > 0 {
|
||||
if writeErr := ws.WriteMessage(websocket.TextMessage, buf[:n]); writeErr != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// WebSocket → SSH stdin (text frames) or resize (binary frames)
|
||||
go func() {
|
||||
defer cleanup()
|
||||
for {
|
||||
msgType, data, err := ws.ReadMessage()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
switch msgType {
|
||||
case websocket.TextMessage:
|
||||
if _, err := stdin.Write(data); err != nil {
|
||||
return
|
||||
}
|
||||
case websocket.BinaryMessage:
|
||||
var msg resizeMsg
|
||||
if json.Unmarshal(data, &msg) == nil && msg.Type == "resize" {
|
||||
session.WindowChange(msg.Rows, msg.Cols)
|
||||
}
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
// Wait for either side to close
|
||||
select {
|
||||
case <-done:
|
||||
}
|
||||
|
||||
// Ensure SSH session ends
|
||||
_ = session.Close()
|
||||
_ = client.Close()
|
||||
_ = io.WriteCloser(stdin).Close()
|
||||
}
|
||||
120
web/static/index.html
Normal file
120
web/static/index.html
Normal file
@@ -0,0 +1,120 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>Catacombs</title>
|
||||
<link rel="stylesheet" href="https://unpkg.com/@xterm/xterm@5.5.0/css/xterm.css">
|
||||
<style>
|
||||
* { margin: 0; padding: 0; box-sizing: border-box; }
|
||||
html, body { height: 100%; overflow: hidden; background: #1a1a2e; }
|
||||
#terminal { height: 100%; width: 100%; }
|
||||
#overlay {
|
||||
display: none;
|
||||
position: fixed; top: 0; left: 0; right: 0; bottom: 0;
|
||||
background: rgba(26, 26, 46, 0.9);
|
||||
justify-content: center; align-items: center;
|
||||
z-index: 10;
|
||||
}
|
||||
#overlay.visible { display: flex; }
|
||||
#overlay-text {
|
||||
color: #e0e0e0; font-family: monospace; font-size: 18px;
|
||||
text-align: center; line-height: 2;
|
||||
}
|
||||
#overlay-text span { color: #51d0ff; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="terminal"></div>
|
||||
<div id="overlay">
|
||||
<div id="overlay-text">
|
||||
Connection lost.<br>
|
||||
<span>Press any key to reconnect.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="https://unpkg.com/@xterm/xterm@5.5.0/lib/xterm.js"></script>
|
||||
<script src="https://unpkg.com/@xterm/addon-fit@0.10.0/lib/addon-fit.js"></script>
|
||||
<script>
|
||||
const termEl = document.getElementById('terminal');
|
||||
const overlay = document.getElementById('overlay');
|
||||
|
||||
const term = new Terminal({
|
||||
cursorBlink: true,
|
||||
fontSize: 16,
|
||||
fontFamily: "'Cascadia Code', 'Fira Code', 'JetBrains Mono', monospace",
|
||||
theme: {
|
||||
background: '#1a1a2e',
|
||||
foreground: '#e0e0e0',
|
||||
cursor: '#51d0ff',
|
||||
selectionBackground: '#44475a',
|
||||
},
|
||||
allowProposedApi: true,
|
||||
});
|
||||
|
||||
const fitAddon = new FitAddon.FitAddon();
|
||||
term.loadAddon(fitAddon);
|
||||
term.open(termEl);
|
||||
fitAddon.fit();
|
||||
|
||||
let ws = null;
|
||||
let connected = false;
|
||||
|
||||
function connect() {
|
||||
const proto = location.protocol === 'https:' ? 'wss:' : 'ws:';
|
||||
ws = new WebSocket(`${proto}//${location.host}/ws`);
|
||||
|
||||
ws.onopen = () => {
|
||||
connected = true;
|
||||
overlay.classList.remove('visible');
|
||||
term.clear();
|
||||
term.focus();
|
||||
sendResize();
|
||||
};
|
||||
|
||||
ws.onmessage = (e) => {
|
||||
term.write(e.data);
|
||||
};
|
||||
|
||||
ws.onclose = () => {
|
||||
connected = false;
|
||||
overlay.classList.add('visible');
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
connected = false;
|
||||
overlay.classList.add('visible');
|
||||
};
|
||||
}
|
||||
|
||||
function sendResize() {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
const msg = JSON.stringify({ type: 'resize', cols: term.cols, rows: term.rows });
|
||||
ws.send(new Blob([msg]));
|
||||
}
|
||||
}
|
||||
|
||||
term.onData((data) => {
|
||||
if (ws && ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(data);
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('resize', () => {
|
||||
fitAddon.fit();
|
||||
sendResize();
|
||||
});
|
||||
|
||||
// Reconnect on any key when disconnected
|
||||
document.addEventListener('keydown', (e) => {
|
||||
if (!connected) {
|
||||
e.preventDefault();
|
||||
connect();
|
||||
}
|
||||
});
|
||||
|
||||
// Initial connection
|
||||
connect();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user