From c26befc911f8a680e0ec67a0ad124bd61e14d63a Mon Sep 17 00:00:00 2001 From: Joshua Barrett Date: Fri, 30 Oct 2026 17:45:26 -0400 Subject: [PATCH] decouple the webapp from tsbridge The webapp moves to the top-level webapp/ directory and tsbridge no longer embeds it: the handler serves whatever filesystem directory it is given, validated at startup to contain index.html, so the served webapp can be swapped by whoever runs the server. The desktop runner grows a -webapp flag (default: ./webapp). tsnet's Start and ServePlain take the webapp directory as a parameter; Start fails fast on a missing or index-less directory instead of quietly 404ing. The webapp stays bundled with the Android app: a Gradle copy task syncs webapp/ into the APK's assets, and on service start the app unpacks those assets into app storage and hands the path to tsbridge. A new settings option lets the user pick a folder from phone storage (SAF document tree) to serve instead; because Go can only read real paths, the picked tree is copied into app storage on every start (so edits to the folder are picked up), falling back to the bundled webapp if the folder can't be read. Regenerated the gomobile AAR for the new Start signature. --- AGENTS.md | 4 +- app/build.gradle.kts | 11 ++ app/libs/tsbridge-sources.jar | Bin 6785 -> 6951 bytes .../java/com/tsbutt/app/ControlService.kt | 5 + .../main/java/com/tsbutt/app/MainActivity.kt | 38 +++++ .../main/java/com/tsbutt/app/SettingsStore.kt | 4 + .../main/java/com/tsbutt/app/WebappStore.kt | 139 ++++++++++++++++++ tsbridge/README.md | 10 +- tsbridge/cmd/desktop/main.go | 5 +- tsbridge/server.go | 58 ++++++-- tsbridge/server_test.go | 65 +++++++- tsbridge/tsnet.go | 15 +- {tsbridge/webapp => webapp}/app.js | 0 {tsbridge/webapp => webapp}/index.html | 0 {tsbridge/webapp => webapp}/logic.js | 0 {tsbridge/webapp => webapp}/style.css | 0 {tsbridge/webapp => webapp}/test.html | 0 .../webapp => webapp}/vendor/buttplug.mjs | 0 18 files changed, 328 insertions(+), 26 deletions(-) create mode 100644 app/src/main/java/com/tsbutt/app/WebappStore.kt rename {tsbridge/webapp => webapp}/app.js (100%) rename {tsbridge/webapp => webapp}/index.html (100%) rename {tsbridge/webapp => webapp}/logic.js (100%) rename {tsbridge/webapp => webapp}/style.css (100%) rename {tsbridge/webapp => webapp}/test.html (100%) rename {tsbridge/webapp => webapp}/vendor/buttplug.mjs (100%) diff --git a/AGENTS.md b/AGENTS.md index 2bdebed..4a5ed82 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -22,7 +22,9 @@ Conventions for working in this repository. - Android (non-Go) code is **Kotlin + Jetpack Compose only**. - Go is allowed only in `tsbridge/` (server + tsnet + gomobile surface). - The webapp is vanilla ESM JavaScript; no npm, no bundler, no build step. - `buttplug.mjs` is vendored under `tsbridge/webapp/vendor/`. + It lives in the top-level `webapp/` directory (independent of tsbridge, + which serves any directory it is pointed at); `buttplug.mjs` is vendored + under `webapp/vendor/`. - No other languages (no Node, no Rust). ## Gotchas diff --git a/app/build.gradle.kts b/app/build.gradle.kts index 880c06f..f939cf7 100644 --- a/app/build.gradle.kts +++ b/app/build.gradle.kts @@ -4,10 +4,21 @@ plugins { alias(libs.plugins.kotlin.compose) } +// The webapp lives at the repo root, independent of tsbridge (which serves +// whatever directory it is pointed at). This copy makes it part of the APK's +// assets so the app can unpack and serve it by default. +val syncWebappAssets = tasks.register("syncWebappAssets") { + from(rootDir.resolve("webapp")) + into(layout.buildDirectory.dir("generated/webappAssets/webapp")) +} +tasks.named("preBuild") { dependsOn(syncWebappAssets) } + android { namespace = "com.tsbutt.app" compileSdk = 35 + sourceSets["main"].assets.srcDir(layout.buildDirectory.dir("generated/webappAssets")) + defaultConfig { applicationId = "com.tsbutt.app" minSdk = 26 diff --git a/app/libs/tsbridge-sources.jar b/app/libs/tsbridge-sources.jar index 8638e2b7100383b5d0adddb45a537f0abfb2c75c..bc1762e801ad9c9f1f7356a9bd9c21a06941415f 100644 GIT binary patch literal 6951 zcmWFVW@h1H00FW7xL6Pk!<-B<3?;=$MVTq-srsQIoD9sfg`Q^36?&RgTEWf0$nt`j zfq^B3fq?;Jga`uz0|x`hh|IeN_m;6SFns4_U=Tw#A_QudURGjRBHTQXnP}#%4ZGcU z+f1N#+rFd=OpUTPiY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VTICPanYiw?TZx$)Wdi=sVD@AnkWc_3sG*4e;guRUM(+n3@~CXAMH zRza#MVh;Fco@M;%=vUd+Tw;GAlQlU!;{LKIDfJ~yYjn2nGv%w>v%4)h z{T1J~CZi8YmZco|C8}QYWILD+3-)GgnEzRZcg3V%b`h6;E;Lxa*7EPI??((;L^qt@ ztg>_BLivaVN*7*fy}x3nQ}-dM*L&BRR)aMO${`W*w`O#x&P`hBVwKKeJC8y4cM5+Q zS3vKy2hXl5$X>ZNAvkn}GN(?&Nh78i>7c}xq+GM$a+S?CKkd_JS!S&`_wATxlb>KK z^V|pb7UcEv&GVJ}w5IRMgg&X$8@B(8IIzyS(c?Y4aOc6w?S4lY4^B%A{JrnEY4Cx< zNB(=x8sCj$6wPJSlsouMDbRe`{?nox3b*p9cwG#feCUwC8p)S;SLe@~H1GG9zYZT+ zG=zLjISh6F`7B&KPwCe5`kgy>)-~1MXz`e}qW_tA)}>ED?%gi=@)jX}bIcByY>Q^9 zQF=cwpv_}xxUtlA6Qkg>Tb{nWq@@A`J0%`om zgyLtdVBT_Ump9v46X}VG-@o5Jz1lkBO!Go#R(Y?Nhc_{NzEN{_v&qgahx_L2+oJnN z?%#2Rzv~%yNob!=St)jI^KrI^n`WeS^*`UaZqg>-rcD=rJUrU{e1pUcCH6I%=Vds# zudx@n_3nf+^$V>K&6P_QuUB{FyO-50ZFkz> z?&`Rj?R9K>S~`ABVS0IC={;NN&IhZ@PyM{V=6eY1Jhe088NV6s@EY~T@#;7|?qAoi zy6xA4);TptvwdqKY{IVl|Ey;N*IKPEdsY{*F)+mPf+}Z5CJ_e2qzUrO258a*bs`1Z z6iR?MstJHiKxzbnW Unit) { // client — Tailscale's login page cannot deep-link back to us itself). var openBrowserForLogin by remember { mutableStateOf(false) } + // Pick a folder from phone storage to serve as the webapp instead of the + // bundled one (which tsbridge then receives as a plain directory path). + val webappPicker = rememberLauncherForActivityResult( + ActivityResultContracts.OpenDocumentTree(), + ) { uri -> + if (uri != null) { + runCatching { + context.contentResolver.takePersistableUriPermission( + uri, + Intent.FLAG_GRANT_READ_URI_PERMISSION, + ) + } + settings = settings.copy(webappTreeUri = uri.toString()) + } + } + // Poll Status() every 1.5 s. Status is a JSON string (gomobile exposes no // structs across the boundary). LaunchedEffect(Unit) { @@ -282,6 +299,27 @@ private fun StatusScreen(onRequestNotifications: () -> Unit) { onCheckedChange = { settings = settings.copy(allowCors = it) }, ) } + Text("Webapp folder", style = MaterialTheme.typography.titleSmall) + Text( + if (settings.webappTreeUri.isBlank()) { + "Using the bundled webapp. Pick a folder from phone " + + "storage to serve a different webapp instead." + } else { + "Serving the picked folder (falls back to the bundled " + + "webapp if it can't be read)." + }, + style = MaterialTheme.typography.bodySmall, + ) + Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) { + OutlinedButton(onClick = { webappPicker.launch(null) }) { + Text("Choose folder…") + } + if (settings.webappTreeUri.isNotBlank()) { + OutlinedButton(onClick = { + settings = settings.copy(webappTreeUri = "") + }) { Text("Use bundled") } + } + } } } } diff --git a/app/src/main/java/com/tsbutt/app/SettingsStore.kt b/app/src/main/java/com/tsbutt/app/SettingsStore.kt index 80cc3fd..4e4ac10 100644 --- a/app/src/main/java/com/tsbutt/app/SettingsStore.kt +++ b/app/src/main/java/com/tsbutt/app/SettingsStore.kt @@ -27,6 +27,7 @@ data class Settings( val authKey: String, val intifaceUrl: String, val allowCors: Boolean, + val webappTreeUri: String = "", ) const val DEFAULT_INTIFACE_HOST = "localhost" @@ -103,6 +104,7 @@ class SettingsStore(private val store: KeyValueStore) { }, ), allowCors = store.getString(KEY_ALLOW_CORS, "false") == "true", + webappTreeUri = store.getString(KEY_WEBAPP_TREE_URI, ""), ) fun save(settings: Settings) { @@ -110,6 +112,7 @@ class SettingsStore(private val store: KeyValueStore) { store.putString(KEY_AUTH_KEY, settings.authKey.trim()) store.putString(KEY_INTIFACE_URL, settings.intifaceUrl.trim()) store.putString(KEY_ALLOW_CORS, settings.allowCors.toString()) + store.putString(KEY_WEBAPP_TREE_URI, settings.webappTreeUri) } companion object { @@ -118,6 +121,7 @@ class SettingsStore(private val store: KeyValueStore) { const val KEY_AUTH_KEY = "auth_key" const val KEY_INTIFACE_URL = "intiface_url" const val KEY_ALLOW_CORS = "allow_cors" + const val KEY_WEBAPP_TREE_URI = "webapp_tree_uri" // Pre-URL setting; read only for migration. const val KEY_INTIFACE_PORT = "intiface_port" diff --git a/app/src/main/java/com/tsbutt/app/WebappStore.kt b/app/src/main/java/com/tsbutt/app/WebappStore.kt new file mode 100644 index 0000000..c62a607 --- /dev/null +++ b/app/src/main/java/com/tsbutt/app/WebappStore.kt @@ -0,0 +1,139 @@ +package com.tsbutt.app + +import android.content.Context +import android.net.Uri +import android.provider.DocumentsContract +import java.io.File + +/** + * Resolves the directory tsbridge should serve as the webapp. + * + * By default the webapp bundled as APK assets (synced at build time from the + * repo's `webapp/` directory) is unpacked into app storage and served. If + * the user picked a folder from phone storage (a SAF tree URI), that + * folder's files are copied instead — copying rather than serving in place, + * because Go can only read real filesystem paths, not content:// URIs. The + * copy is refreshed on every service start so edits to the chosen folder are + * picked up. If the chosen folder can't be read, the bundled webapp is used + * as a fallback so the server never comes up without a UI. + */ +object WebappStore { + + fun bundledDir(context: Context): File = File(context.filesDir, "webapp") + + fun customDir(context: Context): File = File(context.filesDir, "webapp-custom") + + /** + * Returns the absolute path of a directory containing a webapp + * (index.html at its root) for [treeUriString]; empty means bundled. + */ + fun prepareWebappDir(context: Context, treeUriString: String): String { + val custom = treeUriString.isNotBlank() + val dest = if (custom) customDir(context) else bundledDir(context) + dest.deleteRecursively() + val copied = if (custom) { + runCatching { copyDocumentTree(context, Uri.parse(treeUriString), dest) } + .getOrElse { false } + } else { + copyBundledAssets(context, dest) + } + if (!copied) { + // The custom folder was unreadable (revoked permission, moved, + // deleted): fall back to the bundled webapp. + dest.deleteRecursively() + copyBundledAssets(context, dest) + } + return dest.absolutePath + } + + /** Copies the webapp synced into APK assets (assets/webapp/) to dest. */ + fun copyBundledAssets(context: Context, dest: File): Boolean { + val children = try { + context.assets.list("webapp") ?: return false + } catch (e: Exception) { + return false + } + dest.mkdirs() + for (child in children) { + if (!copyAssetPath(context, "webapp/$child", dest)) return false + } + return true + } + + private fun copyAssetPath(context: Context, assetPath: String, dest: File): Boolean { + val children = try { + context.assets.list(assetPath) + } catch (e: Exception) { + null + } + val name = assetPath.substringAfterLast('/') + if (children == null) return false + if (children.isEmpty()) { + // Assets have no empty directories, so this is a file. + return runCatching { + context.assets.open(assetPath).use { input -> + File(dest, name).outputStream().use { input.copyTo(it) } + } + }.isSuccess + } + val sub = File(dest, name) + sub.mkdirs() + for (child in children) { + if (!copyAssetPath(context, "$assetPath/$child", sub)) return false + } + return true + } + + /** Recursively copies a SAF document tree into dest. */ + fun copyDocumentTree(context: Context, treeUri: Uri, dest: File): Boolean { + val resolver = context.contentResolver + val rootDocId = DocumentsContract.getTreeDocumentId(treeUri) + val rootUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, rootDocId) + return copyDocumentRecursive(resolver, rootUri, dest) + } + + private fun copyDocumentRecursive( + resolver: android.content.ContentResolver, + dirUri: Uri, + dest: File, + ): Boolean { + if (!dest.mkdirs() && !dest.isDirectory) return false + val childrenUri = DocumentsContract.buildChildDocumentsUriUsingTree( + dirUri, + DocumentsContract.getDocumentId(dirUri), + ) + val projection = arrayOf( + DocumentsContract.Document.COLUMN_DISPLAY_NAME, + DocumentsContract.Document.COLUMN_MIME_TYPE, + DocumentsContract.Document.COLUMN_DOCUMENT_ID, + ) + return try { + resolver.query(childrenUri, projection, null, null, null)?.use { cursor -> + while (cursor.moveToNext()) { + val name = cursor.getString(0) ?: continue + val mime = cursor.getString(1) + val docId = cursor.getString(2) + val childUri = DocumentsContract.buildDocumentUriUsingTree(dirUri, docId) + if (mime == DocumentsContract.Document.MIME_TYPE_DIR) { + if (!copyDocumentRecursive(resolver, childUri, File(dest, name))) { + return false + } + } else { + val ok = runCatching { + resolver.openInputStream(childUri)?.use { input -> + File(dest, name).outputStream().use { output -> + input.copyTo(output) + true + } + } ?: false + }.getOrElse { false } + if (!ok) return false + } + } + true + } ?: false + } catch (e: Exception) { + false + } + } +} diff --git a/tsbridge/README.md b/tsbridge/README.md index 7684fc8..cf4db89 100644 --- a/tsbridge/README.md +++ b/tsbridge/README.md @@ -1,7 +1,13 @@ # tsbridge -Go module bound to Kotlin with gomobile. Serves the embedded webapp at `/` -and reverse-proxies WebSocket upgrades to Intiface Central on localhost. +Go module bound to Kotlin with gomobile. Serves a webapp directory over +HTTP (the repo's `webapp/` by default) and reverse-proxies WebSocket +upgrades to the configured Intiface Central WebSocket server. + +The webapp is **not** embedded here: the handler serves whatever directory +it is given (`-webapp` for the desktop runner; the Android app unpacks the +webapp bundled in its APK assets, or a folder the user picked from phone +storage), so the running webapp can be swapped without touching tsbridge. ## Android interface workaround (tailscale#17311) diff --git a/tsbridge/cmd/desktop/main.go b/tsbridge/cmd/desktop/main.go index 3bb4663..9d3d4f8 100644 --- a/tsbridge/cmd/desktop/main.go +++ b/tsbridge/cmd/desktop/main.go @@ -23,6 +23,7 @@ func main() { 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") + webappDir := flag.String("webapp", "webapp", "directory whose files are served as the webapp (must contain index.html; e.g. the repo's webapp/ directory)") flag.Parse() if *cors { @@ -50,7 +51,7 @@ func main() { } stateDir = filepath.Join(base, "tsbutt") } - if err := tsbridge.Start(stateDir, os.TempDir(), *hostname, *authKey, *tags, int32(*servePort), *intiface); err != nil { + if err := tsbridge.Start(stateDir, os.TempDir(), *hostname, *authKey, *tags, int32(*servePort), *intiface, *webappDir); err != nil { fmt.Fprintln(os.Stderr, "tsnet:", err) os.Exit(1) } @@ -73,7 +74,7 @@ func main() { } } - if err := tsbridge.ServePlain(*addr, *intiface); err != nil { + if err := tsbridge.ServePlain(*addr, *intiface, *webappDir); err != nil { fmt.Fprintln(os.Stderr, "server:", err) os.Exit(1) } diff --git a/tsbridge/server.go b/tsbridge/server.go index 6b463f7..7cc28bc 100644 --- a/tsbridge/server.go +++ b/tsbridge/server.go @@ -8,7 +8,6 @@ package tsbridge import ( - "embed" "encoding/json" "fmt" "io/fs" @@ -17,16 +16,15 @@ import ( "net/http" "net/http/httputil" "net/url" + "os" "path" + "path/filepath" "strings" "sync" "golang.org/x/net/http/httpguts" ) -//go:embed webapp -var webappFS embed.FS - // DefaultIntifaceTarget is the address used when nothing else is configured: // Intiface Central's default WebSocket server on localhost. const DefaultIntifaceTarget = "ws://localhost:12345" @@ -58,8 +56,11 @@ func mustMime(ext, typ string) { // // 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. -func newHandler(log *slog.Logger, intifaceTarget *url.URL) http.Handler { +// 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() @@ -67,7 +68,7 @@ func newHandler(log *slog.Logger, intifaceTarget *url.URL) http.Handler { mux := http.NewServeMux() mux.HandleFunc("/healthz", handleHealthz(intifaceTarget)) - mux.Handle("/", staticHandler()) + 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 @@ -150,31 +151,60 @@ func wsProxy(log *slog.Logger, intifaceTarget *url.URL) http.Handler { return rp } -func staticHandler() http.Handler { - sub, err := fs.Sub(webappFS, "webapp") +// 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 { - panic(fmt.Sprintf("embedded webapp missing: %v", err)) + 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 } - fileServer := http.FileServerFS(sub) 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") } - fileServer.ServeHTTP(w, r) + 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) error { +func ServePlain(addr string, intifaceTarget string, webappDir string) error { target, err := parseIntifaceTarget(intifaceTarget) if err != nil { return err } - srv := &http.Server{Addr: addr, Handler: newHandler(slog.Default(), target)} + 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 } diff --git a/tsbridge/server_test.go b/tsbridge/server_test.go index 1fba767..10fc90f 100644 --- a/tsbridge/server_test.go +++ b/tsbridge/server_test.go @@ -8,6 +8,8 @@ import ( "net" "net/http" "net/http/httptest" + "os" + "path/filepath" "strings" "testing" @@ -15,12 +17,17 @@ import ( ) func testHandler(t *testing.T, intifaceTarget string) http.Handler { + t.Helper() + return testHandlerWebapp(t, intifaceTarget, writeTestWebapp(t)) +} + +func testHandlerWebapp(t *testing.T, intifaceTarget, webappDir string) http.Handler { t.Helper() target, err := parseIntifaceTarget(intifaceTarget) if err != nil { t.Fatalf("parse intiface target %q: %v", intifaceTarget, err) } - return newHandler(slog.New(slog.DiscardHandler), target) + return newHandler(slog.New(slog.DiscardHandler), target, webappDir) } // wsTargetOf converts a mock upstream's http://127.0.0.1:PORT URL into the @@ -33,6 +40,26 @@ func wsTargetOf(t *testing.T, httpURL string) string { return "ws://" + strings.TrimPrefix(httpURL, "http://") } +// writeTestWebapp creates a minimal webapp directory for static-serving +// tests (the real webapp lives outside this module now). +func writeTestWebapp(t *testing.T) string { + t.Helper() + dir := t.TempDir() + if err := os.MkdirAll(filepath.Join(dir, "vendor"), 0o755); err != nil { + t.Fatalf("mkdir vendor: %v", err) + } + files := map[string]string{ + "index.html": "tsbutt test", + "vendor/buttplug.mjs": "export {};", + } + for name, content := range files { + if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil { + t.Fatalf("write %s: %v", name, err) + } + } + return dir +} + func TestStaticServing(t *testing.T) { srv := httptest.NewServer(testHandler(t, "")) defer srv.Close() @@ -249,7 +276,6 @@ func TestParseIntifaceTarget(t *testing.T) { func TestHealthz(t *testing.T) { srv := httptest.NewServer(testHandler(t, "")) defer srv.Close() - resp, err := http.Get(srv.URL + "/healthz") if err != nil { t.Fatalf("GET /healthz: %v", err) @@ -270,6 +296,41 @@ func TestHealthz(t *testing.T) { } } +func TestWebappDirValidation(t *testing.T) { + t.Run("missing dir and empty path are rejected", func(t *testing.T) { + if err := validateWebappDir(""); err == nil { + t.Error("validateWebappDir(\"\") = nil error, want rejection") + } + if err := validateWebappDir(filepath.Join(t.TempDir(), "nope")); err == nil { + t.Error("validateWebappDir(missing) = nil error, want rejection") + } + }) + t.Run("dir without index.html is rejected", func(t *testing.T) { + dir := t.TempDir() + if err := validateWebappDir(dir); err == nil { + t.Error("validateWebappDir(dir without index.html) = nil error, want rejection") + } + }) + t.Run("valid dir passes and serves", func(t *testing.T) { + dir := writeTestWebapp(t) + if err := validateWebappDir(dir); err != nil { + t.Fatalf("validateWebappDir(valid): %v", err) + } + // A handler pointed at a directory without index.html must 404 + // rather than serve a directory listing. + srv := httptest.NewServer(testHandlerWebapp(t, "", t.TempDir())) + defer srv.Close() + resp, err := http.Get(srv.URL + "/") + if err != nil { + t.Fatalf("GET /: %v", err) + } + resp.Body.Close() + if resp.StatusCode != http.StatusNotFound { + t.Errorf("GET / on an empty webapp dir: status = %d, want 404", resp.StatusCode) + } + }) +} + func TestPublicURL(t *testing.T) { tests := []struct { scheme, domain string diff --git a/tsbridge/tsnet.go b/tsbridge/tsnet.go index 9d5f25c..2e677e6 100644 --- a/tsbridge/tsnet.go +++ b/tsbridge/tsnet.go @@ -81,10 +81,11 @@ var ( // cacheDir is used as TMPDIR (Android has no /tmp). intifaceTarget is the // ws:// or wss:// URL of Intiface Central's WebSocket server (empty selects // ws://localhost:12345). servePort is the HTTPS port; use 443 (userspace -// netstack needs no privileges). Plain HTTP is served on port 80 alongside -// it, so http:/// works as well — the webapp picks ws:// or wss:// -// from the page's own scheme. -func Start(stateDir, cacheDir, hostname, authKey, tags string, servePort int32, intifaceTarget string) error { +// netstack needs no privileges). webappDir is the directory whose files are +// served as the webapp (must contain index.html; see validateWebappDir). +// Plain HTTP is served on port 80 alongside HTTPS, so http:/// works +// as well — the webapp picks ws:// or wss:// from the page's own scheme. +func Start(stateDir, cacheDir, hostname, authKey, tags string, servePort int32, intifaceTarget, webappDir string) error { if strings.TrimSpace(hostname) == "" { return errors.New("hostname must not be empty") } @@ -123,6 +124,10 @@ func Start(stateDir, cacheDir, hostname, authKey, tags string, servePort int32, mu.Unlock() return err } + if err := validateWebappDir(webappDir); err != nil { + mu.Unlock() + return err + } gen++ myGen := gen st = serverState{hostname: hostname} @@ -215,7 +220,7 @@ func Start(stateDir, cacheDir, hostname, authKey, tags string, servePort int32, } domain := domains[0] httpSrv := &http.Server{ - Handler: newHandler(nil, target), + Handler: newHandler(nil, target, webappDir), // Surface TLS handshake failures (bad cert, wrong SNI, …) in // the in-app status log instead of only logcat. ErrorLog: log.New(&captureWriter{capture}, "", 0), diff --git a/tsbridge/webapp/app.js b/webapp/app.js similarity index 100% rename from tsbridge/webapp/app.js rename to webapp/app.js diff --git a/tsbridge/webapp/index.html b/webapp/index.html similarity index 100% rename from tsbridge/webapp/index.html rename to webapp/index.html diff --git a/tsbridge/webapp/logic.js b/webapp/logic.js similarity index 100% rename from tsbridge/webapp/logic.js rename to webapp/logic.js diff --git a/tsbridge/webapp/style.css b/webapp/style.css similarity index 100% rename from tsbridge/webapp/style.css rename to webapp/style.css diff --git a/tsbridge/webapp/test.html b/webapp/test.html similarity index 100% rename from tsbridge/webapp/test.html rename to webapp/test.html diff --git a/tsbridge/webapp/vendor/buttplug.mjs b/webapp/vendor/buttplug.mjs similarity index 100% rename from tsbridge/webapp/vendor/buttplug.mjs rename to webapp/vendor/buttplug.mjs -- knotmirror 0.0.1