update readme and build

This commit is contained in:
2026-05-24 07:18:54 +00:00
parent 45e18b5423
commit 5b4803bc49
9 changed files with 447 additions and 38 deletions
+38
View File
@@ -11,6 +11,44 @@ import (
"time"
)
// ── CSRF ──────────────────────────────────────────────────────────────
func newCSRFToken() string {
b := make([]byte, 24)
rand.Read(b) //nolint:errcheck
return hex.EncodeToString(b)
}
// setCSRFCookie writes a fresh CSRF token to a short-lived cookie and returns
// the token value so it can be embedded in the rendered HTML form.
func setCSRFCookie(w http.ResponseWriter) string {
tok := newCSRFToken()
http.SetCookie(w, &http.Cookie{
Name: csrfCookieName,
Value: tok,
Path: "/",
HttpOnly: true,
Secure: true,
SameSite: http.SameSiteStrictMode,
MaxAge: 900, // 15 min — covers slow typists
})
return tok
}
// checkCSRF returns true iff the submitted csrf_token form field matches the
// cookie value (constant-time compare to prevent timing side-channels).
func checkCSRF(r *http.Request) bool {
c, err := r.Cookie(csrfCookieName)
if err != nil || c.Value == "" {
return false
}
formTok := r.FormValue("csrf_token")
if formTok == "" {
return false
}
return hmac.Equal([]byte(c.Value), []byte(formTok))
}
func checkCreds(username, password string) bool {
if username != appCreds.Username {
return false
+1
View File
@@ -14,6 +14,7 @@ const (
maxUploadSize = 512 << 20
sessionTTL = 24 * time.Hour
authCookieName = "gws_auth"
csrfCookieName = "gws_csrf"
authTokenTTL = 12 * time.Hour
credsFilename = "gws-creds.json"
defaultUser = "ivor"
+79 -9
View File
@@ -18,6 +18,9 @@ import (
//go:embed web/shell.html
var shellPageHTML string
//go:embed web/login.html
var loginPageHTML string
//go:embed web/favicon.svg
var faviconSVG string
@@ -57,24 +60,68 @@ func handleStaticJS(w http.ResponseWriter, r *http.Request) {
w.Write(data)
}
// handleIndex: always creates a fresh workspace and redirects to its stable URL.
// PTY sessions are started lazily by the frontend via WebSocket connections.
// handleLogin serves the standalone login page (GET) or redirects authed users.
func handleLogin(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/login" {
http.NotFound(w, r)
return
}
if isAuthed(r) {
http.Redirect(w, r, "/", http.StatusFound)
return
}
next := r.URL.Query().Get("next")
if !isValidNext(next) {
next = "/"
}
tok := setCSRFCookie(w)
html := strings.NewReplacer(
"[[CSRF_TOKEN]]", tok,
"[[NEXT]]", next,
).Replace(loginPageHTML)
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
w.Write([]byte(html)) //nolint:errcheck
}
// isValidNext rejects open-redirect targets; only "/" and "/s/<hex>" allowed.
func isValidNext(next string) bool {
if next == "" || next == "/" {
return true
}
if strings.HasPrefix(next, "/s/") {
return validID(strings.TrimPrefix(next, "/s/"))
}
return false
}
// handleIndex: creates a fresh workspace and redirects to its stable URL.
// Unauthenticated requests are sent to the login page first.
func handleIndex(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
if !isAuthed(r) {
http.Redirect(w, r, "/login", http.StatusFound)
return
}
http.Redirect(w, r, "/s/"+randHex(16), http.StatusFound)
}
// handleShell: serves the terminal page for an existing (or new) workspace ID.
// handleShell: serves the terminal page for a workspace ID.
// Unauthenticated requests are redirected to /login?next=...
func handleShell(w http.ResponseWriter, r *http.Request) {
id := strings.TrimPrefix(r.URL.Path, "/s/")
if !validID(id) {
http.NotFound(w, r)
return
}
serveTerminalPage(w, id, isAuthed(r))
if !isAuthed(r) {
http.Redirect(w, r, "/login?next=/s/"+id, http.StatusFound)
return
}
serveTerminalPage(w, id, true)
}
func serveTerminalPage(w http.ResponseWriter, workspaceID string, authed bool) {
@@ -94,15 +141,36 @@ func handleAuth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
if r.Method != http.MethodPost {
w.WriteHeader(http.StatusMethodNotAllowed)
w.Write([]byte(`{"error":"POST only"}`))
w.Write([]byte(`{"error":"POST only"}`)) //nolint:errcheck
return
}
if err := r.ParseForm(); err != nil {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"bad form"}`))
w.Write([]byte(`{"error":"bad form"}`)) //nolint:errcheck
return
}
if checkCreds(strings.TrimSpace(r.FormValue("username")), r.FormValue("password")) {
// CSRF validation (skipped in -nopw mode which never shows the login page)
if !nopwMode && !checkCSRF(r) {
logAuthAttempt(r, "", false, "csrf_invalid")
w.WriteHeader(http.StatusForbidden)
w.Write([]byte(`{"error":"invalid request"}`)) //nolint:errcheck
return
}
username := strings.TrimSpace(r.FormValue("username"))
password := r.FormValue("password")
// Input bounds — reject obviously bad values before touching the hasher
if len(username) == 0 || len(username) > 64 || len(password) == 0 || len(password) > 1024 {
time.Sleep(500 * time.Millisecond)
logAuthAttempt(r, username, false, "invalid_input")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"error":"invalid input"}`)) //nolint:errcheck
return
}
if checkCreds(username, password) {
http.SetCookie(w, &http.Cookie{
Name: authCookieName,
Value: makeAuthToken(),
@@ -112,11 +180,13 @@ func handleAuth(w http.ResponseWriter, r *http.Request) {
SameSite: http.SameSiteLaxMode,
MaxAge: int(authTokenTTL.Seconds()),
})
w.Write([]byte(`{"ok":true}`))
logAuthAttempt(r, username, true, "login_success")
w.Write([]byte(`{"ok":true}`)) //nolint:errcheck
} else {
time.Sleep(500 * time.Millisecond) // blunt brute-force deterrent
logAuthAttempt(r, username, false, "invalid_credentials")
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte(`{"error":"Invalid username or password"}`))
w.Write([]byte(`{"error":"Invalid username or password"}`)) //nolint:errcheck
}
}
+106
View File
@@ -0,0 +1,106 @@
package internals
import (
"encoding/json"
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"strings"
"time"
)
// authFileLog writes structured JSON-lines to a file; nil = file logging off.
// Console logging always fires regardless of this setting.
var authFileLog *log.Logger
// authLogEntry is the structured format for each auth event.
// One JSON object per line — compatible with CrowdSec, fail2ban, jq.
type authLogEntry struct {
Time string `json:"time"` // RFC3339 UTC
RemoteIP string `json:"remote_ip"` // real client IP (proxy-aware)
Username string `json:"username"`
Success bool `json:"success"`
Message string `json:"message"` // login_success | invalid_credentials | csrf_invalid | invalid_input
}
// initAuthLogger opens (or creates) the log file.
// path "off" disables file logging; console output is always on.
func initAuthLogger(path string) {
if strings.EqualFold(path, "off") {
fmt.Println("auth log: disabled (console only)")
return
}
dir := filepath.Dir(path)
if dir != "" && dir != "." {
if err := os.MkdirAll(dir, 0750); err != nil {
fmt.Fprintf(os.Stderr, "auth log: cannot create dir %q: %v\n", dir, err)
return
}
}
f, err := os.OpenFile(path, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640)
if err != nil {
fmt.Fprintf(os.Stderr, "auth log: cannot open %q: %v\n", path, err)
return
}
// log.New with empty flags → raw lines, no timestamp prefix (timestamp is in JSON)
authFileLog = log.New(f, "", 0)
fmt.Printf("auth log: %s\n", path)
}
// logAuthAttempt records one auth event.
// Always prints to stdout; also writes to file if enabled.
func logAuthAttempt(r *http.Request, username string, success bool, message string) {
entry := authLogEntry{
Time: time.Now().UTC().Format(time.RFC3339),
RemoteIP: realIP(r),
Username: username,
Success: success,
Message: message,
}
b, _ := json.Marshal(entry)
line := string(b)
// Console — always visible
fmt.Println(line)
// File — if enabled
if authFileLog != nil {
authFileLog.Println(line) // log.Logger serialises concurrent writes
}
}
// realIP returns the originating client IP, respecting common reverse-proxy
// headers in priority order: Cloudflare → X-Forwarded-For → X-Real-IP → RemoteAddr.
func realIP(r *http.Request) string {
// Cloudflare sets CF-Connecting-IP to the unmodified client IP.
if ip := r.Header.Get("CF-Connecting-IP"); ip != "" && net.ParseIP(ip) != nil {
return ip
}
// X-Forwarded-For may be a comma-separated list; the leftmost entry is the
// originating client (rightmost entries are added by each successive proxy).
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
if idx := strings.IndexByte(xff, ','); idx != -1 {
xff = xff[:idx]
}
xff = strings.TrimSpace(xff)
if net.ParseIP(xff) != nil {
return xff
}
}
// Nginx / Traefik single-value header.
if ip := r.Header.Get("X-Real-IP"); ip != "" && net.ParseIP(ip) != nil {
return ip
}
// Direct connection.
host, _, err := net.SplitHostPort(r.RemoteAddr)
if err != nil {
return r.RemoteAddr
}
return host
}
+9
View File
@@ -20,6 +20,7 @@ func Run() {
certFlag := flag.String("cert", "", "set custom TLS certificate PEM file (stored encrypted)")
cetkeyFlag := flag.String("certkey", "", "set custom TLS private key PEM file")
certreset := flag.Bool("certreset", false, "remove stored custom certificate, revert to self-signed")
logFlag := flag.String("log", "", "auth log file path; 'off' disables file logging (default: gotermix.log next to binary)")
flag.Parse()
initialCwd, _ = os.Getwd()
@@ -100,6 +101,13 @@ func Run() {
fmt.Printf("auth: enabled user=%q creds=%s\n", appCreds.Username, credsPath)
}
// Auth logging — default path is gotermix.log next to the binary.
logPath := *logFlag
if logPath == "" {
logPath = filepath.Join(filepath.Dir(exe), "gotermix.log")
}
initAuthLogger(logPath)
// Reap idle sessions.
go func() {
t := time.NewTicker(10 * time.Minute)
@@ -137,6 +145,7 @@ func Run() {
mux := http.NewServeMux()
mux.HandleFunc("/", handleIndex)
mux.HandleFunc("/login", handleLogin)
mux.HandleFunc("/s/", handleShell)
mux.HandleFunc("/ws/", handleWS)
mux.HandleFunc("/auth", handleAuth)
+95
View File
@@ -0,0 +1,95 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GoTermix — Sign in</title>
<link rel="icon" type="image/svg+xml" href="/favicon.svg">
<link rel="stylesheet" href="/static/app.css" />
<style>
/* login page overrides — no tab bar or toolbar offsets */
body { display: flex; align-items: center; justify-content: center; min-height: 100vh; }
</style>
</head>
<body>
<div class="m-card" style="max-width:360px;width:100%;margin:16px;">
<div class="auth-card">
<div class="auth-logo"><em>&gt;_</em> GoTermix</div>
<div class="auth-sub">Authentication required</div>
<label class="m-label" for="fUser">Username</label>
<input class="m-input" type="text" id="fUser"
autofocus autocomplete="username"
placeholder="username" spellcheck="false"
maxlength="64">
<label class="m-label" for="fPass">Password</label>
<input class="m-input" type="password" id="fPass"
autocomplete="current-password"
placeholder="password"
maxlength="1024">
<div class="auth-err" id="authErr"></div>
<button class="auth-btn" id="authBtn" onclick="doLogin()">
<div class="auth-spin"></div>
<span class="btn-text">Sign in</span>
</button>
</div>
</div>
<script>
const CSRF_TOKEN = "[[CSRF_TOKEN]]";
const NEXT = "[[NEXT]]";
document.getElementById('fUser').addEventListener('keydown', e => {
if (e.key === 'Enter') document.getElementById('fPass').focus();
});
document.getElementById('fPass').addEventListener('keydown', e => {
if (e.key === 'Enter') doLogin();
});
async function doLogin() {
const username = document.getElementById('fUser').value.trim();
const password = document.getElementById('fPass').value;
const btn = document.getElementById('authBtn');
if (!username || !password) { showErr('Enter username and password'); return; }
btn.disabled = true; btn.classList.add('busy');
document.getElementById('authErr').classList.remove('show');
const form = new URLSearchParams();
form.append('username', username);
form.append('password', password);
form.append('csrf_token', CSRF_TOKEN);
try {
const res = await fetch('/auth', {
method: 'POST',
body: form,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
const data = await res.json();
if (data.ok) {
window.location.href = NEXT || '/';
} else {
showErr(data.error || 'Authentication failed');
}
} catch (_) {
showErr('Network error — try again');
} finally {
btn.disabled = false; btn.classList.remove('busy');
}
}
function showErr(msg) {
const e = document.getElementById('authErr');
e.textContent = msg; e.classList.add('show');
document.getElementById('fPass').value = '';
document.getElementById('fPass').focus();
}
</script>
</body>
</html>