Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(chat-server): bind loopback, require a token, confine file reads and restrict CORS
nirholasf79cbc79a15a
diff --git a/chat/README.md b/chat/README.mdindex 752af8fa9..520eca593 100644--- a/chat/README.md+++ b/chat/README.md@@ -15,6 +15,15 @@ description, click Sync in the UI). The three.ws copy has diverged heavily: platauth, wallets, forge tools, and the inline 3D viewer are all three.ws additions.This directory is covered by [LICENSE](LICENSE) (proprietary, copyright 2026 nirholas).+### Running the tool server safely++The tool server can run shell commands and edit files, so it is locked down by default:+it listens on `127.0.0.1` only (`-port`, default 8081), requires the password on every+request (`-password`; when omitted a random token is generated and printed at startup),+allows browser calls only from `https://three.ws`, `localhost` and `127.0.0.1` (add more+with `-origins https://example.com`), and `/read_file` only serves files inside `-files`.+Enter the password or printed token in Settings, remote server, password.+## What it does- **Models**: a Built-in free lane (server-selected `:free` models via `POST /api/chat/proxy`,diff --git a/chat/server/files.go b/chat/server/files.goindex 977f1cef4..484e4fb22 100644--- a/chat/server/files.go+++ b/chat/server/files.go@@ -5,6 +5,8 @@ import ("net/http""os""path/filepath"++ "github.com/nirholas/server/guard")// FileInfo represents information about a file or directory@@ -79,10 +81,20 @@ func ListDirectory(w http.ResponseWriter, r *http.Request) {}func ReadFile(w http.ResponseWriter, r *http.Request) {- path := r.URL.Query().Get("path")+ root, err := filepath.Abs(*filesPath)+ if err != nil {+ http.Error(w, "Failed to resolve served directory", http.StatusInternalServerError)+ return+ }+ path, err := guard.Confine(root, r.URL.Query().Get("path"))+ if err != nil {+ http.Error(w, "Forbidden: "+err.Error(), http.StatusForbidden)+ return+ }data, err := os.ReadFile(path)if err != nil {http.Error(w, "Failed to read file: "+err.Error(), http.StatusInternalServerError)+ return}w.Header().Set("Content-Type", "text/plain")w.Write(data)diff --git a/chat/server/guard/guard.go b/chat/server/guard/guard.gonew file mode 100644index 000000000..8159880c9--- /dev/null+++ b/chat/server/guard/guard.go@@ -0,0 +1,91 @@+// Package guard holds the access controls for the local tool server: loopback+// binding, fail-closed password auth, CORS origin matching, and path+// confinement. It depends only on the standard library.+package guard++import (+ "crypto/rand"+ "crypto/subtle"+ "encoding/hex"+ "fmt"+ "net/http"+ "net/url"+ "path/filepath"+ "strings"+)++// DefaultOrigins are the web origins allowed to call the server from a browser.+var DefaultOrigins = []string{"https://three.ws", "https://www.three.ws"}++// LoopbackAddr returns the listen address bound to the loopback interface only.+func LoopbackAddr(port int) string { return fmt.Sprintf("127.0.0.1:%d", port) }++// NewToken returns a random 128-bit hex token for use as a generated password.+func NewToken() (string, error) {+ b := make([]byte, 16)+ if _, err := rand.Read(b); err != nil {+ return "", err+ }+ return hex.EncodeToString(b), nil+}++// OriginAllowed reports whether a browser Origin may call the server: an exact+// match in allowed, or any http(s) localhost / 127.0.0.1 origin.+func OriginAllowed(allowed []string, origin string) bool {+ if origin == "" {+ return false+ }+ for _, a := range allowed {+ if origin == a {+ return true+ }+ }+ u, err := url.Parse(origin)+ if err != nil || (u.Scheme != "http" && u.Scheme != "https") {+ return false+ }+ h := u.Hostname()+ return h == "localhost" || h == "127.0.0.1" || h == "::1"+}++// Auth requires "Authorization: Basic <password>" on every request except CORS+// preflight. An empty configured password rejects everything (fail closed).+func Auth(password string) func(http.Handler) http.Handler {+ want := []byte("Basic " + password)+ return func(next http.Handler) http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.Method == http.MethodOptions {+ next.ServeHTTP(w, r)+ return+ }+ got := []byte(r.Header.Get("Authorization"))+ if password == "" || subtle.ConstantTimeCompare(got, want) != 1 {+ w.WriteHeader(http.StatusUnauthorized)+ return+ }+ next.ServeHTTP(w, r)+ })+ }+}++// Confine resolves path (following symlinks) and returns it only if it lies+// inside root.+func Confine(root, path string) (string, error) {+ realRoot, err := filepath.EvalSymlinks(root)+ if err != nil {+ return "", err+ }+ realRoot, err = filepath.Abs(realRoot)+ if err != nil {+ return "", err+ }+ real, err := filepath.EvalSymlinks(path)+ if err != nil {+ return "", err+ }+ rel, err := filepath.Rel(realRoot, real)+ if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(filepath.Separator)) {+ return "", fmt.Errorf("path is outside the served directory")+ }+ return real, nil+}diff --git a/chat/server/guard/guard_test.go b/chat/server/guard/guard_test.gonew file mode 100644index 000000000..06ca747f1--- /dev/null+++ b/chat/server/guard/guard_test.go@@ -0,0 +1,85 @@+package guard++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"+)++func ok() http.Handler {+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(200) })+}++func do(h http.Handler, auth string) int {+ req := httptest.NewRequest("POST", "/tool", nil)+ if auth != "" {+ req.Header.Set("Authorization", auth)+ }+ rec := httptest.NewRecorder()+ h.ServeHTTP(rec, req)+ return rec.Code+}++func TestAuthRejectsWhenNoPasswordConfigured(t *testing.T) {+ if got := do(Auth("")(ok()), ""); got != 401 {+ t.Fatalf("empty password must fail closed, got %d", got)+ }+}++func TestAuthChecksPassword(t *testing.T) {+ h := Auth("s3cret")(ok())+ if do(h, "") != 401 || do(h, "Basic wrong") != 401 {+ t.Fatal("bad credentials accepted")+ }+ if do(h, "Basic s3cret") != 200 {+ t.Fatal("good credentials rejected")+ }+}++func TestAuthLetsPreflightThrough(t *testing.T) {+ req := httptest.NewRequest("OPTIONS", "/tool", nil)+ rec := httptest.NewRecorder()+ Auth("x")(ok()).ServeHTTP(rec, req)+ if rec.Code != 200 {+ t.Fatalf("preflight got %d", rec.Code)+ }+}++func TestConfine(t *testing.T) {+ root := t.TempDir()+ inside := filepath.Join(root, "a.txt")+ os.WriteFile(inside, []byte("x"), 0600)+ outsideDir := t.TempDir()+ secret := filepath.Join(outsideDir, "secret")+ os.WriteFile(secret, []byte("x"), 0600)+ os.Symlink(secret, filepath.Join(root, "link"))++ if _, err := Confine(root, inside); err != nil {+ t.Fatalf("inside rejected: %v", err)+ }+ for _, p := range []string{secret, "/etc/passwd", filepath.Join(root, "..", "x"), filepath.Join(root, "link")} {+ if _, err := Confine(root, p); err == nil {+ t.Fatalf("%s must be rejected", p)+ }+ }+}++func TestLoopbackAddr(t *testing.T) {+ if LoopbackAddr(8081) != "127.0.0.1:8081" {+ t.Fatal("must bind loopback")+ }+}++func TestOriginAllowed(t *testing.T) {+ l := DefaultOrigins+ for o, want := range map[string]bool{+ "https://three.ws": true, "http://localhost:5174": true, "http://127.0.0.1:3000": true,+ "https://evil.example": false, "https://three.ws.evil.example": false, "": false,+ } {+ if OriginAllowed(l, o) != want {+ t.Fatalf("%q want %v", o, want)+ }+ }+}diff --git a/chat/server/main.go b/chat/server/main.goindex a930b7462..0fe91c272 100644--- a/chat/server/main.go+++ b/chat/server/main.go@@ -18,24 +18,42 @@ import ("github.com/go-chi/chi/v5""github.com/go-chi/chi/v5/middleware""github.com/go-chi/cors"+ "github.com/nirholas/server/guard""github.com/nirholas/server/toolfns")var (- password = flag.String("password", "", "Password for basic auth.")+ password = flag.String("password", "", "Password for auth. A random token is generated and printed when omitted.")+ port = flag.Int("port", 8081, "Port to listen on (loopback only).")+ origins = flag.String("origins", "", "Comma-separated extra web origins allowed by CORS (localhost and three.ws are always allowed).")filesPath = flag.String("files", ".", "Path to the directory we're working with"))func main() {flag.Parse()+ if *password == "" {+ token, err := guard.NewToken()+ if err != nil {+ log.Fatal(err)+ }+ *password = token+ fmt.Println("No -password given. Generated token (enter it as the password in Settings):", token)+ }+ allowedOrigins := append([]string{}, guard.DefaultOrigins...)+ for _, o := range strings.Split(*origins, ",") {+ if o = strings.TrimSpace(o); o != "" {+ allowedOrigins = append(allowedOrigins, o)+ }+ }+r := chi.NewRouter()r.Use(cors.Handler(cors.Options{- AllowedOrigins: []string{"*"},- AllowedMethods: []string{"GET", "POST", "OPTIONS"},- AllowedHeaders: []string{"*"},+ AllowOriginFunc: func(_ *http.Request, origin string) bool { return guard.OriginAllowed(allowedOrigins, origin) },+ AllowedMethods: []string{"GET", "POST", "OPTIONS"},+ AllowedHeaders: []string{"Authorization", "Content-Type"},}))- r.Use(authMiddleware)+ r.Use(guard.Auth(*password))r.Use(middleware.RequestID)r.Use(middleware.RealIP)r.Use(middleware.Logger)@@ -49,8 +67,9 @@ func main() {r.Get("/read_file", ReadFile)r.Post("/api/tts/google", TTSHandler)- fmt.Println("Tool server running at http://localhost:8081")- httpServer := &http.Server{Addr: ":8081", Handler: r}+ addr := guard.LoopbackAddr(*port)+ fmt.Println("Tool server running at http://" + addr)+ httpServer := &http.Server{Addr: addr, Handler: r}go func() {if err := httpServer.ListenAndServe(); err != nil && err != http.ErrServerClosed {log.Fatal(err)@@ -109,16 +128,6 @@ func TTSHandler(w http.ResponseWriter, r *http.Request) {w.Write(audio)}-func authMiddleware(next http.Handler) http.Handler {- return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {- if *password != "" && r.Header.Get("Authorization") != ("Basic "+*password) {- w.WriteHeader(http.StatusUnauthorized)- return- }- next.ServeHTTP(w, r)- })-}-func writeJSON(w http.ResponseWriter, status int, v any) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(status)@@ -151,7 +160,7 @@ func (tr *ToolHandler) InvokeTool(w http.ResponseWriter, r *http.Request) {Name string `json:"name"`Args map[string]any `json:"arguments"`}- if err := json.NewDecoder(io.TeeReader(r.Body, os.Stdout)).Decode(&call); err != nil {+ if err := json.NewDecoder(r.Body).Decode(&call); err != nil {writeJSON(w, http.StatusBadRequest, map[string]any{"error": err.Error()})return}