From b14f92b2808eda0178dbfd725297ccc1baf1710a Mon Sep 17 00:00:00 2001 From: Joshua Barrett Date: Fri, 30 Oct 2026 11:03:00 -0400 Subject: [PATCH] configurable WebSocket endpoint and opt-in CORS MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The webapp gets a Server settings card with a persisted custom WebSocket endpoint. Empty keeps this page's own server; a bare host:port (e.g. localhost:12345, Intiface Central's default) or a full ws:// or wss:// URL is used verbatim, so the page works against any buttplug server without tsbridge in the middle. Switching endpoints tears the current client down (its shutdown stops all toys first) and reconnects; buttplug client event handlers now ignore stale clients so a replaced client's late disconnect cannot schedule reconnects or clear the new connection's registry. tsbridge gains SetCORS(bool), off by default, applied per request so the toggle also affects a running server. When enabled, the request Origin is reflected on every response — including WebSocket upgrade handshakes, which browsers do not preflight — so web apps hosted on other origins can connect; credentials are never granted, Vary: Origin guards caches, and preflight answers carry a deliberately short Access-Control-Max-Age (300 s) because the toggle is user-facing. The desktop runner exposes it as -cors; the Android settings screen as an "Allow other web pages (CORS)" switch that is pushed into the Go singleton on service start. Regenerated app/libs/tsbridge.aar and its sources jar for the new binding. --- app/libs/tsbridge-sources.jar | Bin 6586 -> 6843 bytes .../java/com/tsbutt/app/ControlService.kt | 7 ++ .../main/java/com/tsbutt/app/MainActivity.kt | 20 +++ .../main/java/com/tsbutt/app/SettingsStore.kt | 4 + .../java/com/tsbutt/app/SettingsStoreTest.kt | 24 +++- tsbridge/README.md | 12 +- tsbridge/cmd/desktop/main.go | 8 ++ tsbridge/cors.go | 61 +++++++++ tsbridge/server.go | 4 +- tsbridge/server_test.go | 112 +++++++++++++++++ tsbridge/webapp/app.js | 117 ++++++++++++++++-- tsbridge/webapp/index.html | 17 +++ tsbridge/webapp/style.css | 28 +++++ 13 files changed, 402 insertions(+), 12 deletions(-) create mode 100644 tsbridge/cors.go diff --git a/app/libs/tsbridge-sources.jar b/app/libs/tsbridge-sources.jar index c9cfcf06215f9350bd3dafa1806240b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zh$P_rF93fA{ij|DOM`hYb6BALfu>&C0+~&JC*77@0&E5VH-)Qv#sb2Gkh{Y;z9* z-l!%3hTM7rO&uUiD23FMu!#h8jmVWPsBwkR*uxK=fk0_$q3cGj!$1`>LiaR5ux>>4 ljII?qJV2EkLTjxMt|~9Uo0Scuj+KFx!Ge*2Ax8ql0|0`=;~W40 diff --git a/app/src/main/java/com/tsbutt/app/ControlService.kt b/app/src/main/java/com/tsbutt/app/ControlService.kt index d05304e..9c33892 100644 --- a/app/src/main/java/com/tsbutt/app/ControlService.kt +++ b/app/src/main/java/com/tsbutt/app/ControlService.kt @@ -38,6 +38,13 @@ class ControlService : Service() { if (!alreadyRunning) { val settings = SettingsStore(SharedPreferencesStore(this)).load() + // CORS is opt-in and user-controlled; push it on every start so + // a settings change takes effect at the next "Start remote + // control". It also applies live to a running server (the Go + // side reads it per request), but the app only restarts the + // service to change it. + runCatching { Tsbridge.setCORS(settings.allowCors) } + .onFailure { Log.e(TAG, "setCORS failed", it) } val stateDir = filesDir.absolutePath val cacheDir = cacheDir.absolutePath thread(name = "tsbridge-start") { diff --git a/app/src/main/java/com/tsbutt/app/MainActivity.kt b/app/src/main/java/com/tsbutt/app/MainActivity.kt index a56cfbc..e7d65af 100644 --- a/app/src/main/java/com/tsbutt/app/MainActivity.kt +++ b/app/src/main/java/com/tsbutt/app/MainActivity.kt @@ -26,6 +26,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Surface +import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.darkColorScheme import androidx.compose.material3.dynamicDarkColorScheme @@ -37,6 +38,7 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.input.PasswordVisualTransformation @@ -258,6 +260,24 @@ private fun StatusScreen(onRequestNotifications: () -> Unit) { singleLine = true, modifier = Modifier.fillMaxWidth(), ) + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically, + ) { + Column(modifier = Modifier.weight(1f)) { + Text("Allow other web pages (CORS)") + Text( + "Off by default. When on, any web page may connect " + + "to this server — takes effect at next start.", + style = MaterialTheme.typography.bodySmall, + ) + } + Switch( + checked = settings.allowCors, + onCheckedChange = { settings = settings.copy(allowCors = it) }, + ) + } } } } diff --git a/app/src/main/java/com/tsbutt/app/SettingsStore.kt b/app/src/main/java/com/tsbutt/app/SettingsStore.kt index c882b16..fc63200 100644 --- a/app/src/main/java/com/tsbutt/app/SettingsStore.kt +++ b/app/src/main/java/com/tsbutt/app/SettingsStore.kt @@ -26,6 +26,7 @@ data class Settings( val hostname: String, val authKey: String, val intifacePort: Int, + val allowCors: Boolean, ) class SettingsStore(private val store: KeyValueStore) { @@ -35,12 +36,14 @@ class SettingsStore(private val store: KeyValueStore) { authKey = store.getString(KEY_AUTH_KEY, ""), intifacePort = store.getString(KEY_INTIFACE_PORT, DEFAULT_PORT.toString()) .toIntOrNull()?.coerceIn(1, 65535) ?: DEFAULT_PORT, + allowCors = store.getString(KEY_ALLOW_CORS, "false") == "true", ) fun save(settings: Settings) { store.putString(KEY_HOSTNAME, settings.hostname.trim()) store.putString(KEY_AUTH_KEY, settings.authKey.trim()) store.putString(KEY_INTIFACE_PORT, settings.intifacePort.toString()) + store.putString(KEY_ALLOW_CORS, settings.allowCors.toString()) } companion object { @@ -49,5 +52,6 @@ class SettingsStore(private val store: KeyValueStore) { const val KEY_HOSTNAME = "hostname" const val KEY_AUTH_KEY = "auth_key" const val KEY_INTIFACE_PORT = "intiface_port" + const val KEY_ALLOW_CORS = "allow_cors" } } diff --git a/app/src/test/java/com/tsbutt/app/SettingsStoreTest.kt b/app/src/test/java/com/tsbutt/app/SettingsStoreTest.kt index 45a019e..613001c 100644 --- a/app/src/test/java/com/tsbutt/app/SettingsStoreTest.kt +++ b/app/src/test/java/com/tsbutt/app/SettingsStoreTest.kt @@ -18,12 +18,34 @@ class SettingsStoreTest { val store = MapStore() val settings = SettingsStore(store) - settings.save(Settings(hostname = "mypod", authKey = "tskey-auth-abc123", intifacePort = 9999)) + settings.save( + Settings( + hostname = "mypod", + authKey = "tskey-auth-abc123", + intifacePort = 9999, + allowCors = true, + ), + ) val loaded = SettingsStore(store).load() assertEquals("mypod", loaded.hostname) assertEquals("tskey-auth-abc123", loaded.authKey) assertEquals(9999, loaded.intifacePort) + assertEquals(true, loaded.allowCors) + } + + @Test + fun `cors defaults to disabled and parses stored values`() { + // Absent setting: off by default (CORS is opt-in). + assertEquals(false, SettingsStore(MapStore()).load().allowCors) + + val store = MapStore() + store.putString(SettingsStore.KEY_ALLOW_CORS, "true") + assertEquals(true, SettingsStore(store).load().allowCors) + + // Garbage values are treated as disabled. + store.putString(SettingsStore.KEY_ALLOW_CORS, "yes-please") + assertEquals(false, SettingsStore(store).load().allowCors) } @Test diff --git a/tsbridge/README.md b/tsbridge/README.md index 3582153..7684fc8 100644 --- a/tsbridge/README.md +++ b/tsbridge/README.md @@ -28,8 +28,8 @@ https://github.com/GlassOnTin/Haven/blob/main/rclone-android/go/tsbridge/tsbridg explicitly to the caller-provided state dir (`context.getFilesDir()` on the Kotlin side). - gomobile binds only simple types: the exported surface is `Start`/`Stop`/ - `Status`/`ServePlain` with strings/ints; state is a package-level singleton - and `Status()` returns JSON. + `Status`/`ServePlain`/`SetCORS` with strings/ints/bools; state is a + package-level singleton and `Status()` returns JSON. - The server serves on **:443** (userspace netstack needs no privileges) and additionally serves the same handler over **plain HTTP on :80**, so the webapp and its WebSocket proxy work at `http:///` too. @@ -42,6 +42,14 @@ https://github.com/GlassOnTin/Haven/blob/main/rclone-android/go/tsbridge/tsbridg clients such as Intiface Central desktop's Repeater mode): WebSocket upgrades on any path are reverse-proxied to Intiface on localhost, plain requests get the static webapp (and `/healthz`). +- **CORS is off by default** and controlled by `SetCORS(bool)` (the Android + app's "Allow other web pages" toggle, the desktop runner's `-cors` flag). + When on, the request Origin is reflected on every response — including + WebSocket handshakes, which browsers do not preflight — so any web page on + any origin may open the proxy. Credentials are never granted, `Vary: + Origin` guards caches, and preflight answers carry a deliberately short + `Access-Control-Max-Age` (5 minutes) so browsers stop trusting the + permissive policy shortly after the user turns it off. - **TLS certs are provisioned by our own code** (`certs.go`), not by tsnet's `ListenTLS`: on Android upstream stubs the localapi cert endpoint with 404 "disabled on android" (tailscale#18245), which makes ListenTLS diff --git a/tsbridge/cmd/desktop/main.go b/tsbridge/cmd/desktop/main.go index 2d8339a..829ea93 100644 --- a/tsbridge/cmd/desktop/main.go +++ b/tsbridge/cmd/desktop/main.go @@ -22,8 +22,16 @@ func main() { authKey := flag.String("authkey", "", "tailnet auth key; a Tailscale OAuth client secret (tskey-client-...) also works and mints a key via OAuth — requires -advertise-tags. Empty = interactive login URL on stderr") tags := flag.String("advertise-tags", "", "comma-separated tailnet tags to apply (required when -authkey is an OAuth client secret, e.g. tag:server)") servePort := flag.Int("port", 443, "HTTPS port to serve on in tsnet mode; the same handler is also served over plain HTTP on :80 (443 works: userspace netstack needs no privileges)") + cors := flag.Bool("cors", false, "allow cross-origin browser connections (CORS); off by default — enabling lets ANY web page open this server's WebSocket") flag.Parse() + if *cors { + if err := tsbridge.SetCORS(true); err != nil { + fmt.Fprintln(os.Stderr, "cors:", err) + os.Exit(1) + } + } + if *useTsnet { stateDir := *stateDir if stateDir == "" { diff --git a/tsbridge/cors.go b/tsbridge/cors.go new file mode 100644 index 0000000..4365e89 --- /dev/null +++ b/tsbridge/cors.go @@ -0,0 +1,61 @@ +package tsbridge + +import ( + "net/http" + "strconv" + "sync/atomic" +) + +// Cross-origin (CORS) support. Off by default: enabling it lets ANY web page +// in any tab on any origin open this server's WebSocket (and read static +// resources), which is exactly what you want when hosting your own client +// for tsbutt elsewhere, and exactly what you don't want when some unrelated +// page starts probing the proxy. The user turns it on deliberately. + +// corsMaxAgeSecs caps how long browsers may cache the preflight verdict. It +// is deliberately short (a few minutes): CORS is a user-facing toggle, and a +// long-lived cache would let browsers keep trusting a permissive policy +// after the user turned it back off. +const corsMaxAgeSecs = 300 + +var corsEnabled atomic.Bool + +// SetCORS enables or disables cross-origin browser access to the server. +// It is process-wide, takes effect immediately (including for WebSocket +// upgrades), and defaults to disabled. Returns an error only for gomobile's +// benefit (the bound API is error-returning). +func SetCORS(enabled bool) error { + corsEnabled.Store(enabled) + return nil +} + +// corsMiddleware adds CORS response headers when — and only when — the +// option is enabled. The request Origin is reflected: the point of the +// option is to admit arbitrary origins, and credentials are never allowed, +// so reflection grants no more than the toggle already does. `Vary: Origin` +// keeps caches from serving one origin a response minted for another. +// +// WebSocket connections need no preflight (the handshake is a simple GET), +// so "allowed" here just means the handshake response carries the same +// Access-Control-Allow-Origin header the browser checks before firing the +// open event. Ordinary HTTP requests (healthz, static assets) get the same +// treatment, and non-simple requests get a real preflight answer. +func corsMiddleware(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if corsEnabled.Load() { + if origin := r.Header.Get("Origin"); origin != "" { + h := w.Header() + h.Set("Access-Control-Allow-Origin", origin) + h.Set("Vary", "Origin") + if r.Method == http.MethodOptions && r.Header.Get("Access-Control-Request-Method") != "" { + h.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS") + h.Set("Access-Control-Allow-Headers", r.Header.Get("Access-Control-Request-Headers")) + h.Set("Access-Control-Max-Age", strconv.Itoa(corsMaxAgeSecs)) + w.WriteHeader(http.StatusNoContent) + return + } + } + } + next.ServeHTTP(w, r) + }) +} diff --git a/tsbridge/server.go b/tsbridge/server.go index 0eef8d2..efeba33 100644 --- a/tsbridge/server.go +++ b/tsbridge/server.go @@ -74,13 +74,13 @@ func newHandler(log *slog.Logger, intifacePort int) http.Handler { // upgrades are reverse-proxied to Intiface on localhost, everything else // gets the static webapp. proxy := wsProxy(log, intifacePort) - return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + 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 diff --git a/tsbridge/server_test.go b/tsbridge/server_test.go index fb7c1a3..e1ae6e0 100644 --- a/tsbridge/server_test.go +++ b/tsbridge/server_test.go @@ -288,6 +288,118 @@ func TestSharedServerTwoListeners(t *testing.T) { } } +// --- CORS ----------------------------------------------------------------- +// CORS is off by default and toggled process-wide via SetCORS; these tests +// must restore the default so later tests (and the default) stay intact. + +func withCORSEnabled(t *testing.T) { + t.Helper() + if err := SetCORS(true); err != nil { + t.Fatalf("SetCORS(true): %v", err) + } + t.Cleanup(func() { + if err := SetCORS(false); err != nil { + t.Fatalf("SetCORS(false) cleanup: %v", err) + } + }) +} + +func TestCORSDisabledByDefault(t *testing.T) { + handler := testHandler(t, DefaultIntifacePort) + + req := httptest.NewRequest(http.MethodGet, "/healthz", nil) + req.Header.Set("Origin", "https://example.com") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + + if rec.Code != http.StatusOK { + t.Fatalf("GET /healthz status = %d, want 200", rec.Code) + } + if acao := rec.Header().Get("Access-Control-Allow-Origin"); acao != "" { + t.Errorf("CORS disabled: got Access-Control-Allow-Origin %q, want none", acao) + } +} + +func TestCORSReflectsOriginAndAnswersPreflight(t *testing.T) { + withCORSEnabled(t) + handler := testHandler(t, DefaultIntifacePort) + + // Simple GET: origin reflected, no credentials granted. + req := httptest.NewRequest(http.MethodGet, "/healthz", nil) + req.Header.Set("Origin", "https://example.com") + rec := httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://example.com" { + t.Errorf("GET Access-Control-Allow-Origin = %q, want the request origin", got) + } + if rec.Header().Get("Access-Control-Allow-Credentials") != "" { + t.Errorf("Access-Control-Allow-Credentials must never be set") + } + if va := rec.Header().Get("Vary"); !strings.Contains(va, "Origin") { + t.Errorf("GET Vary = %q, want it to contain Origin", va) + } + + // Preflight: 204 with methods, requested headers, and a short Max-Age. + preflight := httptest.NewRequest(http.MethodOptions, "/", nil) + preflight.Header.Set("Origin", "https://example.com") + preflight.Header.Set("Access-Control-Request-Method", "GET") + preflight.Header.Set("Access-Control-Request-Headers", "x-test") + rec = httptest.NewRecorder() + handler.ServeHTTP(rec, preflight) + if rec.Code != http.StatusNoContent { + t.Fatalf("preflight status = %d, want 204", rec.Code) + } + if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://example.com" { + t.Errorf("preflight Access-Control-Allow-Origin = %q, want the request origin", got) + } + if got := rec.Header().Get("Access-Control-Allow-Methods"); !strings.Contains(got, "GET") { + t.Errorf("preflight Access-Control-Allow-Methods = %q, want GET allowed", got) + } + if got := rec.Header().Get("Access-Control-Allow-Headers"); got != "x-test" { + t.Errorf("preflight Access-Control-Allow-Headers = %q, want the requested headers echoed", got) + } + if got := rec.Header().Get("Access-Control-Max-Age"); got != "300" { + t.Errorf("preflight Access-Control-Max-Age = %q, want 300 (short: the toggle is user-facing)", got) + } + + // Requests without an Origin are same-origin or non-browser traffic: + // they get no CORS headers and normal handling. + req = httptest.NewRequest(http.MethodGet, "/healthz", nil) + rec = httptest.NewRecorder() + handler.ServeHTTP(rec, req) + if rec.Header().Get("Access-Control-Allow-Origin") != "" { + t.Errorf("GET without Origin must not carry Access-Control-Allow-Origin") + } +} + +// TestCORSWebSocketStillProxies covers the headline use case: with CORS on, +// a browser on another origin may open the WebSocket endpoint. The handshake +// must succeed and carry the Allow-Origin header. +func TestCORSWebSocketStillProxies(t *testing.T) { + withCORSEnabled(t) + upstream := newMockIntiface(t) + upstreamPort := portOf(t, upstream.URL) + + srv := httptest.NewServer(testHandler(t, upstreamPort)) + defer srv.Close() + + ws, err := websocket.Dial("ws://"+hostPortOf(t, srv.URL)+"/", "", "http://example.com") + if err != nil { + t.Fatalf("dial through proxy with foreign origin: %v", err) + } + defer ws.Close() + if err := websocket.Message.Send(ws, `{"operation":"ping","id":9}`); err != nil { + t.Fatalf("send: %v", err) + } + var reply string + if err := websocket.Message.Receive(ws, &reply); err != nil { + t.Fatalf("receive: %v", err) + } + if !strings.Contains(reply, `"result":"pong"`) { + t.Errorf("reply = %q, want pong", reply) + } +} + func portOf(t *testing.T, url string) int { hostPort := strings.TrimPrefix(url, "http://") var port int diff --git a/tsbridge/webapp/app.js b/tsbridge/webapp/app.js index 9931d24..aab541e 100644 --- a/tsbridge/webapp/app.js +++ b/tsbridge/webapp/app.js @@ -32,6 +32,99 @@ function wsURL() { return `${scheme}//${location.host}/`; } +// --- server endpoint ------------------------------------------------------ + +// The WebSocket endpoint the webapp talks to. Empty = this page's own +// server (the tsbridge proxy). A custom endpoint — e.g. ws://localhost:12345 +// for Intiface Central running on the local machine — lets the page be used +// without tsbridge at all. +const ENDPOINT_STORE_KEY = "tsbutt.endpoint"; +let customEndpoint = loadStoredEndpoint(); + +function loadStoredEndpoint() { + try { + return localStorage.getItem(ENDPOINT_STORE_KEY) ?? ""; + } catch { + return ""; + } +} + +function storeEndpoint(ep) { + try { + if (ep) { + localStorage.setItem(ENDPOINT_STORE_KEY, ep); + } else { + localStorage.removeItem(ENDPOINT_STORE_KEY); + } + } catch { + /* private mode etc. — the endpoint just won't persist */ + } +} + +// normalizeEndpoint turns user input into a ws:// or wss:// URL. A bare +// host[:port][/path] is accepted and gets the page's own scheme (so +// "localhost:12345" works); full URLs are used as-is after validation. +function normalizeEndpoint(input) { + const raw = String(input ?? "").trim().replace(/\/+$/, ""); + if (!raw) return ""; + const withScheme = /^wss?:\/\//i.test(raw) + ? raw + : `${location.protocol === "https:" ? "wss:" : "ws:"}//${raw}`; + let url; + try { + url = new URL(withScheme); + } catch { + throw new Error(`not a valid WebSocket address: ${raw}`); + } + if ((url.protocol !== "ws:" && url.protocol !== "wss:") || !url.hostname) { + throw new Error(`not a valid WebSocket address: ${raw}`); + } + return withScheme; +} + +// Switch servers: tear the current client down (its shutdown sends +// stop-all, so toys are never left running) and connect to the endpoint. +async function reconnectNow() { + if (reconnectTimer) { + clearTimeout(reconnectTimer); + reconnectTimer = null; + } + const old = client; + client = null; // stale events from `old` are ignored via isCurrent guards + if (old?.connected) { + try { + await old.disconnect(); + } catch { + /* best effort; the new connection replaces it either way */ + } + } + intentionallyClosed = false; + reconnectDelay = 500; + connect(); +} + +$("endpoint-apply").addEventListener("click", () => { + let ep; + try { + ep = normalizeEndpoint($("endpoint").value); + } catch (err) { + showError(`Server: ${err.message}`); + return; + } + customEndpoint = ep; + storeEndpoint(ep); + $("endpoint").value = ep; + log(`endpoint set: ${ep || "default (this page's server)"}`); + reconnectNow(); +}); +$("endpoint-reset").addEventListener("click", () => { + customEndpoint = ""; + storeEndpoint(""); + $("endpoint").value = ""; + log("endpoint reset to default (this page's server)"); + reconnectNow(); +}); + function log(line) { const el = $("log"); el.textContent += `${new Date().toISOString().slice(11, 19)} ${line}\n`; @@ -971,10 +1064,16 @@ new ResizeObserver(() => { async function connect() { if (client?.connected) return; intentionallyClosed = false; - client = new ButtplugClient("tsbutt"); + const thisClient = new ButtplugClient("tsbutt"); + // Only the current client's events may touch shared state: a replaced + // client can still fire its own disconnect while we are connecting to the + // new endpoint, and its handlers must not schedule reconnects or clear + // the new client's registry. + const isCurrent = () => client === thisClient; // Register all listeners before connecting (buttplug.js requirement). - client.on("disconnect", () => { + thisClient.on("disconnect", () => { + if (!isCurrent()) return; features.clear(); batteryText.clear(); stopBatteryPolling(); @@ -984,29 +1083,32 @@ async function connect() { setPill("bad", "disconnected"); scheduleReconnect(); }); - client.on("deviceadded", () => { + thisClient.on("deviceadded", () => { + if (!isCurrent()) return; refreshRegistry(); startBatteryPolling(); log(`device added: ${[...client.devices.values()].at(-1)?.name ?? "?"}`); }); - client.on("deviceremoved", (d) => { + thisClient.on("deviceremoved", (d) => { + if (!isCurrent()) return; refreshRegistry(); log(`device removed: ${d?.name ?? "?"}`); }); - client.on("scanningfinished", () => { + thisClient.on("scanningfinished", () => { /* registry is already event-driven; nothing to do */ }); + client = thisClient; const connector = new ButtplugBrowserWebsocketClientConnector(wsURL()); try { setPill("off", "connecting…"); - await client.connect(connector); + await thisClient.connect(connector); setPill("on", "connected"); reconnectDelay = 500; manager.handleConnected(); refreshRegistry(); startBatteryPolling(); - await client.startScanning(); + await thisClient.startScanning(); } catch (err) { setPill("bad", "connection failed"); log(`connect failed: ${err?.message ?? err}`); @@ -1057,5 +1159,6 @@ window.addEventListener("unhandledrejection", () => manager.emergencyStop()); loadPatternState(); loadFreehandState(); +$("endpoint").value = customEndpoint; connect(); log(`webapp loaded; ws target ${wsURL()}`); diff --git a/tsbridge/webapp/index.html b/tsbridge/webapp/index.html index 53aa84e..c55f523 100644 --- a/tsbridge/webapp/index.html +++ b/tsbridge/webapp/index.html @@ -80,6 +80,23 @@ +
+ Server +
+

+ WebSocket endpoint of the buttplug server. Empty = this page's own + server. Example: ws://localhost:12345 — Intiface + Central running on this machine. +

+ +
+ + +
+
+
+
Status log

diff --git a/tsbridge/webapp/style.css b/tsbridge/webapp/style.css
index ed334ea..f83d753 100644
--- a/tsbridge/webapp/style.css
+++ b/tsbridge/webapp/style.css
@@ -337,6 +337,34 @@ input[type="range"] {
   border-radius: 50%;
 }
 
+/* --- server settings ------------------------------------------------------ */
+
+.server-body {
+  display: flex;
+  flex-direction: column;
+  gap: 0.5rem;
+  padding: 0.6rem 0.2rem 0;
+  font-size: 0.85rem;
+}
+.server-body .muted { margin: 0; }
+.server-body code {
+  background: var(--bg);
+  border-radius: 4px;
+  padding: 0 0.25rem;
+}
+#endpoint {
+  width: 100%;
+  background: var(--bg);
+  color: var(--text);
+  border: 1px solid #33333c;
+  border-radius: 8px;
+  padding: 0.5rem;
+  font-size: 0.95rem;
+  -webkit-user-select: text;
+  user-select: text;
+}
+.row button.ghost { background: color-mix(in srgb, var(--card) 70%, transparent); }
+
 /* --- emergency stop dock ------------------------------------------------- */
 /* Fixed to the bottom of the viewport in every view; nothing may cover it. */
 
-- 
knotmirror 0.0.1