Merge branch 'auth' into dev

This commit is contained in:
2026-06-11 21:45:39 -05:00
4 changed files with 124 additions and 10 deletions

View File

@@ -19,6 +19,7 @@ type AppConfig struct {
Daemon struct {
ListenAddress string `json:"listen_address"`
Port int `json:"port"`
AuthToken string `json:"auth_token"`
} `json:"daemon"`
Instances map[string]InstanceMetadata `json:"instances"`

View File

@@ -1,20 +1,26 @@
package main
import (
"embed"
"encoding/json"
"fmt"
"io"
"io/fs"
"net/http"
"os"
"os/signal"
"path/filepath"
"slices"
"strconv"
"strings"
"sync"
"syscall"
"time"
)
//go:embed web/dist
var webFS embed.FS
type CommandPayload struct {
Command string `json:"command"`
}
@@ -52,16 +58,45 @@ func StartDaemon(cfg *AppConfig, configPath string) error {
mux.HandleFunc("/instances/getConfig", ds.handleGetConfig)
mux.HandleFunc("/instances/setConfig", ds.handleSetConfig)
webContent, err := fs.Sub(webFS, "web/dist")
if err != nil {
return fmt.Errorf("failed to load embedded web assets: %w", err)
}
mux.Handle("/", http.FileServer(http.FS(webContent)))
corsWrappedHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusOK)
return
}
authCheck := func() bool {
if !strings.HasPrefix(r.URL.Path, "/instances/") {
return true
}
ds.RLock()
defer ds.RUnlock()
if ds.cfg.Daemon.AuthToken != "" {
authHeader := r.Header.Get("Authorization")
expected := "Bearer " + ds.cfg.Daemon.AuthToken
if authHeader != expected {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return false
}
}
return true
}()
if !authCheck {
return
}
mux.ServeHTTP(w, r)
})

94
main.go
View File

@@ -2,6 +2,8 @@ package main
import (
"bytes"
"crypto/rand"
"encoding/hex"
"encoding/json"
"flag"
"fmt"
@@ -13,6 +15,7 @@ import (
"path/filepath"
"strconv"
"text/tabwriter"
"time"
)
func main() {
@@ -71,11 +74,42 @@ func main() {
switch subCommand {
case "daemon":
if isDaemonRunning(cfg) {
log.Fatalf("Cannot start daemon as it is already running. Stop it first (`pkill vssm`).")
}
fmt.Printf("Initializing VSSM Daemon [Config: %s]...\n", absConfigPath)
if err := StartDaemon(cfg, absConfigPath); err != nil {
log.Fatalf("Daemon runtime fatal error: %v", err)
}
case "generate-token":
if isDaemonRunning(cfg) {
log.Fatalf("Cannot generate a new token while the daemon is running. Stop it first (`pkill vssm`).")
}
token, err := generateToken()
if err != nil {
log.Fatalf("Failed to generate token: %v", err)
}
overwritten := cfg.Daemon.AuthToken != ""
cfg.Daemon.AuthToken = token
data, err := json.MarshalIndent(cfg, "", " ")
if err != nil {
log.Fatalf("Failed to marshal config: %v", err)
}
if err := os.WriteFile(absConfigPath, data, 0644); err != nil {
log.Fatalf("Failed to write config: %v", err)
}
if overwritten {
fmt.Println("Existing auth token was overwritten.")
}
fmt.Printf("New auth token: %s\n", token)
case "create":
if len(args) < 4 {
log.Fatalf("Usage: vssm create <instance_name> <version> <port>")
@@ -156,6 +190,10 @@ func sendIPCRequest(cfg *AppConfig, method string, path string, body io.Reader)
req.Header.Set("Content-Type", "application/json")
}
if cfg.Daemon.AuthToken != "" {
req.Header.Set("Authorization", "Bearer "+cfg.Daemon.AuthToken)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("IPC connection failed. Is the VSSM daemon running? Error: %v", err)
@@ -174,7 +212,17 @@ func sendIPCRequest(cfg *AppConfig, method string, path string, body io.Reader)
func fetchAndPrintStatus(cfg *AppConfig) {
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
targetUrl := fmt.Sprintf("http://%s/instances/list", listenAddress)
resp, err := http.Get(targetUrl)
req, err := http.NewRequest("GET", targetUrl, nil)
if err != nil {
log.Fatalf("Failed to construct status request: %v", err)
}
if cfg.Daemon.AuthToken != "" {
req.Header.Set("Authorization", "Bearer "+cfg.Daemon.AuthToken)
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatalf("IPC connection failed. Is the VSSM daemon running? Error: %v", err)
}
@@ -205,16 +253,44 @@ func fetchAndPrintStatus(cfg *AppConfig) {
w.Flush()
}
func generateToken() (string, error) {
bytes := make([]byte, 32)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
func isDaemonRunning(cfg *AppConfig) bool {
listenAddress := cfg.Daemon.ListenAddress + ":" + strconv.Itoa(cfg.Daemon.Port)
client := http.Client{Timeout: 500 * time.Millisecond}
resp, err := client.Get(fmt.Sprintf("http://%s/instances/list", listenAddress))
if err != nil {
return false
}
resp.Body.Close()
return true
}
func printUsage() {
fmt.Println("VintageStory Server Manager")
fmt.Println("\nGlobal Options:")
fmt.Println(" --config <path> Explicitly target a non-default config structure file location")
w := tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
fmt.Fprintln(w, " --config <path>\tExplicitly target a non-default config structure file location")
w.Flush()
fmt.Println("\nUsage Commands:")
fmt.Println(" vssm daemon Starts the daemon")
fmt.Println(" vssm create <name> <version> Creates the instance configuration and profile")
fmt.Println(" vssm delete <name> <options> Deletes an instance profile, optionally deletes all files with the `--purge` flag")
fmt.Println(" vssm start <name> Launches an existing server instance from a stored profile")
fmt.Println(" vssm stop <name> Gracefully shuts down a server instance")
fmt.Println(" vssm cmd <name> \"<command>\" Sends a command to an instance")
fmt.Println(" vssm list Displays a list of all instances and their status")
w = tabwriter.NewWriter(os.Stdout, 0, 0, 3, ' ', 0)
fmt.Fprintln(w, " vssm daemon\tStarts the daemon")
fmt.Fprintln(w, " vssm generate-token\tGenerates a new auth token and stores it in the config")
fmt.Fprintln(w, " vssm create <name> <version> <port>\tCreates the instance configuration and profile")
fmt.Fprintln(w, " vssm delete <name> [--purge]\tDeletes an instance profile, optionally deleting all files")
fmt.Fprintln(w, " vssm start <name>\tLaunches an existing server instance from a stored profile")
fmt.Fprintln(w, " vssm stop <name>\tGracefully shuts down a server instance")
fmt.Fprintln(w, " vssm cmd <name> \"<command>\"\tSends a command to an instance")
fmt.Fprintln(w, " vssm modify <name> <new_name> <new_port>\tRenames an instance and/or changes its port")
fmt.Fprintln(w, " vssm list\tDisplays a list of all instances and their status")
w.Flush()
}

2
web/dist/index.html vendored Normal file
View File

@@ -0,0 +1,2 @@
<!DOCTYPE html>
<html><body>Web UI not embedded in this build.</body></html>