Skip to content

Agent Mesh

sam-one: a codespaces tunnel provider

Antonio Ojeabb11c1059c51
diff --git a/internal/tunnel/codespaces.go b/internal/tunnel/codespaces.go
new file mode 100644
index 00000000..feb97042
--- /dev/null
+++ b/internal/tunnel/codespaces.go
@@ -0,0 +1,179 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package tunnel
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "net/url"
+ "os"
+ "sync"
+ "time"
+)
+
+// Codespaces publishes the target on the https URL GitHub Codespaces assigns
+// to a forwarded port, https://<CODESPACE_NAME>-<port>.<forwarding domain>.
+// GitHub runs the forwarder, so nothing is started here and the URL is known
+// at once. A forwarded port is private to the codespace owner until they
+// make it public, and no API inside the codespace can do that; Open returns
+// immediately and a background probe reports whether the URL answers from
+// the internet, and what to click if it does not.
+type Codespaces struct {
+ // Getenv reads the platform variables; nil uses os.Getenv.
+ Getenv func(string) string
+ // Transport performs the probe requests; nil uses the default.
+ Transport http.RoundTripper
+ // ProbeTimeout bounds how long the probe waits for a first answer;
+ // defaults to 90s.
+ ProbeTimeout time.Duration
+ // ProbeInterval is the pause between probe requests; defaults to 2s.
+ ProbeInterval time.Duration
+}
+
+const (
+ codespaceNameEnv = "CODESPACE_NAME"
+ codespaceDomainEnv = "GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN"
+)
+
+// Name implements Provider.
+func (c *Codespaces) Name() string { return "codespaces" }
+
+// Open implements Provider.
+func (c *Codespaces) Open(ctx context.Context, target string) (Tunnel, error) {
+ getenv := c.Getenv
+ if getenv == nil {
+ getenv = os.Getenv
+ }
+ name, domain := getenv(codespaceNameEnv), getenv(codespaceDomainEnv)
+ if name == "" || domain == "" {
+ return nil, fmt.Errorf("not running in GitHub Codespaces (%s and %s are unset); behind another proxy pass --external-url", codespaceNameEnv, codespaceDomainEnv)
+ }
+ t, err := url.Parse(target)
+ if err != nil || t.Port() == "" {
+ return nil, fmt.Errorf("tunnel target %q has no port", target)
+ }
+ port := t.Port()
+ public := fmt.Sprintf("https://%s-%s.%s", name, port, domain)
+
+ probeCtx, cancel := context.WithCancel(context.Background())
+ tun := &static{url: public, cancel: cancel, done: make(chan struct{})}
+ go c.watch(probeCtx, public, name, port)
+ return tun, nil
+}
+
+// watch tells the operator how the public URL answers: at once when the
+// port is public, and with the visibility hint when GitHub answers in place
+// of the mesh. After the hint it keeps waiting, so flipping the port in the
+// PORTS panel is confirmed in the log.
+func (c *Codespaces) watch(ctx context.Context, public, name, port string) {
+ timeout := c.ProbeTimeout
+ if timeout <= 0 {
+ timeout = 90 * time.Second
+ }
+ switch c.probe(ctx, public, time.Now().Add(timeout), true) {
+ case probeReachable:
+ logger.Infof("%s answers from the internet; devices can enroll", public)
+ case probePrivate:
+ logger.Warnf("GitHub answers for %s: port %s is private, so only your own browser can open it. "+
+ "To let devices enroll, make it public: PORTS tab -> right-click %s -> Port Visibility -> Public "+
+ "(or `gh codespace ports visibility %s:public -c %s`)", public, port, port, port, name)
+ if c.probe(ctx, public, time.Time{}, false) == probeReachable {
+ logger.Infof("%s answers from the internet; devices can enroll", public)
+ }
+ case probeTimeout:
+ logger.Warnf("%s did not answer within %s; check the PORTS tab lists port %s and forwards it", public, timeout, port)
+ }
+}
+
+type probeOutcome int
+
+const (
+ probeReachable probeOutcome = iota
+ probePrivate
+ probeTimeout
+ probeCancelled
+)
+
+// probe requests /healthz on base until the mesh answers 200 through the
+// proxy, deadline passes (zero means never) or ctx ends. A redirect or an
+// authentication status is GitHub's login gate, reported as probePrivate
+// when stopOnPrivate is set and otherwise waited out like any other answer.
+func (c *Codespaces) probe(ctx context.Context, base string, deadline time.Time, stopOnPrivate bool) probeOutcome {
+ interval := c.ProbeInterval
+ if interval <= 0 {
+ interval = 2 * time.Second
+ }
+ client := &http.Client{
+ Transport: c.Transport,
+ Timeout: 5 * time.Second,
+ // The redirect target is GitHub's login page; following it would
+ // report the gate as a healthy answer.
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ }
+ for {
+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, base+"/healthz", nil)
+ if err != nil {
+ return probeTimeout
+ }
+ resp, err := client.Do(req)
+ if err == nil {
+ _ = resp.Body.Close()
+ switch {
+ case resp.StatusCode == http.StatusOK:
+ return probeReachable
+ case stopOnPrivate && isLoginGate(resp.StatusCode):
+ return probePrivate
+ }
+ }
+ if !deadline.IsZero() && time.Now().After(deadline) {
+ return probeTimeout
+ }
+ select {
+ case <-ctx.Done():
+ return probeCancelled
+ case <-time.After(interval):
+ }
+ }
+}
+
+// isLoginGate reports whether status is what GitHub's proxy returns for a
+// private port to a client without a session: a redirect to the login page
+// or an authentication failure. Gateway errors mean the mesh is not
+// listening yet and are not a verdict on visibility.
+func isLoginGate(status int) bool {
+ return (status >= 300 && status < 400) || status == http.StatusUnauthorized || status == http.StatusForbidden
+}
+
+// static is a Tunnel whose forwarder is run by the platform: it never
+// fails on its own and lives until Close.
+type static struct {
+ url string
+ cancel context.CancelFunc
+ done chan struct{}
+ once sync.Once
+}
+
+func (s *static) URL() string { return s.url }
+func (s *static) Done() <-chan struct{} { return s.done }
+func (s *static) Err() error { return nil }
+
+func (s *static) Close() error {
+ s.once.Do(func() {
+ s.cancel()
+ close(s.done)
+ })
+ return nil
+}
diff --git a/internal/tunnel/codespaces_test.go b/internal/tunnel/codespaces_test.go
new file mode 100644
index 00000000..24f7cbf4
--- /dev/null
+++ b/internal/tunnel/codespaces_test.go
@@ -0,0 +1,180 @@
+// Copyright 2026 Google LLC
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+package tunnel
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+)
+
+func codespaceEnv(name, domain string) func(string) string {
+ return func(key string) string {
+ switch key {
+ case codespaceNameEnv:
+ return name
+ case codespaceDomainEnv:
+ return domain
+ }
+ return ""
+ }
+}
+
+// rewriteTo sends every request to the test server standing in for GitHub's
+// proxy, whatever host the request names.
+type rewriteTo string
+
+func (r rewriteTo) RoundTrip(req *http.Request) (*http.Response, error) {
+ u, err := url.Parse(string(r))
+ if err != nil {
+ return nil, err
+ }
+ req = req.Clone(req.Context())
+ req.URL.Scheme, req.URL.Host = u.Scheme, u.Host
+ return http.DefaultTransport.RoundTrip(req)
+}
+
+// scriptedProxy answers /healthz with the given statuses in order and the
+// last one forever after, counting requests.
+func scriptedProxy(t *testing.T, statuses ...int) (*httptest.Server, *atomic.Int32) {
+ t.Helper()
+ var n atomic.Int32
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.URL.Path != "/healthz" {
+ t.Errorf("probe requested %s, want /healthz", r.URL.Path)
+ }
+ i := int(n.Add(1)) - 1
+ if i >= len(statuses) {
+ i = len(statuses) - 1
+ }
+ if statuses[i] >= 300 && statuses[i] < 400 {
+ w.Header().Set("Location", "https://github.com/login")
+ }
+ w.WriteHeader(statuses[i])
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &n
+}
+
+func TestCodespacesOpenDerivesURLFromPlatformEnv(t *testing.T) {
+ c := &Codespaces{
+ Getenv: codespaceEnv("octocat-sam-abc123", "app.github.dev"),
+ Transport: rewriteTo("http://127.0.0.1:0"),
+ ProbeTimeout: 10 * time.Millisecond,
+ }
+ tun, err := c.Open(context.Background(), "http://127.0.0.1:8080")
+ if err != nil {
+ t.Fatalf("Open: %v", err)
+ }
+ if got, want := tun.URL(), "https://octocat-sam-abc123-8080.app.github.dev"; got != want {
+ t.Fatalf("URL = %q, want %q", got, want)
+ }
+ select {
+ case <-tun.Done():
+ t.Fatal("Done closed before Close")
+ default:
+ }
+ if err := tun.Close(); err != nil {
+ t.Fatalf("Close: %v", err)
+ }
+ if err := tun.Close(); err != nil {
+ t.Fatalf("second Close: %v", err)
+ }
+ select {
+ case <-tun.Done():
+ case <-time.After(time.Second):
+ t.Fatal("Done not closed after Close")
+ }
+ if tun.Err() != nil {
+ t.Fatalf("Err = %v after Close, want nil", tun.Err())
+ }
+}
+
+func TestCodespacesOpenRejectsOtherPlatforms(t *testing.T) {
+ for name, getenv := range map[string]func(string) string{
+ "no env": codespaceEnv("", ""),
+ "name only": codespaceEnv("octocat-sam-abc123", ""),
+ "domain only": codespaceEnv("", "app.github.dev"),
+ } {
+ t.Run(name, func(t *testing.T) {
+ c := &Codespaces{Getenv: getenv}
+ if _, err := c.Open(context.Background(), "http://127.0.0.1:8080"); err == nil || !strings.Contains(err.Error(), codespaceNameEnv) {
+ t.Fatalf("Open error = %v, want one naming %s", err, codespaceNameEnv)
+ }
+ })
+ }
+ c := &Codespaces{Getenv: codespaceEnv("octocat-sam-abc123", "app.github.dev")}
+ if _, err := c.Open(context.Background(), "http://127.0.0.1"); err == nil {
+ t.Fatal("Open accepted a target without a port")
+ }
+}
+
+func TestCodespacesProbeWaitsForTheMeshBehindThePublicPort(t *testing.T) {
+ // 502 is what the proxy returns while sam-one is still binding.
+ proxy, n := scriptedProxy(t, http.StatusBadGateway, http.StatusBadGateway, http.StatusOK)
+ c := &Codespaces{Transport: rewriteTo(proxy.URL), ProbeInterval: time.Millisecond}
+ if got := c.probe(context.Background(), "https://name-8080.app.github.dev", time.Now().Add(5*time.Second), true); got != probeReachable {
+ t.Fatalf("probe = %v, want probeReachable", got)
+ }
+ if n.Load() != 3 {
+ t.Fatalf("probe made %d requests, want 3", n.Load())
+ }
+}
+
+func TestCodespacesProbeReportsGitHubLoginGateOnce(t *testing.T) {
+ proxy, n := scriptedProxy(t, http.StatusFound, http.StatusUnauthorized, http.StatusOK)
+ c := &Codespaces{Transport: rewriteTo(proxy.URL), ProbeInterval: time.Millisecond}
+ if got := c.probe(context.Background(), "https://name-8080.app.github.dev", time.Now().Add(5*time.Second), true); got != probePrivate {
+ t.Fatalf("first probe = %v, want probePrivate", got)
+ }
+ if n.Load() != 1 {
+ t.Fatalf("private verdict took %d requests, want 1", n.Load())
+ }
+ // Once reported, the gate is waited out until the operator flips the port.
+ if got := c.probe(context.Background(), "https://name-8080.app.github.dev", time.Time{}, false); got != probeReachable {
+ t.Fatalf("second probe = %v, want probeReachable", got)
+ }
+ if n.Load() != 3 {
+ t.Fatalf("probe made %d requests in total, want 3", n.Load())
+ }
+}
+
+func TestCodespacesProbeGivesUpAtDeadlineAndOnCancel(t *testing.T) {
+ proxy, _ := scriptedProxy(t, http.StatusBadGateway)
+ c := &Codespaces{Transport: rewriteTo(proxy.URL), ProbeInterval: time.Millisecond}
+ if got := c.probe(context.Background(), "https://name-8080.app.github.dev", time.Now().Add(20*time.Millisecond), true); got != probeTimeout {
+ t.Fatalf("probe = %v, want probeTimeout", got)
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ cancel()
+ if got := c.probe(ctx, "https://name-8080.app.github.dev", time.Time{}, true); got != probeCancelled {
+ t.Fatalf("probe = %v, want probeCancelled", got)
+ }
+}
+
+func TestLookupKnowsCodespaces(t *testing.T) {
+ p, err := Lookup("codespaces")
+ if err != nil {
+ t.Fatalf("Lookup: %v", err)
+ }
+ if _, ok := p.(*Codespaces); !ok || p.Name() != "codespaces" {
+ t.Fatalf("Lookup returned %T named %q", p, p.Name())
+ }
+}
diff --git a/internal/tunnel/tunnel.go b/internal/tunnel/tunnel.go
index 31024bca..166c0e0a 100644
--- a/internal/tunnel/tunnel.go
+++ b/internal/tunnel/tunnel.go
@@ -15,8 +15,9 @@
// Package tunnel publishes a local HTTP listener on a public https URL
// through a third-party connector, so devices that cannot route to the host
// (a phone on cellular, a laptop on another network) can still enroll and
-// join the mesh. Providers wrap external programs; the mesh only learns the
-// resulting URL, which it advertises exactly like a configured external URL.
+// join the mesh. Providers wrap external programs, or name a forwarder the
+// hosting platform already runs; the mesh only learns the resulting URL,
+// which it advertises exactly like a configured external URL.
package tunnel
import (
@@ -49,6 +50,7 @@ type Provider interface {
var providers = map[string]func() Provider{
"cloudflare": func() Provider { return &Cloudflare{} },
+ "codespaces": func() Provider { return &Codespaces{} },
}
// Names lists the registered providers.
diff --git a/site/content/docs/reference/sam-one.md b/site/content/docs/reference/sam-one.md
index 82a29ad4..ccfd2c7d 100644
--- a/site/content/docs/reference/sam-one.md
+++ b/site/content/docs/reference/sam-one.md
@@ -28,7 +28,7 @@ downloaded tunnel connector.
| `--bind-address` | `0.0.0.0` | Host to bind. |
| `--port` | `0` | TCP port. `0` picks a free one and prints it in the banner. |
| `--external-url` | | Public URL on which nodes reach this instance, for a reverse proxy or a hosted platform. Can also be set with `SAM_EXTERNAL_URL`. When omitted behind an HTTPS proxy (Cloud Run, Fly.io), `/info` infers the advertised `wss` address from the incoming `Host` / `X-Forwarded-Proto` headers automatically. |
-| `--tunnel` | | Publish the port through a tunnel provider and use the resulting URL as the external URL. The provider is `cloudflare` (defaults to a free quick tunnel on `*.trycloudflare.com`, no account needed). |
+| `--tunnel` | | Publish the port through a tunnel provider and use the resulting URL as the external URL. Providers: `cloudflare` (a free quick tunnel on `*.trycloudflare.com` by default, no account needed) and `codespaces` (the `https` URL GitHub Codespaces assigns to the forwarded port, read from `CODESPACE_NAME` and `GITHUB_CODESPACES_PORT_FORWARDING_DOMAIN`; nothing is started, and the log reports whether the port answers from the internet). |
| `--tunnel-token-path` | | File containing the tunnel provider authentication token (can also be set with `SAM_TUNNEL_TOKEN`). Use together with `--tunnel <provider> --external-url https://mesh.example.com` for a permanent custom domain. |
| `--tunnel-install` | `false` | Download the pinned, digest-verified `cloudflared` into `<data-dir>/bin` without asking. Implies acceptance of its license. |
| `--cloudflared-path` | `PATH`, then `<data-dir>/bin` | Explicit connector binary. |
@@ -106,6 +106,9 @@ The subcommands talk to a running instance over its HTTP API. Shared flags:
- **A laptop behind NAT**: `--tunnel cloudflare` gives a temporary `https`
hostname. See [your own mesh](../../getting-started/your-own-mesh/).
+- **A GitHub codespace**: `--port 8080 --tunnel codespaces` advertises the
+ codespace's forwarded-port URL. The port must be public for devices to
+ reach it. See the [Codespaces guide](../../guides/codespaces/).
- **A host with a name**: `--port 8080 --external-url https://mesh.example.com`
behind a reverse proxy that forwards WebSockets.
- **Cloud Run**: pinned `SAM_TOKEN` and `SAM_ADMIN_TOKEN`, one instance, no