Skip to content

Agent Mesh

feat(sam-one): zero-config cloud deploy, link-local filtering, and developer-oriented URL docs

Antonio Ojea898f935dac29
diff --git a/cmd/sam-one/main.go b/cmd/sam-one/main.go
index 0eeebb0f..65b98e9a 100644
--- a/cmd/sam-one/main.go
+++ b/cmd/sam-one/main.go
@@ -55,6 +55,7 @@ func main() {
allowedAudiencesFlag string
logLevel string
tunnelProvider string
+ tunnelTokenPath string
tunnelInstall bool
cloudflaredPath string
enrollQR bool
@@ -98,6 +99,10 @@ func main() {
if err != nil {
logger.Fatalf("Invalid --admin-token-path: %v", err)
}
+ tunnelToken, err := secretFromPathOrEnv(tunnelTokenPath, "CLOUDFLARE_TUNNEL_TOKEN")
+ if err != nil {
+ logger.Fatalf("Invalid --tunnel-token-path: %v", err)
+ }
if externalURL == "" {
externalURL = os.Getenv("SAM_EXTERNAL_URL")
}
@@ -114,8 +119,11 @@ func main() {
// port settled now rather than at bind time.
var tun tunnel.Tunnel
if tunnelProvider != "" {
- if externalURL != "" {
- logger.Fatal("--tunnel and --external-url are mutually exclusive: the tunnel provides the external URL")
+ if tunnelToken == "" && externalURL != "" {
+ logger.Fatal("--tunnel and --external-url are mutually exclusive unless --tunnel-token-path / CLOUDFLARE_TUNNEL_TOKEN is set")
+ }
+ if tunnelToken != "" && externalURL == "" {
+ logger.Fatal("--tunnel-token-path / CLOUDFLARE_TUNNEL_TOKEN requires --external-url (the public https:// hostname routed to the named tunnel)")
}
if port == 0 {
var err error
@@ -131,6 +139,8 @@ func main() {
dataDir: dataDir,
cloudflaredPath: cloudflaredPath,
install: tunnelInstall,
+ token: tunnelToken,
+ externalURL: externalURL,
}); err != nil {
logger.Fatalf("Failed to open tunnel: %v", err)
}
@@ -202,6 +212,7 @@ func main() {
rootCmd.Flags().StringVar(&allowedAudiencesFlag, "allowed-audiences", api.DefaultAudience, "Comma-separated list of allowed OIDC audiences")
rootCmd.Flags().StringVar(&logLevel, "log-level", "", "Log level: debug, info, warn, error")
rootCmd.Flags().StringVar(&tunnelProvider, "tunnel", "", "Publish the listener on a public URL through a tunnel provider ("+strings.Join(tunnel.Names(), ", ")+"); sets the external URL")
+ rootCmd.Flags().StringVar(&tunnelTokenPath, "tunnel-token-path", "", "File containing a Cloudflare Named Tunnel token (or env CLOUDFLARE_TUNNEL_TOKEN); use with --tunnel cloudflare --external-url https://...")
rootCmd.Flags().BoolVar(&tunnelInstall, "tunnel-install", false, "Download the pinned connector binary (cloudflared "+tunnel.CloudflaredVersion+", digest-verified) into <data-dir>/bin without asking; implies accepting its license")
rootCmd.Flags().StringVar(&cloudflaredPath, "cloudflared-path", "", "Explicit cloudflared executable for --tunnel cloudflare (default: PATH, then <data-dir>/bin)")
rootCmd.Flags().BoolVar(&enrollQR, "enroll-qr", stdoutIsTerminal(), "Print a device enrollment QR code at startup (default: when stdout is a terminal)")
@@ -304,6 +315,8 @@ type tunnelOptions struct {
dataDir string
cloudflaredPath string
install bool
+ token string
+ externalURL string
}
// openTunnel publishes the listener that Start is about to bind. The
@@ -317,6 +330,8 @@ func openTunnel(ctx context.Context, o tunnelOptions) (tunnel.Tunnel, error) {
cf.Binary = o.cloudflaredPath
cf.InstallDir = filepath.Join(o.dataDir, "bin")
cf.Consent = installConsent(o.install)
+ cf.Token = o.token
+ cf.ExternalURL = o.externalURL
}
host := o.bindAddress
if ip := net.ParseIP(host); host == "" || (ip != nil && ip.IsUnspecified()) {
diff --git a/deploy/fly/fly.toml b/deploy/fly/fly.toml
new file mode 100644
index 00000000..bc85c233
--- /dev/null
+++ b/deploy/fly/fly.toml
@@ -0,0 +1,44 @@
+# Fly.io blueprint for running a persistent standalone SAM mesh (sam-one).
+#
+# Deploy in one command:
+# fly launch --copy-config --config deploy/fly/fly.toml --ha=false
+# fly logs
+#
+# What you get automatically:
+# - Public HTTPS + WebSocket URL: https://<your-app-name>.fly.dev
+# - 1 GB persistent volume mounted at /data (preserves SQLite DB, router PeerID,
+# join-token, and admin-token across restarts)
+# - Automatic /info wss:// address discovery from the Fly.io Host header
+# - Startup banner in `fly logs` with your URL, Admin Token, and Join Token
+
+app = "sam-one-hub"
+primary_region = "ord"
+
+[build]
+ image = "ghcr.io/google/sam-one:latest"
+
+[env]
+ PORT = "8080"
+
+[[mounts]]
+ source = "sam_data"
+ destination = "/data"
+ initial_size = "1gb"
+
+[http_service]
+ internal_port = 8080
+ force_https = true
+ auto_stop_machines = "off"
+ auto_start_machines = true
+ min_machines_running = 1
+
+ [[http_service.checks]]
+ interval = "15s"
+ timeout = "5s"
+ grace_period = "10s"
+ method = "GET"
+ path = "/readyz"
+
+[[vm]]
+ size = "shared-cpu-1x"
+ memory = "512mb"
diff --git a/deploy/skypilot/sam-one.yaml b/deploy/skypilot/sam-one.yaml
new file mode 100644
index 00000000..450209de
--- /dev/null
+++ b/deploy/skypilot/sam-one.yaml
@@ -0,0 +1,65 @@
+# SkyPilot recipe for running a standalone SAM control plane + router (sam-one)
+# on the cheapest or Always-Free tier VM in your cloud account (GCP, AWS,
+# Azure, OCI, or Kubernetes).
+#
+# Quick start (free TryCloudflare HTTPS tunnel, zero DNS/TLS/firewall setup):
+# sky launch -y -c sam-hub deploy/skypilot/sam-one.yaml --detach-run
+# sky logs sam-hub 1 --no-follow
+#
+# The startup banner in `sky logs sam-hub 1 --no-follow` prints:
+# - API URL: https://<name>.trycloudflare.com
+# - Web Console: https://<name>.trycloudflare.com/console
+# - Admin Token & Join Token
+# - The exact `sam-node join <URL>` command and mobile QR code
+#
+# Optional: For a permanent custom domain ($0/mo Cloudflare Named Tunnel), pass:
+# sky launch -y -c sam-hub deploy/skypilot/sam-one.yaml --detach-run \
+# --env SAM_EXTERNAL_URL=https://mesh.example.com \
+# --secret CLOUDFLARE_TUNNEL_TOKEN
+
+name: sam-hub
+
+resources:
+ cpus: 0.25+
+ memory: 1+
+ disk_size: 10
+ use_spot: false
+
+envs:
+ SAM_EXTERNAL_URL: ""
+
+secrets:
+ CLOUDFLARE_TUNNEL_TOKEN: ""
+
+setup: |
+ set -euo pipefail
+ if ! command -v sam-one >/dev/null 2>&1; then
+ ARCH="$(uname -m)"
+ case "${ARCH}" in
+ x86_64*) ARCH_NAME="x86_64" ;;
+ aarch64*|arm64*) ARCH_NAME="arm64" ;;
+ *) echo "Unsupported architecture: ${ARCH}" >&2; exit 1 ;;
+ esac
+ VERSION=$(curl -fsSL "https://api.github.com/repos/google/sam/releases?per_page=1" | grep '"tag_name":' | head -n 1 | sed -E 's/.*"([^"]+)".*/\1/')
+ TMP_DIR=$(mktemp -d)
+ curl -fsSL -o "${TMP_DIR}/sam.tar.gz" "https://github.com/google/sam/releases/download/${VERSION}/sam_Linux_${ARCH_NAME}.tar.gz"
+ tar -xzf "${TMP_DIR}/sam.tar.gz" -C "${TMP_DIR}"
+ sudo mv "${TMP_DIR}/sam-one" "${TMP_DIR}/sam-node" /usr/local/bin/
+ rm -rf "${TMP_DIR}"
+ fi
+
+run: |
+ set -euo pipefail
+ mkdir -p "${HOME}/sam-one"
+
+ ARGS=(
+ --data-dir "${HOME}/sam-one"
+ --port 8080
+ --tunnel cloudflare
+ --tunnel-install
+ )
+ if [[ -n "${SAM_EXTERNAL_URL:-}" ]]; then
+ ARGS+=(--external-url "${SAM_EXTERNAL_URL}")
+ fi
+
+ exec sam-one "${ARGS[@]}"
diff --git a/internal/router/router.go b/internal/router/router.go
index 425b4a90..e2be378c 100644
--- a/internal/router/router.go
+++ b/internal/router/router.go
@@ -358,14 +358,15 @@ func (r *Router) Start() error {
libp2p.EnableAutoNATv2(),
libp2p.EnableNATService(),
libp2p.AddrsFactory(func(addrs []multiaddr.Multiaddr) []multiaddr.Multiaddr {
- if r.config.AllowLoopback {
- return addrs
- }
var filtered []multiaddr.Multiaddr
for _, addr := range addrs {
- if !isLoopbackOrLinkLocal(addr) {
- filtered = append(filtered, addr)
+ if isLinkLocal(addr) {
+ continue
}
+ if !r.config.AllowLoopback && isLoopbackOrLinkLocal(addr) {
+ continue
+ }
+ filtered = append(filtered, addr)
}
return filtered
}),
@@ -1361,6 +1362,22 @@ func getOrGeneratePeerKey(keyPath string) (crypto.PrivKey, error) {
return priv, nil
}
+func isLinkLocal(addr multiaddr.Multiaddr) bool {
+ for _, proto := range addr.Protocols() {
+ if proto.Code == multiaddr.P_IP4 || proto.Code == multiaddr.P_IP6 {
+ value, err := addr.ValueForProtocol(proto.Code)
+ if err == nil {
+ if ip := net.ParseIP(value); ip != nil {
+ if ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() {
+ return true
+ }
+ }
+ }
+ }
+ }
+ return false
+}
+
func isLoopbackOrLinkLocal(addr multiaddr.Multiaddr) bool {
for _, proto := range addr.Protocols() {
if proto.Code == multiaddr.P_IP4 || proto.Code == multiaddr.P_IP6 {
diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.go
index 1578b32e..8762b5b0 100644
--- a/internal/standalone/standalone.go
+++ b/internal/standalone/standalone.go
@@ -21,6 +21,7 @@
package standalone
import (
+ "bytes"
"context"
"crypto/rand"
"crypto/sha256"
@@ -28,6 +29,7 @@ import (
"fmt"
"net"
"net/http"
+ "net/http/httptest"
"net/url"
"os"
"path/filepath"
@@ -40,8 +42,10 @@ import (
"github.com/google/sam/internal/router"
"github.com/google/sam/internal/storage"
golog "github.com/ipfs/go-log/v2"
+ "github.com/libp2p/go-libp2p/core/crypto"
"github.com/multiformats/go-multiaddr"
"google.golang.org/protobuf/encoding/protojson"
+ "google.golang.org/protobuf/proto"
)
var logger = golog.Logger("sam-one")
@@ -329,12 +333,17 @@ func (s *Server) Start(ctx context.Context) error {
externalAddrs = []string{ext}
}
+ routerKeyPath := filepath.Join(s.opts.DataDir, routerKeyFile)
+ if err := ensureRouterKey(routerKeyPath, s.opts.AdminToken); err != nil {
+ return fmt.Errorf("failed to provision router key: %w", err)
+ }
+
rtr, err := router.NewRouter(ctx, router.Options{
ControlPlaneURL: "http://" + cp.Addr(),
ListenAddrs: append([]string{wsAddr}, s.opts.P2PListen...),
ExternalAddrs: externalAddrs,
AllowLoopback: !s.opts.Router.DisallowLoopback,
- KeysDBPath: filepath.Join(s.opts.DataDir, routerKeyFile),
+ KeysDBPath: routerKeyPath,
BootstrapToken: routerToken,
KeysSyncInterval: s.opts.Router.KeysSyncInterval,
LeaseRenewInterval: s.opts.Router.LeaseRenewInterval,
@@ -347,7 +356,7 @@ func (s *Server) Start(ctx context.Context) error {
// source IPs; libp2p's default 8-conns-per-IP cap would throttle
// the whole listener.
ConnsPerSourceIP: s.opts.Router.ConnsPerSourceIP,
- HTTPFallbackHandler: mux,
+ HTTPFallbackHandler: s.wrapPublicHTTPHandler(mux),
})
if err != nil {
return fmt.Errorf("failed to create router: %w", err)
@@ -634,3 +643,178 @@ func externalMultiaddr(rawURL string) (string, error) {
}
return addr, nil
}
+
+// ensureRouterKey seeds router.key deterministically from an operator-supplied
+// adminToken when no router.key file exists on disk yet. On stateless
+// single-container platforms (e.g. Cloud Run) where /data is ephemeral and
+// SAM_ADMIN_TOKEN is pinned via environment variable, this keeps the embedded
+// router's libp2p PeerID stable across container restarts without extra config.
+func ensureRouterKey(keyPath, adminToken string) error {
+ if _, err := os.Stat(keyPath); err == nil {
+ return nil
+ } else if !os.IsNotExist(err) {
+ return err
+ }
+ if strings.TrimSpace(adminToken) == "" {
+ return nil
+ }
+ seed := sha256.Sum256([]byte("sam-one-router-ed25519-v1:" + strings.TrimSpace(adminToken)))
+ priv, _, err := crypto.GenerateEd25519Key(bytes.NewReader(seed[:]))
+ if err != nil {
+ return err
+ }
+ data, err := crypto.MarshalPrivateKey(priv)
+ if err != nil {
+ return err
+ }
+ if err := os.MkdirAll(filepath.Dir(keyPath), 0o755); err != nil {
+ return err
+ }
+ return os.WriteFile(keyPath, data, 0o600)
+}
+
+// wrapPublicHTTPHandler augments control-plane endpoints that return
+// RouterAddresses (/info, /enroll, /enroll/status, /enroll/oidc, /refresh) on
+// the public listener when no explicit --external-url was configured: it
+// derives the router's public ws/wss multiaddr from the incoming request's
+// Host / X-Forwarded-Host and X-Forwarded-Proto headers so single-step PaaS
+// deployments (Cloud Run, Fly.io, Render) advertise a dialable wss multiaddr
+// without a second deploy pass.
+func (s *Server) wrapPublicHTTPHandler(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if s.opts.ExternalURL != "" || s.router == nil || !returnsRouterAddresses(r.URL.Path) {
+ next.ServeHTTP(w, r)
+ return
+ }
+ inferredAddr, ok := inferredRequestMultiaddr(r, s.PeerID())
+ if !ok {
+ next.ServeHTTP(w, r)
+ return
+ }
+ rec := httptest.NewRecorder()
+ next.ServeHTTP(rec, r)
+ for k, vals := range rec.Header() {
+ for _, v := range vals {
+ w.Header().Add(k, v)
+ }
+ }
+ if rec.Code != http.StatusOK {
+ w.WriteHeader(rec.Code)
+ _, _ = w.Write(rec.Body.Bytes())
+ return
+ }
+ out, ok := prependInferredRouterAddr(r.URL.Path, rec.Body.Bytes(), inferredAddr)
+ if !ok {
+ w.WriteHeader(rec.Code)
+ _, _ = w.Write(rec.Body.Bytes())
+ return
+ }
+ w.Header().Set("Content-Type", "application/x-protobuf")
+ w.WriteHeader(http.StatusOK)
+ _, _ = w.Write(out)
+ })
+}
+
+func returnsRouterAddresses(path string) bool {
+ switch path {
+ case "/info", "/enroll", "/enroll/status", "/enroll/oidc", "/refresh":
+ return true
+ default:
+ return false
+ }
+}
+
+func prependInferredRouterAddr(path string, body []byte, inferredAddr string) ([]byte, bool) {
+ prepend := func(existing []string) []string {
+ out := make([]string, 0, len(existing)+1)
+ out = append(out, inferredAddr)
+ for _, a := range existing {
+ if a != inferredAddr {
+ out = append(out, a)
+ }
+ }
+ return out
+ }
+ switch path {
+ case "/info":
+ var msg api.ControlPlaneInfoResponse
+ if err := proto.Unmarshal(body, &msg); err != nil {
+ return nil, false
+ }
+ msg.RouterAddresses = prepend(msg.RouterAddresses)
+ b, err := proto.Marshal(&msg)
+ return b, err == nil
+ case "/enroll", "/enroll/status":
+ var msg api.BootstrapEnrollResponse
+ if err := proto.Unmarshal(body, &msg); err != nil {
+ return nil, false
+ }
+ msg.RouterAddresses = prepend(msg.RouterAddresses)
+ b, err := proto.Marshal(&msg)
+ return b, err == nil
+ case "/enroll/oidc", "/refresh":
+ var msg api.EnrollResponse
+ if err := proto.Unmarshal(body, &msg); err != nil {
+ return nil, false
+ }
+ msg.RouterAddresses = prepend(msg.RouterAddresses)
+ b, err := proto.Marshal(&msg)
+ return b, err == nil
+ default:
+ return nil, false
+ }
+}
+
+// inferredRequestMultiaddr derives `/dns4/<host>/tcp/<port>/ws(s)/p2p/<peerID>`
+// from an HTTP request when the request either arrived over HTTPS (TLS or
+// X-Forwarded-Proto: https) or names a non-loopback host.
+func inferredRequestMultiaddr(r *http.Request, peerID string) (string, bool) {
+ if peerID == "" {
+ return "", false
+ }
+ host := firstForwardedValue(r.Header.Get("X-Forwarded-Host"))
+ if host == "" {
+ host = strings.TrimSpace(r.Host)
+ }
+ if host == "" {
+ return "", false
+ }
+ scheme := "http"
+ if r.TLS != nil || strings.EqualFold(firstForwardedValue(r.Header.Get("X-Forwarded-Proto")), "https") {
+ scheme = "https"
+ }
+ if scheme == "http" && isLoopbackOrUnspecifiedHostPort(host) {
+ return "", false
+ }
+ base, err := externalMultiaddr(scheme + "://" + host)
+ if err != nil {
+ return "", false
+ }
+ full := base + "/p2p/" + peerID
+ if _, err := multiaddr.NewMultiaddr(full); err != nil {
+ return "", false
+ }
+ return full, true
+}
+
+func firstForwardedValue(v string) string {
+ if i := strings.IndexByte(v, ','); i >= 0 {
+ v = v[:i]
+ }
+ return strings.TrimSpace(v)
+}
+
+func isLoopbackOrUnspecifiedHostPort(hostport string) bool {
+ h := hostport
+ if splitHost, _, err := net.SplitHostPort(hostport); err == nil {
+ h = splitHost
+ }
+ h = strings.Trim(h, "[]")
+ if strings.EqualFold(h, "localhost") || h == "" {
+ return true
+ }
+ if ip := net.ParseIP(h); ip != nil {
+ return ip.IsLoopback() || ip.IsUnspecified()
+ }
+ return false
+}
diff --git a/internal/standalone/standalone_test.go b/internal/standalone/standalone_test.go
index 3229b155..1aae3ae8 100644
--- a/internal/standalone/standalone_test.go
+++ b/internal/standalone/standalone_test.go
@@ -14,7 +14,18 @@
package standalone
-import "testing"
+import (
+ "crypto/tls"
+ "net/http"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/google/sam/api"
+ "github.com/libp2p/go-libp2p/core/crypto"
+ "github.com/libp2p/go-libp2p/core/peer"
+ "google.golang.org/protobuf/proto"
+)
func TestWsListenMultiaddr(t *testing.T) {
cases := []struct {
@@ -77,3 +88,99 @@ func TestExternalMultiaddr(t *testing.T) {
}
}
}
+
+func TestEnsureRouterKeyDeterministic(t *testing.T) {
+ dir1 := t.TempDir()
+ dir2 := t.TempDir()
+ key1 := filepath.Join(dir1, routerKeyFile)
+ key2 := filepath.Join(dir2, routerKeyFile)
+
+ if err := ensureRouterKey(key1, "sam_adm_fixed_secret"); err != nil {
+ t.Fatalf("ensureRouterKey(key1): %v", err)
+ }
+ if err := ensureRouterKey(key2, "sam_adm_fixed_secret"); err != nil {
+ t.Fatalf("ensureRouterKey(key2): %v", err)
+ }
+
+ b1, err := os.ReadFile(key1)
+ if err != nil {
+ t.Fatalf("ReadFile(key1): %v", err)
+ }
+ b2, err := os.ReadFile(key2)
+ if err != nil {
+ t.Fatalf("ReadFile(key2): %v", err)
+ }
+ p1, err := crypto.UnmarshalPrivateKey(b1)
+ if err != nil {
+ t.Fatalf("UnmarshalPrivateKey(b1): %v", err)
+ }
+ p2, err := crypto.UnmarshalPrivateKey(b2)
+ if err != nil {
+ t.Fatalf("UnmarshalPrivateKey(b2): %v", err)
+ }
+ id1, _ := peer.IDFromPrivateKey(p1)
+ id2, _ := peer.IDFromPrivateKey(p2)
+ if id1 != id2 {
+ t.Fatalf("peer IDs differ for same adminToken: %s vs %s", id1, id2)
+ }
+
+ // Existing key file must not be overwritten by a different admin token.
+ if err := ensureRouterKey(key1, "sam_adm_other_secret"); err != nil {
+ t.Fatalf("ensureRouterKey existing: %v", err)
+ }
+ b1After, err := os.ReadFile(key1)
+ if err != nil {
+ t.Fatalf("ReadFile(key1 after): %v", err)
+ }
+ if string(b1) != string(b1After) {
+ t.Fatalf("ensureRouterKey overwrote an existing router.key")
+ }
+}
+
+func TestInferredRequestMultiaddr(t *testing.T) {
+ const testPeerID = "12D3KooWBzUDQCkZhz2rWrYBhpjcCH8VnrRNcwCW6DoF36iADYrY"
+
+ reqCloudRun, _ := http.NewRequest(http.MethodGet, "http://0.0.0.0:8080/info", nil)
+ reqCloudRun.Host = "sam-one-xyz-uc.a.run.app"
+ reqCloudRun.Header.Set("X-Forwarded-Proto", "https")
+ got, ok := inferredRequestMultiaddr(reqCloudRun, testPeerID)
+ want := "/dns4/sam-one-xyz-uc.a.run.app/tcp/443/wss/p2p/" + testPeerID
+ if !ok || got != want {
+ t.Fatalf("CloudRun inferredRequestMultiaddr = (%q, %v), want (%q, true)", got, ok, want)
+ }
+
+ reqTLS, _ := http.NewRequest(http.MethodGet, "https://mesh.example.com:8443/info", nil)
+ reqTLS.Host = "mesh.example.com:8443"
+ reqTLS.TLS = &tls.ConnectionState{}
+ got, ok = inferredRequestMultiaddr(reqTLS, testPeerID)
+ want = "/dns4/mesh.example.com/tcp/8443/wss/p2p/" + testPeerID
+ if !ok || got != want {
+ t.Fatalf("TLS inferredRequestMultiaddr = (%q, %v), want (%q, true)", got, ok, want)
+ }
+
+ reqLoopback, _ := http.NewRequest(http.MethodGet, "http://127.0.0.1:8080/info", nil)
+ reqLoopback.Host = "127.0.0.1:8080"
+ if got, ok := inferredRequestMultiaddr(reqLoopback, testPeerID); ok {
+ t.Fatalf("Loopback HTTP should not infer external multiaddr, got %q", got)
+ }
+}
+
+func TestPrependInferredRouterAddr(t *testing.T) {
+ const inferred = "/dns4/sam-one-xyz.a.run.app/tcp/443/wss/p2p/12D3KooWBzUDQCkZhz2rWrYBhpjcCH8VnrRNcwCW6DoF36iADYrY"
+ const local = "/ip4/127.0.0.1/tcp/8080/ws/p2p/12D3KooWBzUDQCkZhz2rWrYBhpjcCH8VnrRNcwCW6DoF36iADYrY"
+
+ enrollIn, _ := proto.Marshal(&api.BootstrapEnrollResponse{
+ RouterAddresses: []string{local},
+ })
+ enrollOutBytes, ok := prependInferredRouterAddr("/enroll", enrollIn, inferred)
+ if !ok {
+ t.Fatal("prependInferredRouterAddr(/enroll) returned false")
+ }
+ var enrollOut api.BootstrapEnrollResponse
+ if err := proto.Unmarshal(enrollOutBytes, &enrollOut); err != nil {
+ t.Fatalf("Unmarshal BootstrapEnrollResponse: %v", err)
+ }
+ if len(enrollOut.RouterAddresses) != 2 || enrollOut.RouterAddresses[0] != inferred || enrollOut.RouterAddresses[1] != local {
+ t.Fatalf("BootstrapEnrollResponse.RouterAddresses = %v, want [%s %s]", enrollOut.RouterAddresses, inferred, local)
+ }
+}
diff --git a/internal/tunnel/cloudflare.go b/internal/tunnel/cloudflare.go
index 0344c236..425329b8 100644
--- a/internal/tunnel/cloudflare.go
+++ b/internal/tunnel/cloudflare.go
@@ -71,6 +71,15 @@ type Cloudflare struct {
// the zone's authoritative nameserver (see authoritativeLookup). Tests
// stub it.
LookupHost func(ctx context.Context, host string) ([]string, error)
+ // Token is an optional Cloudflare Named Tunnel token (from
+ // --tunnel-token-path or CLOUDFLARE_TUNNEL_TOKEN). When set, Open runs
+ // `cloudflared tunnel --no-autoupdate run --url <target>` with
+ // TUNNEL_TOKEN in the child environment instead of a random
+ // trycloudflare.com quick tunnel, and publishes ExternalURL.
+ Token string
+ // ExternalURL is the public https:// hostname routed to the named
+ // tunnel when Token is set.
+ ExternalURL string
}
// quickTunnelURL matches the assigned hostname in cloudflared's banner. The
@@ -94,6 +103,9 @@ func (c *Cloudflare) Name() string { return "cloudflare" }
// Open implements Provider.
func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
+ if c.Token != "" && strings.TrimSpace(c.ExternalURL) == "" {
+ return nil, fmt.Errorf("cloudflare named tunnel requires ExternalURL (--external-url)")
+ }
binary, err := c.resolveBinary(ctx)
if err != nil {
return nil, err
@@ -106,7 +118,13 @@ func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
// The process outlives Open: its lifetime is the tunnel's, ended by Close.
procCtx, cancel := context.WithCancel(context.Background())
- cmd := exec.CommandContext(procCtx, binary, "tunnel", "--url", target, "--no-autoupdate")
+ var cmd *exec.Cmd
+ if c.Token != "" {
+ cmd = exec.CommandContext(procCtx, binary, "tunnel", "--no-autoupdate", "run", "--url", target)
+ cmd.Env = append(os.Environ(), "TUNNEL_TOKEN="+c.Token)
+ } else {
+ cmd = exec.CommandContext(procCtx, binary, "tunnel", "--url", target, "--no-autoupdate")
+ }
cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }
cmd.WaitDelay = 5 * time.Second
pr, pw := io.Pipe()
@@ -117,7 +135,7 @@ func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
cancel()
return nil, fmt.Errorf("failed to start cloudflared: %w", err)
}
- t := &process{cancel: cancel, done: make(chan struct{})}
+ t := &process{cancel: cancel, done: make(chan struct{}), namedURL: strings.TrimRight(strings.TrimSpace(c.ExternalURL), "/")}
urlCh := make(chan string, 1)
go t.scan(pr, urlCh)
go func() {
@@ -129,7 +147,9 @@ func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {
select {
case u := <-urlCh:
t.url = u
- c.awaitPublished(ctx, u, deadline)
+ if c.Token == "" {
+ c.awaitPublished(ctx, u, deadline)
+ }
return t, nil
case <-t.done:
return nil, fmt.Errorf("cloudflared exited before publishing a URL: %w", t.Err())
@@ -259,9 +279,10 @@ func (c *Cloudflare) resolveBinary(ctx context.Context) (string, error) {
// process is a Tunnel backed by a child connector process.
type process struct {
- url string
- cancel context.CancelFunc
- done chan struct{}
+ url string
+ namedURL string
+ cancel context.CancelFunc
+ done chan struct{}
mu sync.Mutex
closed bool
@@ -298,7 +319,8 @@ func (p *process) finish(err error) {
}
// scan drains the connector's output for its lifetime (a full pipe would
-// stall the child) and reports the first quick-tunnel URL it sees.
+// stall the child) and reports the first quick-tunnel URL (or named-tunnel
+// edge registration) it sees.
func (p *process) scan(r io.Reader, urlCh chan<- string) {
sc := bufio.NewScanner(r)
found := false
@@ -306,7 +328,12 @@ func (p *process) scan(r io.Reader, urlCh chan<- string) {
line := sc.Text()
logger.Debugf("cloudflared: %s", line)
if !found {
- if m := assignedQuickTunnelURL(line); m != "" {
+ if p.namedURL != "" {
+ if strings.Contains(line, "Registered tunnel connection") {
+ found = true
+ urlCh <- p.namedURL
+ }
+ } else if m := assignedQuickTunnelURL(line); m != "" {
found = true
urlCh <- m
}
diff --git a/internal/tunnel/cloudflare_test.go b/internal/tunnel/cloudflare_test.go
index e61bcf07..d3ee8674 100644
--- a/internal/tunnel/cloudflare_test.go
+++ b/internal/tunnel/cloudflare_test.go
@@ -148,6 +148,31 @@ while :; do sleep 1; done
}
}
+func TestCloudflareOpenNamedTunnel(t *testing.T) {
+ bin := stubCloudflared(t, `
+[ "$1" = tunnel ] && [ "$2" = --no-autoupdate ] && [ "$3" = run ] && [ "$4" = --url ] || { echo "bad args: $*" >&2; exit 2; }
+[ "$TUNNEL_TOKEN" = "cf_secret_tok" ] || { echo "missing env TUNNEL_TOKEN" >&2; exit 3; }
+echo "INF Registered tunnel connection connIndex=0" >&2
+trap 'exit 0' TERM
+while :; do sleep 1; done
+`)
+ p := &Cloudflare{
+ Binary: bin,
+ Timeout: 5 * time.Second,
+ Token: "cf_secret_tok",
+ ExternalURL: "https://mesh.example.com/",
+ }
+ tun, err := p.Open(context.Background(), "http://127.0.0.1:18080")
+ if err != nil {
+ t.Fatalf("Open named tunnel: %v", err)
+ }
+ defer func() { _ = tun.Close() }()
+
+ if got, want := tun.URL(), "https://mesh.example.com"; got != want {
+ t.Errorf("URL = %q, want %q", got, want)
+ }
+}
+
func TestCloudflareOpenReportsEarlyExit(t *testing.T) {
bin := stubCloudflared(t, `echo "ERR failed to request quick tunnel" >&2; exit 1`)
p := &Cloudflare{Binary: bin, Timeout: 5 * time.Second}
diff --git a/site/content/docs/getting-started/_index.md b/site/content/docs/getting-started/_index.md
index a7033be7..e3a9c268 100644
--- a/site/content/docs/getting-started/_index.md
+++ b/site/content/docs/getting-started/_index.md
@@ -4,7 +4,26 @@ linkTitle: "Getting started"
weight: 1
---
-Two short walkthroughs. The first puts one node on the public testnet and
-calls a tool through it, which is enough to see what a node does. The
-second runs a complete mesh of your own on a laptop with `sam-one`, which is
-the shape every real deployment takes.
+To connect an agent or machine to a SAM mesh, `sam-node` only needs one thing:
+a **Control Plane URL** (`https://...`).
+
+## How to obtain a Control Plane URL
+
+Pick the option that matches what you want to do right now:
+
+| Option | Command to get your URL | Cost & Setup | Best for |
+|---|---|---|---|
+| **1. Public Testnet** | Use **`https://bananas.sam-mesh.dev`** directly | **$0** — zero setup, already running | Trying SAM and calling your first remote tool or model in 60 seconds ([Quick start](quickstart/)). |
+| **2. Your Laptop (Instant Public HTTPS)** | `sam-one --data-dir ~/sam-one --tunnel cloudflare --tunnel-install` | **$0** — no cloud account needed | Running your own private mesh across laptops, VMs, and phones in 10 seconds. Prints your `https://*.trycloudflare.com` URL, join token, and QR code in the terminal ([Your own mesh](your-own-mesh/)). |
+| **3. Your Own Cloud (1 Command)** | **SkyPilot**: `sky launch -c sam-hub deploy/skypilot/sam-one.yaml`<br>**Fly.io**: `fly launch --copy-config --config deploy/fly/fly.toml --ha=false`<br>**Cloud Run**: `gcloud run deploy sam-one --image ghcr.io/google/sam-one:latest ...` | **Free tiers** (GCP `e2-micro`, OCI, Cloudflare Named Tunnel, or serverless credits) | An always-on sovereign mesh in your own cloud account—without writing Terraform, building Docker images, or managing Kubernetes ([Cloud & Free-Tier Hosting](../guides/cloud-run/)). |
+
+---
+
+## Walkthroughs
+
+1. **[Quick start](quickstart/)**: Join the public `bananas.sam-mesh.dev`
+ testnet, discover remote MCP tools and inference models, and give your AI
+ agent the SAM skill.
+2. **[Your own mesh](your-own-mesh/)**: Start `sam-one` in one command, grab
+ the Control Plane URL from the startup banner, publish a local Ollama model,
+ and call it from another node.
diff --git a/site/content/docs/getting-started/quickstart.md b/site/content/docs/getting-started/quickstart.md
index 0ad91d33..343c30c7 100644
--- a/site/content/docs/getting-started/quickstart.md
+++ b/site/content/docs/getting-started/quickstart.md
@@ -33,20 +33,26 @@ On Windows, download `sam_Windows_x86_64.zip` from the
[releases page](https://github.com/google/sam/releases) and put `sam-node.exe`
on your `PATH`.
-## 2. Enroll
+## 2. Enroll with a Control Plane URL
-A node needs an identity before it can join a mesh. `sam-node join` obtains one
-by logging you in with the mesh's identity provider and registering the node's
-key with the control plane:
+Every node joins a mesh using its **Control Plane URL**:
+
+- **Public playground (used below)**: `https://bananas.sam-mesh.dev` — open to any developer; authenticates in your browser.
+- **Your own mesh**: run `sam-one --tunnel cloudflare --tunnel-install` (or deploy `ghcr.io/google/sam-one:latest` via [SkyPilot, Fly.io, or Cloud Run](../your-own-mesh/#where-to-get-your-control-plane-url)) and copy the `API URL` and `sam-node join` command printed in the startup banner.
+
+Enroll your node against the public testnet:
```bash
sam-node join https://bananas.sam-mesh.dev
```
The command opens a browser for the login. If no browser is available, it
-prints a URL and a code to enter on another device. When the login completes,
-the credential is stored under `~/.config/sam-mesh/`. You do this once per
-machine. Later starts reuse the stored identity and renew it automatically.
+prints a URL and a code to enter on another device. (When joining your own
+`sam-one` server before setting up OIDC, pass `--bootstrap-token-path <join-token-file>`
+as shown in the `sam-one` banner instead of logging in through a browser.)
+When enrollment completes, the credential is stored under `~/.config/sam-mesh/`.
+You do this once per machine. Later starts reuse the stored identity and renew
+it automatically.
## 3. Run the node
diff --git a/site/content/docs/getting-started/your-own-mesh.md b/site/content/docs/getting-started/your-own-mesh.md
index c8f1d8cd..86c166cd 100644
--- a/site/content/docs/getting-started/your-own-mesh.md
+++ b/site/content/docs/getting-started/your-own-mesh.md
@@ -15,7 +15,24 @@ code as a Kubernetes deployment, so what you learn here applies there too.
You need the `sam-one` and `sam-node` binaries. The
[install script](../quickstart/#1-install) provides both.
-## 1. Start the mesh
+## 1. Start the control plane and get your URL
+
+`sam-one` packages the control plane, the libp2p WebSocket router, and the web
+console into a single binary on one port. Whenever it starts—on your laptop, in
+a container, or on a cloud VM—it prints a startup banner containing your
+**Control Plane URL (`API URL`)**, your tokens, and the exact `sam-node join`
+command to copy-paste.
+
+### Where to get your Control Plane URL
+
+| Where your nodes run | How to start `sam-one` | Control Plane URL you get |
+|---|---|---|
+| **Across machines, VMs, or phones** *(Instant HTTPS tunnel)* | `sam-one --data-dir ~/sam-one --tunnel cloudflare --tunnel-install` | Public `https://<name>.trycloudflare.com` URL + terminal QR code |
+| **Same machine only** *(Local development)* | `sam-one --data-dir ~/sam-one` | Local `http://127.0.0.1:<port>` URL |
+| **Custom domain behind NAT/firewall** *(Cloudflare Named Tunnel)* | `sam-one --data-dir ~/sam-one --tunnel cloudflare --tunnel-token-path ~/cf-token --external-url https://mesh.example.com` | Permanent `https://mesh.example.com` URL (no inbound firewall ports) |
+| **Always-on Cloud Deployment** *(Cloud Run, SkyPilot, Fly.io)* | See [Cloud Deployment](../../guides/cloud-run/) (`gcloud run deploy`, `sky launch`, or `fly launch`) | `https://<svc>.a.run.app`, `https://mesh.example.com`, or `https://<app>.fly.dev` |
+
+For example, starting `sam-one` locally:
```bash
sam-one --data-dir ~/sam-one
diff --git a/site/content/docs/guides/cloud-run.md b/site/content/docs/guides/cloud-run.md
index f131c1ab..9685b607 100644
--- a/site/content/docs/guides/cloud-run.md
+++ b/site/content/docs/guides/cloud-run.md
@@ -1,42 +1,43 @@
---
-title: "Cloud Run"
-linkTitle: "Cloud Run"
+title: "Cloud Run & Free-Tier Hosting"
+linkTitle: "Cloud Run & Free Tiers"
weight: 5
aliases:
- /docs/user/cloud-run-deployment/
---
-`sam-one` serves its HTTP API, the console and the router's WebSocket
-transport on one port. That is the shape Cloud Run expects. This guide
-deploys it there, joins nodes from anywhere, and lists what changes when
-`sam-one` runs on Cloud Run. The same steps apply to any platform that
-forwards HTTP and WebSockets to a container.
+`sam-one` serves its HTTP API, the web console, and the router's WebSocket
+transport on a single port (`8080`), and ships as a pre-built container image
+(`ghcr.io/google/sam-one:latest`). You can deploy a private control plane to
+your own cloud account in **one command**—without building Docker images,
+configuring container registries, or writing Terraform.
-## 1. Build and push
+## Pick a deployment path
-```bash
-PROJECT=my-project
-REGION=us-central1
-IMG=${REGION}-docker.pkg.dev/${PROJECT}/sam-mesh/sam-one:latest
+| Platform | Command | Free Tier & Persistence | How you obtain the Control Plane URL |
+|---|---|---|---|
+| **1. SkyPilot** *(Any cloud: GCP, AWS, Azure, OCI, k8s)* | `sky launch -y -c sam-hub deploy/skypilot/sam-one.yaml --detach-run` | Uses your cloud's cheapest or **Always-Free VM** (`e2-micro`, `t4g.micro`) + persistent disk + free Cloudflare HTTPS tunnel | Run `sky logs sam-hub 1 --no-follow` and copy `API URL: https://...trycloudflare.com` |
+| **2. Fly.io** | `fly launch --copy-config --config deploy/fly/fly.toml --ha=false` | 1 GB persistent `/data` volume (SQLite + keys survive restarts) + automatic TLS/WSS | `https://<your-app>.fly.dev` (also printed in `fly logs`) |
+| **3. Google Cloud Run** | `gcloud run deploy sam-one --image ghcr.io/google/sam-one:latest ...` *(below)* | Serverless container; pair with a free Postgres (Neon / Supabase) for durable state across restarts | Printed at the end of `gcloud run deploy` (`Service URL: https://...a.run.app`) |
-docker build -f Dockerfile.sam-one -t "$IMG" .
-gcloud auth configure-docker ${REGION}-docker.pkg.dev
-docker push "$IMG"
-```
+---
-## 2. Deploy
+## Option 1: Google Cloud Run (1 Command)
-Cloud Run has no persistent disk, so the join and admin tokens are set
-through environment variables. Without this, a new instance would generate
-new tokens and nodes that enrolled earlier could not renew.
+Because `sam-one` automatically detects its public `wss://` address from Cloud
+Run's `Host` / `X-Forwarded-Proto` headers on `/info` and `/enroll` and derives
+a deterministic router `PeerID` from `SAM_ADMIN_TOKEN`, deploying to Cloud Run
+takes a single command using the pre-built image:
```bash
+PROJECT=my-gcp-project
+REGION=us-central1
JOIN_TOKEN="sam_tok_$(openssl rand -hex 16)"
ADMIN_TOKEN="sam_adm_$(openssl rand -hex 16)"
gcloud run deploy sam-one \
--project "$PROJECT" --region "$REGION" \
- --image "$IMG" \
+ --image ghcr.io/google/sam-one:latest \
--allow-unauthenticated \
--min-instances 1 --max-instances 1 \
--port 8080 \
@@ -45,60 +46,134 @@ gcloud run deploy sam-one \
--set-env-vars "SAM_TOKEN=${JOIN_TOKEN},SAM_ADMIN_TOKEN=${ADMIN_TOKEN}"
```
-Each flag is needed:
+### Obtain your URL and join a node
+
+`gcloud run deploy` outputs your `Service URL` directly:
+
+```text
+Service [sam-one] revision [sam-one-00001-xxx] has been deployed and is serving 100 percent of traffic.
+Service URL: https://sam-one-628944397724.us-central1.run.app
+```
+
+Verify readiness and enroll a node from anywhere:
+
+```bash
+URL=$(gcloud run services describe sam-one --project "$PROJECT" --region "$REGION" \
+ --format='value(status.url)')
+
+curl -s "$URL/readyz" # {"status":"ready"}
+
+echo -n "$JOIN_TOKEN" > join-token
+sam-node join "$URL" --bootstrap-token-path join-token
+sam-node run --daemonize
+```
+
+> [!TIP]
+> **Free-tier persistent database for Cloud Run:** By default, Cloud Run's
+> filesystem is in-memory, so when an instance restarts it keeps its router
+> `PeerID` and pinned tokens (`SAM_TOKEN`, `SAM_ADMIN_TOKEN`), while enrolled
+> nodes automatically re-enroll. To persist enrolled nodes, minted tokens, and
+> policies across restarts for **$0/mo**, create a free serverless Postgres
+> database (for example on [Neon](https://neon.tech) or
+> [Supabase](https://supabase.com)) and add
+> `--args="--data-dir=/data,--port=8080,--db-driver=postgres,--db-dsn=<YOUR_POSTGRES_URI>"`
+> to `gcloud run deploy`.
+
+Why each Cloud Run flag matters:
- `--min-instances 1 --max-instances 1`: the router's DHT and relay state
- live in the one process. Two instances would be two separate meshes behind
+ live in the single process. Two instances would be two separate meshes behind
one URL.
- `--no-cpu-throttling`: the router runs background loops (lease renewal,
- key sync, DHT maintenance) between requests.
+ key sync, DHT maintenance) between HTTP requests.
- `--timeout 3600`: Cloud Run limits the lifetime of a streaming request,
- and each node's WebSocket connection is one. Nodes reconnect when the limit
- closes a connection, but a low value causes unnecessary reconnects.
-- `--allow-unauthenticated`: the mesh authenticates its own callers. Cloud
- Run's IAM check would block nodes before they could present a credential.
+ and each node's WebSocket connection is one. Nodes reconnect seamlessly when
+ the limit closes a connection.
+- `--allow-unauthenticated`: the mesh authenticates its own callers with
+ Biscuit credentials and tokens.
+
+---
-The router needs to know its public URL so that it can advertise an address
-that nodes can dial. The URL only exists after the first deploy:
+## Option 2: SkyPilot (Multi-Cloud & Always-Free VMs)
+
+If you use [SkyPilot](https://docs.skypilot.co/) (`sky check`) with your GCP,
+AWS, Azure, OCI, or Kubernetes account, launch the included recipe in the
+background:
```bash
-URL=$(gcloud run services describe sam-one --project "$PROJECT" --region "$REGION" \
- --format='value(status.url)')
+sky launch -y -c sam-hub deploy/skypilot/sam-one.yaml --detach-run
+```
+
+SkyPilot provisions the cheapest available VM (including `e2-micro` / `t4g.micro`
+Always-Free instances), installs `sam-one`, and opens an outbound Cloudflare
+HTTPS tunnel (requiring zero inbound firewall ports or DNS setup).
+
+### Obtain your URL and join token from SkyPilot logs
+
+Read the startup banner from job `1`:
+
+```bash
+sky logs sam-hub 1 --no-follow
+```
+
+```text
+══════════════════════════════════════════════════════════════════
+SAM standalone mesh is ready!
-gcloud run services update sam-one --project "$PROJECT" --region "$REGION" \
- --update-env-vars "SAM_EXTERNAL_URL=${URL}"
+API URL: https://distinct-kent-bradford-elderly.trycloudflare.com
+Tunnel: https://distinct-kent-bradford-elderly.trycloudflare.com -> http://0.0.0.0:8080
+Web Console: https://distinct-kent-bradford-elderly.trycloudflare.com/console
+Router Peer: 12D3KooWScRWXVx2zSaPWC7NectYnuyhaGxpLYkNgCkp2g2tkfkY
+Admin Token: sam_adm_e4075529d72bb22d78446799f683dd89
+Join Token: sam_tok_05a5d01cf091187c980e68e1bd7d7d7a
+
+To enroll a node:
+ sam-node join https://distinct-kent-bradford-elderly.trycloudflare.com --bootstrap-token-path /home/gcpuser/sam-one/join-token
+══════════════════════════════════════════════════════════════════
```
-## 3. Verify
+Save the `Join Token` on your local machine and join:
```bash
-curl -s "$URL/readyz" # 200
-curl -s "$URL/info" | head -c 200 # contains /dns4/<host>/tcp/443/wss/p2p/<peer-id>
+echo -n "sam_tok_..." > join-token
+sam-node join https://distinct-kent-bradford-elderly.trycloudflare.com --bootstrap-token-path join-token
+sam-node run --daemonize
```
-The console is at `$URL/console`. Use `/readyz` for probes. `/healthz` is
-reserved by Cloud Run's frontend on `run.app` domains and never reaches the
-container.
+To use a **permanent custom domain** for **$0/mo** via a Cloudflare Named
+Tunnel instead of a random `trycloudflare.com` hostname:
-## 4. Join nodes
+```bash
+sky launch -y -c sam-hub deploy/skypilot/sam-one.yaml --detach-run \
+ --env SAM_EXTERNAL_URL=https://mesh.example.com \
+ --secret CLOUDFLARE_TUNNEL_TOKEN
+```
+
+To tear down the SkyPilot hub when done:
```bash
-echo -n "$JOIN_TOKEN" > join-token
-sam-node run --control-plane "$URL" --bootstrap-token-path join-token
+sky down -y sam-hub
```
-The node enrolls over HTTPS, reads the router's `wss` address from `/info`,
-and connects through the same port. Nodes behind NAT reach each other
-through relay circuits on the Cloud Run instance, so neither node needs an
-inbound port. Pass `--announce-private=false` to the nodes so that they do
-not advertise LAN addresses that no remote peer can use.
+---
+
+## Option 3: Fly.io (1 Command + Persistent Volume)
-Publishing and calling a service works as in
-[your own mesh](../../getting-started/your-own-mesh/): declare the service in
-`sam-node.yaml` on one node, and call it through
-`/sam/<peer-id>/<type>/<name>/` on another.
+The repository includes [`deploy/fly/fly.toml`](https://github.com/google/sam/blob/main/deploy/fly/fly.toml),
+which deploys `ghcr.io/google/sam-one:latest` with a 1 GB persistent volume
+mounted at `/data` (so SQLite, `router.key`, `join-token`, and `admin-token`
+persist across restarts):
-## 5. Administer
+```bash
+fly launch --copy-config --config deploy/fly/fly.toml --ha=false
+```
+
+Once deployed, run `fly logs` to read your `Admin Token`, `Join Token`, and
+`sam-node join https://<your-app>.fly.dev` command from the startup banner.
+
+---
+
+## Administer from your workstation
`sam-one` is also the admin client. With `SAM_ADMIN_TOKEN` exported:
@@ -109,24 +184,3 @@ sam-one token list --server "$URL"
sam-one token revoke <token-id> --server "$URL"
sam-one admin ban <peer-id> --server "$URL"
```
-
-## What Cloud Run changes
-
-- **State is ephemeral.** The SQLite database is in the container's memory.
- When an instance restarts, it forgets enrolled nodes and minted tokens,
- and the router gets a new peer ID. Nodes read `/info` again and re-enroll
- with the pinned join token. For state that survives restarts, point
- `--db-driver postgres --db-dsn <dsn>` at a managed database, or run
- `sam-one` on a VM with a disk.
-- **Rollouts overlap.** During a deploy, `/info` may advertise the new
- instance while some WebSocket upgrades still reach the old one. Nodes
- detect the peer ID mismatch and retry. Joins succeed once the old revision
- has drained.
-- **One source IP for everyone.** All traffic arrives from a small number of
- frontend proxies. `sam-one` raises libp2p's per-source-IP connection limit
- for this automatically. A separate `sam-router` behind a proxy needs
- `--conns-per-source-ip` raised by hand.
-- **Policy.** First boot seeds the open development policy. Build a
- `--policy-file` into the image or post a policy after the deploy, and run
- with `--no-join-token` once you mint per-device tokens. The
- [sam-one reference](../../reference/sam-one/) lists the flags.
diff --git a/site/content/docs/reference/sam-one.md b/site/content/docs/reference/sam-one.md
index 10217f02..d5b6d7eb 100644
--- a/site/content/docs/reference/sam-one.md
+++ b/site/content/docs/reference/sam-one.md
@@ -27,12 +27,13 @@ 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`. Sets the advertised `wss` address. |
-| `--tunnel` | | Publish the port through a tunnel provider and use the resulting URL as the external URL. The only provider is `cloudflare` (a quick tunnel, no account needed). |
+| `--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-token-path` | | File containing a Cloudflare Named Tunnel token (can also be set with `CLOUDFLARE_TUNNEL_TOKEN`). Use together with `--tunnel cloudflare --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. |
| `--p2p-listen` | none | Extra native libp2p listen addresses, in addition to the WebSocket transport on the main port. |
-| `--data-dir` | `.` | See above. |
+| `--data-dir` | `.` | See above. On stateless platforms where `router.key` is absent and `SAM_ADMIN_TOKEN` / `--admin-token-path` is supplied, `router.key` is derived deterministically so the router keeps its PeerID across restarts. |
| `--db-driver` | `sqlite` | `sqlite` or `postgres`. |
| `--db-dsn` | `<data-dir>/sam.db` | Database DSN. |
| `--token-path` | | File containing the standing join token. Can also be set with `SAM_TOKEN`. Generated and saved to the data directory when neither is set. |
diff --git a/site/static/install.sh b/site/static/install.sh
index 8acf692d..20fc5e17 100755
--- a/site/static/install.sh
+++ b/site/static/install.sh
@@ -26,8 +26,11 @@ esac
echo "Fetching latest release information..."
LATEST_RELEASE_URL="https://api.github.com/repos/${REPO}/releases/latest"
# `|| true`: with pipefail, a grep that matches nothing would kill the script
-# here instead of reaching the friendly error below.
-VERSION=$(curl -s $LATEST_RELEASE_URL | grep '"tag_name":' | sed -E 's/.*"([^"]+)".*/\1/' || true)
+# here instead of reaching the fallback/error below.
+VERSION=$(curl -s "$LATEST_RELEASE_URL" | grep '"tag_name":' | head -n 1 | sed -E 's/.*"([^"]+)".*/\1/' || true)
+if [ -z "$VERSION" ]; then
+ VERSION=$(curl -s "https://api.github.com/repos/${REPO}/releases?per_page=1" | grep '"tag_name":' | head -n 1 | sed -E 's/.*"([^"]+)".*/\1/' || true)
+fi
if [ -z "$VERSION" ]; then
echo "Error: Could not find the latest release."
@@ -56,7 +59,7 @@ tar -xzf "${TAR_NAME}"
echo "Installing to ${INSTALL_DIR} (may require sudo)..."
INSTALLED_BINS=()
-for b in sam-node sam-control-plane sam-router mcp-client sam-box sam-console nano-init; do
+for b in sam-one sam-node sam-control-plane sam-router mcp-client sam-box sam-console nano-init; do
if [ -f "$b" ]; then
INSTALLED_BINS+=("$b")
fi