From 24c8ac9b37d602c97d55022789d256f0692f07b5 Mon Sep 17 00:00:00 2001 From: Jeff Casimir Date: Wed, 25 Nov 2026 08:00:03 -0700 Subject: [PATCH] Open the box's sign-in links in this machine's browser A Switchboard sign-in link copied out of the box's tmux lost its redirect_uri. Over ssh, work now takes the link from the box's BROWSER helper and opens it, if it is one of our sign-in pages. Co-Authored-By: Claude Opus 5.5 --- README.md | 5 +++ main.go | 19 ++++++++-- opener.go | 95 +++++++++++++++++++++++++++++++++++++++++++++++++ opener_test.go | 96 ++++++++++++++++++++++++++++++++++++++++++++++++++ 4 files changed, 212 insertions(+), 3 deletions(-) create mode 100644 opener.go create mode 100644 opener_test.go diff --git a/README.md b/README.md index ff86886..0062377 100644 --- a/README.md +++ b/README.md @@ -47,6 +47,11 @@ instead. - **Connect:** `et @ -c "tmux new-session -A -s work"`, falling back to `ssh -t`. +- **Sign-in links from the box:** over ssh, `work` opens them in this machine's + browser. The box's `BROWSER` helper posts the link to its localhost:3336, which + the connection forwards back here. Only https sign-in pages on a fixed list + (`opener.go`) are opened. Not over Eternal Terminal; the link is shown as usual. + ## Develop ```sh diff --git a/main.go b/main.go index a9d87c8..3fda0f3 100644 --- a/main.go +++ b/main.go @@ -183,12 +183,15 @@ func stayConnected(sshPath string, c connect) error { signal.Notify(sig, os.Interrupt) defer signal.Stop(sig) + openerPort, stopOpener := startOpener(openBrowser) + defer stopOpener() + everUp := false var offlineSince time.Time wait := reconnectWait for { start := time.Now() - cmd := exec.Command(sshPath, connectArgs("ssh", c)[1:]...) + cmd := exec.Command(sshPath, sshArgs(c, openerPort)[1:]...) cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr err := cmd.Run() var exit *exec.ExitError @@ -228,12 +231,22 @@ func connectArgs(tool string, c connect) []string { if tool == "et" { return []string{"et", "-t", mcpCallbackPort + ":" + mcpCallbackPort, target, "-c", attach} } - return []string{"ssh", "-t", + return sshArgs(c, "") +} + +// sshArgs is connectArgs for ssh; openerPort, when set, is the local port that +// opens the box's sign-in links (opener.go). +func sshArgs(c connect, openerPort string) []string { + args := []string{"ssh", "-t", // Notice a dead connection within ~45s instead of hanging on it. "-o", "ServerAliveInterval=15", "-o", "ServerAliveCountMax=3", // macOS: ask for the key's passphrase once and keep it in the Keychain. "-o", "IgnoreUnknown=UseKeychain", "-o", "UseKeychain=yes", "-o", "AddKeysToAgent=yes", - "-L", mcpCallbackPort + ":localhost:" + mcpCallbackPort, target, attach} + "-L", mcpCallbackPort + ":localhost:" + mcpCallbackPort} + if openerPort != "" { + args = append(args, "-R", "127.0.0.1:"+openPort+":127.0.0.1:"+openerPort) + } + return append(args, c.User+"@"+c.Host, "tmux new-session -A -s work") } func code(name, dir string) error { diff --git a/opener.go b/opener.go new file mode 100644 index 0000000..6d0e9cb --- /dev/null +++ b/opener.go @@ -0,0 +1,95 @@ +package main + +import ( + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "strconv" + "strings" + "sync" + "time" +) + +// A box has no browser for a person to sign in with, and a sign-in link copied +// out of its terminal is easily cut short (it wraps over several lines, and +// tmux hides that from the terminal). So `work` listens here, every ssh +// connection forwards the box's openPort back to it, and the box's BROWSER +// helper (server-admin dev/jmoses/bin/open-on-client) posts the link. +// +// Anything running on the box can post, so this opens sign-in pages only: +// https, an exact host, and that host's sign-in paths. Claude's own sign-in is +// left out on purpose: the link it hands a browser returns to a random localhost +// port that isn't forwarded; the short link it prints asks for a code instead. +const openPort = "3336" + +var signInPaths = map[string][]string{ + "my.jumpstartlab.com": {"/oauth/authorize"}, + "identity.jumpstartlab.com": {"/oauth/v2/authorize", "/device"}, +} + +// signInURL returns the normalized URL if it is a sign-in page we may open. +func signInURL(raw string) (string, bool) { + raw = strings.TrimSpace(raw) + if strings.ContainsAny(raw, " \t\r\n\\") { + return "", false + } + u, err := url.Parse(raw) + if err != nil || u.Scheme != "https" || u.User != nil || u.Opaque != "" { + return "", false + } + for _, p := range signInPaths[u.Host] { // exact: a port is part of Host + if u.EscapedPath() == p { + return u.String(), true + } + } + return "", false +} + +// openerHandler opens posted sign-in links, at most one every few seconds. The +// custom header keeps web pages in the local browser out: they cannot send it +// cross-origin without a preflight, which is refused. +func openerHandler(open func(string)) http.Handler { + var mu sync.Mutex + var last time.Time + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/open" || r.Header.Get("X-Work-Open") != "1" { + http.Error(w, "not found", http.StatusNotFound) + return + } + body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, 8192)) + if err != nil { + http.Error(w, "too large", http.StatusRequestEntityTooLarge) + return + } + u, ok := signInURL(string(body)) + if !ok { + http.Error(w, "not a sign-in page", http.StatusForbidden) + return + } + mu.Lock() + defer mu.Unlock() + if !last.IsZero() && time.Since(last) < 3*time.Second { + http.Error(w, "too soon", http.StatusTooManyRequests) + return + } + last = time.Now() + open(u) + w.WriteHeader(http.StatusNoContent) + }) +} + +// startOpener serves the opener on a free localhost port and returns the port, +// or "" when it can't: the box then shows the link as usual. +func startOpener(open func(string)) (string, func()) { + l, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + fmt.Fprintln(os.Stderr, "work: sign-in links from the box won't open by themselves:", err) + return "", func() {} + } + srv := &http.Server{Handler: openerHandler(open), ReadTimeout: 5 * time.Second, WriteTimeout: 5 * time.Second} + go func() { _ = srv.Serve(l) }() + return strconv.Itoa(l.Addr().(*net.TCPAddr).Port), func() { _ = srv.Close() } +} diff --git a/opener_test.go b/opener_test.go new file mode 100644 index 0000000..35ac4a8 --- /dev/null +++ b/opener_test.go @@ -0,0 +1,96 @@ +package main + +import ( + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestSignInURLAllowsOnlySignInPages(t *testing.T) { + for _, u := range []string{ + "https://my.jumpstartlab.com/oauth/authorize?client_id=1&redirect_uri=http%3A%2F%2Flocalhost%3A3335%2Fcallback", + "https://identity.jumpstartlab.com/device?user_code=ABCD", + "https://identity.jumpstartlab.com/oauth/v2/authorize?client_id=1\n", + } { + if got, ok := signInURL(u); !ok || got != strings.TrimSpace(u) { + t.Errorf("should open %q unchanged, got %q %v", u, got, ok) + } + } + for _, u := range []string{ + "https://claude.ai/oauth/authorize?abc", "https://claude.com/cai/oauth/authorize?code=true", + "", "file:///etc/passwd", "-a Calculator", "javascript:alert(1)", + "http://my.jumpstartlab.com/oauth/authorize", + "https://my.jumpstartlab.com/", "https://my.jumpstartlab.com/share/x", "https://my.jumpstartlab.com/oauth/authorize/../x", + "https://my.jumpstartlab.com/oauth/%61uthorize", + "https://my.jumpstartlab.com.evil.com/oauth/authorize", "https://evilmy.jumpstartlab.com/oauth/authorize", + "https://my.jumpstartlab.com:8443/oauth/authorize", "https://my.jumpstartlab.com@evil.com/oauth/authorize", + "https://x@my.jumpstartlab.com/oauth/authorize", `https://evil.com\@my.jumpstartlab.com/oauth/authorize`, + "https://my.jumpstartlab.com/oauth/authorize?a\nhttps://evil.com", + } { + if _, ok := signInURL(u); ok { + t.Errorf("should refuse %q", u) + } + } +} + +func TestOpenerServesOnlyTheHelper(t *testing.T) { + var opened []string + h := openerHandler(func(u string) { opened = append(opened, u) }) + const good = "https://my.jumpstartlab.com/oauth/authorize?client_id=1" + call := func(method, path, header, body string) int { + r := httptest.NewRequest(method, path, strings.NewReader(body)) + if header != "" { + r.Header.Set("X-Work-Open", header) + } + w := httptest.NewRecorder() + h.ServeHTTP(w, r) + return w.Code + } + for _, c := range []struct { + method, path, header, body string + want int + }{ + {"POST", "/open", "", good, http.StatusNotFound}, + {"GET", "/open", "1", good, http.StatusNotFound}, + {"OPTIONS", "/open", "", "", http.StatusNotFound}, + {"POST", "/other", "1", good, http.StatusNotFound}, + {"POST", "/open", "1", "https://evil.com/", http.StatusForbidden}, + {"POST", "/open", "1", good + strings.Repeat("a", 9000), http.StatusRequestEntityTooLarge}, + {"POST", "/open", "1", good, http.StatusNoContent}, + {"POST", "/open", "1", good, http.StatusTooManyRequests}, + } { + if got := call(c.method, c.path, c.header, c.body); got != c.want { + t.Errorf("%s %s header=%q: %d, want %d", c.method, c.path, c.header, got, c.want) + } + } + if len(opened) != 1 || opened[0] != good { + t.Fatalf("opened %v", opened) + } +} + +func TestStartOpenerListensOnLocalhost(t *testing.T) { + got := make(chan string, 1) + port, stop := startOpener(func(u string) { got <- u }) + defer stop() + r, _ := http.NewRequest("POST", "http://127.0.0.1:"+port+"/open", strings.NewReader("https://my.jumpstartlab.com/oauth/authorize?x")) + r.Header.Set("X-Work-Open", "1") + resp, err := http.DefaultClient.Do(r) + if err != nil || resp.StatusCode != http.StatusNoContent { + t.Fatalf("%v %v", resp, err) + } + if u := <-got; u != "https://my.jumpstartlab.com/oauth/authorize?x" { + t.Fatal(u) + } +} + +func TestSSHForwardsTheOpenerOnlyWhenItRuns(t *testing.T) { + c := connect{User: "guest", Host: "guest-vm"} + with := strings.Join(sshArgs(c, "50001"), " ") + if !strings.Contains(with, " -R 127.0.0.1:3336:127.0.0.1:50001 guest@guest-vm ") { + t.Fatalf("argv: %s", with) + } + if strings.Contains(strings.Join(sshArgs(c, ""), " "), "-R") { + t.Fatal("forwarded with no opener") + } +}