// Package tsbridge implements the HTTP surface served over tsnet: a static // single-page webapp plus a reverse proxy to Intiface Central's WebSocket // server on localhost. // // This package is bound to Kotlin with gomobile, so its exported surface is // limited to bindable types (strings, ints, errors). Internal machinery lives // in unexported functions. package tsbridge import ( "encoding/json" "fmt" "io/fs" "log/slog" "mime" "net/http" "net/http/httputil" "net/url" "os" "path" "path/filepath" "strings" "sync" "golang.org/x/net/http/httpguts" ) // DefaultIntifaceTarget is the address used when nothing else is configured: // Intiface Central's default WebSocket server on localhost. const DefaultIntifaceTarget = "ws://localhost:12345" var mimeOnce sync.Once // registerMimeTypes pins the content types we serve. Android app sandboxes // have no /etc/mime.types, and Go's OS fallback can return an empty or wrong // type for .mjs, which breaks the browser's ES-module import. func registerMimeTypes() { mimeOnce.Do(func() { mustMime(".html", "text/html; charset=utf-8") mustMime(".css", "text/css; charset=utf-8") mustMime(".js", "text/javascript; charset=utf-8") mustMime(".mjs", "text/javascript; charset=utf-8") mustMime(".json", "application/json") mustMime(".svg", "image/svg+xml") mustMime(".png", "image/png") }) } func mustMime(ext, typ string) { if err := mime.AddExtensionType(ext, typ); err != nil { panic(fmt.Sprintf("mime.AddExtensionType(%q): %v", ext, err)) } } // newHandler returns the full HTTP handler. // // intifaceTarget is the ws:// or wss:// URL of Intiface Central's WebSocket // server (see parseIntifaceTarget); it is a parameter so the Android app can // point the proxy at whatever server the user configured. webappDir is the // filesystem directory whose files are served over HTTP (see // validateWebappDir); it is a parameter so a deployment can serve a // different webapp without touching tsbridge. func newHandler(log *slog.Logger, intifaceTarget *url.URL, webappDir string) http.Handler { registerMimeTypes() if log == nil { log = slog.Default() } mux := http.NewServeMux() mux.HandleFunc("/healthz", handleHealthz(intifaceTarget)) mux.Handle("/", staticHandler(webappDir)) // "/" is dual-purpose, mirroring Intiface Central's own server (which // accepts websocket upgrades on any path, and is dialed without one by // clients such as Intiface Central desktop's Repeater mode): websocket // upgrades are reverse-proxied to Intiface, everything else gets the // static webapp. proxy := wsProxy(log, intifaceTarget) return corsMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if isWebsocketUpgrade(r) { proxy.ServeHTTP(w, r) return } mux.ServeHTTP(w, r) })) } // isWebsocketUpgrade reports whether r asks for an RFC 6455 websocket // handshake ("Connection: Upgrade" + "Upgrade: websocket"). func isWebsocketUpgrade(r *http.Request) bool { return httpguts.HeaderValuesContainsToken(r.Header.Values("Connection"), "Upgrade") && strings.EqualFold(r.Header.Get("Upgrade"), "websocket") } // parseIntifaceTarget normalizes the configured Intiface WebSocket URL. // Empty selects DefaultIntifaceTarget. ws:// and wss:// are the accepted // schemes (mapped to http/https for proxying). func parseIntifaceTarget(s string) (*url.URL, error) { if strings.TrimSpace(s) == "" { s = DefaultIntifaceTarget } u, err := url.Parse(s) if err != nil { return nil, fmt.Errorf("intiface target %q: %w", s, err) } if u.Scheme != "ws" && u.Scheme != "wss" { return nil, fmt.Errorf("intiface target %q: scheme must be ws:// or wss://", s) } if u.Hostname() == "" { return nil, fmt.Errorf("intiface target %q: host is missing", s) } return u, nil } func handleHealthz(intifaceTarget *url.URL) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) json.NewEncoder(w).Encode(map[string]any{ "status": "ok", "intiface_target": intifaceTarget.String(), }) } } // wsProxy reverse-proxies WebSocket upgrade requests (and any other request) // to the configured Intiface Central WebSocket server. buttplug-rs's server // accepts upgrade requests with no Origin/Host/path validation, so the proxy // needs to rewrite only the scheme and host; the upgrade handshake and // bidirectional frame streaming are handled natively by // httputil.ReverseProxy. func wsProxy(log *slog.Logger, intifaceTarget *url.URL) http.Handler { scheme := "http" if intifaceTarget.Scheme == "wss" { scheme = "https" } target := &url.URL{Scheme: scheme, Host: intifaceTarget.Host} rp := &httputil.ReverseProxy{ Rewrite: func(pr *httputil.ProxyRequest) { // Preserves the request path; Intiface ignores it. pr.SetURL(target) }, // Websocket frames are proxied over hijacked connections; this only // affects ordinary HTTP responses. FlushInterval: -1, ErrorHandler: func(w http.ResponseWriter, r *http.Request, err error) { log.Error("intiface proxy error", "path", r.URL.Path, "err", err) http.Error(w, "intiface upstream unreachable", http.StatusBadGateway) }, } return rp } // validateWebappDir checks that dir exists and looks like a webapp root (has // an index.html). Entry points (Start, ServePlain) call this so a bad path // fails loudly at startup instead of quietly 404ing every request. func validateWebappDir(dir string) error { if strings.TrimSpace(dir) == "" { return fmt.Errorf("webapp directory is required (the directory containing the webapp's index.html)") } info, err := os.Stat(dir) if err != nil { return fmt.Errorf("webapp directory %q: %w", dir, err) } if !info.IsDir() { return fmt.Errorf("webapp directory %q: not a directory", dir) } if _, err := os.Stat(filepath.Join(dir, "index.html")); err != nil { return fmt.Errorf("webapp directory %q has no index.html", dir) } return nil } func staticHandler(webappDir string) http.Handler { // When the directory is missing or invalid, everything 404s; the entry // points validate up front, this only guards direct construction. sub := os.DirFS(webappDir) var files fs.FS = sub if _, err := fs.Stat(sub, "index.html"); err != nil { files = nil } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if files == nil { http.Error(w, "webapp directory unavailable", http.StatusNotFound) return } // Never cache the entry point; hashed assets would be safe to cache // but the webapp has no build step and thus no content hashes. switch path.Clean(r.URL.Path) { case "/", "/index.html": w.Header().Set("Cache-Control", "no-cache") } http.FileServerFS(files).ServeHTTP(w, r) }) } // ServePlain runs a blocking plain-HTTP server for the desktop runner. Not // used on Android (tsnet serves HTTPS there); harmless to expose. func ServePlain(addr string, intifaceTarget string, webappDir string) error { target, err := parseIntifaceTarget(intifaceTarget) if err != nil { return err } if err := validateWebappDir(webappDir); err != nil { return err } srv := &http.Server{Addr: addr, Handler: newHandler(slog.Default(), target, webappDir)} if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed { return err } return nil }