Agent Mesh
Go a2aa2a-protocolagent-meshagentic-aiinferencemcpmeshmesh-networknetwork-securitynetworking-aip2p-network
sam-one: device enrollment QR codes and Cloudflare quick tunnels
Antonio Ojea56f90ec712a9
diff --git a/api/enroll_uri.go b/api/enroll_uri.gonew file mode 100644index 00000000..6c125c9d--- /dev/null+++ b/api/enroll_uri.go@@ -0,0 +1,88 @@+// 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 api++import (+ "errors"+ "fmt"+ "net/url"+ "strings"+)++// ============================================================================+// Device Enrollment URI+// ============================================================================+//+// A control plane hands a new device everything it needs to enroll in one+// scannable string:+//+// sam://enroll?server=<control-plane-url>&token=<bootstrap-token>+//+// The token is an ordinary bootstrap token (POST /enroll spends it), so the+// URI grants exactly what the token grants: one enrollment, in the token's+// role, until it expires, against any control plane deployment — sam-one or+// a full sam-control-plane. The server URL is the same base URL a node+// passes to `sam-node join`, and the same transport rule applies+// (ValidateControlPlaneTransport): https, or plaintext http only to a+// loopback host, because whoever answers that URL becomes the device's trust+// root. Clients (the mobile app, CLIs) parse the URI with ParseEnrollURI and+// must reject anything else; there is deliberately no second form to keep+// the scanner-to-enrollment path free of guesswork.++const (+ // EnrollURIScheme is the URI scheme of a device enrollment payload.+ EnrollURIScheme = "sam"+ // EnrollURIHost is the fixed host component; it names the action.+ EnrollURIHost = "enroll"+)++// EnrollURI builds the device enrollment URI for the given control plane+// base URL and bootstrap token.+func EnrollURI(server, token string) string {+ q := url.Values{}+ q.Set("server", server)+ q.Set("token", token)+ u := url.URL{Scheme: EnrollURIScheme, Host: EnrollURIHost, RawQuery: q.Encode()}+ return u.String()+}++// ParseEnrollURI extracts the control plane URL and bootstrap token from a+// device enrollment URI. The server must be an absolute URL that a device+// may trust as its control plane: https, or http to a loopback host.+func ParseEnrollURI(raw string) (server, token string, err error) {+ u, err := url.Parse(strings.TrimSpace(raw))+ if err != nil {+ return "", "", fmt.Errorf("invalid enrollment URI: %w", err)+ }+ if u.Scheme != EnrollURIScheme || u.Host != EnrollURIHost {+ return "", "", fmt.Errorf("invalid enrollment URI: expected %s://%s?server=<url>&token=<token>", EnrollURIScheme, EnrollURIHost)+ }+ q := u.Query()+ server, token = q.Get("server"), q.Get("token")+ if token == "" {+ return "", "", fmt.Errorf("invalid enrollment URI: missing token")+ }+ if su, err := url.Parse(server); err != nil || su.Host == "" {+ return "", "", fmt.Errorf("invalid enrollment URI: server must be an absolute http(s) URL")+ }+ if err := ValidateControlPlaneTransport(server, false); err != nil {+ if errors.Is(err, ErrInsecureControlPlaneURL) {+ // Devices have no --insecure-control-plane escape hatch.+ return "", "", fmt.Errorf("invalid enrollment URI: server %q must use https:// (plaintext http:// is accepted for loopback hosts only)", server)+ }+ return "", "", fmt.Errorf("invalid enrollment URI: %w", err)+ }+ return server, token, nil+}diff --git a/api/enroll_uri_test.go b/api/enroll_uri_test.gonew file mode 100644index 00000000..bb71fa7f--- /dev/null+++ b/api/enroll_uri_test.go@@ -0,0 +1,58 @@+// 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 api++import "testing"++func TestEnrollURIRoundTrip(t *testing.T) {+ const server, token = "https://abc-def-123.trycloudflare.com", "sam_dev_0123456789abcdef"+ uri := EnrollURI(server, token)+ if want := "sam://enroll?server=https%3A%2F%2Fabc-def-123.trycloudflare.com&token=sam_dev_0123456789abcdef"; uri != want {+ t.Fatalf("EnrollURI = %q, want %q", uri, want)+ }+ gotServer, gotToken, err := ParseEnrollURI(" " + uri + "\n")+ if err != nil {+ t.Fatalf("ParseEnrollURI: %v", err)+ }+ if gotServer != server || gotToken != token {+ t.Fatalf("ParseEnrollURI = (%q, %q), want (%q, %q)", gotServer, gotToken, server, token)+ }+}++func TestParseEnrollURIAcceptsLoopbackHTTP(t *testing.T) {+ // Emulators reach the host over adb reverse, i.e. loopback.+ server, _, err := ParseEnrollURI("sam://enroll?server=http%3A%2F%2F127.0.0.1%3A18432&token=t")+ if err != nil || server != "http://127.0.0.1:18432" {+ t.Fatalf("ParseEnrollURI loopback http = (%q, %v)", server, err)+ }+}++func TestParseEnrollURIRejects(t *testing.T) {+ for name, raw := range map[string]string{+ "wrong scheme": "samone://enroll?server=https%3A%2F%2Fx&token=t",+ "wrong host": "sam://join?server=https%3A%2F%2Fx&token=t",+ "missing token": "sam://enroll?server=https%3A%2F%2Fx",+ "missing server": "sam://enroll?token=t",+ "non-http server": "sam://enroll?server=ftp%3A%2F%2Fx&token=t",+ "relative server": "sam://enroll?server=x.example.com&token=t",+ "plaintext to LAN": "sam://enroll?server=http%3A%2F%2F192.168.1.50%3A18432&token=t",+ "plaintext to host": "sam://enroll?server=http%3A%2F%2Fmesh.example.com&token=t",+ "plain token only": "sam_dev_0123",+ } {+ if _, _, err := ParseEnrollURI(raw); err == nil {+ t.Errorf("%s: ParseEnrollURI(%q) accepted", name, raw)+ }+ }+}diff --git a/cmd/sam-one/admin.go b/cmd/sam-one/admin.goindex 06a73c35..bd112c90 100644--- a/cmd/sam-one/admin.go+++ b/cmd/sam-one/admin.go@@ -21,6 +21,7 @@ import ("io""net/http""os"+ "strings""text/tabwriter""time"@@ -128,6 +129,41 @@ func (c *adminClient) banPeer(peerID string) error {return err}+// revokeToken soft-revokes a bootstrap token. idOrPrefix may be the full+// SHA-256 id or the unique prefix `token list` and `token qr` print.+func (c *adminClient) revokeToken(idOrPrefix string) (string, error) {+ id, err := c.resolveTokenID(idOrPrefix)+ if err != nil {+ return "", err+ }+ _, err = c.do(http.MethodDelete, "/admin/bootstrap-tokens/"+id, "", nil)+ return id, err+}++func (c *adminClient) resolveTokenID(idOrPrefix string) (string, error) {+ if idOrPrefix == "" {+ return "", fmt.Errorf("token id is required")+ }+ list, err := c.listTokens()+ if err != nil {+ return "", err+ }+ var matches []string+ for _, tok := range list {+ if strings.HasPrefix(tok.ID, idOrPrefix) {+ matches = append(matches, tok.ID)+ }+ }+ switch len(matches) {+ case 1:+ return matches[0], nil+ case 0:+ return "", fmt.Errorf("no bootstrap token with id %q", idOrPrefix)+ default:+ return "", fmt.Errorf("token id %q is ambiguous (%d matches); pass more characters", idOrPrefix, len(matches))+ }+}+// newAdminSubcommands wires the token and admin command trees onto root.func newAdminSubcommands() []*cobra.Command {var (@@ -185,7 +221,7 @@ func newAdminSubcommands() []*cobra.Command {tokenList := &cobra.Command{Use: "list",- Short: "List active bootstrap tokens",+ Short: "List bootstrap tokens and their status",RunE: func(cmd *cobra.Command, args []string) error {c, err := clientFactory()if err != nil {@@ -195,24 +231,46 @@ func newAdminSubcommands() []*cobra.Command {if err != nil {return err}+ now := time.Now()tw := tabwriter.NewWriter(cmd.OutOrStdout(), 2, 4, 2, ' ', 0)- _, _ = fmt.Fprintln(tw, "ID\tROLE\tUSAGES\tEXPIRES\tDESCRIPTION")+ _, _ = fmt.Fprintln(tw, "ID\tROLE\tUSAGES\tSTATUS\tEXPIRES\tDESCRIPTION")for _, tok := range list {id := tok.IDif len(id) > 12 {id = id[:12]}- _, _ = fmt.Fprintf(tw, "%s\t%s\t%d/%d\t%s\t%s\n",- id, tok.Role, tok.UsagesCount, tok.MaxUsages,+ _, _ = fmt.Fprintf(tw, "%s\t%s\t%d/%d\t%s\t%s\t%s\n",+ id, tok.Role, tok.UsagesCount, tok.MaxUsages, tokenStatus(&tok, now),tok.ExpiresAt.Format(time.RFC3339), tok.Description)}return tw.Flush()},}+ tokenRevoke := &cobra.Command{+ Use: "revoke <token-id>",+ Short: "Revoke a bootstrap token so no further device can enroll with it",+ Long: "Soft-revokes a bootstrap token by its id or the id prefix shown by " ++ "`token list` and `token qr`. Devices already enrolled keep their identity; " ++ "use `admin ban` for those.",+ Args: cobra.ExactArgs(1),+ RunE: func(cmd *cobra.Command, args []string) error {+ c, err := clientFactory()+ if err != nil {+ return err+ }+ id, err := c.revokeToken(args[0])+ if err != nil {+ return err+ }+ cmd.Printf("Token %s revoked\n", id[:12])+ return nil+ },+ }+tokenCmd := &cobra.Command{Use: "token", Short: "Manage bootstrap tokens on a running sam-one"}addSharedFlags(tokenCmd)- tokenCmd.AddCommand(tokenCreate, tokenList)+ tokenCmd.AddCommand(tokenCreate, tokenList, tokenRevoke, newTokenQRCommand(clientFactory, &server))adminBan := &cobra.Command{Use: "ban <peer-id>",@@ -237,3 +295,71 @@ func newAdminSubcommands() []*cobra.Command {return []*cobra.Command{tokenCmd, adminCmd}}++// tokenStatus mirrors the control plane's usability check (/enroll and+// ConsumeBootstrapTokenUsage) for display.+func tokenStatus(tok *storage.BootstrapToken, now time.Time) string {+ switch {+ case tok.IsRevoked():+ return "revoked"+ case !tok.ExpiresAt.IsZero() && now.After(tok.ExpiresAt):+ return "expired"+ case tok.UsagesCount >= tok.MaxUsages:+ return "exhausted"+ default:+ return "active"+ }+}++// newTokenQRCommand mints a node token and renders it, with the URL devices+// must enroll against, as a terminal QR code. server points at the shared+// --server flag so the QR defaults to the URL the admin used.+func newTokenQRCommand(clientFactory func() (*adminClient, error), server *string) *cobra.Command {+ var (+ enrollURL string+ ttlHours int+ maxUsages int+ description string+ )+ cmd := &cobra.Command{+ Use: "qr",+ Short: "Mint a device enrollment token and print it as a QR code",+ Long: "Mints a bootstrap token for the node role and renders " ++ "sam://enroll?server=<url>&token=<token> as a QR code for the SAM mobile app. " ++ "Single use by default; --max-usages lets one code, projected in a room, enroll " ++ "many devices until it is exhausted, expires or is revoked. " ++ "The embedded URL defaults to --server; pass --enroll-url when devices reach " ++ "the mesh on a different address (a tunnel hostname, a reverse proxy). Devices " ++ "only trust https control planes (plaintext http is accepted for loopback only).",+ RunE: func(cmd *cobra.Command, args []string) error {+ target := enrollURL+ if target == "" {+ target = *server+ }+ target = strings.TrimRight(target, "/")+ if _, _, err := api.ParseEnrollURI(api.EnrollURI(target, "probe")); err != nil {+ return fmt.Errorf("enrollment URL %q: %w", target, err)+ }+ if maxUsages < 1 {+ return fmt.Errorf("--max-usages must be at least 1")+ }+ c, err := clientFactory()+ if err != nil {+ return err+ }+ if description == "" {+ description = "device enrollment via " + target+ }+ created, err := c.createToken(api.RoleNode, ttlHours, maxUsages, description)+ if err != nil {+ return err+ }+ return printEnrollQR(cmd.OutOrStdout(), target, created.Token, time.Duration(ttlHours)*time.Hour, maxUsages)+ },+ }+ cmd.Flags().StringVar(&enrollURL, "enroll-url", "", "https URL embedded in the QR code when it differs from --server")+ cmd.Flags().IntVar(&ttlHours, "ttl-hours", 1, "Token validity in hours")+ cmd.Flags().IntVar(&maxUsages, "max-usages", 1, "How many devices may enroll with this code")+ cmd.Flags().StringVar(&description, "description", "", "Free-form note stored with the token")+ return cmd+}diff --git a/cmd/sam-one/admin_test.go b/cmd/sam-one/admin_test.goindex 7d2b17ab..51262baf 100644--- a/cmd/sam-one/admin_test.go+++ b/cmd/sam-one/admin_test.go@@ -65,6 +65,17 @@ func newFakeAdminAPI(t *testing.T) *httptest.Server {http.Error(w, "method", http.StatusMethodNotAllowed)}})+ mux.HandleFunc("/admin/bootstrap-tokens/", func(w http.ResponseWriter, r *http.Request) {+ if r.Header.Get("Authorization") != "Bearer adm-tok" {+ http.Error(w, "Unauthorized", http.StatusUnauthorized)+ return+ }+ if r.Method != http.MethodDelete || r.URL.Path != "/admin/bootstrap-tokens/abcdef123456" {+ http.Error(w, "wrong revoke request "+r.Method+" "+r.URL.Path, http.StatusNotFound)+ return+ }+ w.WriteHeader(http.StatusNoContent)+ })mux.HandleFunc("/admin/revoke", func(w http.ResponseWriter, r *http.Request) {if r.Header.Get("Authorization") != "Bearer adm-tok" {http.Error(w, "Unauthorized", http.StatusUnauthorized)@@ -107,6 +118,15 @@ func TestAdminClient(t *testing.T) {t.Fatalf("banPeer failed: %v", err)}+ // Revocation accepts the id prefix `token list` prints and sends the+ // full id; an unknown prefix never reaches the DELETE route.+ if id, err := c.revokeToken("abcdef"); err != nil || id != "abcdef123456" {+ t.Fatalf("revokeToken by prefix = (%q, %v)", id, err)+ }+ if _, err := c.revokeToken("zzz"); err == nil || !strings.Contains(err.Error(), "no bootstrap token") {+ t.Fatalf("revokeToken unknown prefix: err = %v", err)+ }+bad := &adminClient{client: ts.Client(), server: ts.URL, token: "wrong"}if _, err := bad.listTokens(); err == nil || !strings.Contains(err.Error(), "401") {t.Errorf("expected 401 error with wrong token, got %v", err)diff --git a/cmd/sam-one/main.go b/cmd/sam-one/main.goindex 2eb1964e..ee56163d 100644--- a/cmd/sam-one/main.go+++ b/cmd/sam-one/main.go@@ -17,17 +17,20 @@package mainimport (+ "bufio""context""fmt""net""os""os/signal"+ "path/filepath""strconv""strings""syscall""github.com/google/sam/api""github.com/google/sam/internal/standalone"+ "github.com/google/sam/internal/tunnel"golog "github.com/ipfs/go-log/v2""github.com/spf13/cobra")@@ -50,6 +53,11 @@ func main() {oidcClientID stringallowedAudiencesFlag stringlogLevel string+ tunnelProvider string+ tunnelInstall bool+ cloudflaredPath string+ enrollQR bool+ enrollQRMaxUsages intcpTunables standalone.ControlPlaneTunablesrouterTunables standalone.RouterTunablesrouterAllowLoopback bool@@ -88,6 +96,35 @@ func main() {}}+ // The router advertises the external URL from its first lease, so+ // a tunnel must exist before it starts; that in turn needs the+ // 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 port == 0 {+ var err error+ if port, err = freePort(bindAddress); err != nil {+ logger.Fatalf("Failed to pick a port for the tunnel target: %v", err)+ }+ }+ var err error+ if tun, err = openTunnel(cmd.Context(), tunnelOptions{+ provider: tunnelProvider,+ bindAddress: bindAddress,+ port: port,+ dataDir: dataDir,+ cloudflaredPath: cloudflaredPath,+ install: tunnelInstall,+ }); err != nil {+ logger.Fatalf("Failed to open tunnel: %v", err)+ }+ defer func() { _ = tun.Close() }()+ externalURL = tun.URL()+ }+routerTunables.DisallowLoopback = !routerAllowLoopbacksrv, err := standalone.New(standalone.Options{BindAddress: net.JoinHostPort(bindAddress, strconv.Itoa(port)),@@ -117,7 +154,20 @@ func main() {}}()- printBanner(srv, externalURL)+ printBanner(srv, tun)+ if enrollQR {+ if err := printBootEnrollQR(cmd.Context(), srv, enrollQRMaxUsages); err != nil {+ logger.Errorf("Device enrollment QR: %v", err)+ }+ }+ if tun != nil {+ go func() {+ <-tun.Done()+ if err := tun.Err(); err != nil {+ logger.Errorf("Tunnel %s closed: %v; remote devices can no longer reach %s", tunnelProvider, err, tun.URL())+ }+ }()+ }<-cmd.Context().Done()},}@@ -136,6 +186,11 @@ func main() {rootCmd.Flags().StringVar(&oidcClientID, "oidc-client-id", "", "OAuth client id advertised via /info (defaults to the first allowed audience)")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().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)")+ rootCmd.Flags().IntVar(&enrollQRMaxUsages, "enroll-qr-max-usages", 1, "How many devices the startup QR code admits (1 = single use; raise it to project one code to a room)")// Embedded control plane tunables.rootCmd.Flags().DurationVar(&cpTunables.LeaseDuration, "control-plane-lease-duration", 0, "Router lease validity (0 keeps the component default)")@@ -164,15 +219,15 @@ func main() {}}-func printBanner(srv *standalone.Server, externalURL string) {- base := externalURL- if base == "" {- base = "http://" + srv.Addr()- }+func printBanner(srv *standalone.Server, tun tunnel.Tunnel) {+ base := srv.PublicURL()fmt.Println("══════════════════════════════════════════════════════════════════")fmt.Println("SAM standalone mesh is ready!")fmt.Println()fmt.Printf("API URL: %s\n", base)+ if tun != nil {+ fmt.Printf("Tunnel: %s -> http://%s\n", tun.URL(), srv.Addr())+ }fmt.Printf("Web Console: %s/console\n", base)fmt.Printf("Router Peer: %s\n", srv.PeerID())fmt.Printf("Admin Token: %s\n", srv.AdminToken())@@ -182,3 +237,93 @@ func printBanner(srv *standalone.Server, externalURL string) {fmt.Printf(" sam-node join %s --bootstrap-token %s\n", base, srv.JoinToken())fmt.Println("══════════════════════════════════════════════════════════════════")}++// printBootEnrollQR mints the per-boot device token and draws it under the+// banner; `sam-one token qr` produces further ones on demand. Without a+// public https URL there is nothing a device could trust, so no token is+// spent and a hint is printed instead.+func printBootEnrollQR(ctx context.Context, srv *standalone.Server, maxUsages int) error {+ if err := api.ValidateControlPlaneTransport(srv.PublicURL(), false); err != nil {+ fmt.Printf("\nDevice enrollment QR skipped: devices only trust an https control plane.\n"++ "Run with --tunnel %s or --external-url https://... to enroll phones.\n", strings.Join(tunnel.Names(), "|"))+ return nil+ }+ tok, err := srv.MintDeviceEnrollmentToken(ctx, standalone.DeviceTokenTTL, maxUsages)+ if err != nil {+ return err+ }+ fmt.Println()+ return printEnrollQR(os.Stdout, srv.PublicURL(), tok, standalone.DeviceTokenTTL, maxUsages)+}++// tunnelOptions collects what openTunnel needs from the flags.+type tunnelOptions struct {+ provider string+ bindAddress string+ port int+ dataDir string+ cloudflaredPath string+ install bool+}++// openTunnel publishes the listener that Start is about to bind. The+// connector dials the bind host, or loopback when binding all interfaces.+func openTunnel(ctx context.Context, o tunnelOptions) (tunnel.Tunnel, error) {+ p, err := tunnel.Lookup(o.provider)+ if err != nil {+ return nil, err+ }+ if cf, ok := p.(*tunnel.Cloudflare); ok {+ cf.Binary = o.cloudflaredPath+ cf.InstallDir = filepath.Join(o.dataDir, "bin")+ cf.Consent = installConsent(o.install)+ }+ host := o.bindAddress+ if ip := net.ParseIP(host); host == "" || (ip != nil && ip.IsUnspecified()) {+ host = "127.0.0.1"+ }+ target := "http://" + net.JoinHostPort(host, strconv.Itoa(o.port))+ logger.Infof("Opening %s tunnel to %s", p.Name(), target)+ return p.Open(ctx, target)+}++// installConsent decides whether a missing connector may be downloaded:+// --tunnel-install says yes up front; otherwise an interactive terminal is+// asked, and a non-interactive run is refused (a container or service must+// opt in explicitly rather than fetch binaries on its own).+func installConsent(preApproved bool) func(version, url string) bool {+ return func(version, url string) bool {+ fmt.Printf("cloudflared is not installed. sam-one can download release %s (SHA-256 verified) from\n %s\ninto its data directory. Installing cloudflared means accepting Cloudflare's license:\n %s\n",+ version, url, tunnel.CloudflaredLicenseURL)+ if preApproved {+ fmt.Println("Proceeding (--tunnel-install).")+ return true+ }+ if !stdinIsTerminal() {+ fmt.Println("Not a terminal: pass --tunnel-install to accept, or install cloudflared yourself.")+ return false+ }+ fmt.Print("Download and accept? [y/N] ")+ line, err := bufio.NewReader(os.Stdin).ReadString('\n')+ switch strings.ToLower(strings.TrimSpace(line)) {+ case "y", "yes":+ return true+ }+ if err != nil {+ // /dev/null is a char device too; EOF is the tell.+ fmt.Println("\nNo answer: pass --tunnel-install to accept, or install cloudflared yourself.")+ }+ return false+ }+}++// freePort asks the kernel for an unused port on host; the listener is+// released immediately, so the port is only reserved by convention.+func freePort(host string) (int, error) {+ l, err := net.Listen("tcp", net.JoinHostPort(host, "0"))+ if err != nil {+ return 0, err+ }+ defer func() { _ = l.Close() }()+ return l.Addr().(*net.TCPAddr).Port, nil+}diff --git a/cmd/sam-one/qr.go b/cmd/sam-one/qr.gonew file mode 100644index 00000000..33b0106a--- /dev/null+++ b/cmd/sam-one/qr.go@@ -0,0 +1,80 @@+// 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 main++import (+ "crypto/sha256"+ "fmt"+ "io"+ "net/url"+ "os"+ "time"++ "github.com/google/sam/api"+ qrcode "github.com/skip2/go-qrcode"+)++// printEnrollQR writes the device onboarding block: the URL the device will+// enroll against, the sam:// payload for copy-paste, and the same payload+// as a half-block QR code that the SAM mobile app (or a stock camera app,+// via the sam:// link) scans. The server must pass the control-plane+// transport rule a device enforces, or the code would scan and then fail.+// maxUsages is how many devices the code admits; the token id lets the+// operator revoke a shared code before it is exhausted.+func printEnrollQR(w io.Writer, server, token string, ttl time.Duration, maxUsages int) error {+ uri := api.EnrollURI(server, token)+ if _, _, err := api.ParseEnrollURI(uri); err != nil {+ return err+ }+ code, err := qrcode.New(uri, qrcode.Medium)+ if err != nil {+ return fmt.Errorf("failed to encode enrollment QR: %w", err)+ }+ host := server+ if u, err := url.Parse(server); err == nil && u.Host != "" {+ host = u.Host+ }+ budget := "single use"+ if maxUsages > 1 {+ budget = fmt.Sprintf("up to %d devices", maxUsages)+ }+ _, _ = fmt.Fprintf(w, "Scan with the SAM app to enroll a device into %s\n", host)+ _, _ = fmt.Fprintf(w, "(%s, valid for %s):\n\n", budget, ttl.Round(time.Minute))+ // inverseColor=false draws light modules as blocks, so the code reads+ // black-on-white on the dark terminals scanners cope with best.+ _, _ = io.WriteString(w, code.ToSmallString(false))+ _, _ = fmt.Fprintf(w, "\n%s\n", uri)+ // Same derivation as the control plane's token id, so `token list` and+ // `token revoke` line up with what is printed here.+ _, _ = fmt.Fprintf(w, "Token ID: %s (revoke early with: sam-one token revoke %[1]s)\n", tokenID(token)[:12])+ return nil+}++// tokenID mirrors the control plane: the hex SHA-256 of the plaintext.+func tokenID(token string) string {+ return fmt.Sprintf("%x", sha256.Sum256([]byte(token)))+}++// stdoutIsTerminal reports whether stdout is an interactive terminal, the+// only place a QR code is worth drawing by default.+func stdoutIsTerminal() bool { return isTerminal(os.Stdout) }++// stdinIsTerminal reports whether a human can answer a prompt.+func stdinIsTerminal() bool { return isTerminal(os.Stdin) }++func isTerminal(f *os.File) bool {+ fi, err := f.Stat()+ return err == nil && fi.Mode()&os.ModeCharDevice != 0+}diff --git a/go.mod b/go.modindex ebb5f225..20069286 100644--- a/go.mod+++ b/go.mod@@ -25,6 +25,7 @@ require (github.com/openai/openai-go v1.12.0github.com/prometheus/client_golang v1.24.1github.com/prometheus/client_model v0.6.3+ github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686egithub.com/spf13/cobra v1.10.2go.etcd.io/bbolt v1.5.0go.uber.org/zap v1.28.0diff --git a/go.sum b/go.sumindex 4642073b..5237f04a 100644--- a/go.sum+++ b/go.sum@@ -268,6 +268,8 @@ github.com/segmentio/asm v1.2.1 h1:DTNbBqs57ioxAD4PrArqftgypG4/qNpXoJx8TVXxPR0=github.com/segmentio/asm v1.2.1/go.mod h1:BqMnlJP91P8d+4ibuonYZw9mfnzI9HfxselHZr5aAcs=github.com/segmentio/encoding v0.5.4 h1:OW1VRern8Nw6ITAtwSZ7Idrl3MXCFwXHPgqESYfvNt0=github.com/segmentio/encoding v0.5.4/go.mod h1:HS1ZKa3kSN32ZHVZ7ZLPLXWvOVIiZtyJnO1gPH1sKt0=+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY=github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec=github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY=diff --git a/internal/standalone/standalone.go b/internal/standalone/standalone.goindex 3622d642..07c729b9 100644--- a/internal/standalone/standalone.go+++ b/internal/standalone/standalone.go@@ -47,8 +47,9 @@ import (var logger = golog.Logger("sam-one")const (- joinTokenPrefix = "sam_tok_"- adminTokenPrefix = "sam_adm_"+ joinTokenPrefix = "sam_tok_"+ adminTokenPrefix = "sam_adm_"+ deviceTokenPrefix = "sam_dev_"joinTokenFile = "join-token"adminTokenFile = "admin-token"@@ -64,6 +65,11 @@ const (// routerTokenTTL bounds the per-boot single-use token the embedded router// enrolls with; it never leaves the process.routerTokenTTL = time.Hour++ // DeviceTokenTTL bounds a device enrollment token: long enough to walk+ // over and scan the QR code, short enough that a screenshot of it goes+ // stale.+ DeviceTokenTTL = time.Hour)// Options configures the standalone all-in-one server.@@ -375,6 +381,15 @@ func (s *Server) Close() error {// Addr returns the public host:port actually bound (useful with port 0).func (s *Server) Addr() string { return s.publicAddr }+// PublicURL is the base URL clients should reach this server on: the+// configured external URL, else the bound listener over plain HTTP.+func (s *Server) PublicURL() string {+ if s.opts.ExternalURL != "" {+ return strings.TrimRight(s.opts.ExternalURL, "/")+ }+ return "http://" + s.publicAddr+}+// AdminToken returns the resolved admin API token.func (s *Server) AdminToken() string { return s.adminToken }@@ -384,6 +399,28 @@ func (s *Server) JoinToken() string { return s.joinToken }// PeerID returns the embedded router's peer ID.func (s *Server) PeerID() string { return s.router.Host.ID().String() }+// MintDeviceEnrollmentToken registers a fresh node bootstrap token good for+// maxUsages enrollments (1 = burned by the first device; more lets one code+// on a projector enroll a room) and returns its plaintext once. Unlike the+// join token it is never persisted; a device that missed the window simply+// gets a new one, and `sam-one token revoke` ends a shared one early.+func (s *Server) MintDeviceEnrollmentToken(ctx context.Context, ttl time.Duration, maxUsages int) (string, error) {+ if ttl <= 0 {+ ttl = DeviceTokenTTL+ }+ if maxUsages <= 0 {+ maxUsages = 1+ }+ tok, err := generateToken(deviceTokenPrefix)+ if err != nil {+ return "", err+ }+ if err := s.ensureBootstrapToken(ctx, tok, api.RoleNode, maxUsages, ttl, "sam-one device enrollment via "+s.PublicURL()); err != nil {+ return "", fmt.Errorf("failed to register device enrollment token: %w", err)+ }+ return tok, nil+}+// seedPolicyOnFirstBoot installs the mesh policy only when none exists; the// database stays authoritative afterwards.func (s *Server) seedPolicyOnFirstBoot(ctx context.Context) error {diff --git a/internal/tunnel/cloudflare.go b/internal/tunnel/cloudflare.gonew file mode 100644index 00000000..0be0e418--- /dev/null+++ b/internal/tunnel/cloudflare.go@@ -0,0 +1,234 @@+// 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 (+ "bufio"+ "context"+ "errors"+ "fmt"+ "io"+ "net/http"+ "os"+ "os/exec"+ "regexp"+ "runtime"+ "sync"+ "syscall"+ "time"++ golog "github.com/ipfs/go-log/v2"+)++var logger = golog.Logger("tunnel")++// Cloudflare opens a TryCloudflare quick tunnel: `cloudflared tunnel --url+// <target>` publishes the target on a random https://*.trycloudflare.com+// subdomain with no account or login. Quick tunnels are a development+// convenience with no SLA; cloudflared prints the assigned URL on its log+// output, which is the only thing this provider parses.+//+// The connector binary is resolved in order: Binary if set, `cloudflared` on+// PATH, a previously installed copy under InstallDir whose digest still+// matches the pin, and finally a fresh download of the pinned release, which+// happens only if Consent agrees. A cached copy that fails verification is+// never run.+type Cloudflare struct {+ // Binary is an explicit cloudflared executable; when set, nothing else+ // is tried.+ Binary string+ // Timeout bounds how long Open waits for the URL; defaults to 30s.+ Timeout time.Duration+ // InstallDir is where a downloaded cloudflared is kept (sam-one uses+ // <data-dir>/bin). Empty disables both the cache and downloads.+ InstallDir string+ // Consent is asked before downloading; installing cloudflared means+ // accepting Cloudflare's license, so this must be an explicit choice.+ // Nil never downloads.+ Consent func(version, url string) bool+ // ReleaseURL overrides the GitHub release download prefix (mirrors,+ // tests). The pinned digests still apply.+ ReleaseURL string+ // HTTPClient performs the download; nil uses a 10 minute timeout.+ HTTPClient *http.Client+}++// quickTunnelURL matches the assigned hostname in cloudflared's banner. The+// same pattern also matches cloudflared's own API endpoint, which shows up+// in retry logs before the banner; assignedQuickTunnelURL filters it out.+var quickTunnelURL = regexp.MustCompile(`https://([a-z0-9-]+)\.trycloudflare\.com`)++// assignedQuickTunnelURL returns the quick-tunnel URL in line, or "" when+// the line has none or only names api.trycloudflare.com.+func assignedQuickTunnelURL(line string) string {+ for _, m := range quickTunnelURL.FindAllStringSubmatch(line, -1) {+ if m[1] != "api" {+ return m[0]+ }+ }+ return ""+}++// Name implements Provider.+func (c *Cloudflare) Name() string { return "cloudflare" }++// Open implements Provider.+func (c *Cloudflare) Open(ctx context.Context, target string) (Tunnel, error) {+ binary, err := c.resolveBinary(ctx)+ if err != nil {+ return nil, err+ }+ timeout := c.Timeout+ if timeout <= 0 {+ timeout = 30 * time.Second+ }++ // 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")+ cmd.Cancel = func() error { return cmd.Process.Signal(syscall.SIGTERM) }+ cmd.WaitDelay = 5 * time.Second+ pr, pw := io.Pipe()+ cmd.Stdout = pw+ cmd.Stderr = pw++ if err := cmd.Start(); err != nil {+ cancel()+ return nil, fmt.Errorf("failed to start cloudflared: %w", err)+ }+ t := &process{cancel: cancel, done: make(chan struct{})}+ urlCh := make(chan string, 1)+ go t.scan(pr, urlCh)+ go func() {+ err := cmd.Wait()+ _ = pw.Close()+ t.finish(err)+ }()++ select {+ case u := <-urlCh:+ t.url = u+ return t, nil+ case <-t.done:+ return nil, fmt.Errorf("cloudflared exited before publishing a URL: %w", t.Err())+ case <-time.After(timeout):+ _ = t.Close()+ return nil, fmt.Errorf("cloudflared did not publish a URL within %s", timeout)+ case <-ctx.Done():+ _ = t.Close()+ return nil, ctx.Err()+ }+}++// resolveBinary picks the cloudflared to run; see the type doc for the order.+func (c *Cloudflare) resolveBinary(ctx context.Context) (string, error) {+ if c.Binary != "" {+ path, err := exec.LookPath(c.Binary)+ if err != nil {+ return "", fmt.Errorf("%w at %q: %v", ErrCloudflaredUnavailable, c.Binary, err)+ }+ return path, nil+ }+ if path, err := exec.LookPath("cloudflared"); err == nil {+ return path, nil+ }+ if c.InstallDir == "" {+ return "", fmt.Errorf("%w on PATH (install it from %s)", ErrCloudflaredUnavailable, CloudflaredLicenseURL)+ }+ asset, ok := pinnedAsset()+ if !ok {+ return "", fmt.Errorf("%w on PATH and no pinned build for %s/%s (install it from %s)", ErrCloudflaredUnavailable, runtime.GOOS, runtime.GOARCH, CloudflaredLicenseURL)+ }+ cached := installedCloudflared(c.InstallDir)+ if verifyBinary(cached, asset.BinarySHA256) {+ return cached, nil+ }+ if _, err := os.Stat(cached); err == nil {+ logger.Warnf("Ignoring %s: digest does not match the pinned cloudflared %s", cached, CloudflaredVersion)+ }+ base := c.ReleaseURL+ if base == "" {+ base = DefaultCloudflaredReleaseURL+ }+ url := base + CloudflaredVersion + "/" + asset.Name+ if c.Consent == nil || !c.Consent(CloudflaredVersion, url) {+ return "", fmt.Errorf("%w on PATH and download not authorized (install it from %s, or allow sam-one to download the pinned release)", ErrCloudflaredUnavailable, CloudflaredLicenseURL)+ }+ client := c.HTTPClient+ if client == nil {+ client = defaultDownloadClient()+ }+ return downloadCloudflared(ctx, client, base, c.InstallDir)+}++// process is a Tunnel backed by a child connector process.+type process struct {+ url string+ cancel context.CancelFunc+ done chan struct{}++ mu sync.Mutex+ closed bool+ err error+}++func (p *process) URL() string { return p.url }+func (p *process) Done() <-chan struct{} { return p.done }++func (p *process) Err() error {+ p.mu.Lock()+ defer p.mu.Unlock()+ return p.err+}++func (p *process) Close() error {+ p.mu.Lock()+ p.closed = true+ p.mu.Unlock()+ p.cancel()+ <-p.done+ return nil+}++// finish records the exit and releases Done; an exit caused by Close is+// not an error.+func (p *process) finish(err error) {+ p.mu.Lock()+ if !p.closed && err != nil {+ p.err = err+ }+ p.mu.Unlock()+ close(p.done)+}++// 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.+func (p *process) scan(r io.Reader, urlCh chan<- string) {+ sc := bufio.NewScanner(r)+ found := false+ for sc.Scan() {+ line := sc.Text()+ logger.Debugf("cloudflared: %s", line)+ if !found {+ if m := assignedQuickTunnelURL(line); m != "" {+ found = true+ urlCh <- m+ }+ }+ }+ if err := sc.Err(); err != nil && !errors.Is(err, io.ErrClosedPipe) {+ logger.Debugf("cloudflared output closed: %v", err)+ }+}diff --git a/internal/tunnel/cloudflare_release.go b/internal/tunnel/cloudflare_release.gonew file mode 100644index 00000000..4dd9869e--- /dev/null+++ b/internal/tunnel/cloudflare_release.go@@ -0,0 +1,248 @@+// 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 (+ "archive/tar"+ "compress/gzip"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "fmt"+ "io"+ "net/http"+ "os"+ "path/filepath"+ "runtime"+ "time"+)++// CloudflaredVersion is the cloudflared release this build knows how to+// install. Bump it together with cloudflaredAssets: the digests are the only+// thing standing between "download from GitHub" and "run whatever answered".+const CloudflaredVersion = "2026.9.1"++// CloudflaredLicenseURL is what a user accepts by installing cloudflared.+const CloudflaredLicenseURL = "https://developers.cloudflare.com/cloudflare-one/networks/connectors/cloudflare-tunnel/downloads/license/"++// DefaultCloudflaredReleaseURL is the GitHub releases download prefix.+const DefaultCloudflaredReleaseURL = "https://github.com/cloudflare/cloudflared/releases/download/"++// maxCloudflaredDownload caps the asset size; current builds are ~40 MiB.+const maxCloudflaredDownload = 128 << 20++// releaseAsset pins one downloadable build. AssetSHA256 covers the bytes+// fetched; BinarySHA256 covers the executable that ends up on disk (equal for+// raw binaries, the inner file for tarballs) and is what gets re-checked+// before every launch.+type releaseAsset struct {+ Name string+ AssetSHA256 string+ BinarySHA256 string+ Tarball bool+}++// cloudflaredAssets maps GOOS/GOARCH to the pinned asset. Verified against+// the GitHub asset digests of CloudflaredVersion; the macOS entries also+// match the per-binary checksums Cloudflare lists in the release notes.+var cloudflaredAssets = map[string]releaseAsset{+ "linux/amd64": {+ Name: "cloudflared-linux-amd64",+ AssetSHA256: "03f1f25d1cc93b9ad6c60569d44060bc4f17ed97075760ed8cfca4b12dcd68cc",+ BinarySHA256: "03f1f25d1cc93b9ad6c60569d44060bc4f17ed97075760ed8cfca4b12dcd68cc",+ },+ "linux/arm64": {+ Name: "cloudflared-linux-arm64",+ AssetSHA256: "3d97437c71848bd8df68041e12436b484a661d95073ea1937f01a845ce88faa3",+ BinarySHA256: "3d97437c71848bd8df68041e12436b484a661d95073ea1937f01a845ce88faa3",+ },+ "linux/arm": {+ Name: "cloudflared-linux-arm",+ AssetSHA256: "093ffa3638ab2b636de63c43a8c68f96a69cf71f9699dd8277a91b160b0f4fc0",+ BinarySHA256: "093ffa3638ab2b636de63c43a8c68f96a69cf71f9699dd8277a91b160b0f4fc0",+ },+ "linux/386": {+ Name: "cloudflared-linux-386",+ AssetSHA256: "5d66134cf7646cb98f33aeee7bcc8b97d8feacd76db279f5903f9585226e0922",+ BinarySHA256: "5d66134cf7646cb98f33aeee7bcc8b97d8feacd76db279f5903f9585226e0922",+ },+ "darwin/amd64": {+ Name: "cloudflared-darwin-amd64.tgz",+ AssetSHA256: "ff0d3b51d5ff70eceef89d6b32145fee985018a2174596a5dbe405e2766e2ac4",+ BinarySHA256: "1ea07ae775b03236bd6be18ca1848d6bdc4af2f4f3bce398823b5a36e5761b75",+ Tarball: true,+ },+ "darwin/arm64": {+ Name: "cloudflared-darwin-arm64.tgz",+ AssetSHA256: "c27ab8fd0aa489449e3d201eb02f957ef460a13b613662928b1b23394bf1bcfe",+ BinarySHA256: "9a0b19f67dc7a3011bc6b972c7ce06a5fcea8784ac6bd599ffa382ea4aeb5a6e",+ Tarball: true,+ },+}++// ErrCloudflaredUnavailable is returned when no usable cloudflared exists and+// the provider was not allowed to install one.+var ErrCloudflaredUnavailable = errors.New("cloudflared not found")++// pinnedAsset returns the asset for this platform, if there is one.+func pinnedAsset() (releaseAsset, bool) {+ a, ok := cloudflaredAssets[runtime.GOOS+"/"+runtime.GOARCH]+ return a, ok+}++// installedCloudflared is the path a downloaded binary lives at.+func installedCloudflared(dir string) string {+ return filepath.Join(dir, "cloudflared")+}++// verifyBinary reports whether the file at path hashes to want.+func verifyBinary(path, want string) bool {+ f, err := os.Open(path)+ if err != nil {+ return false+ }+ defer func() { _ = f.Close() }()+ h := sha256.New()+ if _, err := io.Copy(h, f); err != nil {+ return false+ }+ return hex.EncodeToString(h.Sum(nil)) == want+}++// downloadCloudflared fetches the pinned asset for this platform into dir,+// verifying the asset digest before anything is extracted and the binary+// digest before the file is put in place. Nothing is executed here.+func downloadCloudflared(ctx context.Context, client *http.Client, baseURL, dir string) (string, error) {+ asset, ok := pinnedAsset()+ if !ok {+ return "", fmt.Errorf("no pinned cloudflared build for %s/%s", runtime.GOOS, runtime.GOARCH)+ }+ if err := os.MkdirAll(dir, 0o755); err != nil {+ return "", fmt.Errorf("failed to create %s: %w", dir, err)+ }+ url := baseURL + CloudflaredVersion + "/" + asset.Name+ logger.Infof("Downloading cloudflared %s from %s", CloudflaredVersion, url)++ // Whole asset to a temp file first: the digest must be checked before a+ // single byte is interpreted as a tarball or an executable.+ tmp, err := os.CreateTemp(dir, ".cloudflared-download-*")+ if err != nil {+ return "", err+ }+ tmpPath := tmp.Name()+ defer func() { _ = os.Remove(tmpPath) }()+ if err := fetchVerified(ctx, client, url, tmp, asset.AssetSHA256); err != nil {+ _ = tmp.Close()+ return "", err+ }+ if _, err := tmp.Seek(0, io.SeekStart); err != nil {+ _ = tmp.Close()+ return "", err+ }++ bin, err := os.CreateTemp(dir, ".cloudflared-bin-*")+ if err != nil {+ _ = tmp.Close()+ return "", err+ }+ binPath := bin.Name()+ defer func() { _ = os.Remove(binPath) }()+ var src io.Reader = tmp+ if asset.Tarball {+ if src, err = tarballEntry(tmp, "cloudflared"); err != nil {+ _ = tmp.Close()+ _ = bin.Close()+ return "", err+ }+ }+ h := sha256.New()+ if _, err := io.Copy(io.MultiWriter(bin, h), src); err != nil {+ _ = tmp.Close()+ _ = bin.Close()+ return "", fmt.Errorf("failed to write cloudflared: %w", err)+ }+ _ = tmp.Close()+ if err := bin.Close(); err != nil {+ return "", err+ }+ if got := hex.EncodeToString(h.Sum(nil)); got != asset.BinarySHA256 {+ return "", fmt.Errorf("cloudflared binary digest mismatch: got %s, want %s", got, asset.BinarySHA256)+ }+ if err := os.Chmod(binPath, 0o755); err != nil {+ return "", err+ }+ dest := installedCloudflared(dir)+ if err := os.Rename(binPath, dest); err != nil {+ return "", fmt.Errorf("failed to install cloudflared: %w", err)+ }+ return dest, nil+}++// fetchVerified streams url into w and fails unless the bytes hash to want.+// The caller must discard w's contents on error.+func fetchVerified(ctx context.Context, client *http.Client, url string, w io.Writer, want string) error {+ req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)+ if err != nil {+ return err+ }+ resp, err := client.Do(req)+ if err != nil {+ return fmt.Errorf("download failed: %w", err)+ }+ defer func() { _ = resp.Body.Close() }()+ if resp.StatusCode != http.StatusOK {+ return fmt.Errorf("download failed: %s returned %s", url, resp.Status)+ }+ h := sha256.New()+ n, err := io.Copy(io.MultiWriter(w, h), io.LimitReader(resp.Body, maxCloudflaredDownload+1))+ if err != nil {+ return fmt.Errorf("download failed: %w", err)+ }+ if n > maxCloudflaredDownload {+ return fmt.Errorf("download exceeds %d bytes", maxCloudflaredDownload)+ }+ if got := hex.EncodeToString(h.Sum(nil)); got != want {+ return fmt.Errorf("cloudflared asset digest mismatch: got %s, want %s (refusing to install)", got, want)+ }+ return nil+}++// tarballEntry positions a reader on the named regular file inside a+// gzip-compressed tarball.+func tarballEntry(r io.Reader, name string) (io.Reader, error) {+ gz, err := gzip.NewReader(r)+ if err != nil {+ return nil, fmt.Errorf("invalid cloudflared tarball: %w", err)+ }+ tr := tar.NewReader(gz)+ for {+ hdr, err := tr.Next()+ if err == io.EOF {+ return nil, fmt.Errorf("cloudflared tarball has no %q entry", name)+ }+ if err != nil {+ return nil, fmt.Errorf("invalid cloudflared tarball: %w", err)+ }+ if hdr.Typeflag == tar.TypeReg && filepath.Base(hdr.Name) == name {+ return tr, nil+ }+ }+}++// defaultDownloadClient bounds a ~40 MiB fetch generously.+func defaultDownloadClient() *http.Client {+ return &http.Client{Timeout: 10 * time.Minute}+}diff --git a/internal/tunnel/cloudflare_test.go b/internal/tunnel/cloudflare_test.gonew file mode 100644index 00000000..fb9ba954--- /dev/null+++ b/internal/tunnel/cloudflare_test.go@@ -0,0 +1,282 @@+// 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 (+ "archive/tar"+ "bytes"+ "compress/gzip"+ "context"+ "crypto/sha256"+ "encoding/hex"+ "errors"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "runtime"+ "strings"+ "sync/atomic"+ "testing"+ "time"+)++// stubCloudflared writes a shell script that mimics cloudflared's banner on+// stderr and then runs until killed, like the real connector.+func stubCloudflared(t *testing.T, body string) string {+ t.Helper()+ path := filepath.Join(t.TempDir(), "cloudflared")+ if err := os.WriteFile(path, []byte("#!/bin/sh\n"+body), 0o755); err != nil {+ t.Fatal(err)+ }+ return path+}++func TestCloudflareOpenParsesQuickTunnelURL(t *testing.T) {+ bin := stubCloudflared(t, `+[ "$1" = tunnel ] && [ "$2" = --url ] || { echo "bad args: $*" >&2; exit 2; }+echo "$3" > "$(dirname "$0")/target"+echo "INF Requesting new quick Tunnel on trycloudflare.com..." >&2+echo 'ERR Request failed error="Post \"https://api.trycloudflare.com/tunnel\": context deadline exceeded" retrying' >&2+echo "INF +------------------------------------------------------------+" >&2+echo "INF | Your quick Tunnel has been created! Visit it at: |" >&2+echo "INF | https://brave-otter-quick-1234.trycloudflare.com |" >&2+echo "INF +------------------------------------------------------------+" >&2+trap 'exit 0' TERM+while :; do sleep 1; done+`)+ p := &Cloudflare{Binary: bin, Timeout: 5 * time.Second}+ tun, err := p.Open(context.Background(), "http://127.0.0.1:18080")+ if err != nil {+ t.Fatalf("Open: %v", err)+ }+ if got, want := tun.URL(), "https://brave-otter-quick-1234.trycloudflare.com"; got != want {+ t.Fatalf("URL = %q, want %q", got, want)+ }+ target, err := os.ReadFile(filepath.Join(filepath.Dir(bin), "target"))+ if err != nil {+ t.Fatal(err)+ }+ if strings.TrimSpace(string(target)) != "http://127.0.0.1:18080" {+ t.Fatalf("connector got target %q", target)+ }+ select {+ case <-tun.Done():+ t.Fatal("tunnel reported done while the connector is running")+ default:+ }+ if err := tun.Close(); err != nil {+ t.Fatalf("Close: %v", err)+ }+ select {+ case <-tun.Done():+ case <-time.After(5 * time.Second):+ t.Fatal("Done not closed after Close")+ }+ if err := tun.Err(); err != nil {+ t.Fatalf("Err after Close = %v, want nil", err)+ }+}++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}+ if _, err := p.Open(context.Background(), "http://127.0.0.1:1"); err == nil || !strings.Contains(err.Error(), "exited before publishing") {+ t.Fatalf("Open error = %v, want early-exit error", err)+ }+}++func TestCloudflareOpenTimesOutWithoutURL(t *testing.T) {+ bin := stubCloudflared(t, `trap 'exit 0' TERM; while :; do sleep 1; done`)+ p := &Cloudflare{Binary: bin, Timeout: 200 * time.Millisecond}+ if _, err := p.Open(context.Background(), "http://127.0.0.1:1"); err == nil || !strings.Contains(err.Error(), "did not publish") {+ t.Fatalf("Open error = %v, want timeout error", err)+ }+}++func TestCloudflareOpenMissingBinary(t *testing.T) {+ p := &Cloudflare{Binary: filepath.Join(t.TempDir(), "missing")}+ if _, err := p.Open(context.Background(), "http://127.0.0.1:1"); err == nil || !errors.Is(err, ErrCloudflaredUnavailable) {+ t.Fatalf("Open error = %v, want ErrCloudflaredUnavailable", err)+ }+}++// fakeRelease serves one asset for this platform and swaps the pinned+// digests to match it, restoring the table when the test ends. The asset is+// a shell script (raw or tarred, like the real linux/macOS assets), so a+// successful install can also be executed.+func fakeRelease(t *testing.T, script string, tarball bool) (baseURL string, hits *int32) {+ t.Helper()+ orig, ok := pinnedAsset()+ if !ok {+ t.Skipf("no pinned asset for %s/%s", runtime.GOOS, runtime.GOARCH)+ }+ body := []byte("#!/bin/sh\n" + script)+ binSum := sha256.Sum256(body)+ asset := body+ if tarball {+ var buf bytes.Buffer+ gz := gzip.NewWriter(&buf)+ tw := tar.NewWriter(gz)+ if err := tw.WriteHeader(&tar.Header{Name: "cloudflared", Mode: 0o755, Size: int64(len(body)), Typeflag: tar.TypeReg}); err != nil {+ t.Fatal(err)+ }+ if _, err := tw.Write(body); err != nil {+ t.Fatal(err)+ }+ _ = tw.Close()+ _ = gz.Close()+ asset = buf.Bytes()+ }+ assetSum := sha256.Sum256(asset)+ key := runtime.GOOS + "/" + runtime.GOARCH+ cloudflaredAssets[key] = releaseAsset{+ Name: orig.Name,+ AssetSHA256: hex.EncodeToString(assetSum[:]),+ BinarySHA256: hex.EncodeToString(binSum[:]),+ Tarball: tarball,+ }+ t.Cleanup(func() { cloudflaredAssets[key] = orig })++ var count int32+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ atomic.AddInt32(&count, 1)+ if r.URL.Path != "/"+CloudflaredVersion+"/"+orig.Name {+ http.NotFound(w, r)+ return+ }+ _, _ = w.Write(asset)+ }))+ t.Cleanup(srv.Close)+ return srv.URL + "/", &count+}++// idleConnector is the script body of a fake cloudflared that publishes a+// URL and waits to be terminated.+const idleConnector = `echo "INF | https://installed-quick-1234.trycloudflare.com |" >&2+trap 'exit 0' TERM+while :; do sleep 1; done+`++func TestCloudflareDownloadsPinnedReleaseWithConsent(t *testing.T) {+ for _, tarball := range []bool{false, true} {+ t.Run(map[bool]string{false: "raw", true: "tarball"}[tarball], func(t *testing.T) {+ base, hits := fakeRelease(t, idleConnector, tarball)+ dir := filepath.Join(t.TempDir(), "bin")+ var asked []string+ p := &Cloudflare{+ InstallDir: dir,+ ReleaseURL: base,+ Timeout: 5 * time.Second,+ Consent: func(version, url string) bool {+ asked = append(asked, version+" "+url)+ return true+ },+ }+ t.Setenv("PATH", t.TempDir()) // no system cloudflared++ tun, err := p.Open(context.Background(), "http://127.0.0.1:1")+ if err != nil {+ t.Fatalf("Open: %v", err)+ }+ _ = tun.Close()+ if len(asked) != 1 || !strings.Contains(asked[0], CloudflaredVersion) || !strings.Contains(asked[0], base) {+ t.Fatalf("consent asked = %v", asked)+ }+ if tun.URL() != "https://installed-quick-1234.trycloudflare.com" {+ t.Fatalf("URL = %q", tun.URL())+ }+ installed := installedCloudflared(dir)+ if fi, err := os.Stat(installed); err != nil || fi.Mode().Perm()&0o111 == 0 {+ t.Fatalf("installed binary missing or not executable: %v %v", fi, err)+ }+ if leftovers, _ := filepath.Glob(filepath.Join(dir, ".cloudflared-*")); len(leftovers) != 0 {+ t.Fatalf("temp files left behind: %v", leftovers)+ }++ // Second run: the verified cache is reused, nothing is asked or fetched.+ tun, err = p.Open(context.Background(), "http://127.0.0.1:1")+ if err != nil {+ t.Fatalf("second Open: %v", err)+ }+ _ = tun.Close()+ if len(asked) != 1 || atomic.LoadInt32(hits) != 1 {+ t.Fatalf("cache not used: consent asked %d times, release fetched %d times", len(asked), *hits)+ }+ })+ }+}++func TestCloudflareRefusesDownloadWithoutConsent(t *testing.T) {+ base, hits := fakeRelease(t, idleConnector, false)+ t.Setenv("PATH", t.TempDir())+ p := &Cloudflare{InstallDir: filepath.Join(t.TempDir(), "bin"), ReleaseURL: base}+ _, err := p.Open(context.Background(), "http://127.0.0.1:1")+ if !errors.Is(err, ErrCloudflaredUnavailable) {+ t.Fatalf("nil Consent: err = %v, want ErrCloudflaredUnavailable", err)+ }+ p.Consent = func(string, string) bool { return false }+ _, err = p.Open(context.Background(), "http://127.0.0.1:1")+ if !errors.Is(err, ErrCloudflaredUnavailable) || atomic.LoadInt32(hits) != 0 {+ t.Fatalf("declined Consent: err = %v, fetches = %d", err, *hits)+ }+}++func TestCloudflareRejectsTamperedDownloadAndCache(t *testing.T) {+ base, _ := fakeRelease(t, idleConnector, false)+ t.Setenv("PATH", t.TempDir())+ dir := filepath.Join(t.TempDir(), "bin")+ p := &Cloudflare{InstallDir: dir, ReleaseURL: base, Timeout: 5 * time.Second, Consent: func(string, string) bool { return true }}++ // A cached file with the right name but the wrong content is never run;+ // it is replaced by a verified download.+ if err := os.MkdirAll(dir, 0o755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(installedCloudflared(dir), []byte("#!/bin/sh\necho pwned >&2; exit 1\n"), 0o755); err != nil {+ t.Fatal(err)+ }+ tun, err := p.Open(context.Background(), "http://127.0.0.1:1")+ if err != nil {+ t.Fatalf("Open with tampered cache: %v", err)+ }+ _ = tun.Close()+ if asset, _ := pinnedAsset(); !verifyBinary(installedCloudflared(dir), asset.BinarySHA256) {+ t.Fatal("tampered cache was not replaced by the verified build")+ }++ // A download whose bytes do not match the pin is discarded.+ key := runtime.GOOS + "/" + runtime.GOARCH+ bad := cloudflaredAssets[key]+ bad.AssetSHA256 = strings.Repeat("0", 64)+ cloudflaredAssets[key] = bad+ _ = os.Remove(installedCloudflared(dir))+ if _, err := p.Open(context.Background(), "http://127.0.0.1:1"); err == nil || !strings.Contains(err.Error(), "digest mismatch") {+ t.Fatalf("Open with mismatching asset digest: err = %v", err)+ }+ if _, err := os.Stat(installedCloudflared(dir)); !os.IsNotExist(err) {+ t.Fatal("mismatching download was installed")+ }+}++func TestLookup(t *testing.T) {+ p, err := Lookup(" Cloudflare ")+ if err != nil || p.Name() != "cloudflare" {+ t.Fatalf("Lookup = %v, %v", p, err)+ }+ if _, err := Lookup("ngrok"); err == nil || !strings.Contains(err.Error(), "available: cloudflare") {+ t.Fatalf("Lookup unknown = %v", err)+ }+}diff --git a/internal/tunnel/tunnel.go b/internal/tunnel/tunnel.gonew file mode 100644index 00000000..31024bca--- /dev/null+++ b/internal/tunnel/tunnel.go@@ -0,0 +1,71 @@+// 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 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.+package tunnel++import (+ "context"+ "fmt"+ "sort"+ "strings"+)++// Tunnel is an open public endpoint forwarding to a local target.+type Tunnel interface {+ // URL is the public https base URL that reaches the local target.+ URL() string+ // Done is closed once the tunnel has stopped forwarding, for whatever+ // reason; Err then reports why (nil after Close).+ Done() <-chan struct{}+ Err() error+ // Close tears the tunnel down.+ Close() error+}++// Provider opens tunnels through one connector implementation.+type Provider interface {+ // Name is the operator-facing identifier (e.g. "cloudflare").+ Name() string+ // Open publishes target, a local http://host:port URL, and returns once+ // the public URL is known or ctx expires.+ Open(ctx context.Context, target string) (Tunnel, error)+}++var providers = map[string]func() Provider{+ "cloudflare": func() Provider { return &Cloudflare{} },+}++// Names lists the registered providers.+func Names() []string {+ names := make([]string, 0, len(providers))+ for n := range providers {+ names = append(names, n)+ }+ sort.Strings(names)+ return names+}++// Lookup returns a fresh provider by name.+func Lookup(name string) (Provider, error) {+ ctor, ok := providers[strings.ToLower(strings.TrimSpace(name))]+ if !ok {+ return nil, fmt.Errorf("unknown tunnel provider %q (available: %s)", name, strings.Join(Names(), ", "))+ }+ return ctor(), nil+}diff --git a/tests/integration/standalone_test.go b/tests/integration/standalone_test.goindex a4d2d7ee..e6b8f676 100644--- a/tests/integration/standalone_test.go+++ b/tests/integration/standalone_test.go@@ -79,35 +79,7 @@ func TestStandaloneNodeJoin(t *testing.T) {// A stock node joins through the public port with the generated token and// ends up connected to the router over WebSocket.- nodeStore, err := node.NewStore(t.TempDir())- if err != nil {- t.Fatalf("failed to create node store: %v", err)- }- t.Cleanup(func() { _ = nodeStore.Close() })-- priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)- if err != nil {- t.Fatalf("failed to generate node key: %v", err)- }- samNode, err := node.NewSamNode(node.Options{- PrivKey: priv,- Store: nodeStore,- ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},- AllowLoopback: true,- RequiredRole: api.RoleNode,- })- if err != nil {- t.Fatalf("failed to create node: %v", err)- }- if err := samNode.Start(ctx); err != nil {- t.Fatalf("failed to start node: %v", err)- }- t.Cleanup(func() {- if samNode.Host != nil {- _ = samNode.Host.Close()- }- })-+ samNode := newStandaloneTestNode(t, ctx)if err := samNode.EnrollBootstrap(ctx, "http://"+srv.Addr(), srv.JoinToken()); err != nil {t.Fatalf("node enrollment through the single port failed: %v", err)}@@ -137,4 +109,88 @@ func TestStandaloneNodeJoin(t *testing.T) {if !strings.Contains(string(body), "<html") {t.Errorf("GET /console/ did not return the embedded frontend")}++ // Device onboarding: the QR payload carries the public URL and a fresh+ // single-use token; the first device enrolls with it, the second is+ // refused because /enroll burned it.+ t.Run("DeviceEnrollmentToken", func(t *testing.T) {+ devTok, err := srv.MintDeviceEnrollmentToken(ctx, 0, 1)+ if err != nil {+ t.Fatalf("failed to mint device token: %v", err)+ }+ if devTok == srv.JoinToken() || !strings.HasPrefix(devTok, "sam_dev_") {+ t.Fatalf("device token %q must be distinct from the join token and prefixed sam_dev_", devTok)+ }+ server, token, err := api.ParseEnrollURI(api.EnrollURI(srv.PublicURL(), devTok))+ if err != nil {+ t.Fatalf("failed to parse enrollment URI: %v", err)+ }+ if server != "http://"+srv.Addr() || token != devTok {+ t.Fatalf("enrollment URI round trip = (%q, %q)", server, token)+ }++ device := newStandaloneTestNode(t, ctx)+ if err := device.EnrollBootstrap(ctx, server, token); err != nil {+ t.Fatalf("device enrollment with the QR token failed: %v", err)+ }+ if got := device.Host.Network().Connectedness(routerID); got != network.Connected {+ t.Fatalf("device connectedness to embedded router = %s, want Connected", got)+ }++ replay := newStandaloneTestNode(t, ctx)+ err = replay.EnrollBootstrap(ctx, server, token)+ if err == nil || !strings.Contains(err.Error(), "exhausted") && !strings.Contains(err.Error(), "max usages") {+ t.Fatalf("second device reusing the burned token: err = %v, want rejection", err)+ }+ })++ // A code projected to a room: one token, a usage budget, several devices.+ t.Run("SharedDeviceEnrollmentToken", func(t *testing.T) {+ shared, err := srv.MintDeviceEnrollmentToken(ctx, 0, 2)+ if err != nil {+ t.Fatalf("failed to mint shared device token: %v", err)+ }+ for i := 0; i < 2; i++ {+ if err := newStandaloneTestNode(t, ctx).EnrollBootstrap(ctx, srv.PublicURL(), shared); err != nil {+ t.Fatalf("device %d enrollment with the shared token failed: %v", i+1, err)+ }+ }+ if err := newStandaloneTestNode(t, ctx).EnrollBootstrap(ctx, srv.PublicURL(), shared); err == nil {+ t.Fatal("third device enrolled past the shared token's budget")+ }+ })+}++// newStandaloneTestNode returns a started, unenrolled loopback node.+func newStandaloneTestNode(t *testing.T, ctx context.Context) *node.SamNode {+ t.Helper()+ nodeStore, err := node.NewStore(t.TempDir())+ if err != nil {+ t.Fatalf("failed to create node store: %v", err)+ }+ t.Cleanup(func() { _ = nodeStore.Close() })++ priv, _, err := crypto.GenerateKeyPair(crypto.Ed25519, -1)+ if err != nil {+ t.Fatalf("failed to generate node key: %v", err)+ }+ samNode, err := node.NewSamNode(node.Options{+ PrivKey: priv,+ Store: nodeStore,+ ListenAddrs: []string{"/ip4/127.0.0.1/tcp/0"},+ AllowLoopback: true,+ RequiredRole: api.RoleNode,+ })+ if err != nil {+ t.Fatalf("failed to create node: %v", err)+ }+ if err := samNode.Start(ctx); err != nil {+ t.Fatalf("failed to start node: %v", err)+ }+ t.Cleanup(func() {+ if samNode.Host != nil {+ _ = samNode.Host.Close()+ }+ })+ return samNode}